Skip to content

Commit ca5b2e5

Browse files
[local_auth] Convert Android to new Pigeon suspend support (#12894)
Switches the async authenticate method from the old callback system to Pigeon's new `suspend` support. Because the underlying SDK doesn't have a `suspend`-style method currently, the plugin bridges the existing intrenal callback to a `suspend` coroutine. This will simplify later conversion to JNI-backed Pigeon, and also simplifies unit tests. Part of flutter/flutter#192417 ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent a0e7807 commit ca5b2e5

7 files changed

Lines changed: 96 additions & 84 deletions

File tree

‎packages/local_auth/local_auth_android/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 2.3.0
2+
3+
* Updates internal platform API from callbacks to `suspend`.
4+
15
## 2.2.1
26

37
* Updates Robolectric to 4.17 and adds the JVM arguments it requires for unit tests.

‎packages/local_auth/local_auth_android/android/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ dependencies {
8787
testImplementation("org.mockito:mockito-core:5.23.0")
8888
testImplementation("org.mockito.kotlin:mockito-kotlin:6.3.0")
8989
testImplementation("org.robolectric:robolectric:4.17")
90+
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.1")
9091
androidTestImplementation("androidx.test:runner:1.7.0")
9192
androidTestImplementation("androidx.test:rules:1.7.0")
9293
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")

‎packages/local_auth/local_auth_android/android/src/main/kotlin/io/flutter/plugins/localauth/LocalAuthPlugin.kt‎

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
1717
import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter
1818
import io.flutter.plugins.localauth.LocalAuthApi.Companion.setUp
1919
import java.util.concurrent.atomic.AtomicBoolean
20+
import kotlin.coroutines.Continuation
21+
import kotlin.coroutines.resume
22+
import kotlin.coroutines.suspendCoroutine
2023

2124
/**
2225
* Flutter plugin providing access to local authentication.
@@ -69,52 +72,48 @@ class LocalAuthPlugin
6972
authHelper?.stopAuthentication()
7073
authHelper = null
7174
}
72-
authInProgress.set(false)
7375
return true
7476
} catch (_: Exception) {
7577
return false
7678
}
7779
}
7880

79-
override fun authenticate(
80-
options: AuthOptions,
81-
strings: AuthStrings,
82-
callback: (Result<AuthResult>) -> Unit
83-
) {
81+
override suspend fun authenticate(options: AuthOptions, strings: AuthStrings): AuthResult {
8482
val currentActivity = activity
8583
if (authInProgress.get()) {
86-
callback(Result.success(AuthResult(AuthResultCode.ALREADY_IN_PROGRESS, null)))
87-
return
84+
return AuthResult(AuthResultCode.ALREADY_IN_PROGRESS, null)
8885
}
8986

9087
if (currentActivity?.isFinishing ?: true) {
91-
callback(Result.success(AuthResult(AuthResultCode.NO_ACTIVITY, null)))
92-
return
88+
return AuthResult(AuthResultCode.NO_ACTIVITY, null)
9389
}
9490

9591
if (currentActivity !is FragmentActivity) {
96-
callback(Result.success(AuthResult(AuthResultCode.NOT_FRAGMENT_ACTIVITY, null)))
97-
return
92+
return AuthResult(AuthResultCode.NOT_FRAGMENT_ACTIVITY, null)
9893
}
9994

10095
if (!isDeviceSupported()) {
101-
callback(Result.success(AuthResult(AuthResultCode.NO_CREDENTIALS, null)))
102-
return
96+
return AuthResult(AuthResultCode.NO_CREDENTIALS, null)
10397
}
10498

10599
authInProgress.set(true)
106-
val completionHandler = createAuthCompletionHandler(callback)
107-
108100
val allowCredentials = !options.biometricOnly && canAuthenticateWithDeviceCredential()
109101

110-
sendAuthenticationRequest(
111-
options, strings, allowCredentials, currentActivity, completionHandler)
102+
return suspendCoroutine { continuation ->
103+
val completionHandler = createAuthCompletionHandler(continuation)
104+
sendAuthenticationRequest(
105+
options, strings, allowCredentials, currentActivity, completionHandler)
106+
}
112107
}
113108

114109
internal fun createAuthCompletionHandler(
115-
callback: (Result<AuthResult>) -> Unit
110+
continuation: Continuation<AuthResult>
116111
): (AuthResult) -> Unit {
117-
return { authResult -> onAuthenticationCompleted(callback, authResult) }
112+
return { authResult ->
113+
if (authInProgress.compareAndSet(true, false)) {
114+
continuation.resume(authResult)
115+
}
116+
}
118117
}
119118

120119
internal fun sendAuthenticationRequest(
@@ -131,12 +130,6 @@ class LocalAuthPlugin
131130
helper.authenticate()
132131
}
133132

134-
private fun onAuthenticationCompleted(callback: (Result<AuthResult>) -> Unit, value: AuthResult) {
135-
if (authInProgress.compareAndSet(true, false)) {
136-
callback(Result.success(value))
137-
}
138-
}
139-
140133
internal val isDeviceSecure: Boolean
141134
get() {
142135
return keyguardManager?.isDeviceSecure ?: false

‎packages/local_auth/local_auth_android/android/src/main/kotlin/io/flutter/plugins/localauth/Messages.kt‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright 2013 The Flutter Authors
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
4-
// Autogenerated from Pigeon (v27.3.2), do not edit directly.
4+
// Autogenerated from Pigeon (v29.0.1), do not edit directly.
55
// See also: https://pub.dev/packages/pigeon
66
@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass")
77

@@ -14,6 +14,9 @@ import io.flutter.plugin.common.MessageCodec
1414
import io.flutter.plugin.common.StandardMessageCodec
1515
import java.io.ByteArrayOutputStream
1616
import java.nio.ByteBuffer
17+
import kotlinx.coroutines.CoroutineScope
18+
import kotlinx.coroutines.Dispatchers
19+
import kotlinx.coroutines.launch
1720

1821
private object MessagesPigeonUtils {
1922

@@ -483,11 +486,7 @@ interface LocalAuthApi {
483486
/**
484487
* Attempts to authenticate the user with the provided [options], and using [strings] for any UI.
485488
*/
486-
fun authenticate(
487-
options: AuthOptions,
488-
strings: AuthStrings,
489-
callback: (Result<AuthResult>) -> Unit
490-
)
489+
suspend fun authenticate(options: AuthOptions, strings: AuthStrings): AuthResult
491490

492491
companion object {
493492
/** The codec used by LocalAuthApi. */
@@ -592,14 +591,14 @@ interface LocalAuthApi {
592591
val args = message as List<Any?>
593592
val optionsArg = args[0] as AuthOptions
594593
val stringsArg = args[1] as AuthStrings
595-
api.authenticate(optionsArg, stringsArg) { result: Result<AuthResult> ->
596-
val error = result.exceptionOrNull()
597-
if (error != null) {
598-
reply.reply(MessagesPigeonUtils.wrapError(error))
599-
} else {
600-
val data = result.getOrNull()
601-
reply.reply(MessagesPigeonUtils.wrapResult(data))
602-
}
594+
CoroutineScope(Dispatchers.Main).launch {
595+
val wrapped: List<Any?> =
596+
try {
597+
listOf(api.authenticate(optionsArg, stringsArg))
598+
} catch (exception: Throwable) {
599+
MessagesPigeonUtils.wrapError(exception)
600+
}
601+
reply.reply(wrapped)
603602
}
604603
}
605604
} else {

‎packages/local_auth/local_auth_android/android/src/test/kotlin/io/flutter/plugins/localauth/LocalAuthTest.kt‎

Lines changed: 55 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,13 @@ import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
1414
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
1515
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference
1616
import io.flutter.plugin.common.BinaryMessenger
17+
import kotlinx.coroutines.test.runTest
1718
import org.junit.Assert
1819
import org.junit.Test
1920
import org.junit.runner.RunWith
2021
import org.mockito.kotlin.any
2122
import org.mockito.kotlin.argumentCaptor
22-
import org.mockito.kotlin.doNothing
23+
import org.mockito.kotlin.doAnswer
2324
import org.mockito.kotlin.eq
2425
import org.mockito.kotlin.mock
2526
import org.mockito.kotlin.spy
@@ -30,56 +31,38 @@ import org.robolectric.annotation.Config
3031
@RunWith(RobolectricTestRunner::class)
3132
class LocalAuthTest {
3233
@Test
33-
fun authenticate_returnsErrorWhenAuthInProgress() {
34+
fun authenticate_returnsErrorWhenAuthInProgress() = runTest {
3435
val plugin = LocalAuthPlugin()
3536
plugin.authInProgress.set(true)
36-
var callbackCalled = false
37-
plugin.authenticate(defaultOptions, dummyStrings) { reply ->
38-
callbackCalled = true
39-
Assert.assertEquals(AuthResultCode.ALREADY_IN_PROGRESS, reply.getOrNull()?.code)
40-
}
41-
Assert.assertTrue(callbackCalled)
37+
val result = plugin.authenticate(defaultOptions, dummyStrings)
38+
Assert.assertEquals(AuthResultCode.ALREADY_IN_PROGRESS, result.code)
4239
}
4340

4441
@Test
45-
fun authenticate_returnsErrorWithNoForegroundActivity() {
42+
fun authenticate_returnsErrorWithNoForegroundActivity() = runTest {
4643
val plugin = LocalAuthPlugin()
47-
var callbackCalled = false
48-
49-
plugin.authenticate(defaultOptions, dummyStrings) { reply ->
50-
callbackCalled = true
51-
Assert.assertEquals(AuthResultCode.NO_ACTIVITY, reply.getOrNull()?.code)
52-
}
53-
Assert.assertTrue(callbackCalled)
44+
val result = plugin.authenticate(defaultOptions, dummyStrings)
45+
Assert.assertEquals(AuthResultCode.NO_ACTIVITY, result.code)
5446
}
5547

5648
@Test
57-
fun authenticate_returnsErrorWhenActivityNotFragmentActivity() {
49+
fun authenticate_returnsErrorWhenActivityNotFragmentActivity() = runTest {
5850
val plugin = LocalAuthPlugin()
5951
setPluginActivity(plugin, buildMockActivityWithContext(mock<NativeActivity>()))
60-
var callbackCalled = false
61-
plugin.authenticate(defaultOptions, dummyStrings) { reply ->
62-
callbackCalled = true
63-
Assert.assertEquals(AuthResultCode.NOT_FRAGMENT_ACTIVITY, reply.getOrNull()?.code)
64-
}
65-
Assert.assertTrue(callbackCalled)
52+
val result = plugin.authenticate(defaultOptions, dummyStrings)
53+
Assert.assertEquals(AuthResultCode.NOT_FRAGMENT_ACTIVITY, result.code)
6654
}
6755

6856
@Test
69-
fun authenticate_returnsErrorWhenDeviceNotSupported() {
57+
fun authenticate_returnsErrorWhenDeviceNotSupported() = runTest {
7058
val plugin = LocalAuthPlugin()
7159
setPluginActivity(plugin, buildMockActivityWithContext(mock<FragmentActivity>()))
72-
var callbackCalled = false
73-
74-
plugin.authenticate(defaultOptions, dummyStrings) { reply ->
75-
callbackCalled = true
76-
Assert.assertEquals(AuthResultCode.NO_CREDENTIALS, reply.getOrNull()?.code)
77-
}
78-
Assert.assertTrue(callbackCalled)
60+
val result = plugin.authenticate(defaultOptions, dummyStrings)
61+
Assert.assertEquals(AuthResultCode.NO_CREDENTIALS, result.code)
7962
}
8063

8164
@Test
82-
fun authenticate_properlyConfiguresBiometricOnlyAuthenticationRequest() {
65+
fun authenticate_properlyConfiguresBiometricOnlyAuthenticationRequest() = runTest {
8366
val plugin = spy(LocalAuthPlugin())
8467
val activity = buildMockActivityWithContext(mock<FragmentActivity>())
8568
setPluginActivity(plugin, activity)
@@ -94,19 +77,22 @@ class LocalAuthTest {
9477
plugin.setBiometricManager(mockBiometricManager)
9578

9679
val allowCredentialsCaptor = argumentCaptor<Boolean>()
97-
doNothing()
80+
doAnswer {
81+
val completionHandler = it.getArgument<(AuthResult) -> Unit>(4)
82+
completionHandler(AuthResult(AuthResultCode.SUCCESS, null))
83+
}
9884
.whenever(plugin)
9985
.sendAuthenticationRequest(
10086
any(), any(), allowCredentialsCaptor.capture(), eq(activity), any())
10187
val options = AuthOptions(biometricOnly = true, sensitiveTransaction = false, sticky = false)
10288

103-
plugin.authenticate(options, dummyStrings) {}
89+
plugin.authenticate(options, dummyStrings)
10490
Assert.assertFalse(allowCredentialsCaptor.firstValue)
10591
}
10692

10793
@Test
10894
@Config(sdk = [30])
109-
fun authenticate_properlyConfiguresBiometricAndDeviceCredentialAuthenticationRequest() {
95+
fun authenticate_properlyConfiguresBiometricAndDeviceCredentialAuthenticationRequest() = runTest {
11096
val plugin = spy(LocalAuthPlugin())
11197
val activity = buildMockActivityWithContext(mock<FragmentActivity>())
11298
setPluginActivity(plugin, activity)
@@ -119,17 +105,20 @@ class LocalAuthTest {
119105
plugin.setBiometricManager(mockBiometricManager)
120106

121107
val allowCredentialsCaptor = argumentCaptor<Boolean>()
122-
doNothing()
108+
doAnswer {
109+
val completionHandler = it.getArgument<(AuthResult) -> Unit>(4)
110+
completionHandler(AuthResult(AuthResultCode.SUCCESS, null))
111+
}
123112
.whenever(plugin)
124113
.sendAuthenticationRequest(
125114
any(), any(), allowCredentialsCaptor.capture(), eq(activity), any())
126-
plugin.authenticate(defaultOptions, dummyStrings) {}
115+
plugin.authenticate(defaultOptions, dummyStrings)
127116
Assert.assertTrue(allowCredentialsCaptor.firstValue)
128117
}
129118

130119
@Test
131120
@Config(sdk = [30])
132-
fun authenticate_properlyConfiguresDeviceCredentialOnlyAuthenticationRequest() {
121+
fun authenticate_properlyConfiguresDeviceCredentialOnlyAuthenticationRequest() = runTest {
133122
val plugin = spy(LocalAuthPlugin())
134123
val activity = buildMockActivityWithContext(mock<FragmentActivity>())
135124
setPluginActivity(plugin, activity)
@@ -144,14 +133,40 @@ class LocalAuthTest {
144133
plugin.setBiometricManager(mockBiometricManager)
145134

146135
val allowCredentialsCaptor = argumentCaptor<Boolean>()
147-
doNothing()
136+
doAnswer {
137+
val completionHandler = it.getArgument<(AuthResult) -> Unit>(4)
138+
completionHandler(AuthResult(AuthResultCode.SUCCESS, null))
139+
}
148140
.whenever(plugin)
149141
.sendAuthenticationRequest(
150142
any(), any(), allowCredentialsCaptor.capture(), eq(activity), any())
151-
plugin.authenticate(defaultOptions, dummyStrings) {}
143+
plugin.authenticate(defaultOptions, dummyStrings)
152144
Assert.assertTrue(allowCredentialsCaptor.firstValue)
153145
}
154146

147+
@Test
148+
fun authenticate_returnsResultFromCompletionHandler() = runTest {
149+
val plugin = spy(LocalAuthPlugin())
150+
val activity = buildMockActivityWithContext(mock<FragmentActivity>())
151+
setPluginActivity(plugin, activity)
152+
whenever(plugin.isDeviceSupported()).thenReturn(true)
153+
154+
val mockBiometricManager = mock<BiometricManager>()
155+
whenever(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
156+
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS)
157+
plugin.setBiometricManager(mockBiometricManager)
158+
159+
doAnswer {
160+
val completionHandler = it.getArgument<(AuthResult) -> Unit>(4)
161+
completionHandler(AuthResult(AuthResultCode.SUCCESS, null))
162+
}
163+
.whenever(plugin)
164+
.sendAuthenticationRequest(any(), any(), any(), eq(activity), any())
165+
166+
val result = plugin.authenticate(defaultOptions, dummyStrings)
167+
Assert.assertEquals(AuthResultCode.SUCCESS, result.code)
168+
}
169+
155170
@Test
156171
fun isDeviceSupportedReturnsFalse() {
157172
val plugin = LocalAuthPlugin()

‎packages/local_auth/local_auth_android/lib/src/messages.g.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright 2013 The Flutter Authors
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
4-
// Autogenerated from Pigeon (v27.3.2), do not edit directly.
4+
// Autogenerated from Pigeon (v29.0.1), do not edit directly.
55
// See also: https://pub.dev/packages/pigeon
66
// ignore_for_file: unused_import, unused_shown_name
77
// ignore_for_file: type=lint
@@ -377,8 +377,8 @@ class LocalAuthApi {
377377
pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty
378378
? '.$messageChannelSuffix'
379379
: '';
380-
final BinaryMessenger? pigeonVar_binaryMessenger;
381380

381+
final BinaryMessenger? pigeonVar_binaryMessenger;
382382
static const MessageCodec<Object?> pigeonChannelCodec = _PigeonCodec();
383383

384384
final String pigeonVar_messageChannelSuffix;

‎packages/local_auth/local_auth_android/pubspec.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: local_auth_android
22
description: Android implementation of the local_auth plugin.
33
repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_android
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
5-
version: 2.2.1
5+
version: 2.3.0
66

77
environment:
88
sdk: ^3.12.0
@@ -30,7 +30,7 @@ dev_dependencies:
3030
flutter_test:
3131
sdk: flutter
3232
mockito: ^5.4.4
33-
pigeon: ^27.3.2
33+
pigeon: ^29.0.1
3434

3535
topics:
3636
- authentication

0 commit comments

Comments
 (0)