Skip to content

Commit

Permalink
Code documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
SAUL committed Jan 10, 2025
1 parent 594702a commit 92028f5
Show file tree
Hide file tree
Showing 20 changed files with 362 additions and 17 deletions.
4 changes: 4 additions & 0 deletions src/main/kotlin/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import di.viewModelModule
import org.koin.core.context.GlobalContext.startKoin
import ui.App

/**
* Main entry point of the application.
* Initializes Koin for dependency injection and sets up the main application window.
*/
fun main() = application {

startKoin {
Expand Down
55 changes: 54 additions & 1 deletion src/main/kotlin/core/AppState.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,54 +10,99 @@ import ui.screens.LoginScreen
import ui.screens.LoginSplashScreen
import ui.screens.RegisterScreen

/**
* AppState class manages the state of the application, including the current user,
* master password, and the initial screen to display.
*/
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
}

/**
* Sets whether a user exists.
* @param exists Boolean indicating if a user exists.
*/
fun userExists(exists: Boolean) {
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 -> LoginScreen()
else -> RegisterScreen()
}

/**
* Initializes the master password.
* @param password The master password to set.
*/
fun initializeMasterPassword(password: CharArray) {
clearMasterPassword()
masterPassword = password.copyOf()
}

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

/**
* Clears the master password.
*/
fun clearMasterPassword() {
masterPassword?.fill('\u0000')
masterPassword = null
}

/**
* Checks if the master password is present.
* @return True if the master password is present, false otherwise.
*/
fun isMasterPasswordPresent(): Boolean {
return masterPassword != null
}

/**
* Encrypts a string using the master password.
* @param text The string to encrypt.
* @return The encrypted string.
*/
fun encryptString(text: String?): String {
return text?.let {
MasterPasswordManager.encryptString(
Expand All @@ -69,6 +114,11 @@ class AppState {
} ?: ""
}

/**
* Decrypts a string using the master password.
* @param text The string to decrypt.
* @return The decrypted string.
*/
fun decryptPassword(text: String?): String {
return text?.let {
MasterPasswordManager.decryptString(
Expand All @@ -80,7 +130,10 @@ class AppState {
} ?: ""
}


/**
* Checks if the user is authenticated.
* @return True if the user is authenticated, false otherwise.
*/
private val isAuthenticated: Boolean
get() = currentUser != null

Expand Down
16 changes: 14 additions & 2 deletions src/main/kotlin/core/Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,31 @@ import com.fasterxml.jackson.module.kotlin.KotlinModule
import core.configs.DatabaseConfig
import core.configs.JwtConfig

/**
* Data class representing the configuration settings for the application.
*
* @property database The database configuration settings.
* @property jwt The JWT configuration settings.
*/
data class Config(
val database: DatabaseConfig,
val jwt: JwtConfig
)

/**
* Loads the configuration settings from the `application.yaml` file.
*
* @return The loaded configuration settings.
* @throws IllegalArgumentException if the `application.yaml` resource is not found.
*/
fun loadConfigs(): Config {
val mapper = ObjectMapper(YAMLFactory()).apply {
registerModule(KotlinModule.Builder().build())
}

val resourceStream = Config::class.java.classLoader
.getResourceAsStream("application.yaml")
?: throw IllegalArgumentException("Resource not found: application.yaml")
.getResourceAsStream("application.yaml")
?: throw IllegalArgumentException("Resource not found: application.yaml")

return mapper.readValue(resourceStream, Config::class.java)
}
9 changes: 9 additions & 0 deletions src/main/kotlin/core/DatabaseFactory.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,17 @@ import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.DatabaseConfig
import org.jetbrains.exposed.sql.Slf4jSqlDebugLogger

/**
* The `DatabaseFactory` object is responsible for creating and configuring the database connection.
*/
object DatabaseFactory {

/**
* Creates and configures a database connection using the provided configuration.
*
* @param config The configuration object containing database settings.
* @return The configured `Database` instance.
*/
fun create(config: Config): Database {
val dbConfig = config.database

Expand Down
3 changes: 3 additions & 0 deletions src/main/kotlin/core/form/FormField.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import core.form.validation.Validator

/**
* Represents a form field with a value, an error state, and a validator.
*/
data class FormField(
var value: MutableState<String> = mutableStateOf(""),
var error: MutableState<String?> = mutableStateOf(null),
Expand Down
3 changes: 3 additions & 0 deletions src/main/kotlin/core/form/validation/CommonRules.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package core.form.validation
import core.form.FormField
import java.util.*

/**
* Contains common validation rules for form fields.
*/
val emailRule: ValidationRule = ValidationRule(
condition = { email ->
email.matches(Regex("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"))
Expand Down
43 changes: 42 additions & 1 deletion src/main/kotlin/core/form/validation/FormValidator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,36 @@ import androidx.compose.runtime.mutableStateOf
import core.form.FormField
import core.form.FormFieldName

/**
* A class responsible for managing and validating form fields.
*/
class FormValidator {

private val fields = mutableMapOf<FormFieldName, FormField>()
private val _isValid = mutableStateOf(true)

/**
* A read-only state representing the overall validity of the form.
*/
val isValid: State<Boolean> get() = _isValid


/**
* Adds a form field to the validator.
*
* @param name The name of the form field.
* @param field The form field to be added.
* @return The current instance of FormValidator.
*/
fun addField(name: FormFieldName, field: FormField): FormValidator {
fields[name] = field
return this
}

/**
* Validates a specific form field by its name.
*
* @param name The name of the form field to validate.
*/
fun validateField(name: FormFieldName) {
fields[name]?.let { field ->
val (isValid, errorMessage) = field.validator.validate(field.value.value)
Expand All @@ -26,26 +43,50 @@ class FormValidator {
}
}

/**
* Retrieves a form field by its name.
*
* @param name The name of the form field.
* @return The form field if found, otherwise null.
*/
fun getField(name: FormFieldName): FormField? = fields[name]

/**
* Checks if all form fields are valid.
*
* @return True if all form fields are valid, otherwise false.
*/
fun isValid(): Boolean {
return fields.values.all { field ->
validateField(field)
field.error.value == null
}
}

/**
* Validates all form fields.
*
* @return The current instance of FormValidator.
*/
fun validateAllFields(): FormValidator {
fields.keys.forEach { name -> validateField(name) }
return this
}

/**
* Updates the overall validity state of the form.
*/
private fun updateFormValidity() {
_isValid.value = fields.values.all { field ->
field.error.value == null
}
}

/**
* Validates a form field.
*
* @param field The form field to validate.
*/
private fun validateField(field: FormField) {
val (isValid, errorMessage) = field.validator.validate(field.value.value)
field.error.value = if (isValid) null else errorMessage
Expand Down
8 changes: 7 additions & 1 deletion src/main/kotlin/core/form/validation/ValidationRule.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package core.form.validation

/**
* Represents a validation rule for form input.
*
* @property condition A lambda function that takes a String and returns a Boolean indicating if the condition is met.
* @property errorMessage The error message to be displayed if the condition is not met.
*/
data class ValidationRule(
val condition: (String) -> Boolean,
val errorMessage: String
)
)
4 changes: 4 additions & 0 deletions src/main/kotlin/core/form/validation/Validator.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package core.form.validation

/**
* Validator class for managing and applying validation rules to input strings.
*/
class Validator {

private val rules = mutableListOf<ValidationRule>()

fun addRule(rule: ValidationRule): Validator {
Expand Down
15 changes: 15 additions & 0 deletions src/main/kotlin/core/models/Result.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
package core.models

/**
* A sealed class representing a result, which can be either a success or an error.
*/
sealed class Result<out T> {
/**
* Represents a successful result containing data.
*
* @param T The type of the data.
* @property data The data of the successful result.
*/
data class Success<out T>(val data: T) : Result<T>()

/**
* Represents an error result containing a message.
*
* @property message The error message.
*/
data class Error(val message: String) : Result<Nothing>()
}
Loading

0 comments on commit 92028f5

Please sign in to comment.