generated from bitwarden/template
-
Notifications
You must be signed in to change notification settings - Fork 9
/
AuthenticatorRepositoryImpl.kt
292 lines (262 loc) · 11.3 KB
/
AuthenticatorRepositoryImpl.kt
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package com.bitwarden.authenticator.data.authenticator.repository
import android.net.Uri
import com.bitwarden.authenticator.data.authenticator.datasource.disk.AuthenticatorDiskSource
import com.bitwarden.authenticator.data.authenticator.datasource.disk.entity.AuthenticatorItemEntity
import com.bitwarden.authenticator.data.authenticator.manager.FileManager
import com.bitwarden.authenticator.data.authenticator.manager.TotpCodeManager
import com.bitwarden.authenticator.data.authenticator.manager.model.ExportJsonData
import com.bitwarden.authenticator.data.authenticator.manager.model.VerificationCodeItem
import com.bitwarden.authenticator.data.authenticator.repository.model.AuthenticatorData
import com.bitwarden.authenticator.data.authenticator.repository.model.CreateItemResult
import com.bitwarden.authenticator.data.authenticator.repository.model.DeleteItemResult
import com.bitwarden.authenticator.data.authenticator.repository.model.ExportDataResult
import com.bitwarden.authenticator.data.authenticator.repository.model.TotpCodeResult
import com.bitwarden.authenticator.data.authenticator.repository.model.UpdateItemRequest
import com.bitwarden.authenticator.data.authenticator.repository.model.UpdateItemResult
import com.bitwarden.authenticator.data.platform.manager.DispatcherManager
import com.bitwarden.authenticator.data.platform.repository.model.DataState
import com.bitwarden.authenticator.data.platform.repository.util.bufferedMutableSharedFlow
import com.bitwarden.authenticator.data.platform.repository.util.combineDataStates
import com.bitwarden.authenticator.data.platform.repository.util.map
import com.bitwarden.authenticator.ui.platform.feature.settings.export.model.ExportFormat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import javax.inject.Inject
/**
* A "stop timeout delay" in milliseconds used to let a shared coroutine continue to run for the
* specified period of time after it no longer has subscribers.
*/
private const val STOP_TIMEOUT_DELAY_MS: Long = 5_000L
class AuthenticatorRepositoryImpl @Inject constructor(
private val authenticatorDiskSource: AuthenticatorDiskSource,
private val totpCodeManager: TotpCodeManager,
private val fileManager: FileManager,
dispatcherManager: DispatcherManager,
) : AuthenticatorRepository {
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
private val mutableCiphersStateFlow =
MutableStateFlow<DataState<List<AuthenticatorItemEntity>>>(DataState.Loading)
private val mutableTotpCodeResultFlow =
bufferedMutableSharedFlow<TotpCodeResult>()
override val totpCodeFlow: Flow<TotpCodeResult>
get() = mutableTotpCodeResultFlow.asSharedFlow()
override val authenticatorDataFlow: StateFlow<DataState<AuthenticatorData>> =
ciphersStateFlow.map { cipherDataState ->
when (cipherDataState) {
is DataState.Error -> {
DataState.Error(
cipherDataState.error,
AuthenticatorData(cipherDataState.data.orEmpty()),
)
}
is DataState.Loaded -> {
DataState.Loaded(AuthenticatorData(items = cipherDataState.data))
}
DataState.Loading -> {
DataState.Loading
}
is DataState.NoNetwork -> {
DataState.NoNetwork(AuthenticatorData(items = cipherDataState.data.orEmpty()))
}
is DataState.Pending -> {
DataState.Pending(AuthenticatorData(items = cipherDataState.data))
}
}
}.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(stopTimeoutMillis = STOP_TIMEOUT_DELAY_MS),
initialValue = DataState.Loading,
)
override val ciphersStateFlow: StateFlow<DataState<List<AuthenticatorItemEntity>>>
get() = mutableCiphersStateFlow.asStateFlow()
init {
authenticatorDiskSource
.getItems()
.onStart {
mutableCiphersStateFlow.value = DataState.Loading
}
.onEach {
mutableCiphersStateFlow.value = DataState.Loaded(it)
}
.launchIn(unconfinedScope)
}
override fun getItemStateFlow(itemId: String): StateFlow<DataState<AuthenticatorItemEntity?>> =
authenticatorDataFlow
.map { dataState ->
dataState.map { authenticatorData ->
authenticatorData
.items
.find { it.id == itemId }
}
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_DELAY_MS),
initialValue = DataState.Loading,
)
@OptIn(ExperimentalCoroutinesApi::class)
override fun getAuthCodeFlow(cipherId: String): StateFlow<DataState<VerificationCodeItem?>> {
return getItemStateFlow(cipherId)
.flatMapLatest { cipherDataState ->
val cipher = cipherDataState.data
?: return@flatMapLatest flowOf(DataState.Loaded(null))
totpCodeManager.getTotpCodeStateFlow(item = cipher)
.map { totpCodeDataState ->
combineDataStates(
totpCodeDataState,
cipherDataState,
) { totpCodeData, _ ->
// Just return the verification items; we are only combining the
// DataStates to know the overall state.
totpCodeData
}
}
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_DELAY_MS),
initialValue = DataState.Loading,
)
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun getAuthCodesFlow(): StateFlow<DataState<List<VerificationCodeItem>>> {
return authenticatorDataFlow
.map { dataState ->
dataState.map { authenticatorData -> authenticatorData.items }
}
.flatMapLatest { cipherDataState ->
val cipherList = cipherDataState.data ?: emptyList()
totpCodeManager.getTotpCodesStateFlow(itemList = cipherList)
.map { verificationCodeDataStates ->
combineDataStates(
verificationCodeDataStates,
cipherDataState,
) { verificationCodeItems, _ ->
// Just return the verification items; we are only combining the
// DataStates to know the overall state.
verificationCodeItems
}
}
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_DELAY_MS),
initialValue = DataState.Loading,
)
}
override fun emitTotpCodeResult(totpCodeResult: TotpCodeResult) {
mutableTotpCodeResultFlow.tryEmit(totpCodeResult)
}
override suspend fun createItem(item: AuthenticatorItemEntity): CreateItemResult {
return try {
authenticatorDiskSource.saveItem(item)
CreateItemResult.Success
} catch (e: Exception) {
CreateItemResult.Error
}
}
override suspend fun hardDeleteItem(itemId: String): DeleteItemResult {
return try {
authenticatorDiskSource.deleteItem(itemId)
DeleteItemResult.Success
} catch (e: Exception) {
DeleteItemResult.Error
}
}
override suspend fun updateItem(
itemId: String,
updateItemRequest: UpdateItemRequest,
): UpdateItemResult {
return try {
authenticatorDiskSource.saveItem(
AuthenticatorItemEntity(
id = itemId,
key = updateItemRequest.key,
accountName = updateItemRequest.accountName,
type = updateItemRequest.type,
period = updateItemRequest.period,
digits = updateItemRequest.digits,
issuer = updateItemRequest.issuer,
userId = null,
),
)
UpdateItemResult.Success
} catch (e: Exception) {
UpdateItemResult.Error(e.message)
}
}
override suspend fun exportVaultData(format: ExportFormat, fileUri: Uri): ExportDataResult {
return when (format) {
ExportFormat.JSON -> encodeVaultDataToJson(fileUri)
ExportFormat.CSV -> encodeVaultDataToCsv(fileUri)
}
}
private suspend fun encodeVaultDataToCsv(fileUri: Uri): ExportDataResult {
val headerLine =
"folder,favorite,type,name,login_uri,login_totp"
val dataLines = authenticatorDiskSource
.getItems()
.firstOrNull()
.orEmpty()
.joinToString("\n") { it.toCsvFormat() }
val csvString = "$headerLine\n$dataLines"
return if (fileManager.stringToUri(fileUri = fileUri, dataString = csvString)) {
ExportDataResult.Success
} else {
ExportDataResult.Error
}
}
private fun AuthenticatorItemEntity.toCsvFormat() =
",,1,$issuer,,${toOtpAuthUriString()},$issuer,$period,$digits"
private suspend fun encodeVaultDataToJson(fileUri: Uri): ExportDataResult {
val dataString: String = Json.encodeToString(
ExportJsonData(
encrypted = false,
items = authenticatorDiskSource
.getItems()
.firstOrNull()
.orEmpty()
.map { it.toExportJsonItem() },
)
)
return if (
fileManager.stringToUri(
fileUri = fileUri,
dataString = dataString,
)
) {
ExportDataResult.Success
} else {
ExportDataResult.Error
}
}
private fun AuthenticatorItemEntity.toExportJsonItem() = ExportJsonData.ExportItem(
id = id,
folderId = null,
organizationId = null,
collectionIds = null,
name = issuer,
notes = null,
type = 1,
login = ExportJsonData.ExportItem.ItemLoginData(
totp = toOtpAuthUriString(),
),
favorite = false,
)
}