generated from bitwarden/template
-
Notifications
You must be signed in to change notification settings - Fork 9
/
TotpCodeManagerImpl.kt
137 lines (125 loc) · 5.5 KB
/
TotpCodeManagerImpl.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
package com.bitwarden.authenticator.data.authenticator.manager
import com.bitwarden.core.DateTime
import com.bitwarden.authenticator.data.authenticator.datasource.disk.entity.AuthenticatorItemEntity
import com.bitwarden.authenticator.data.authenticator.datasource.sdk.AuthenticatorSdkSource
import com.bitwarden.authenticator.data.authenticator.manager.model.VerificationCodeItem
import com.bitwarden.authenticator.data.platform.manager.DispatcherManager
import com.bitwarden.authenticator.data.platform.repository.model.DataState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import java.time.Clock
import javax.inject.Inject
private const val ONE_SECOND_MILLISECOND = 1000L
/**
* Primary implementation of [TotpCodeManager].
*/
class TotpCodeManagerImpl @Inject constructor(
private val authenticatorSdkSource: AuthenticatorSdkSource,
dispatcherManager: DispatcherManager,
private val clock: Clock,
) : TotpCodeManager {
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
private val mutableVerificationCodeStateFlowMap =
mutableMapOf<AuthenticatorItemEntity, StateFlow<DataState<VerificationCodeItem?>>>()
override fun getTotpCodesStateFlow(
itemList: List<AuthenticatorItemEntity>,
): StateFlow<DataState<List<VerificationCodeItem>>> {
// Generate state flows
val stateFlows = itemList.map { itemEntity ->
getTotpCodeStateFlowInternal(itemEntity)
}
return combine(stateFlows) { results ->
when {
results.any { it is DataState.Loading } -> {
DataState.Loading
}
else -> {
DataState.Loaded(
data = results.mapNotNull { (it as DataState.Loaded).data },
)
}
}
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(),
initialValue = DataState.Loading,
)
}
override fun getTotpCodeStateFlow(
item: AuthenticatorItemEntity,
): StateFlow<DataState<VerificationCodeItem?>> =
getTotpCodeStateFlowInternal(itemEntity = item)
@Suppress("LongMethod")
private fun getTotpCodeStateFlowInternal(
itemEntity: AuthenticatorItemEntity?,
): StateFlow<DataState<VerificationCodeItem?>> {
val cipherId = itemEntity?.id ?: return MutableStateFlow(DataState.Loaded(null))
return mutableVerificationCodeStateFlowMap.getOrPut(itemEntity) {
flow<DataState<VerificationCodeItem?>> {
val totpCode = itemEntity.toOtpAuthUriString()
var item: VerificationCodeItem? = null
while (currentCoroutineContext().isActive) {
val time = (clock.millis() / ONE_SECOND_MILLISECOND).toInt()
val dateTime = DateTime.now()
if (item == null || item.isExpired(clock = clock)) {
authenticatorSdkSource
.generateTotp(
totp = totpCode,
time = dateTime,
)
.onSuccess { response ->
item = VerificationCodeItem(
code = response.code,
totpCode = totpCode,
periodSeconds = response.period.toInt(),
timeLeftSeconds = response.period.toInt() -
time % response.period.toInt(),
issueTime = clock.millis(),
id = cipherId,
username = itemEntity.accountName,
issuer = itemEntity.issuer,
)
}
.onFailure {
emit(DataState.Loaded(null))
return@flow
}
} else {
item?.let {
item = it.copy(
timeLeftSeconds = it.periodSeconds -
(time % it.periodSeconds),
)
}
}
item?.let {
emit(DataState.Loaded(it))
}
delay(ONE_SECOND_MILLISECOND)
}
}
.onCompletion {
mutableVerificationCodeStateFlowMap.remove(itemEntity)
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.WhileSubscribed(),
initialValue = DataState.Loading,
)
}
}
}
private fun VerificationCodeItem.isExpired(clock: Clock): Boolean {
val timeExpired = issueTime + (timeLeftSeconds * ONE_SECOND_MILLISECOND)
return timeExpired < clock.millis()
}