Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Shade authored and Shade committed Feb 14, 2025
1 parent b957be1 commit 98e7225
Show file tree
Hide file tree
Showing 9 changed files with 26 additions and 62 deletions.
45 changes: 8 additions & 37 deletions src/main/kotlin/core/AppState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import cafe.adriel.voyager.core.screen.Screen
import core.security.MasterPasswordManager
import repository.user.User
import core.security.SecurityContext
import ui.screens.LoginScreen
import ui.screens.LoginSplashScreen
import ui.screens.RegisterScreen
Expand All @@ -16,29 +16,14 @@ import ui.screens.RegisterScreen
*/
class AppState {

private var currentUser by mutableStateOf<User?>(null)
private var userExists by mutableStateOf(false)
private var masterPassword by mutableStateOf<CharArray?>(null)

/**
* Gets the authenticated user.
*/
val getAuthenticatedUser: User?
get() = currentUser

/**
* Gets the username of the current user if they exist, otherwise returns "system".
*/
val userName: String
get() = currentUser?.userName.takeIf { userExists } ?: "system"

/**
* Updates the current user.
* @param user The user to set as the current user.
*/
fun updateCurrentUser(user: User?) {
currentUser = user
}
get() = SecurityContext.authenticatedUser?.userName.takeIf { userExists } ?: "system"

/**
* Sets whether a user exists.
Expand All @@ -48,19 +33,12 @@ class AppState {
userExists = exists
}

/**
* Clears the current user.
*/
fun clearCurrentUser() {
currentUser = null
}

/**
* Determines the initial screen to display based on user existence and authentication status.
* @return The initial screen to display.
*/
fun initialScreen(): Screen = when {
userExists && isAuthenticated -> LoginSplashScreen()
userExists && SecurityContext.isAuthenticated -> LoginSplashScreen()
userExists -> LoginScreen()
else -> RegisterScreen()
}
Expand All @@ -74,14 +52,6 @@ class AppState {
masterPassword = password.copyOf()
}

/**
* Fetches the master password.
* @return A copy of the master password.
*/
fun fetchMasterPassword(): CharArray? {
return masterPassword?.copyOf()
}

/**
* Clears the master password.
*/
Expand Down Expand Up @@ -131,10 +101,11 @@ class AppState {
}

/**
* Checks if the user is authenticated.
* @return True if the user is authenticated, false otherwise.
* Fetches the master password.
* @return A copy of the master password.
*/
private val isAuthenticated: Boolean
get() = currentUser != null
private fun fetchMasterPassword(): CharArray? {
return masterPassword?.copyOf()
}

}
8 changes: 4 additions & 4 deletions src/main/kotlin/core/security/AuthenticationManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class AuthenticationManager(
return userRepository.findByUsername(username).let { result ->
if (result is Result.Success && BCrypt.checkpw(password, result.data.password)) {
result.data.also {
appState.updateCurrentUser(it)
SecurityContext.setAuthenticatedUser(it)
TokenManager.saveToken(jwtService.generateToken(it))
}.let { user ->
Result.Success(user)
Expand All @@ -45,7 +45,7 @@ class AuthenticationManager(
appState.initializeMasterPassword(MasterPasswordManager.convertToSecureString(masterPassword))

when (val result = passwordRepository.findFirstEncryptedField(
appState.getAuthenticatedUser?.id?.value!!,
SecurityContext.authenticatedUser?.id?.value!!,
appState.encryptString("sample")
)) {
is Result.Success -> {
Expand Down Expand Up @@ -111,14 +111,14 @@ class AuthenticationManager(
}

fun logout() {
appState.clearCurrentUser()
SecurityContext.clearAuthenticatedUser()
TokenManager.clearToken()
}

private fun loadUserFromToken() {
TokenManager.loadToken()?.let { token ->
jwtService.validateToken(token)?.let { userId ->
appState.updateCurrentUser(userRepository.findById(userId))
SecurityContext.setAuthenticatedUser(userRepository.findById(userId))
} ?: run {
this.logout()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import core.form.validation.FormValidator
import core.models.FormType
import core.models.FormType.CREATION
import core.models.UiState
import core.security.SecurityContext
import kotlinx.coroutines.delay
import repository.creditcard.CreditCard
import repository.user.User
Expand Down Expand Up @@ -334,8 +335,8 @@ class CreditCardForm(creditCard: CreditCard?, formType: FormType) : Screen {
_creditCard?.id?.value,
toCreditCardDto(
formValidator,
screenModel.getAuthenticatedUser(),
selectedItem?.id!!
SecurityContext.authenticatedUser!!,
selectedItem?.id!!
),
formType
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import core.form.validation.FormValidator
import core.models.FormType
import core.models.PasswordCategory
import core.models.dto.PasswordDto
import core.security.SecurityContext
import ui.components.FormTextField
import ui.components.MultiSelectDropdown
import ui.components.PasswordTextField
Expand Down Expand Up @@ -259,7 +260,7 @@ fun PasswordForm(
horizontalArrangement = Arrangement.spacedBy(30.dp, Alignment.CenterHorizontally)
) {
Footer(
{ onSaveClick(toPasswordDto(formValidator, screenModel.getAuthenticatedUser())) },
{ onSaveClick(toPasswordDto(formValidator, SecurityContext.authenticatedUser!!)) },
onCancelClick,
isFormValid
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ fun CreditCardCredentialForm(screenModel: SecVaultScreenModel) {

Row(modifier = Modifier.weight(1f)) {
UnderLineTextFiled(
field = cvc.toString(),
field = cvc,
onFieldChange = { cvc = it },
label = "CVC",
modifier = Modifier.fillMaxWidth(),
Expand All @@ -153,7 +153,7 @@ fun CreditCardCredentialForm(screenModel: SecVaultScreenModel) {

Row(modifier = Modifier.weight(1f)) {
UnderLineTextFiled(
field = pin.toString(),
field = pin,
onFieldChange = { pin = it },
label = "Pin",
modifier = Modifier.fillMaxWidth(),
Expand Down
7 changes: 2 additions & 5 deletions src/main/kotlin/ui/components/secvault/sidebar/Header.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,11 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import core.AppState
import org.koin.java.KoinJavaComponent.inject
import core.security.SecurityContext
import ui.theme.Font

@Composable
fun Header() {
val appState by inject<AppState>(clazz = AppState::class.java)

Column(
modifier = Modifier
.fillMaxWidth()
Expand Down Expand Up @@ -81,7 +78,7 @@ fun Header() {
horizontalAlignment = Alignment.Start
) {
Text(
text = appState.getAuthenticatedUser?.userName ?: "User",
text = SecurityContext.authenticatedUser?.userName ?: "User",
color = Color.White,
fontFamily = Font.RussoOne,
fontWeight = FontWeight.Normal,
Expand Down
7 changes: 2 additions & 5 deletions src/main/kotlin/ui/screens/LoginSplashScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import core.AppState
import core.security.SecurityContext
import kotlinx.coroutines.delay
import org.koin.java.KoinJavaComponent.inject
import ui.theme.Font
import ui.theme.secondary

Expand All @@ -30,8 +29,6 @@ class LoginSplashScreen : Screen {
@Composable
override fun Content() {

val appState by inject<AppState>(clazz = AppState::class.java)

val navigator = LocalNavigator.current
var isVisible by remember { mutableStateOf(false) }

Expand Down Expand Up @@ -93,7 +90,7 @@ class LoginSplashScreen : Screen {
tint = Color.White
)
Text(
text = appState.getAuthenticatedUser?.userName ?: "User",
text = SecurityContext.authenticatedUser?.userName ?: "User",
fontStyle = FontStyle.Normal,
fontWeight = FontWeight.Normal,
color = Color.White,
Expand Down
4 changes: 0 additions & 4 deletions src/main/kotlin/viewmodel/PasswordMgntScreenModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,6 @@ class PasswordMgntScreenModel(
return userRepository.findAll()
}

fun getAuthenticatedUser(): User {
return appState.getAuthenticatedUser!!
}

fun clearError() {
_passwordState.value = UiState.Idle
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/kotlin/viewmodel/SecVaultScreenModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import core.AppState
import core.models.*
import core.models.criteria.CredentialSearchCriteria
import core.security.AuthenticationManager
import core.security.SecurityContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
Expand Down Expand Up @@ -155,7 +156,7 @@ class SecVaultScreenModel(
}

private suspend fun loadPasswords(sort: CredentialSort) {
val criteria = CredentialSearchCriteria(appState.getAuthenticatedUser?.id?.value, sort)
val criteria = CredentialSearchCriteria(SecurityContext.authenticatedUser?.id?.value, sort)
_passwordItems.value = when (val passwords = passwordRepository.findSummaries(criteria)) {
is Result.Success -> {
_secVaultState.value = UiState.Success("Successfully loaded passwords")
Expand All @@ -170,7 +171,7 @@ class SecVaultScreenModel(
}

private suspend fun loadCreditCards(sort: CredentialSort) {
val criteria = CredentialSearchCriteria(appState.getAuthenticatedUser?.id?.value, sort)
val criteria = CredentialSearchCriteria(SecurityContext.authenticatedUser?.id?.value, sort)
_creditCardItems.value = when (val creditCards = creditCardRepository.findSummaries(criteria)) {
is Result.Success -> {
_secVaultState.value = UiState.Success("Successfully loaded credit cards")
Expand Down

0 comments on commit 98e7225

Please sign in to comment.