jwtMobile;parseSneakers;printSneakersNames

This commit is contained in:
Your Name 2025-03-18 12:56:06 +03:00
parent 0789fc62d4
commit 24d01d033f
8 changed files with 139 additions and 211 deletions

View File

@ -1,57 +1,3 @@
//package com.example.testktor
//
//import android.os.Bundle
//import android.util.Log
//import androidx.activity.ComponentActivity
//import androidx.activity.compose.setContent
//import androidx.activity.enableEdgeToEdge
//import androidx.compose.foundation.layout.fillMaxSize
//import androidx.compose.foundation.layout.padding
//import androidx.compose.material3.Scaffold
//import androidx.compose.material3.Text
//import androidx.compose.material3.CircularProgressIndicator
//import androidx.compose.runtime.*
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.tooling.preview.Preview
//import com.example.testktor.ui.theme.TestKtorTheme
//import io.ktor.client.*
//import io.ktor.client.request.*
//import io.ktor.client.engine.android.*
//import io.ktor.client.plugins.contentnegotiation.*
//import io.ktor.client.statement.HttpResponse
//import io.ktor.client.statement.bodyAsText
//import io.ktor.http.ContentType
//import io.ktor.http.contentType
//import kotlinx.coroutines.launch
//import kotlinx.serialization.Serializable
//import io.ktor.serialization.kotlinx.json.*
//import kotlinx.serialization.decodeFromString
//import kotlinx.serialization.json.Json
//
//@Serializable
//data class User(val id: Int, val name: String)
//
//class MainActivity : ComponentActivity() {
// private val client = HttpClient(Android) {
// install(ContentNegotiation) {
// json(Json { prettyPrint = true })
// }
// }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// enableEdgeToEdge()
// setContent {
// TestKtorTheme {
// Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
// UserScreen(modifier = Modifier.padding(innerPadding), client = client)
// }
// }
// }
// }
//}
//
package com.example.testktor package com.example.testktor
import android.os.Bundle import android.os.Bundle
@ -72,10 +18,11 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import com.example.matuletest.ui.auth.FirstScreen import com.example.matuletest.ui.auth.FirstScreen
import com.example.matuletest.ui.auth.SliderScreen import com.example.matuletest.ui.auth.SliderScreen
import com.example.testktor.auth.AuthScreen import com.example.testktor.screen.auth.AuthScreen
import com.example.testktor.auth.ForgotPasswordScreen import com.example.testktor.screen.auth.ForgotPasswordScreen
import com.example.testktor.auth.RegScreen import com.example.testktor.screen.auth.MainSneakersScreen
import com.example.testktor.auth.ResetPasswordScreen import com.example.testktor.screen.auth.RegScreen
import com.example.testktor.screen.auth.ResetPasswordScreen
//import com.example.testktor.auth.AuthScreen //import com.example.testktor.auth.AuthScreen
//import com.example.testktor.auth.RegistrationScreen //import com.example.testktor.auth.RegistrationScreen
import com.example.testktor.ui.theme.TestKtorTheme import com.example.testktor.ui.theme.TestKtorTheme
@ -93,26 +40,6 @@ import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
//class MainActivity : ComponentActivity() {
// private val client = HttpClient(Android) {
// install(ContentNegotiation) {
// json(Json { prettyPrint = true })
// }
// }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// enableEdgeToEdge()
// setContent {
// TestKtorTheme {
// Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
// UserScreen(modifier = Modifier.padding(innerPadding), client = client)
// }
// }
// }
// }
//}
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -144,6 +71,9 @@ class MainActivity : ComponentActivity() {
composable("forgotPassword_screen") { composable("forgotPassword_screen") {
ForgotPasswordScreen(navController) ForgotPasswordScreen(navController)
} }
composable("mainSneakers_screen") {
MainSneakersScreen(navController)
}
} }
} }
} }

View File

