Ver Fonte

добавил новую view для хранения данных о пароле и логине при заходе, и применил это к созданию пользоватля(нужно чуть наладить)

AlexMin há 5 dias atrás
pai
commit
1296190060

BIN
.gradle/8.7/executionHistory/executionHistory.bin


BIN
.gradle/8.7/executionHistory/executionHistory.lock


BIN
.gradle/8.7/fileHashes/fileHashes.bin


BIN
.gradle/8.7/fileHashes/fileHashes.lock


BIN
.gradle/8.7/fileHashes/resourceHashesCache.bin


BIN
.gradle/buildOutputCleanup/buildOutputCleanup.lock


BIN
.gradle/buildOutputCleanup/outputFiles.bin


BIN
.gradle/file-system.probe


+ 6 - 0
app/src/main/java/com/example/iplace/main/viewModel/AuthData.kt

@@ -0,0 +1,6 @@
+package com.example.iplace.main.viewModel
+
+data class AuthData(
+    var email: String = "",
+    var password: String = ""
+)

+ 63 - 56
app/src/main/java/com/example/iplace/main/viewModel/MainViewModel.kt

@@ -1,44 +1,49 @@
 package com.example.iplace.main.viewModel
 
 import android.content.Context
+import android.os.Bundle
 import android.util.Log
 import android.widget.Toast
+import androidx.compose.runtime.MutableState
 import androidx.compose.runtime.State
+import androidx.compose.runtime.derivedStateOf
 import androidx.compose.runtime.getValue
 import androidx.compose.runtime.mutableStateOf
 import androidx.compose.runtime.remember
 import androidx.compose.runtime.setValue
+import androidx.core.os.bundleOf
 import androidx.lifecycle.LiveData
 import androidx.lifecycle.MutableLiveData
 import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
 import androidx.lifecycle.viewModelScope
 import androidx.navigation.NavHostController
+import com.example.iplace.R
 import com.example.iplace.domain.Constants
 import com.example.iplace.model.Gender
 import com.example.iplace.model.Users
 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 io.github.jan.supabase.postgrest.from
