-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTokenManager.kt
More file actions
58 lines (49 loc) · 1.82 KB
/
TokenManager.kt
File metadata and controls
58 lines (49 loc) · 1.82 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
package com.kuit.ourmenu.utils.auth
import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
private val Context.dataStore by preferencesDataStore(name = "user_prefs")
@Singleton
class TokenManager @Inject constructor(@ApplicationContext private val context: Context) {
private val _logoutEvent = MutableSharedFlow<Unit>()
val logoutEvent = _logoutEvent.asSharedFlow()
companion object {
private val ACCESS_TOKEN = stringPreferencesKey("access_token")
private val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
}
fun getAccessToken(): Flow<String?> {
return context.dataStore.data.map { preferences ->
preferences[ACCESS_TOKEN]
}
}
fun getRefreshToken(): Flow<String?> {
return context.dataStore.data.map { preferences ->
preferences[REFRESH_TOKEN]
}
}
suspend fun saveAccessToken(accessToken: String) {
context.dataStore.edit { preferences ->
preferences[ACCESS_TOKEN] = accessToken
}
}
suspend fun saveRefreshToken(refreshToken: String) {
context.dataStore.edit { preferences ->
preferences[REFRESH_TOKEN] = refreshToken
}
}
suspend fun clearToken() {
context.dataStore.edit { preferences ->
preferences.remove(ACCESS_TOKEN)
preferences.remove(REFRESH_TOKEN)
}
_logoutEvent.emit(Unit)
}
}