@ -16,80 +16,24 @@ import com.example.testktor.ui.theme.TestKtorTheme
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
import io.ktor.client.engine.android.Android import io.ktor.client.engine.android.Android
import io.ktor.client.request.get import io.ktor.client.request.get
import io.ktor.client.request.headers
import io.ktor.client.request.post import io.ktor.client.request.post
import io.ktor.client.request.setBody import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText import io.ktor.client.statement.bodyAsText
import io.ktor.client.utils.EmptyContent.contentType import io.ktor.client.utils.EmptyContent.contentType
import io.ktor.client.utils.EmptyContent.headers
import io.ktor.http.ContentType import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType import io.ktor.http.contentType
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import java.math.BigDecimal
import java.sql.Time import java.sql.Time
//@Composable
//fun UserScreen(modifier: Modifier = Modifier, client: HttpClient) {
// var users by remember { mutableStateOf<List<User>?>(null) }
// var isLoading by remember { mutableStateOf(true) }
// var errorMessage by remember { mutableStateOf<String?>(null) }
//
// val scope = rememberCoroutineScope()
//
// LaunchedEffect(Unit) {
// try {
// val fetchedUsers = getUsers(client)
// users = fetchedUsers
// } catch (e: Exception) {
// errorMessage = "Error fetching users: ${e.localizedMessage}"
// Log.e("UserScreen", "Error: ${e.localizedMessage}", e)
// }
// isLoading = false
// }
//
// if (isLoading) {
// CircularProgressIndicator()
// }
//
// errorMessage?.let {
// Text(text = it)
// }
//
// users?.let {
// it.forEach { user ->
// Text(text = "User: ${user.name}, ID: ${user.id}")
// }
// } ?: run {
// Text(text = "No users found or failed to load.")
// }
//}
//
//suspend fun getUsers(client: HttpClient): List<User> {
// val response: HttpResponse = client.get("http://212.67.10.54:8080/users") {
// contentType(ContentType.Application.Json)
// }
// val responseBody = response.bodyAsText()
// Log.d("getUsers", "Response: $responseBody") // Логируем ответ сервера
//
// val json = Json { ignoreUnknownKeys = true }
//
// return try {
// json.decodeFromString<List<User>>(responseBody) // Десериализуем в List<User>
// } catch (e: Exception) {
// Log.e("getUsers", "Error deserializing response", e)
// throw e // Повторно выбрасываем ошибку, чтобы она была обработана в UserScreen
// }
//}
//
//@Preview(showBackground = true)
//@Composable
//fun UserScreenPreview() {
// TestKtorTheme {
// UserScreen(client = HttpClient(Android))
// }
//}
@Serializable @Serializable
data class User( data class User(
val id: Int, val id: Int,
@ -98,59 +42,31 @@ data class User(
val password: String, val password: String,
val resetToken: String) val resetToken: String)
//@Composable //@Serializable
//fun UserScreen(modifier: Modifier = Modifier, client: HttpClient) { //data class Sneaker(
// var user by remember { mutableStateOf<User?>(null) } // val id: Int,
// var isLoading by remember { mutableStateOf(true) } // val name: String,
// var errorMessage by remember { mutableStateOf<String?>(null) } // val description: String,
// // @Contextual val cost: BigDecimal,
// val scope = rememberCoroutineScope() // val discount: Int,
// // val photo: String,
// LaunchedEffect(Unit) { // val gender: Char,
// try { // val bootSize: Int
// val fetchedUser = getUser(client) //)
// user = fetchedUser
// } catch (e: Exception) {
// errorMessage = "Error fetching user: ${e.localizedMessage}"
// Log.e("UserScreen", "Error: ${e.localizedMessage}", e)
// }
// isLoading = false
// }
//
// if (isLoading) {
// CircularProgressIndicator()
// }
//
// errorMessage?.let {
// Text(text = it)
// }
//
// user?.let {
// Text(text = "User: ${it.email}, ID: ${it.id}")
// } ?: run {
// Text(text = "No user found or failed to load.")
// }
//}
//suspend fun getUser(client: HttpClient): User { @Serializable
// val response: HttpResponse = client.get("http://10.0.2.2:8080/user") { data class Sneaker(
// contentType(ContentType.Application.Json) val id: Int,
// } val name: String,
// val responseBody = response.bodyAsText() val description: String,
// Log.d("getUser", "Response: $responseBody") val cost: Double,
// val discount: Int,
// val json = Json { ignoreUnknownKeys = true } val photo: String,
// val gender: Char,
// val buba = json.decodeFromString<User>(responseBody) val bootSize: Int
// Log.d("json", buba.email) )
//
// return try { var Token: String = "";
// json.decodeFromString<User>(responseBody)
// } catch (e: Exception) {
// Log.e("getUser", "Error deserializing response", e)
// throw e
// }
//}
suspend fun authUser(client: HttpClient, email: String, password: String): Boolean { suspend fun authUser(client: HttpClient, email: String, password: String): Boolean {
try { try {
@ -165,7 +81,12 @@ suspend fun authUser(client: HttpClient, email: String, password: String): Boole
val json = Json { ignoreUnknownKeys = true } val json = Json { ignoreUnknownKeys = true }
val responseMap = json.decodeFromString<Map<String, String>>(responseBody) val responseMap = json.decodeFromString<Map<String, String>>(responseBody)
return responseMap["message"] == "Вход успешен" if (responseMap.containsKey("Token") && responseMap["Token"]!!.isNotEmpty()){
Token = responseMap["Token"]!!
return true
}
return false
} catch (e: Exception) { } catch (e: Exception) {
Log.e("authUser", "Error during login request", e) Log.e("authUser", "Error during login request", e)
return false return false
@ -232,10 +153,23 @@ suspend fun resetPassword(client: HttpClient, code: String, newPassword: String)
} }
} }
//@Preview(showBackground = true) suspend fun getSneakers(client: HttpClient): List<Sneaker>{
//@Composable try {
//fun UserScreenPreview() { val response: HttpResponse = client.get("http://10.0.2.2:8080/mainWindow") {
// TestKtorTheme { headers {
// UserScreen(client = HttpClient(Android)) append(HttpHeaders.Authorization, "Bearer $Token")
// } }
//} }
val responseBody = response.bodyAsText()
Log.d("getSneakers", "Response: $responseBody")
val json = Json { ignoreUnknownKeys = true }
val responseMap = json.decodeFromString<Map<String, List<Sneaker>>>(responseBody)
return responseMap["sneakers"] ?: emptyList()
} catch (e: Exception) {
Log.e("getSneakers", "error fetching sneakers", e)
return emptyList()
}
}

