Overview
The AuthRepository class handles all authentication operations including login, registration, password reset, and authentication state management using Firebase Authentication.
Class Definition
class AuthRepository(
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
)
auth
FirebaseAuth
default:"FirebaseAuth.getInstance()"
Firebase Authentication instance used for all auth operations
Methods
login
Authenticates a user with email and password.
suspend fun login(email: String, password: String)
Example:
val authRepository = AuthRepository()
try {
authRepository.login("[email protected]", "password123")
// User successfully logged in
} catch (e: Exception) {
// Handle authentication error
}
register
Creates a new user account with email and password.
suspend fun register(email: String, password: String)
The email address for the new account
The password for the new account
Example:
val authRepository = AuthRepository()
try {
authRepository.register("[email protected]", "securePassword123")
// Account created successfully
} catch (e: Exception) {
// Handle registration error
}
sendPasswordReset
Sends a password reset email to the specified address.
suspend fun sendPasswordReset(email: String)
The email address to send the password reset link to
Example:
val authRepository = AuthRepository()
try {
authRepository.sendPasswordReset("[email protected]")
// Password reset email sent
} catch (e: Exception) {
// Handle error
}
logout
Signs out the current user.
Example:
val authRepository = AuthRepository()
authRepository.logout()
// User signed out
authStateFlow
Returns a Flow that emits the current authentication state whenever it changes.
fun authStateFlow(): Flow<FirebaseUser?>
A Flow that emits the current FirebaseUser when authenticated, or null when signed out
Example:
val authRepository = AuthRepository()
authRepository.authStateFlow().collect { user ->
if (user != null) {
// User is logged in
println("Logged in as: ${user.email}")
} else {
// User is logged out
println("Not authenticated")
}
}
isLoggedIn
Checks if a user is currently authenticated.
fun isLoggedIn(): Boolean
Returns true if a user is currently logged in, false otherwise
Example:
val authRepository = AuthRepository()
if (authRepository.isLoggedIn()) {
// User is authenticated
} else {
// User is not authenticated
}
currentEmail
Retrieves the email address of the currently authenticated user.
fun currentEmail(): String?
Returns the current user’s email address, or null if no user is logged in
Example:
val authRepository = AuthRepository()
val email = authRepository.currentEmail()
if (email != null) {
println("Current user: $email")
} else {
println("No user logged in")
}
Source Location
com.demodogo.ev_sum_2.data.repositories.AuthRepository