浏览代码

wAuthDone

x1tosi 1 月之前
父节点
当前提交
3eb31668b1

+ 1 - 0
app/src/main/java/com/example/fitmarcetplacekuzminiv/MainActivity.kt

@@ -6,6 +6,7 @@ import androidx.activity.compose.setContent
 import androidx.compose.runtime.Composable
 import androidx.compose.ui.tooling.preview.Preview
 import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.navigation.NavHostController
 import androidx.navigation.compose.NavHost
 import androidx.navigation.compose.composable
 import androidx.navigation.compose.rememberNavController

+ 7 - 20
app/src/main/java/com/example/fitmarcetplacekuzminiv/MainViewModel.kt

@@ -1,30 +1,17 @@
 package com.example.fitmarcetplacekuzminiv
 
+import androidx.compose.runtime.mutableStateOf
 import androidx.lifecycle.ViewModel
 import androidx.lifecycle.viewModelScope
 import com.example.fitmarcetplacekuzminiv.domain.Constants
 import io.github.jan.supabase.gotrue.auth
 import io.github.jan.supabase.gotrue.providers.builtin.Email
-import io.github.jan.supabase.gotrue.providers.builtin.OTP
 import kotlinx.coroutines.launch
 
-class MainViewModel():ViewModel() {
+class MainViewModel : ViewModel() {
 
-    fun onSignInEmailCode(emailUser: String) {
-        viewModelScope.launch {
-            try {
-                Constants.supabase.auth.signInWith(OTP) {
-                    email = emailUser
-                    createUser = false
-                }
-
-            } catch (e: Exception) {
-                println(e.message.toString())
-
-            }
-
-        }
-    }
+    // Состояние для хранения результата авторизации
+    var authResult = mutableStateOf("")
 
     fun onSignInEmailPassword(emailUser: String, passwordUser: String) {
         viewModelScope.launch {
@@ -33,13 +20,13 @@ class MainViewModel():ViewModel() {
                     email = emailUser
                     password = passwordUser
                 }
-                println(user.toString())
-                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                 println("Success")
+                authResult.value = "Success" // Устанавливаем успешный результат
             } catch (e: Exception) {
                 println("Error")
+                authResult.value = "Error" // Устанавливаем ошибочный результат
                 println(e.message.toString())
             }
         }
     }
-}
+}

+ 1 - 1
app/src/main/java/com/example/fitmarcetplacekuzminiv/Model/Products.kt

@@ -1,7 +1,7 @@
 package com.example.fitmarcetplacekuzminiv.Model
 
 import kotlinx.serialization.Serializable
-
+//таблица products
 @Serializable
 data class Product(
     val id: Int,

+ 23 - 47
app/src/main/java/com/example/fitmarcetplacekuzminiv/Screens/authScreen.kt

@@ -1,40 +1,32 @@
 package com.example.fitmarcetplacekuzminiv.Screens
 
-import android.os.Bundle
-import androidx.activity.ComponentActivity
-import androidx.activity.compose.setContent
-import androidx.activity.viewModels
 import androidx.compose.foundation.layout.*
 import androidx.compose.material3.*
 import androidx.compose.runtime.*
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
-import androidx.compose.ui.tooling.preview.Preview
-import androidx.compose.ui.unit.dp
 import androidx.compose.ui.text.input.PasswordVisualTransformation
 import androidx.compose.ui.text.input.TextFieldValue
-import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.compose.ui.unit.dp
+import androidx.navigation.NavController
 import com.example.fitmarcetplacekuzminiv.MainViewModel
+//Авторизация
+@Composable
+fun AuthScreen(navController: NavController, mainViewModel: MainViewModel) {
+    val email = remember { mutableStateOf("") }
+    val password = remember { mutableStateOf("") }
 
-class AuthScreenActivity : ComponentActivity() {
-
-    // Инициализируем ViewModel
-    private val mainViewModel: MainViewModel by viewModels()
+    // Слушаем результат авторизации
+    val authResult by mainViewModel.authResult
 
-    override fun onCreate(savedInstanceState: Bundle?) {
-        super.onCreate(savedInstanceState)
-        setContent {
-            AuthScreen(mainViewModel)
+    // Если авторизация прошла успешно, переходим на main_screen
+    LaunchedEffect(authResult) {
+        if (authResult == "Success") {
+            navController.navigate("main_screen") {
+                popUpTo("auth_screen") { inclusive = true }
+            }
         }
     }
-}
-
-@Composable
-fun AuthScreen(mainViewModel: MainViewModel = viewModel()) {
-    var email by remember { mutableStateOf(TextFieldValue("")) }
-    var password by remember { mutableStateOf(TextFieldValue("")) }
-    var errorMessage by remember { mutableStateOf("") }
-    var successMessage by remember { mutableStateOf("") }
 
     Box(
         modifier = Modifier.fillMaxSize(),
@@ -48,47 +40,31 @@ fun AuthScreen(mainViewModel: MainViewModel = viewModel()) {
                 .padding(16.dp)
         ) {
             OutlinedTextField(
-                value = email,
-                onValueChange = { email = it },
+                value = email.value,
+                onValueChange = { newText -> email.value = newText },
                 label = { Text("Email") },
                 modifier = Modifier.fillMaxWidth()
             )
             Spacer(modifier = Modifier.height(16.dp))
             OutlinedTextField(
-                value = password,
-                onValueChange = { password = it },
+                value = password.value,
+                onValueChange = { newText -> password.value = newText },
                 label = { Text("Password") },
                 visualTransformation = PasswordVisualTransformation(),
                 modifier = Modifier.fillMaxWidth()
             )
             Spacer(modifier = Modifier.height(24.dp))
             Button(onClick = {
-                // Вызов авторизации через email и пароль
-                if (email.text.isNotEmpty() && password.text.isNotEmpty()) {
-                    mainViewModel.onSignInEmailPassword(email.text, password.text)
-                } else {
-                    errorMessage = "Заполните все поля"
-                }
+                mainViewModel.onSignInEmailPassword(email.value, password.value)
             }) {
                 Text("Login")
             }
 
-            // Отображение ошибок или успешного входа
-            if (errorMessage.isNotEmpty()) {
-                Spacer(modifier = Modifier.height(16.dp))
-                Text(text = errorMessage, color = MaterialTheme.colorScheme.error)
-            }
-
-            if (successMessage.isNotEmpty()) {
+            // Отображаем сообщение об ошибке, если авторизация не удалась
+            if (authResult == "Error") {
                 Spacer(modifier = Modifier.height(16.dp))
-                Text(text = successMessage, color = MaterialTheme.colorScheme.primary)
+                Text(text = "Ошибка: неверный email или пароль", color = MaterialTheme.colorScheme.error)
             }
         }
     }
 }
-
-@Preview(showBackground = true)
-@Composable
-fun PreviewAuthScreen() {
-    AuthScreen()
-}