-
Notifications
You must be signed in to change notification settings - Fork 1
/
PinAuthenticationActivityViewModel.kt
473 lines (392 loc) · 15.4 KB
/
PinAuthenticationActivityViewModel.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package io.matthewnelson.pin_authentication.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import io.matthewnelson.pin_authentication.model.HashedPin
import io.matthewnelson.pin_authentication.service.PAActivityAccessPoint
import io.matthewnelson.pin_authentication.service.PinAuthentication
import io.matthewnelson.pin_authentication.service.components.PACoroutines
import io.matthewnelson.pin_authentication.service.components.PAViewColors
import io.matthewnelson.pin_authentication.service.components.PAViewData
import io.matthewnelson.pin_authentication.util.annotations.NotForPublicConsumption
import io.matthewnelson.pin_authentication.util.definitions.PAConfirmPinStatus
import io.matthewnelson.pin_authentication.util.definitions.PAPinEntryState
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import javax.inject.Inject
/**
* @suppress
* */
@NotForPublicConsumption
class PinAuthenticationActivityViewModel @Inject constructor(
private val paActivityAP: PAActivityAccessPoint,
private val paViewColors: PAViewColors,
private val paViewData: PAViewData,
private val paCoroutines: PACoroutines
) : ViewModel() {
private val pinEntry = PinEntry()
private inner class PinEntry(private var pin: String = "") {
private lateinit var pinEntryCompare: String
fun isPinEntryCompareEmpty(): Boolean =
if (::pinEntryCompare.isInitialized) pinEntryCompare.isEmpty() else true
fun setPinEntryCompare() {
val pinTemp = pin
this.clear()
pinEntryCompare = pinTemp
}
fun doPinsMatch(): Boolean =
if (::pinEntryCompare.isInitialized) pin == pinEntryCompare else false
fun clear(clearPinEntryCompare: Boolean = true) {
pin = ""
paViewData.setPinLength(0)
if (clearPinEntryCompare && !isPinEntryCompareEmpty()) {
pinEntryCompare = ""
}
}
fun dropLastChar() {
pin = pin.dropLast(1)
paViewData.setPinLength(pin.length)
}
fun addChar(c: Char) {
pin += c
paViewData.setPinLength(pin.length)
}
fun getHashedPin(pinAuthenticationSalt: String): HashedPin =
HashedPin(getSha256Hash(pinAuthenticationSalt) ?: "$pin$pinAuthenticationSalt")
private fun getSha256Hash(pinAuthenticationSalt: String): String? =
try {
val digest = MessageDigest.getInstance("SHA-256")
digest.reset()
bin2hex(digest.digest("$pin$pinAuthenticationSalt".toByteArray()))
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
null
}
private fun bin2hex(data: ByteArray): String {
val hex = StringBuilder(data.size * 2)
for (b in data) hex.append(String.format("%02x", b, 0xFF))
return hex.toString()
}
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////// PinAuthenticationActivity Layout ////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////
// Backspace Button //
//////////////////////
fun getBackspaceButtonImageColor(): String =
paViewColors.getBackspaceButtonImageColor()
fun onBackspacePress() {
toggleHapticFeedback()
if (paViewData.getPinLengthValue() > 0) {
pinEntry.dropLastChar()
}
}
////////////////////
// Confirm Button //
////////////////////
fun getConfirmButtonBackgroundColor(): String =
paViewColors.getConfirmButtonBackgroundColor()
fun getConfirmButtonImageColor(): String =
paViewColors.getConfirmButtonImageColor()
fun getMinPinLength(): Int =
paActivityAP.getMinPinLength()
fun onConfirmPress() {
val hashedPin: HashedPin = pinEntry.getHashedPin(paActivityAP.getPinAuthenticationSalt())
toggleHapticFeedback()
when (currentPinEntryState) {
PAPinEntryState.CONFIRM_PIN -> {
if (confirmPin(hashedPin)) {
paActivityAP.confirmPinToProceedSuccess()
paViewData.setPinEntryState(PAPinEntryState.IDLE)
} else {
pinHintContainerShakeAnimation()
pinEntry.clear()
}
}
PAPinEntryState.ENABLE_PIN_SECURITY -> {
setUsersPin(hashedPin)
}
PAPinEntryState.RESET_PIN -> {
if (confirmPin(hashedPin)) {
paViewData.setPinEntryState(PAPinEntryState.SET_PIN)
} else {
pinHintContainerShakeAnimation()
}
pinEntry.clear()
}
PAPinEntryState.SET_PIN -> {
setUsersPin(hashedPin)
}
PAPinEntryState.SET_PIN_FIRST_TIME -> {
setUsersPin(hashedPin)
}
else -> {
if (confirmPin(hashedPin)) {
paActivityAP.authProcessComplete(!pinResetFlowInterrupted)
paViewData.setPinEntryState(PAPinEntryState.IDLE)
} else {
pinHintContainerShakeAnimation()
pinEntry.clear()
}
}
}
}
private fun confirmPin(hashedPin: HashedPin): Boolean {
if (::lockoutJob.isInitialized && lockoutJob.isActive) return false
return when (paActivityAP.confirmPin(hashedPin)) {
PAConfirmPinStatus.LOCKED_OUT -> {
launchWrongPinLockoutCountdown(paActivityAP.getLockoutDurationSeconds())
false
}
PAConfirmPinStatus.ONE_MORE_ATTEMPT -> {
paActivityAP.showToast(paViewData.getOneMoreAttemptMessage(), paViewColors.getTextColor())
false
}
PAConfirmPinStatus.WRONG_PIN -> {
paActivityAP.showToast(paViewData.getWrongPinMessage(), paViewColors.getTextColor())
false
}
else -> {
true
}
}
}
private fun setUsersPin(hashedPin: HashedPin) {
if (pinEntry.isPinEntryCompareEmpty()) {
pinEntry.setPinEntryCompare()
paViewData.setHeaderTextSetPinStep2()
// Todo: need to allow for some sort of restart pin reset operation.
} else {
if (pinEntry.doPinsMatch()) {
paActivityAP.setUserPin(hashedPin)
paActivityAP.authProcessComplete(true)
paViewData.setPinEntryState(PAPinEntryState.IDLE)
} else {
paActivityAP.showToast(paViewData.getPinDoesNotMatchMessage(), paViewColors.getTextColor())
pinEntry.clear(clearPinEntryCompare = false)
pinHintContainerShakeAnimation()
}
}
}
////////////////////
// Number Buttons //
////////////////////
fun getPinPadButtonBackgroundColor(): String =
paViewColors.getPinPadButtonBackgroundColor()
fun getPinPadIntegers(): LiveData<MutableList<Int>> =
paViewData.getPinPadIntegers()
fun onNumPress(int: Int) {
toggleHapticFeedback()
when (paViewData.getPinLengthValue()) {
14 -> {
pinHintContainerShakeAnimation()
}
else -> {
pinEntry.addChar(int.toChar())
}
}
}
//////////////
// Pin Hint //
//////////////
fun getPinHintContainerColor(): String =
paViewColors.getPinHintContainerColor()
fun getPinHintImageColor(): String =
paViewColors.getPinHintImageColor()
fun getPinLength(): LiveData<Int> =
paViewData.getPinLength()
private fun pinHintContainerShakeAnimation() {
// Todo: shake the pin hint LinearLayout or something
}
///////////////
// Help Info //
///////////////
fun getPinResetInfoImageColor(): String =
paViewColors.getPinResetInfoImageColor()
fun getShowSetPinHelpInfo(): LiveData<String> =
paViewData.getShowSetPinHelpInfo()
///////////
// Other //
///////////
fun getHeaderText(): LiveData<String> =
paViewData.getHeaderText()
fun getScreenBackgroundColor(): String =
paViewColors.getScreenBackgroundColor()
fun getTextColor(): String =
paViewColors.getTextColor()
///////////////////////
// Wrong Pin Lockout //
///////////////////////
private lateinit var lockoutJob: Job
init {
if (paActivityAP.isWrongPinLockoutEnabled()) {
val secondsRemaining = paActivityAP.getLockoutSecondsRemaining()
if (secondsRemaining > 0) {
launchWrongPinLockoutCountdown(secondsRemaining)
} else if (!paViewData.getWrongPinLockoutTime().value.isNullOrEmpty()) {
paViewData.setWrongPinLockoutTime("")
}
}
}
fun getWrongPinLockoutTime(): LiveData<String> =
paViewData.getWrongPinLockoutTime()
private fun launchWrongPinLockoutCountdown(secondsRemaining: Int) {
lockoutJob = viewModelScope.launch(paCoroutines.getDispatcherMain()) {
updateWrongPinLockoutView(secondsRemaining)
}
}
private suspend fun updateWrongPinLockoutView(seconds: Int) {
var secondsRemaining = seconds
while (secondsRemaining >= 0) {
paViewData.setWrongPinLockoutTime("${secondsRemaining}s")
delay(1000)
secondsRemaining--
}
paViewData.setWrongPinLockoutTime("")
}
///////////////////////////////////////////
///////////////////////////////////////////
//////// PinAuthenticationActivity ////////
///////////////////////////////////////////
///////////////////////////////////////////
////////////////////////
// Window Flag Secure //
////////////////////////
fun getBuildConfigDebug(): Boolean =
paActivityAP.getBuildConfigDebug()
/////////////////////
// Haptic Feedback //
/////////////////////
private val hapticFeedback = MutableLiveData<Boolean>()
fun getHapticFeedback(): LiveData<Boolean> {
hapticFeedback.value = null
return hapticFeedback
}
private fun toggleHapticFeedback() {
if (paActivityAP.isHapticFeedBackEnabled()) {
hapticFeedback.value = hapticFeedback.value != true
}
}
///////////////////////
// Protect User Data //
///////////////////////
private lateinit var protectUserDataJob: Job
fun cancelProtectUserDataJobIfNotComplete() {
if (::protectUserDataJob.isInitialized && protectUserDataJob.isActive) {
protectUserDataJob.cancel()
}
}
/**
* This will clear the pin as soon as the app is sent to the background.
*
* It ensures that if the user is doing something with [PinAuthentication] while the
* app is sent to the background that no information is compromised.
*
* It will also send the user back to [PAPinEntryState.RESET_PIN] configuration if they are
* in the middle of the [PAPinEntryState.SET_PIN] process in the event that the app is sent
* to the background.
* */
fun launchProtectUserDataJobIfInactive() {
if (!::protectUserDataJob.isInitialized || !protectUserDataJob.isActive) {
protectUserDataJob = viewModelScope.launch(paCoroutines.getDispatcherMain()) {
protectUserData()
}
}
}
private fun protectUserData() {
if (currentPinEntryState == PAPinEntryState.SET_PIN && paActivityAP.isUserPinSet()) {
paViewData.setPinEntryState(PAPinEntryState.RESET_PIN)
pinEntry.clear()
} else {
pinEntry.clear(clearPinEntryCompare = false)
}
}
//////////////////////////////
// Override On Back Pressed //
//////////////////////////////
fun getCurrentPinEntryState(): @PAPinEntryState.PinEntryState Int =
currentPinEntryState
fun onBackPressed() {
if (currentPinEntryState == PAPinEntryState.CONFIRM_PIN) {
paActivityAP.confirmPinToProceedFailure()
}
if (currentPinEntryState == PAPinEntryState.ENABLE_PIN_SECURITY) {
paActivityAP.enablePinSecurityFailure()
}
paViewData.setPinEntryState(PAPinEntryState.IDLE)
}
/////////////////////
// Pin Entry Event //
/////////////////////
private var currentPinEntryState: @PAPinEntryState.PinEntryState Int = PAPinEntryState.IDLE
private var pinResetFlowInterrupted = false
private var pinConfirmationFlowInterrupted = false
fun getPinEntryState(): LiveData<@PAPinEntryState.PinEntryState Int> =
paViewData.getPinEntryState()
fun setPinEntryStateConfirmPin() {
if (currentPinEntryState != PAPinEntryState.CONFIRM_PIN) {
currentPinEntryState = PAPinEntryState.CONFIRM_PIN
if (!pinConfirmationFlowInterrupted) {
paViewData.setHeaderTextConfirmPin()
paViewData.setShowSetPinHelpInfo(false)
paViewData.setPinPadIntegers(paActivityAP.isScrambledPinEnabled())
}
}
}
fun setPinEntryStateLogin() {
if (currentPinEntryState != PAPinEntryState.LOGIN) {
pinEntry.clear()
if (currentPinEntryState == PAPinEntryState.RESET_PIN ||
currentPinEntryState == PAPinEntryState.SET_PIN) {
pinResetFlowInterrupted = true
}
if (currentPinEntryState == PAPinEntryState.CONFIRM_PIN) {
pinConfirmationFlowInterrupted = true
}
currentPinEntryState = PAPinEntryState.LOGIN
paViewData.setHeaderTextLogin()
paViewData.setShowSetPinHelpInfo(false)
paViewData.setPinPadIntegers(paActivityAP.isScrambledPinEnabled())
}
}
fun setPinEntryStateResetPin() {
if (currentPinEntryState != PAPinEntryState.RESET_PIN) {
currentPinEntryState = PAPinEntryState.RESET_PIN
paViewData.setHeaderTextResetPin()
paViewData.setShowSetPinHelpInfo(false)
paViewData.setPinPadIntegers(paActivityAP.isScrambledPinEnabled())
}
}
fun setPinEntryStateSetPin(pinEntryState: @PAPinEntryState.PinEntryState Int) {
if (currentPinEntryState != pinEntryState) {
currentPinEntryState = pinEntryState
paViewData.setHeaderTextSetPinStep1()
paViewData.setShowSetPinHelpInfo(true)
paViewData.setPinPadIntegers(false)
}
}
fun setPinEntryStateIdle() {
if (currentPinEntryState != PAPinEntryState.IDLE) {
currentPinEntryState = PAPinEntryState.IDLE
pinEntry.clear()
when {
pinResetFlowInterrupted -> {
pinResetFlowInterrupted = false
paViewData.setPinEntryState(PAPinEntryState.SET_PIN)
}
pinConfirmationFlowInterrupted -> {
pinConfirmationFlowInterrupted = false
paActivityAP.confirmPinToProceedSuccess()
}
else -> {}
}
}
}
}