-import io.github.jan.supabase.postgrest.query.Order
-import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
-import com.example.iplace.main.viewModel.SignUpViewModel
 
 class MainViewModel(): ViewModel() {
 
+    private val _authData = mutableStateOf(AuthData())
+    val authData: State<AuthData> = _authData
 
-    fun onSignInEmailPassword(emailUser: String, passwordUser: String, navController: NavHostController) {
+    fun onSignInEmailPassword(emailUser: String, passwordUser1: String, navController: NavHostController) {
+        _authData.value = AuthData(email = emailUser, password = passwordUser1)
         viewModelScope.launch {
             try {
                 val user = Constants.supabase.auth.signInWith(Email) {
                     email = emailUser
-                    password = passwordUser
+                    password = passwordUser1
                 }
+
                 println(user.toString())
                 println(Constants.supabase.auth.currentUserOrNull()!!.id)
                 println("Success")
@@ -50,81 +55,83 @@ class MainViewModel(): ViewModel() {
         }
     }
     fun onSignUpEmail(emailUser: String, passwordUser1: String, passwordUser2: String, navController: NavHostController) {
+        _authData.value = AuthData(email = emailUser, password = passwordUser1)
 
         if(emailUser != "" && passwordUser1 != "" && passwordUser2 != "" ) {
 
-                if(passwordUser1 == passwordUser2) {
-                    if(passwordUser1.length >= 8){
-
-                        viewModelScope.launch {
-                            try{
-                                val signUpViewModel = SignUpViewModel(emailUser, passwordUser1)
-
-                                var  user =  Constants.supabase.auth.signUpWith(Email) {
-                                    email = emailUser
-                                    password = passwordUser1
-                                }
+            if(passwordUser1 == passwordUser2) {
+                if(passwordUser1.length >= 8){
 
-                                println(user.toString())
-                                println(Constants.supabase.auth.currentUserOrNull()!!.id)
-                                println("Success")
-                                navController.navigate("creatingUser")
-                            }
-                            catch (e: Exception) {
-                                println("Error")
-                                println(e.message.toString())
+                    viewModelScope.launch {
+                        try{
+                            val user = Constants.supabase.auth.signUpWith(Email) {
+                                email = emailUser
+                                password = passwordUser1
                             }
 
-                        }
+                            println(user.toString())
+                            println(Constants.supabase.auth.currentUserOrNull()!!.id)
+                            println("Success")
 
+                            navController.navigate("creatingUser")
                         }
-                        else Log.i("Reg", "Длина пароля должна быть от 8 до 64 символов")
+                        catch (e: Exception) {
+                            println("Error")
+                            println(e.message.toString())
+                        }
+
+                    }
                 }
-                else Log.i("Reg", "Пароли не совпадают")
+                else Log.i("Reg", "Длина пароля должна быть от 8 до 64 символов")
+            }
+            else Log.i("Reg", "Пароли не совпадают")
 
         }
         else Log.i("Reg", "Не все поля заполнены")
 
     }
 
+
     fun AddNewUserInTable(nameUser: String, address: String, about_me: String, id_genderFK: String, img_user: String, navController: NavHostController){
         viewModelScope.launch {
-        try {
-            Constants.supabase.auth.signInWith(Email) {
-                email = "signUpViewModel.email"  // Используем email из ViewModel
-                password = "signUpViewModel.password"// Используем password из ViewModel
-            }
-            val idUser = Constants.supabase.auth.currentUserOrNull()?.id ?: return@launch
-            val newUser = Users(id_UUID = idUser, name = nameUser, address = address, about_me = about_me, id_genderFK = 1, img_user = "dsad")
+            try {
+                // Получаем email и password из authData
+                val email = authData.value.email
+                val password = authData.value.password
+
+                // Проверяем, авторизован ли пользователь
+                if (Constants.supabase.auth.currentUserOrNull() == null) {
+                    // Если нет, то пытаемся авторизоваться с сохраненными данными
+                    if (email.isNotEmpty() && password.isNotEmpty()) {
+                        Constants.supabase.auth.signInWith(Email) {
+                            this.email = email
+                            this.password = password
+                        }
+                    } else {
+                        // Обработка ситуации, когда нет сохраненных данных
+                        Log.e("AddNewUserInTable", "No user data found for sign-in.")
+                        return@launch
+                    }
+                }
 
-            Constants.supabase.from("users").insert(newUser)
+                val idUser = Constants.supabase.auth.currentUserOrNull()?.id ?: return@launch
+                val newUser = Users(id_UUID = idUser, name = nameUser, address = address, about_me = about_me, id_genderFK = 1, img_user = "dsad")
 
-            navController.navigate("policyConditionality")
-        } catch (e: Exception) {
-            Log.e("AddNewUserInTable", "Error adding user: ${e.message}")
-        }
+                Constants.supabase.from("users").insert(newUser)
+
+                navController.navigate("policyConditionality")
+            } catch (e: Exception) {
+                Log.e("AddNewUserInTable", "Error adding user: ${e.message}")
+            }
         }
     }
 
+}
+
 
 
 
-}
 
 
-//fun onSignUpEmail2(emailUser: String, passwordUser:String, nameUser: String, address: String, about_me: String, id_genderFK: String, img_user: String, navController: NavHostController) {
-//
-//    viewModelScope.launch {
-//        try{
-//            var  user =  Constants.supabase.auth.signUpWith(Email) {
-//                email = emailUser
-//            }
-//            AddNewUserInTable(emailUser,passwordUser, "as", "123",  "12312",  "1",  "dsad", navController)
-//        }
-//        catch (e: Exception) {
-//            println("Error")
-//            println(e.message.toString())
-//        }
-//    }
 
 

+ 0 - 6
app/src/main/java/com/example/iplace/main/viewModel/SignUpViewModel.kt

@@ -1,6 +0,0 @@
-package com.example.iplace.main.viewModel
-
-data class SignUpViewModel(
-    val email0: String = "",
-    val password0: String = ""
-)

+ 36 - 8
app/src/main/java/com/example/iplace/main/viewModel/dataView/PolicyConditionality.kt

@@ -27,6 +27,7 @@ import androidx.compose.material.icons.filled.KeyboardArrowUp
 import androidx.compose.material3.Button
 import androidx.compose.material3.ButtonDefaults
 import androidx.compose.material3.Card
+import androidx.compose.material3.Checkbox
 import androidx.compose.material3.Icon
 import androidx.compose.material3.IconButton
 import androidx.compose.material3.OutlinedTextField
@@ -68,7 +69,8 @@ fun PolicyConditionality(navController: NavHostController) {
     val basicNunitosans = FontFamily(
         Font(resId = R.font.basic_nunitosans)
     )
-
+    var isChecked by remember { mutableStateOf(false) }
+    var showError by remember { mutableStateOf(false) }
     Image(
         painter = painterResource(id = R.drawable.pc7),
         contentDescription = "",
@@ -128,7 +130,6 @@ fun PolicyConditionality(navController: NavHostController) {
                             .wrapContentSize(Alignment.Center) // Выравнивает текст по центру
                     )
                 }
-
                 Spacer(modifier = Modifier.height(10.dp)) // Отступ от заголовка
                 Column(
                     modifier = Modifier
@@ -153,23 +154,50 @@ fun PolicyConditionality(navController: NavHostController) {
                         fontFamily = basicNunitosans, //шрифт
                         modifier = Modifier.padding(horizontal = 10.dp) //отступ слева и справа
                     )
-
                     Spacer(modifier = Modifier.height(20.dp))
+                    // Поле "Я соглашаюсь"
+                    Row(verticalAlignment = Alignment.CenterVertically) {
+                        Checkbox(
+                            checked = isChecked,
+                            onCheckedChange = { isChecked = it }
+                        )
+                        Text(
+                            text = "Я соглашаюсь с условиями использования",
+                            fontSize = 16.sp,
+                            fontFamily = basicNunitosans
+                        )
+                    }
+
+                    // Отображение ошибки, если галочка не установлена
+                    if (showError) {
+                        Text(
+                            text = "Пожалуйста, подтвердите согласие с условиями использования",
+                            color = Color.Red,
+                            fontSize = 14.sp,
+                            fontFamily = basicNunitosans
+                        )
+                    }
 
                     Button(
-                        onClick = { navController.navigate("profile") },
+                        onClick = {
+                            if (isChecked) {
+                                navController.navigate("profile")
+                            } else {
+                                showError = true
+                            }
+                        },
                         modifier = Modifier.width(290.dp).height(50.dp),
-                        colors = ButtonDefaults.buttonColors(brown_contrast)
+                        colors = ButtonDefaults.buttonColors(brown_contrast),
+                        enabled = isChecked // Отключить кнопку, если галочка не установлена
                     ) {
                         Text(
-                            text = "Соглашаюсь",
+                            text = "Войти",
                             fontSize = 24.sp,
                             fontFamily = basicNunitosans
                         )
                     }
-
                     Spacer(modifier = Modifier.height(16.dp))
-                } // Отступ снизу
+                }
             }
         }
     }

+ 10 - 10
app/src/main/java/com/example/iplace/main/viewModel/mainView/Auth.kt

@@ -43,6 +43,7 @@ import androidx.compose.ui.text.input.VisualTransformation
 import androidx.compose.ui.unit.dp
 import androidx.compose.ui.unit.em
 import androidx.compose.ui.unit.sp
+import androidx.lifecycle.viewmodel.compose.viewModel
 import androidx.navigation.NavHostController
 import com.example.iplace.R
 import com.example.iplace.main.viewModel.MainViewModel
@@ -51,7 +52,10 @@ import com.example.iplace.ui.theme.brown_contrast
 
 @Composable
 fun  Auth(navController: NavHostController){
-    val viewModel = MainViewModel()
+    val viewModelmain = viewModel<MainViewModel>()
+    var email by remember { mutableStateOf("") }
+    var password by remember { mutableStateOf("") }
+
     val headlinesOswald = FontFamily( //загрузка шрифта
         Font(resId = R.font.headlines_oswald)
     )
@@ -59,8 +63,6 @@ fun  Auth(navController: NavHostController){
         Font(resId = R.font.basic_nunitosans)
     )
 
-    val email = remember { mutableStateOf("") }
-    val password = remember { mutableStateOf("") }
     Image(
         painter = painterResource(id = R.drawable.au3),
         contentDescription = "",
@@ -120,11 +122,9 @@ fun  Auth(navController: NavHostController){
                 }
 
                 Spacer(modifier = Modifier.height(40.dp)) // Отступ от заголовка
-
                 OutlinedTextField(
-                    value = email.value,
-
-                    onValueChange = { newText -> email.value = newText },
+                    value = email,
+                    onValueChange = { newText -> email = newText },
                     label = { Text("Логин") },
                     modifier = Modifier
                         .fillMaxWidth()
@@ -136,9 +136,9 @@ fun  Auth(navController: NavHostController){
                 Spacer(modifier = Modifier.height(10.dp))
 
                 OutlinedTextField(
-                    value = password.value,
+                    value = password,
                     visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
-                    onValueChange = { newText -> password.value = newText },
+                    onValueChange = { newText -> password = newText },
                     label = { Text("Пароль") },
                     modifier = Modifier
                         .fillMaxWidth()
@@ -170,7 +170,7 @@ fun  Auth(navController: NavHostController){
 
                 Button(
                     onClick = {
-                        viewModel.onSignInEmailPassword(email.value,password.value, navController = navController)
+                        viewModelmain.onSignInEmailPassword(email, password, navController)
                     },
                     modifier = Modifier.width(290.dp).height(50.dp),
                     colors = ButtonDefaults.buttonColors(brown_contrast)

+ 2 - 13
app/src/main/java/com/example/iplace/main/viewModel/mainView/CreatingUser.kt

@@ -223,17 +223,6 @@ fun CreatingUser(navController: NavHostController) {
                 )
                 Spacer(modifier = Modifier.height(10.dp))
 
-                OutlinedTextField(
-                    value = "",
-                    onValueChange = {  },
-                    label = { Text("Телефон") },
-                    modifier = Modifier
-                        .fillMaxWidth()
-                        .padding(horizontal = 16.dp)
-                        .clip(RoundedCornerShape(20.dp))
-                )
-                Spacer(modifier = Modifier.height(10.dp))
-
                 OutlinedTextField(
                     value = about_me.value,
                     onValueChange = { newText -> about_me.value = newText },
@@ -244,7 +233,7 @@ fun CreatingUser(navController: NavHostController) {
                         .padding(horizontal = 16.dp)
                         .clip(RoundedCornerShape(20.dp))
                 )
-
+                Spacer(modifier = Modifier.height(10.dp))
                 Column(
 //                    modifier = Modifier
 //                        .fillMaxSize()
@@ -310,4 +299,4 @@ fun CreatingUser(navController: NavHostController) {
 fun Uri.toBitmap(context: android.content.Context): android.graphics.Bitmap {
     val resolver = context.contentResolver
     return android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(this))
-}
+}

+ 16 - 11
app/src/main/java/com/example/iplace/main/viewModel/mainView/Registration.kt

@@ -24,8 +24,10 @@ import androidx.compose.material3.IconButton
 import androidx.compose.material3.OutlinedTextField
 import androidx.compose.material3.Text
 import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
 import androidx.compose.runtime.mutableStateOf
 import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
 import androidx.compose.ui.draw.clip
@@ -37,6 +39,7 @@ import androidx.compose.ui.text.font.FontFamily
 import androidx.compose.ui.text.font.FontWeight
 import androidx.compose.ui.unit.dp
 import androidx.compose.ui.unit.sp
+import androidx.lifecycle.viewmodel.compose.viewModel
 import androidx.navigation.NavHostController
 import com.example.iplace.R
 import com.example.iplace.main.viewModel.MainViewModel
@@ -45,7 +48,12 @@ import com.example.iplace.ui.theme.brown_contrast
 
 @Composable
 fun Registration(navController: NavHostController) {
-    val viewModel = MainViewModel()
+
+    val viewModelmain = viewModel<MainViewModel>()
+    var newemail by remember { mutableStateOf("") }
+    var newpassword1 by remember { mutableStateOf("") }
+    var newpassword2 by remember { mutableStateOf("") }
+
     val headlinesOswald = FontFamily( //загрузка шрифта
         Font(resId = R.font.headlines_oswald)
     )
@@ -53,9 +61,6 @@ fun Registration(navController: NavHostController) {
         Font(resId = R.font.basic_nunitosans)
     )
 
-    val newemail = remember { mutableStateOf("") }
-    val newpassword1 = remember { mutableStateOf("") }
-    val newpassword2 = remember { mutableStateOf("") }
 
 
     Image(
@@ -118,8 +123,8 @@ fun Registration(navController: NavHostController) {
                 Spacer(modifier = Modifier.height(40.dp)) // Отступ от заголовка
 
                 OutlinedTextField(
-                    value = newemail.value,
-                    onValueChange = { newText -> newemail.value = newText },
+                    value = newemail,
+                    onValueChange = { newText -> newemail = newText },
                     label = { Text("Логин") },
                     modifier = Modifier
                         .fillMaxWidth()
@@ -130,8 +135,8 @@ fun Registration(navController: NavHostController) {
                 Spacer(modifier = Modifier.height(10.dp))
 
                 OutlinedTextField(
-                    value = newpassword1.value,
-                    onValueChange = { newText -> newpassword1.value = newText },
+                    value = newpassword1,
+                    onValueChange = { newText -> newpassword1 = newText },
                     label = { Text("Пароль") },
                     modifier = Modifier
                         .fillMaxWidth()
@@ -141,8 +146,8 @@ fun Registration(navController: NavHostController) {
                 Spacer(modifier = Modifier.height(10.dp))
 
                 OutlinedTextField(
-                    value = newpassword2.value,
-                    onValueChange = { newText -> newpassword2.value = newText },
+                    value = newpassword2,
+                    onValueChange = { newText -> newpassword2 = newText },
                     label = { Text("Повторите пароль") },
                     modifier = Modifier
                         .fillMaxWidth()
@@ -155,7 +160,7 @@ fun Registration(navController: NavHostController) {
                 Spacer(modifier = Modifier.height(20.dp))
                 Button(
                     onClick = {
-                        viewModel.onSignUpEmail(newemail.value,newpassword1.value,newpassword2.value, navController = navController)
+                        viewModelmain.onSignUpEmail(newemail,newpassword1,newpassword2, navController = navController)
                               },modifier = Modifier.width(290.dp).height(50.dp),
                     colors = ButtonDefaults.buttonColors(brown_contrast)
                 ) {

+ 63 - 0
app/src/main/java/com/example/iplace/ui/theme/TextFields.kt

@@ -0,0 +1,63 @@
+package com.example.iplace.ui.theme
+
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.TextField
+import androidx.compose.material3.TextFieldDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun OneLineTextField(
+    value: String,
+    input: (String) -> Unit,
+    modifier: Modifier
+) {
+    TextField(
+        value,
+        onValueChange = {newValue -> input(newValue)},
+        singleLine = true,
+        shape = RoundedCornerShape(25.dp),
+        modifier = modifier
+            .fillMaxWidth()
+            .background(color = Color.Transparent)
+            ,
+        colors = TextFieldDefaults.textFieldColors(
+
+            focusedIndicatorColor =  Color.Transparent,
+            unfocusedIndicatorColor = Color.Transparent,
+            disabledIndicatorColor = Color.Transparent
+        )
+    )
+}
+
+fun Modifier.drawCustomIndicatorLine(
+    indicatorBorder: BorderStroke,
+    indicatorPadding : Dp = 0.dp
+): Modifier {
+
+    val strokeWidthDp = indicatorBorder.width
+    return drawWithContent {
+        drawContent()
+        if (strokeWidthDp == Dp.Hairline) return@drawWithContent
+        val strokeWidth = strokeWidthDp.value * density
+        val y = size.height - strokeWidth / 1.5f
+        drawLine(
+            indicatorBorder.brush,
+            Offset((indicatorPadding).toPx(), y),
+            Offset(size.width - indicatorPadding.toPx(), y),
+            strokeWidth,
+            StrokeCap.Round
+        )
+    }
+}