1package com.peachpasswords.ui.lock23import android.content.Context4import androidx.biometric.BiometricManager5import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG6import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL7import androidx.biometric.BiometricPrompt8import androidx.core.content.ContextCompat9import androidx.fragment.app.FragmentActivity101112object Biometrics {13 private const val AUTHENTICATORS = BIOMETRIC_STRONG or DEVICE_CREDENTIAL1415 fun isAvailable(context: Context): Boolean =16 BiometricManager.from(context).canAuthenticate(AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS1718 19 fun statusMessage(context: Context): String? =20 when (BiometricManager.from(context).canAuthenticate(BIOMETRIC_STRONG)) {21 BiometricManager.BIOMETRIC_SUCCESS -> null22 BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> "No biometrics enrolled"23 BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE,24 BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> "Biometric hardware unavailable"25 BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> "Security update required"26 else -> null27 }2829 fun authenticate(30 activity: FragmentActivity,31 title: String,32 subtitle: String,33 onSuccess: () -> Unit,34 onFail: () -> Unit = {},35 ) {36 val prompt = BiometricPrompt(37 activity,38 ContextCompat.getMainExecutor(activity),39 object : BiometricPrompt.AuthenticationCallback() {40 override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = onSuccess()41 override fun onAuthenticationError(errorCode: Int, errString: CharSequence) = onFail()42 },43 )44 val info = BiometricPrompt.PromptInfo.Builder()45 .setTitle(title)46 .setSubtitle(subtitle)47 .setAllowedAuthenticators(AUTHENTICATORS)48 .build()49 prompt.authenticate(info)50 }51}