-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthenticationManager.kt
More file actions
203 lines (178 loc) · 8.29 KB
/
AuthenticationManager.kt
File metadata and controls
203 lines (178 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package com.xpeho.xpeapp.domain
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.xpeho.xpeapp.data.DatastorePref
import com.xpeho.xpeapp.data.entity.AuthentificationBody
import com.xpeho.xpeapp.data.model.AuthResult
import com.xpeho.xpeapp.data.model.WordpressToken
import com.xpeho.xpeapp.data.service.FirebaseService
import com.xpeho.xpeapp.data.service.WordpressRepository
import com.xpeho.xpeapp.di.TokenProvider
import com.xpeho.xpeapp.utils.CrashlyticsUtils
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
/**
* Singleton responsible for keeping track of the authentication state,
* logging the user in and logging the user out.
* @param wordpressRepo: Repository for wordpress authentication
* @param datastorePref: Wrapper for the DataStore of Preferences,
* for storing the authentication data
*/
class AuthenticationManager(
val tokenProvider: TokenProvider,
val wordpressRepo: WordpressRepository,
val datastorePref: DatastorePref,
val firebaseService: FirebaseService
) {
companion object {
private val TOKEN_VALIDITY_PERIOD = 5.days
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
private val _authState: MutableStateFlow<AuthState> = MutableStateFlow(AuthState.Unauthenticated)
val authState = _authState.asStateFlow()
fun restoreAuthStateFromStorage() = runBlocking {
datastorePref.getAuthData()?.let { authData ->
// Verify if the token has expired (5 days)
if (isTokenExpired(authData)) {
// The token has expired, perform logout
logout()
} else {
// The token is still valid, restore the authenticated state
_authState.value = AuthState.Authenticated(authData)
tokenProvider.set("Bearer ${authData.token.token}")
}
}
}
suspend fun isAuthValid(): Boolean {
return when (val authState = this.authState.value) {
is AuthState.Unauthenticated -> false
is AuthState.Authenticated -> {
// Verify if the token has expired (5 days)
if (isTokenExpired(authState.authData)) {
logout()
return false
}
// Note(loucas): Order of operations here is important,
// lazy `&&` evalutation makes this faster
firebaseService.isAuthenticated()
&& wordpressRepo.validateToken(authState.authData.token) is AuthResult.Success
}
}
}
/**
* Verify if the token has expired.
* A token is considered expired if it is older than 5 days.
* @param authData: The authentication data containing the token and its saved timestamp.
* @return True if the token has expired, false otherwise.
*/
private fun isTokenExpired(authData: AuthData): Boolean {
val tokenAge = (System.currentTimeMillis() - authData.tokenSavedTimestamp).milliseconds
Log.d("AuthenticationManager", "Token age: ${tokenAge.inWholeDays} days")
return tokenAge > TOKEN_VALIDITY_PERIOD
}
fun getAuthData(): AuthData? = when (val authState = this.authState.value) {
is AuthState.Authenticated -> authState.authData
is AuthState.Unauthenticated -> null
}
suspend fun login(username: String, password: String): AuthResult<WordpressToken> = coroutineScope {
// Crashlytics : Contexte de connexion
CrashlyticsUtils.setCurrentScreen("login")
CrashlyticsUtils.setCurrentFeature("authentication")
CrashlyticsUtils.setUserContext(isLoggedIn = false)
// Crashlytics : Log de la tentative de connexion
CrashlyticsUtils.logEvent("Tentative de connexion pour: $username")
CrashlyticsUtils.setCustomKey("last_login_attempt", System.currentTimeMillis().toString())
val wpDefRes = async {
wordpressRepo.authenticate(AuthentificationBody(username, password))
}
val fbDefRes = async {
wordpressRepo.handleServiceExceptions(
tryBody = {
firebaseService.authenticate()
return@async AuthResult.Success(Unit)
},
catchBody = { e ->
Log.e("AuthenticationManager: login", "Network error: ${e.message}")
// Crashlytics : Enregistrer l'erreur réseau
CrashlyticsUtils.recordException(e)
return@async AuthResult.NetworkError
}
)
}
val result = when (val wpRes = wpDefRes.await()) {
is AuthResult.NetworkError -> {
// Crashlytics : Log erreur réseau
CrashlyticsUtils.logEvent("Erreur réseau lors de la connexion pour: $username")
AuthResult.NetworkError
}
is AuthResult.Unauthorized -> {
// Crashlytics : Log erreur d'authentification
CrashlyticsUtils.logEvent("Erreur d'authentification pour: $username")
CrashlyticsUtils.setCustomKey("last_failed_login", username)
AuthResult.Unauthorized
}
else -> {
val fbRes = fbDefRes.await()
when (fbRes) {
is AuthResult.NetworkError -> AuthResult.NetworkError
is AuthResult.Unauthorized -> AuthResult.Unauthorized
else -> {
val authData = AuthData(username, (wpRes as AuthResult.Success).data)
writeAuthentication(authData)
_authState.value = AuthState.Authenticated(authData)
tokenProvider.set("Bearer ${authData.token.token}")
// Crashlytics : Log connexion réussie
CrashlyticsUtils.logEvent("Connexion réussie pour: $username")
CrashlyticsUtils.setUserId(authData.token.userEmail)
CrashlyticsUtils.setCustomKey("user_email", authData.token.userEmail)
CrashlyticsUtils.setCustomKey("last_successful_login", System.currentTimeMillis().toString())
CrashlyticsUtils.setUserContext(isLoggedIn = true)
CrashlyticsUtils.setCurrentScreen("home")
wpRes
}
}
}
}
return@coroutineScope result
}
private suspend fun writeAuthentication(authData: AuthData) {
val username = authData.username
val wordpressUid = wordpressRepo.getUserId(username)
datastorePref.setAuthData(authData)
datastorePref.setIsConnectedLeastOneTime(true)
datastorePref.setWasConnectedLastTime(true)
datastorePref.setLastEmail(username)
wordpressUid?.let { datastorePref.setUserId(it) }
}
suspend fun logout() {
// Crashlytics : Contexte de déconnexion
CrashlyticsUtils.setCurrentFeature("authentication")
CrashlyticsUtils.setCurrentScreen("logout")
// Crashlytics : Log de la déconnexion
val currentUser = getAuthData()?.token?.userEmail ?: "utilisateur_inconnu"
CrashlyticsUtils.logEvent("Déconnexion de l'utilisateur: $currentUser")
firebaseService.signOut()
datastorePref.clearAuthData()
datastorePref.setWasConnectedLastTime(false)
_authState.value = AuthState.Unauthenticated
// Crashlytics : Nettoyer les infos utilisateur
CrashlyticsUtils.setUserId("")
CrashlyticsUtils.setCustomKey("user_email", "")
CrashlyticsUtils.setUserContext(isLoggedIn = false)
CrashlyticsUtils.setCurrentScreen("login")
}
}
sealed interface AuthState {
object Unauthenticated : AuthState
data class Authenticated(val authData: AuthData) : AuthState
}
data class AuthData(
val username: String,
val token: WordpressToken,
val tokenSavedTimestamp: Long = System.currentTimeMillis()
)