View File

@ -1,4 +1,4 @@
package com.example.testktor.auth package com.example.testktor.screen.auth
import androidx.compose.foundation.hoverable import androidx.compose.foundation.hoverable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@ -75,14 +75,15 @@ fun AuthContent(
// Отображение текста "Success" в левом верхнем углу // Отображение текста "Success" в левом верхнем углу
if (authSuccess != null){ if (authSuccess != null){
if (authSuccess == "Success") { if (authSuccess == "Success") {
Text( // Text(
text = "Success", // text = "Success",
modifier = Modifier // modifier = Modifier
.padding(start = 16.dp, top = 16.dp) // .padding(start = 16.dp, top = 16.dp)
.align(Alignment.Start), // .align(Alignment.Start),
color = Color.Green, // color = Color.Green,
style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold) // style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold)
) // )
navController.navigate("mainSneakers_screen")
} else{ } else{
Text( Text(
text = "Error", text = "Error",

View File

@ -1,4 +1,4 @@
package com.example.testktor.auth package com.example.testktor.screen.auth
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column

View File

@ -0,0 +1,63 @@
package com.example.testktor.screen.auth
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.testktor.Sneaker
import com.example.testktor.authUser
import com.example.testktor.getSneakers
import io.ktor.client.HttpClient
import io.ktor.client.engine.android.Android
import kotlinx.coroutines.launch
@Composable
fun MainSneakersScreen(navController: NavController) {
var sneakers by remember { mutableStateOf<List<Sneaker>>(emptyList()) }
val coroutineScope = rememberCoroutineScope()
val client = HttpClient(Android)
LaunchedEffect(Unit) {
coroutineScope.launch {
sneakers = getSneakers(client)
}
}
SneakersContent(sneakers)
}
@Composable
fun SneakersContent(
sneakers: List<Sneaker>
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Список кроссовок", fontSize = 24.sp, modifier = Modifier.padding(bottom = 16.dp))
LazyColumn(modifier = Modifier.fillMaxWidth()) {
items(sneakers) { sneaker ->
Text(text = sneaker.name, fontSize = 18.sp, modifier = Modifier.padding(8.dp))
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.example.testktor.auth package com.example.testktor.screen.auth
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column

View File

@ -1,4 +1,4 @@
package com.example.testktor.auth package com.example.testktor.screen.auth
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column