From ae97c1e3dfc7cc66850e10eff6a6c447fd4922e7 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 14 Feb 2023 14:18:00 +0100 Subject: [PATCH 001/364] FP-20 WIP Setup pidgeons --- pidgeons/README.md | 2 ++ pidgeons/userProfile.dart | 0 pubspec.yaml | 1 + 3 files changed, 3 insertions(+) create mode 100644 pidgeons/README.md create mode 100644 pidgeons/userProfile.dart diff --git a/pidgeons/README.md b/pidgeons/README.md new file mode 100644 index 00000000..12c95d2a --- /dev/null +++ b/pidgeons/README.md @@ -0,0 +1,2 @@ +# Pidgeon +Pidgeon is used within this project to enable type-save communication between the native platforms. \ No newline at end of file diff --git a/pidgeons/userProfile.dart b/pidgeons/userProfile.dart new file mode 100644 index 00000000..e69de29b diff --git a/pubspec.yaml b/pubspec.yaml index ee40b0df..16ddbd32 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,6 +12,7 @@ dependencies: sdk: flutter dev_dependencies: + pigeon: ^8.0.0 flutter_test: sdk: flutter From 151471fab64c1bd4f2bb91cbe40babff09bb644e Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 15 Feb 2023 11:09:00 +0100 Subject: [PATCH 002/364] FP-20 WIP Working kotlin example --- .../mobile/sdk/flutter/OneginiPlugin.kt | 17 ++- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 104 ++++++++++++++++++ .../useCases/FetchUserProfilesUseCase.kt | 11 ++ example/lib/screens/login_screen.dart | 5 + lib/pigeon.dart | 96 ++++++++++++++++ pidgeons/README.md | 2 - pidgeons/userProfile.dart | 0 pigeons/README.md | 10 ++ pigeons/userProfile.dart | 14 +++ 9 files changed, 256 insertions(+), 3 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt create mode 100644 lib/pigeon.dart delete mode 100644 pidgeons/README.md delete mode 100644 pidgeons/userProfile.dart create mode 100644 pigeons/README.md create mode 100644 pigeons/userProfile.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index a25c1741..81fc952f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -2,13 +2,15 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender +import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile +import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodChannel /** OneginiPlugin */ -class OneginiPlugin : FlutterPlugin { +class OneginiPlugin : FlutterPlugin, UserClientApi { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it @@ -17,6 +19,8 @@ class OneginiPlugin : FlutterPlugin { private lateinit var eventChannel: EventChannel override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) + val oneginiSDK = OneginiSDK() channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onegini") channel.setMethodCallHandler(OnMethodCallMapper(flutterPluginBinding.applicationContext, OneginiMethodsWrapper(), oneginiSDK)) @@ -33,7 +37,18 @@ class OneginiPlugin : FlutterPlugin { } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + UserClientApi.setUp(binding.binaryMessenger, null) channel.setMethodCallHandler(null) } + override fun fetchUserProfiles(callback: (Result>) -> Unit) { + val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) +// val b = Result.failure(SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR)) + callback(a) +// callback.onSuccess { listOf(UserProfile("ghalo", true)) } +// callback?.onFailure { throw Exc } +// { listOf(UserProfile("ghalo", true)) } +// callback?.onFailure { SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR) } + } + } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt new file mode 100644 index 00000000..1a3f2530 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -0,0 +1,104 @@ +// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +package com.onegini.mobile.sdk.flutter.pigeonPlugin + +import android.util.Log +import io.flutter.plugin.common.BasicMessageChannel +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MessageCodec +import io.flutter.plugin.common.StandardMessageCodec +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer + +private fun wrapResult(result: Any?): List { + return listOf(result) +} + +private fun wrapError(exception: Throwable): List { + return listOf( + exception.javaClass.simpleName, + exception.toString(), + "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) + ) +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class PigeonUserProfile ( + val profileId: String, + val isDefault: Boolean + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): PigeonUserProfile { + val profileId = list[0] as String + val isDefault = list[1] as Boolean + return PigeonUserProfile(profileId, isDefault) + } + } + fun toList(): List { + return listOf( + profileId, + isDefault, + ) + } +} + +@Suppress("UNCHECKED_CAST") +private object UserClientApiCodec : StandardMessageCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 128.toByte() -> { + return (readValue(buffer) as? List)?.let { + PigeonUserProfile.fromList(it) + } + } + else -> super.readValueOfType(type, buffer) + } + } + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + when (value) { + is PigeonUserProfile -> { + stream.write(128) + writeValue(stream, value.toList()) + } + else -> super.writeValue(stream, value) + } + } +} + +/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ +interface UserClientApi { + fun fetchUserProfiles(callback: (Result>) -> Unit) + + companion object { + /** The codec used by UserClientApi. */ + val codec: MessageCodec by lazy { + UserClientApiCodec + } + /** Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. */ + @Suppress("UNCHECKED_CAST") + fun setUp(binaryMessenger: BinaryMessenger, api: UserClientApi?) { + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fetchUserProfiles", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.fetchUserProfiles() { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt new file mode 100644 index 00000000..f09468bc --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt @@ -0,0 +1,11 @@ +package com.onegini.mobile.sdk.flutter.useCases + +//import com.onegini.mobile.sdk.flutter.OneginiPlugin +//import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserProfile +// +//class fetchUserProfilesUseCase { +// +// fun fetchUserProfiles(keyword:String): List { +// return listOf() +// } +//} \ No newline at end of file diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index c0312d7b..460ea129 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -8,6 +8,7 @@ import 'package:onegini/callbacks/onegini_registration_callback.dart'; import 'package:onegini/model/onegini_list_response.dart'; import 'package:onegini/model/registration_response.dart'; import 'package:onegini/onegini.dart'; +import 'package:onegini/pigeon.dart'; import 'package:onegini_example/screens/user_screen.dart'; class LoginScreen extends StatefulWidget { @@ -168,6 +169,10 @@ class _LoginScreenState extends State { Future> getUserProfiles() async { try { + var userApi = UserClientApi(); + var derp = await userApi.fetchUserProfiles(); + print(derp[0].profileId); + var profiles = await Onegini.instance.userClient.getUserProfiles(); return profiles; } catch (err) { diff --git a/lib/pigeon.dart b/lib/pigeon.dart new file mode 100644 index 00000000..f2a83c10 --- /dev/null +++ b/lib/pigeon.dart @@ -0,0 +1,96 @@ +// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// See also: https://pub.dev/packages/pigeon +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import + +import 'dart:async'; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; + +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/services.dart'; + +class PigeonUserProfile { + PigeonUserProfile({ + required this.profileId, + required this.isDefault, + }); + + String profileId; + + bool isDefault; + + Object encode() { + return [ + profileId, + isDefault, + ]; + } + + static PigeonUserProfile decode(Object result) { + result as List; + return PigeonUserProfile( + profileId: result[0]! as String, + isDefault: result[1]! as bool, + ); + } +} + +class _UserClientApiCodec extends StandardMessageCodec { + const _UserClientApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is PigeonUserProfile) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return PigeonUserProfile.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +class UserClientApi { + /// Constructor for [UserClientApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + UserClientApi({BinaryMessenger? binaryMessenger}) + : _binaryMessenger = binaryMessenger; + final BinaryMessenger? _binaryMessenger; + + static const MessageCodec codec = _UserClientApiCodec(); + + Future> fetchUserProfiles() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.fetchUserProfiles', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); + } + } +} diff --git a/pidgeons/README.md b/pidgeons/README.md deleted file mode 100644 index 12c95d2a..00000000 --- a/pidgeons/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Pidgeon -Pidgeon is used within this project to enable type-save communication between the native platforms. \ No newline at end of file diff --git a/pidgeons/userProfile.dart b/pidgeons/userProfile.dart deleted file mode 100644 index e69de29b..00000000 diff --git a/pigeons/README.md b/pigeons/README.md new file mode 100644 index 00000000..f2f7afb1 --- /dev/null +++ b/pigeons/README.md @@ -0,0 +1,10 @@ +# Pidgeon +Pidgeon is used within this project to enable type-save communication between the native platforms. + +Command for code generation which is performed from top level: +flutter pub run pigeon \ + --input pigeons/userProfile.dart \ + --dart_out lib/pigeon.dart \ + --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ + --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ + --experimental_swift_out ios/Classes/Pigeon.swift \ No newline at end of file diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart new file mode 100644 index 00000000..72340d05 --- /dev/null +++ b/pigeons/userProfile.dart @@ -0,0 +1,14 @@ +import 'package:pigeon/pigeon.dart'; + +class PigeonUserProfile { + String profileId; + bool isDefault; + + PigeonUserProfile({ required this.profileId, required this.isDefault}); +} + +@HostApi() +abstract class UserClientApi { + @async + List fetchUserProfiles(); +} \ No newline at end of file From eddf7a44d50fddd0086778538af28d468d9951d8 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 16 Feb 2023 11:27:57 +0100 Subject: [PATCH 003/364] FP-20 WIP Working ios version --- .../mobile/sdk/flutter/OneginiPlugin.kt | 9 +- ios/Classes/Pigeon.swift | 119 ++++++++++++++++++ ios/Classes/SwiftOneginiPlugin.swift | 16 ++- pigeons/userProfile.dart | 16 ++- 4 files changed, 157 insertions(+), 3 deletions(-) create mode 100644 ios/Classes/Pigeon.swift diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 81fc952f..bec87f61 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -1,11 +1,14 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MethodChannel @@ -43,8 +46,12 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) -// val b = Result.failure(SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR)) +// throw SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR) +// val b = Result.failure>(Exception("meee", Throwable("boop"))) +// a.onFailure { Throwable("meee", Throwable("boop")) } +// a.i callback(a) +// throw Throwable("meee", Throwable("boop")) // callback.onSuccess { listOf(UserProfile("ghalo", true)) } // callback?.onFailure { throw Exc } // { listOf(UserProfile("ghalo", true)) } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift new file mode 100644 index 00000000..edc13fd9 --- /dev/null +++ b/ios/Classes/Pigeon.swift @@ -0,0 +1,119 @@ +// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +import Foundation +#if os(iOS) +import Flutter +#elseif os(macOS) +import FlutterMacOS +#else +#error("Unsupported platform.") +#endif + + + +private func wrapResult(_ result: Any?) -> [Any?] { + return [result] +} + +private func wrapError(_ error: Any) -> [Any?] { + if let flutterError = error as? FlutterError { + return [ + flutterError.code, + flutterError.message, + flutterError.details + ] + } + return [ + "\(error)", + "\(type(of: error))", + "Stacktrace: \(Thread.callStackSymbols)" + ] +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PigeonUserProfile { + var profileId: String + var isDefault: Bool + + static func fromList(_ list: [Any?]) -> PigeonUserProfile? { + let profileId = list[0] as! String + let isDefault = list[1] as! Bool + + return PigeonUserProfile( + profileId: profileId, + isDefault: isDefault + ) + } + func toList() -> [Any?] { + return [ + profileId, + isDefault, + ] + } +} + +private class UserClientApiCodecReader: FlutterStandardReader { + override func readValue(ofType type: UInt8) -> Any? { + switch type { + case 128: + return PigeonUserProfile.fromList(self.readValue() as! [Any]) + default: + return super.readValue(ofType: type) + } + } +} + +private class UserClientApiCodecWriter: FlutterStandardWriter { + override func writeValue(_ value: Any) { + if let value = value as? PigeonUserProfile { + super.writeByte(128) + super.writeValue(value.toList()) + } else { + super.writeValue(value) + } + } +} + +private class UserClientApiCodecReaderWriter: FlutterStandardReaderWriter { + override func reader(with data: Data) -> FlutterStandardReader { + return UserClientApiCodecReader(data: data) + } + + override func writer(with data: NSMutableData) -> FlutterStandardWriter { + return UserClientApiCodecWriter(data: data) + } +} + +class UserClientApiCodec: FlutterStandardMessageCodec { + static let shared = UserClientApiCodec(readerWriter: UserClientApiCodecReaderWriter()) +} + +/// Generated protocol from Pigeon that represents a handler of messages from Flutter. +protocol UserClientApi { + func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) +} + +/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. +class UserClientApiSetup { + /// The codec used by UserClientApi. + static var codec: FlutterStandardMessageCodec { UserClientApiCodec.shared } + /// Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. + static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UserClientApi?) { + let fetchUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fetchUserProfiles", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + fetchUserProfilesChannel.setMessageHandler { _, reply in + api.fetchUserProfiles() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + fetchUserProfilesChannel.setMessageHandler(nil) + } + } +} diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index cbb2ff54..5cc27c93 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -1,7 +1,9 @@ import Flutter import UIKit -public class SwiftOneginiPlugin: NSObject, FlutterPlugin { +extension FlutterError: Error {} + +public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) let eventChannel = FlutterEventChannel(name: "onegini_events", @@ -9,6 +11,11 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin { let instance = SwiftOneginiPlugin() registrar.addMethodCallDelegate(instance, channel: channel) eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) + + // Init Pigeon communication + let messenger : FlutterBinaryMessenger = registrar.messenger() + let api : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() + UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { @@ -90,4 +97,11 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin { } } } + + func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) { +// let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) + completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) + +// completion(.success([PigeonUserProfile(profileId: "boopios", isDefault: true)])) + } } diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart index 72340d05..ddbfaae2 100644 --- a/pigeons/userProfile.dart +++ b/pigeons/userProfile.dart @@ -1,5 +1,19 @@ import 'package:pigeon/pigeon.dart'; +// @ConfigurePigeon(PigeonOptions( +// dartOut: './../lib/pigeon.dart', +// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', +// kotlinOptions: KotlinOptions( +// // copyrightHeader: ['zero'], +// package: 'com.zero.flutter_pigeon_plugin', +// ), +// objcHeaderOut: 'ios/Runner/Pigeon.h', +// objcSourceOut: 'ios/Runner/Pigeon.m', +// objcOptions: ObjcOptions( +// prefix: 'FLT', +// ), +// )) + class PigeonUserProfile { String profileId; bool isDefault; @@ -10,5 +24,5 @@ class PigeonUserProfile { @HostApi() abstract class UserClientApi { @async - List fetchUserProfiles(); + Result> fetchUserProfiles(); } \ No newline at end of file From cad3ae3d29ef9f992577b598203f0251b6dcee04 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Feb 2023 12:53:44 +0100 Subject: [PATCH 004/364] android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt --- .../mobile/sdk/flutter/OneginiPlugin.kt | 19 ++++++++----------- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 7 ++++--- .../providers/CustomRegistrationActionImpl.kt | 7 ++++++- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index bec87f61..660dc7ef 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -4,6 +4,7 @@ import androidx.annotation.NonNull import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import io.flutter.embedding.engine.plugins.FlutterPlugin @@ -22,9 +23,11 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { private lateinit var eventChannel: EventChannel override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + // Pigeon setup UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) + val nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) - val oneginiSDK = OneginiSDK() + val oneginiSDK = OneginiSDK(nativeApi) channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onegini") channel.setMethodCallHandler(OnMethodCallMapper(flutterPluginBinding.applicationContext, OneginiMethodsWrapper(), oneginiSDK)) eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "onegini_events") @@ -44,18 +47,12 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { channel.setMethodCallHandler(null) } + // Example function on how it could be initiated on Flutter send to Native + // Fixme limitation on failure platform exception structure; see + // https://github.com/flutter/flutter/issues/120861 override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) -// throw SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR) -// val b = Result.failure>(Exception("meee", Throwable("boop"))) -// a.onFailure { Throwable("meee", Throwable("boop")) } -// a.i +// val a = Result.failure>(Exception("meee", Throwable("boop"))) callback(a) -// throw Throwable("meee", Throwable("boop")) -// callback.onSuccess { listOf(UserProfile("ghalo", true)) } -// callback?.onFailure { throw Exc } -// { listOf(UserProfile("ghalo", true)) } -// callback?.onFailure { SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR) } } - } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index a2e3c033..e3c769a0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -15,8 +15,9 @@ import com.onegini.mobile.sdk.flutter.providers.CustomTwoStepRegistrationActionI import io.flutter.plugin.common.MethodChannel import java.util.concurrent.TimeUnit import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -class OneginiSDK { +class OneginiSDK(private var nativeApi: NativeCallFlutterApi) { private var oneginiClient: OneginiClient? = null private var customRegistrationActions = ArrayList() @@ -64,8 +65,8 @@ class OneginiSDK { private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List) { customIdentityProviderConfigs.forEach { val action = when (it.isTwoStep) { - true -> CustomTwoStepRegistrationActionImpl(it.providerId) - false -> CustomRegistrationActionImpl(it.providerId) + true -> CustomTwoStepRegistrationActionImpl(it.providerId, nativeApi) + false -> CustomRegistrationActionImpl(it.providerId, nativeApi) } customRegistrationActions.add(action) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index e97e240b..0934fd17 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -10,16 +10,21 @@ import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import io.flutter.plugin.common.MethodChannel -class CustomRegistrationActionImpl(private val providerId: String) : OneginiCustomRegistrationAction, CustomRegistrationAction { +class CustomRegistrationActionImpl(private val providerId: String, private val onewelcomeEventApi: NativeCallFlutterApi) : OneginiCustomRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback + // Example Tell flutter to start this method from native + onewelcomeEventApi.testEventFunction("customOneStepOnFinish") { } + val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) + } override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { From 1f0876fa182792852c341ec317c265acb16542c7 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Feb 2023 13:01:12 +0100 Subject: [PATCH 005/364] FP-20 Setup pigeon with function callbacks from native and updated readme while highlighting limitation of pigeon with error codes --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 27 ++++++++++++++++- .../CustomTwoStepRegistrationActionImpl.kt | 5 +++- example/lib/main.dart | 5 ++++ example/lib/onegini_pigeon_listener.dart | 9 ++++++ .../Handlers/RegistrationHandler.swift | 6 ++-- ios/Classes/Pigeon.swift | 18 +++++++++++ ios/Classes/SwiftOneginiPlugin.swift | 10 ++++++- lib/pigeon.dart | 30 +++++++++++++++++++ pigeons/README.md | 20 ++++++++++++- pigeons/userProfile.dart | 12 ++++++-- 10 files changed, 132 insertions(+), 10 deletions(-) create mode 100644 example/lib/onegini_pigeon_listener.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 1a3f2530..f5b91c6b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -68,7 +68,11 @@ private object UserClientApiCodec : StandardMessageCodec() { } } -/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ +/** + * Flutter calls native + * + * Generated interface from Pigeon that represents a handler of messages from Flutter. + */ interface UserClientApi { fun fetchUserProfiles(callback: (Result>) -> Unit) @@ -102,3 +106,24 @@ interface UserClientApi { } } } +/** + * Native calls Flutter + * + * Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. + */ +@Suppress("UNCHECKED_CAST") +class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { + companion object { + /** The codec used by NativeCallFlutterApi. */ + val codec: MessageCodec by lazy { + StandardMessageCodec() + } + } + fun testEventFunction(argumentArg: String, callback: (String) -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction", codec) + channel.send(listOf(argumentArg)) { + val result = it as String + callback(result) + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index e8aced21..f435e457 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -11,9 +11,10 @@ import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import io.flutter.plugin.common.MethodChannel -class CustomTwoStepRegistrationActionImpl(private val providerId: String) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { +class CustomTwoStepRegistrationActionImpl(private val providerId: String, private val onewelcomeEventApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null override fun initRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { @@ -26,6 +27,8 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg override fun finishRegistration(callback: OneginiCustomRegistrationCallback, customInfo: CustomInfo?) { this.callback = callback + onewelcomeEventApi.testEventFunction("custom2stepOnFinish") { } + val data = Gson().toJson(CustomRegistrationModel(customInfo?.data.orEmpty(), customInfo?.status, providerId)) OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) } diff --git a/example/lib/main.dart b/example/lib/main.dart index 2465d0f2..0b47a2c5 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:onegini/onegini.dart'; +import 'package:onegini/pigeon.dart'; +import 'package:onegini_example/onegini_pigeon_listener.dart'; import 'package:onegini_example/screens/login_screen.dart'; import 'onegini_listener.dart'; @@ -53,6 +55,9 @@ class _BodyWidgetState extends State { void initState() { _startApplication(); super.initState(); + + // init listener class todo move this to start application + NativeCallFlutterApi.setup(OneginiPigeonListenerImpl()); } void _startApplication() async { diff --git a/example/lib/onegini_pigeon_listener.dart b/example/lib/onegini_pigeon_listener.dart new file mode 100644 index 00000000..0cfa8532 --- /dev/null +++ b/example/lib/onegini_pigeon_listener.dart @@ -0,0 +1,9 @@ +import 'package:onegini/pigeon.dart'; + +class OneginiPigeonListenerImpl extends NativeCallFlutterApi { + @override + Future testEventFunction(String argument) async { + print("testEventFunction was triggered from native: $argument"); + return "boop"; + } +} diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 8e2ed9b5..c382e853 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -22,9 +22,7 @@ protocol CustomRegistrationNotificationReceiverProtocol: class { } class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, PinHandlerToReceiverProtocol, RegistrationHandlerToPinHanlderProtocol { - - var middleTwoStep: Bool? = nil - + var createPinChallenge: ONGCreatePinChallenge? var browserRegistrationChallenge: ONGBrowserRegistrationChallenge? var customRegistrationChallenge: ONGCustomRegistrationChallenge? @@ -174,7 +172,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { var result = Dictionary() result["eventValue"] = challenge.url.absoluteString - + sendCustomRegistrationNotification(CustomRegistrationNotification.eventHandleRegisteredUrl, result) } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index edc13fd9..eaa69574 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -89,6 +89,8 @@ class UserClientApiCodec: FlutterStandardMessageCodec { static let shared = UserClientApiCodec(readerWriter: UserClientApiCodecReaderWriter()) } +/// Flutter calls native +/// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) @@ -117,3 +119,19 @@ class UserClientApiSetup { } } } +/// Native calls Flutter +/// +/// Generated class from Pigeon that represents Flutter messages that can be called from Swift. +class NativeCallFlutterApi { + private let binaryMessenger: FlutterBinaryMessenger + init(binaryMessenger: FlutterBinaryMessenger){ + self.binaryMessenger = binaryMessenger + } + func testEventFunction(argument argumentArg: String, completion: @escaping (String) -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction", binaryMessenger: binaryMessenger) + channel.sendMessage([argumentArg] as [Any?]) { response in + let result = response as! String + completion(result) + } + } +} diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 5cc27c93..97667feb 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -4,6 +4,8 @@ import UIKit extension FlutterError: Error {} public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { + static var flutterApi: NativeCallFlutterApi? + public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) let eventChannel = FlutterEventChannel(name: "onegini_events", @@ -11,11 +13,16 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { let instance = SwiftOneginiPlugin() registrar.addMethodCallDelegate(instance, channel: channel) eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) - + // Init Pigeon communication let messenger : FlutterBinaryMessenger = registrar.messenger() let api : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) + + flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) + + // Example on call flutter function from native during start + flutterApi?.testEventFunction(argument: "we initilized the function", completion: {_ in }) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { @@ -98,6 +105,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } } + // Example function for Flutter -> Native functions and how to return a response or error func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) { // let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) diff --git a/lib/pigeon.dart b/lib/pigeon.dart index f2a83c10..996aad6d 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -57,6 +57,7 @@ class _UserClientApiCodec extends StandardMessageCodec { } } +/// Flutter calls native class UserClientApi { /// Constructor for [UserClientApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default @@ -94,3 +95,32 @@ class UserClientApi { } } } + +/// Native calls Flutter +abstract class NativeCallFlutterApi { + static const MessageCodec codec = StandardMessageCodec(); + + Future testEventFunction(String argument); + + static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction was null.'); + final List args = (message as List?)!; + final String? arg_argument = (args[0] as String?); + assert(arg_argument != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction was null, expected non-null String.'); + final String output = await api.testEventFunction(arg_argument!); + return output; + }); + } + } + } +} diff --git a/pigeons/README.md b/pigeons/README.md index f2f7afb1..ae65c409 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -7,4 +7,22 @@ flutter pub run pigeon \ --dart_out lib/pigeon.dart \ --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ - --experimental_swift_out ios/Classes/Pigeon.swift \ No newline at end of file + --experimental_swift_out ios/Classes/Pigeon.swift + +## Missing documentation +Pigeon is poorly documented; so to keep knowledge on why and how certain things are done we will refer to pull requests where we obtained information. + +### iOS Platform Exceptions +By default, it is not possible to return custom platform exceptions through pigeon, however a merged feature has made this possible. +The steps to obtain this such that we can call "completion(.failure(SdkError(.userProfileDoesNotExist).flutterError()))" for example is explained in this PR: +https://github.com/flutter/packages/pull/3084 + +### Android Platform Exception +Currently, it is not possible to send custom platform exceptions back using the (code, message, details) structure. This PR is requesting it and we hope it gets added soon: +https://github.com/flutter/flutter/issues/120861 + +### Triggering event functions from Native +We can use @FlutterApi to call functions on the dart side from the Native parts. However, as always this is not ducumented but there is an open documentation issue that gives some references with more information +https://github.com/flutter/flutter/issues/108531 + +where https://github.com/zero-li/flutter_pigeon_plugin gives a simple example project (with chines documentation) but gives a good idea on how it works as a reference. diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart index ddbfaae2..356a616d 100644 --- a/pigeons/userProfile.dart +++ b/pigeons/userProfile.dart @@ -21,8 +21,16 @@ class PigeonUserProfile { PigeonUserProfile({ required this.profileId, required this.isDefault}); } +/// Flutter calls native @HostApi() abstract class UserClientApi { @async - Result> fetchUserProfiles(); -} \ No newline at end of file + List fetchUserProfiles(); +} + +/// Native calls Flutter +@FlutterApi() +abstract class NativeCallFlutterApi{ + @async + String testEventFunction(String argument); +} From 1251785830c8fd5d99180decd254b4517ce6bc0d Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 23 Feb 2023 13:10:04 +0100 Subject: [PATCH 006/364] FP-20 WIP Using pr containing potential fix --- .../mobile/sdk/flutter/OneginiPlugin.kt | 11 ++ .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 145 +++++++++++++++++- ios/Classes/Pigeon.swift | 115 +++++++++++++- lib/pigeon.dart | 136 +++++++++++++++- pigeons/README.md | 3 + pigeons/userProfile.dart | 45 +++++- pubspec.yaml | 6 +- 7 files changed, 449 insertions(+), 12 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 1a0b32fc..ea960356 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -2,12 +2,14 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule +import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserProfilesResult import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.FlutterException @@ -71,4 +73,13 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { // val a = Result.failure>(Exception("meee", Throwable("boop"))) callback(a) } + + override fun testFunction(callback: (Result) -> Unit) { +// val a = Result.success(listOf(UserProfilesResult(success = Us, true))) +// val b = FlutterException() Exception("meesage").Fl + +// val a = Result.failure>(Exception("ghallo") +// ()) +// callback(a) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index f5b91c6b..5e18f722 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin @@ -6,6 +6,7 @@ package com.onegini.mobile.sdk.flutter.pigeonPlugin import android.util.Log import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MessageCodec import io.flutter.plugin.common.StandardMessageCodec import java.io.ByteArrayOutputStream @@ -15,14 +16,103 @@ private fun wrapResult(result: Any?): List { return listOf(result) } -private fun wrapError(exception: Throwable): List { - return listOf( +private fun wrapError(exception: Throwable): List { + if (exception is FlutterException) { + return listOf( + exception.code, + exception.message, + exception.details + ) + } + return listOf( exception.javaClass.simpleName, exception.toString(), "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) ) } +enum class State(val raw: Int) { + SUCCESS(0), + ERROR(1); + + companion object { + fun ofRaw(raw: Int): State? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OneWelcomeNativeError ( + val code: String, + val message: String, + val details: Map + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OneWelcomeNativeError { + val code = list[0] as String + val message = list[1] as String + val details = list[2] as Map + return OneWelcomeNativeError(code, message, details) + } + } + fun toList(): List { + return listOf( + code, + message, + details, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class UserProfile ( + val profileId: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): UserProfile { + val profileId = list[0] as String + return UserProfile(profileId) + } + } + fun toList(): List { + return listOf( + profileId, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class UserProfilesResult ( + val state: State, + val success: List? = null, + val error: OneWelcomeNativeError? = null + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): UserProfilesResult { + val state = State.ofRaw(list[0] as Int)!! + val success = list[1] as? List + val error: OneWelcomeNativeError? = (list[2] as? List)?.let { + OneWelcomeNativeError.fromList(it) + } + return UserProfilesResult(state, success, error) + } + } + fun toList(): List { + return listOf( + state?.raw, + success, + error?.toList(), + ) + } +} + /** Generated class from Pigeon that represents data sent in messages. */ data class PigeonUserProfile ( val profileId: String, @@ -50,19 +140,46 @@ private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { 128.toByte() -> { + return (readValue(buffer) as? List)?.let { + OneWelcomeNativeError.fromList(it) + } + } + 129.toByte() -> { return (readValue(buffer) as? List)?.let { PigeonUserProfile.fromList(it) } } + 130.toByte() -> { + return (readValue(buffer) as? List)?.let { + UserProfile.fromList(it) + } + } + 131.toByte() -> { + return (readValue(buffer) as? List)?.let { + UserProfilesResult.fromList(it) + } + } else -> super.readValueOfType(type, buffer) } } override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { when (value) { - is PigeonUserProfile -> { + is OneWelcomeNativeError -> { stream.write(128) writeValue(stream, value.toList()) } + is PigeonUserProfile -> { + stream.write(129) + writeValue(stream, value.toList()) + } + is UserProfile -> { + stream.write(130) + writeValue(stream, value.toList()) + } + is UserProfilesResult -> { + stream.write(131) + writeValue(stream, value.toList()) + } else -> super.writeValue(stream, value) } } @@ -75,6 +192,7 @@ private object UserClientApiCodec : StandardMessageCodec() { */ interface UserClientApi { fun fetchUserProfiles(callback: (Result>) -> Unit) + fun testFunction(callback: (Result) -> Unit) companion object { /** The codec used by UserClientApi. */ @@ -103,6 +221,25 @@ interface UserClientApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.testFunction", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.testFunction() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } } } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index eaa69574..9c1e3f86 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -25,12 +25,90 @@ private func wrapError(_ error: Any) -> [Any?] { ] } return [ - "\(error)", "\(type(of: error))", + "\(error)", "Stacktrace: \(Thread.callStackSymbols)" ] } +enum State: Int { + case success = 0 + case error = 1 +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OneWelcomeNativeError { + var code: String + var message: String + var details: [String?: Any?] + + static func fromList(_ list: [Any?]) -> OneWelcomeNativeError? { + let code = list[0] as! String + let message = list[1] as! String + let details = list[2] as! [String?: Any?] + + return OneWelcomeNativeError( + code: code, + message: message, + details: details + ) + } + func toList() -> [Any?] { + return [ + code, + message, + details, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct UserProfile { + var profileId: String + + static func fromList(_ list: [Any?]) -> UserProfile? { + let profileId = list[0] as! String + + return UserProfile( + profileId: profileId + ) + } + func toList() -> [Any?] { + return [ + profileId, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct UserProfilesResult { + var state: State + var success: [UserProfile?]? = nil + var error: OneWelcomeNativeError? = nil + + static func fromList(_ list: [Any?]) -> UserProfilesResult? { + let state = State(rawValue: list[0] as! Int)! + let success = list[1] as? [UserProfile?] + var error: OneWelcomeNativeError? = nil + if let errorList = list[2] as? [Any?] { + error = OneWelcomeNativeError.fromList(errorList) + } + + return UserProfilesResult( + state: state, + success: success, + error: error + ) + } + func toList() -> [Any?] { + return [ + state.rawValue, + success, + error?.toList(), + ] + } +} + /// Generated class from Pigeon that represents data sent in messages. struct PigeonUserProfile { var profileId: String @@ -57,7 +135,13 @@ private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: + return OneWelcomeNativeError.fromList(self.readValue() as! [Any]) + case 129: return PigeonUserProfile.fromList(self.readValue() as! [Any]) + case 130: + return UserProfile.fromList(self.readValue() as! [Any]) + case 131: + return UserProfilesResult.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) } @@ -66,9 +150,18 @@ private class UserClientApiCodecReader: FlutterStandardReader { private class UserClientApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? PigeonUserProfile { + if let value = value as? OneWelcomeNativeError { super.writeByte(128) super.writeValue(value.toList()) + } else if let value = value as? PigeonUserProfile { + super.writeByte(129) + super.writeValue(value.toList()) + } else if let value = value as? UserProfile { + super.writeByte(130) + super.writeValue(value.toList()) + } else if let value = value as? UserProfilesResult { + super.writeByte(131) + super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -94,6 +187,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) + func testFunction(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -117,6 +211,21 @@ class UserClientApiSetup { } else { fetchUserProfilesChannel.setMessageHandler(nil) } + let testFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.testFunction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + testFunctionChannel.setMessageHandler { _, reply in + api.testFunction() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + testFunctionChannel.setMessageHandler(nil) + } } } /// Native calls Flutter diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 996aad6d..5200bf58 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v8.0.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import @@ -8,6 +8,96 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +enum State { + success, + error, +} + +class OneWelcomeNativeError { + OneWelcomeNativeError({ + required this.code, + required this.message, + required this.details, + }); + + String code; + + String message; + + Map details; + + Object encode() { + return [ + code, + message, + details, + ]; + } + + static OneWelcomeNativeError decode(Object result) { + result as List; + return OneWelcomeNativeError( + code: result[0]! as String, + message: result[1]! as String, + details: (result[2] as Map?)!.cast(), + ); + } +} + +class UserProfile { + UserProfile({ + required this.profileId, + }); + + String profileId; + + Object encode() { + return [ + profileId, + ]; + } + + static UserProfile decode(Object result) { + result as List; + return UserProfile( + profileId: result[0]! as String, + ); + } +} + +class UserProfilesResult { + UserProfilesResult({ + required this.state, + this.success, + this.error, + }); + + State state; + + List? success; + + OneWelcomeNativeError? error; + + Object encode() { + return [ + state.index, + success, + error?.encode(), + ]; + } + + static UserProfilesResult decode(Object result) { + result as List; + return UserProfilesResult( + state: State.values[result[0]! as int], + success: (result[1] as List?)?.cast(), + error: result[2] != null + ? OneWelcomeNativeError.decode(result[2]! as List) + : null, + ); + } +} + class PigeonUserProfile { PigeonUserProfile({ required this.profileId, @@ -38,9 +128,18 @@ class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is PigeonUserProfile) { + if (value is OneWelcomeNativeError) { buffer.putUint8(128); writeValue(buffer, value.encode()); + } else if (value is PigeonUserProfile) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else if (value is UserProfile) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else if (value is UserProfilesResult) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -50,7 +149,13 @@ class _UserClientApiCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: + return OneWelcomeNativeError.decode(readValue(buffer)!); + case 129: return PigeonUserProfile.decode(readValue(buffer)!); + case 130: + return UserProfile.decode(readValue(buffer)!); + case 131: + return UserProfilesResult.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -94,6 +199,33 @@ class UserClientApi { return (replyList[0] as List?)!.cast(); } } + + Future testFunction() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.testFunction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as UserProfilesResult?)!; + } + } } /// Native calls Flutter diff --git a/pigeons/README.md b/pigeons/README.md index ae65c409..48ba1f46 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -21,6 +21,9 @@ https://github.com/flutter/packages/pull/3084 Currently, it is not possible to send custom platform exceptions back using the (code, message, details) structure. This PR is requesting it and we hope it gets added soon: https://github.com/flutter/flutter/issues/120861 +PR Fixing the limitation +https://github.com/flutter/packages/pull/3234 + ### Triggering event functions from Native We can use @FlutterApi to call functions on the dart side from the Native parts. However, as always this is not ducumented but there is an open documentation issue that gives some references with more information https://github.com/flutter/flutter/issues/108531 diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart index 356a616d..16ac236c 100644 --- a/pigeons/userProfile.dart +++ b/pigeons/userProfile.dart @@ -14,11 +14,49 @@ import 'package:pigeon/pigeon.dart'; // ), // )) +// Error Class +class OneWelcomeNativeError { + String code; + String message; + Map details; + + OneWelcomeNativeError( + {required this.code, required this.message, required this.details}); +} + +// Return Objects +class UserProfile { + String profileId; + + UserProfile({required this.profileId}); +} + +// Results +enum State { + success, + error, +} + +// class Result { +// State state; +// OneWelcomeNativeError? error; + +// Result({required this.state}); +// } + +class UserProfilesResult { + State state; + List? success; + OneWelcomeNativeError? error; + + UserProfilesResult({required this.state}); +} + class PigeonUserProfile { String profileId; bool isDefault; - PigeonUserProfile({ required this.profileId, required this.isDefault}); + PigeonUserProfile({required this.profileId, required this.isDefault}); } /// Flutter calls native @@ -26,11 +64,14 @@ class PigeonUserProfile { abstract class UserClientApi { @async List fetchUserProfiles(); + + @async + UserProfilesResult testFunction(); } /// Native calls Flutter @FlutterApi() -abstract class NativeCallFlutterApi{ +abstract class NativeCallFlutterApi { @async String testEventFunction(String argument); } diff --git a/pubspec.yaml b/pubspec.yaml index 16ddbd32..673e3a37 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,7 +12,11 @@ dependencies: sdk: flutter dev_dependencies: - pigeon: ^8.0.0 + pigeon: + git: + url: git@github.com:flutter/packages.git + path: packages/pigeon + ref: 4294185774d8b88989b6a21f9ad9cfc20be4af7b flutter_test: sdk: flutter From 5ba1a16b4fc7f695c116a9898c7352b3c94b243f Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 23 Feb 2023 13:36:30 +0100 Subject: [PATCH 007/364] FP-20 WIP --- .../mobile/sdk/flutter/OneginiPlugin.kt | 15 -- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 131 +---------------- ios/Classes/Pigeon.swift | 111 +-------------- lib/pigeon.dart | 134 +----------------- lib/user_client.dart | 2 + pigeons/userProfile.dart | 39 ----- 6 files changed, 5 insertions(+), 427 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index ea960356..8c30465f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -1,18 +1,12 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule -import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserProfilesResult import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel -import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MethodChannel import javax.inject.Inject @@ -73,13 +67,4 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { // val a = Result.failure>(Exception("meee", Throwable("boop"))) callback(a) } - - override fun testFunction(callback: (Result) -> Unit) { -// val a = Result.success(listOf(UserProfilesResult(success = Us, true))) -// val b = FlutterException() Exception("meesage").Fl - -// val a = Result.failure>(Exception("ghallo") -// ()) -// callback(a) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 5e18f722..bd8bce19 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -31,88 +31,6 @@ private fun wrapError(exception: Throwable): List { ) } -enum class State(val raw: Int) { - SUCCESS(0), - ERROR(1); - - companion object { - fun ofRaw(raw: Int): State? { - return values().firstOrNull { it.raw == raw } - } - } -} - -/** Generated class from Pigeon that represents data sent in messages. */ -data class OneWelcomeNativeError ( - val code: String, - val message: String, - val details: Map - -) { - companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): OneWelcomeNativeError { - val code = list[0] as String - val message = list[1] as String - val details = list[2] as Map - return OneWelcomeNativeError(code, message, details) - } - } - fun toList(): List { - return listOf( - code, - message, - details, - ) - } -} - -/** Generated class from Pigeon that represents data sent in messages. */ -data class UserProfile ( - val profileId: String - -) { - companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): UserProfile { - val profileId = list[0] as String - return UserProfile(profileId) - } - } - fun toList(): List { - return listOf( - profileId, - ) - } -} - -/** Generated class from Pigeon that represents data sent in messages. */ -data class UserProfilesResult ( - val state: State, - val success: List? = null, - val error: OneWelcomeNativeError? = null - -) { - companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): UserProfilesResult { - val state = State.ofRaw(list[0] as Int)!! - val success = list[1] as? List - val error: OneWelcomeNativeError? = (list[2] as? List)?.let { - OneWelcomeNativeError.fromList(it) - } - return UserProfilesResult(state, success, error) - } - } - fun toList(): List { - return listOf( - state?.raw, - success, - error?.toList(), - ) - } -} - /** Generated class from Pigeon that represents data sent in messages. */ data class PigeonUserProfile ( val profileId: String, @@ -140,44 +58,17 @@ private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { 128.toByte() -> { - return (readValue(buffer) as? List)?.let { - OneWelcomeNativeError.fromList(it) - } - } - 129.toByte() -> { return (readValue(buffer) as? List)?.let { PigeonUserProfile.fromList(it) } } - 130.toByte() -> { - return (readValue(buffer) as? List)?.let { - UserProfile.fromList(it) - } - } - 131.toByte() -> { - return (readValue(buffer) as? List)?.let { - UserProfilesResult.fromList(it) - } - } else -> super.readValueOfType(type, buffer) } } override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { when (value) { - is OneWelcomeNativeError -> { - stream.write(128) - writeValue(stream, value.toList()) - } is PigeonUserProfile -> { - stream.write(129) - writeValue(stream, value.toList()) - } - is UserProfile -> { - stream.write(130) - writeValue(stream, value.toList()) - } - is UserProfilesResult -> { - stream.write(131) + stream.write(128) writeValue(stream, value.toList()) } else -> super.writeValue(stream, value) @@ -192,7 +83,6 @@ private object UserClientApiCodec : StandardMessageCodec() { */ interface UserClientApi { fun fetchUserProfiles(callback: (Result>) -> Unit) - fun testFunction(callback: (Result) -> Unit) companion object { /** The codec used by UserClientApi. */ @@ -221,25 +111,6 @@ interface UserClientApi { channel.setMessageHandler(null) } } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.testFunction", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.testFunction() { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } } } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 9c1e3f86..27839eac 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -31,84 +31,6 @@ private func wrapError(_ error: Any) -> [Any?] { ] } -enum State: Int { - case success = 0 - case error = 1 -} - -/// Generated class from Pigeon that represents data sent in messages. -struct OneWelcomeNativeError { - var code: String - var message: String - var details: [String?: Any?] - - static func fromList(_ list: [Any?]) -> OneWelcomeNativeError? { - let code = list[0] as! String - let message = list[1] as! String - let details = list[2] as! [String?: Any?] - - return OneWelcomeNativeError( - code: code, - message: message, - details: details - ) - } - func toList() -> [Any?] { - return [ - code, - message, - details, - ] - } -} - -/// Generated class from Pigeon that represents data sent in messages. -struct UserProfile { - var profileId: String - - static func fromList(_ list: [Any?]) -> UserProfile? { - let profileId = list[0] as! String - - return UserProfile( - profileId: profileId - ) - } - func toList() -> [Any?] { - return [ - profileId, - ] - } -} - -/// Generated class from Pigeon that represents data sent in messages. -struct UserProfilesResult { - var state: State - var success: [UserProfile?]? = nil - var error: OneWelcomeNativeError? = nil - - static func fromList(_ list: [Any?]) -> UserProfilesResult? { - let state = State(rawValue: list[0] as! Int)! - let success = list[1] as? [UserProfile?] - var error: OneWelcomeNativeError? = nil - if let errorList = list[2] as? [Any?] { - error = OneWelcomeNativeError.fromList(errorList) - } - - return UserProfilesResult( - state: state, - success: success, - error: error - ) - } - func toList() -> [Any?] { - return [ - state.rawValue, - success, - error?.toList(), - ] - } -} - /// Generated class from Pigeon that represents data sent in messages. struct PigeonUserProfile { var profileId: String @@ -135,13 +57,7 @@ private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: - return OneWelcomeNativeError.fromList(self.readValue() as! [Any]) - case 129: return PigeonUserProfile.fromList(self.readValue() as! [Any]) - case 130: - return UserProfile.fromList(self.readValue() as! [Any]) - case 131: - return UserProfilesResult.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) } @@ -150,18 +66,9 @@ private class UserClientApiCodecReader: FlutterStandardReader { private class UserClientApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? OneWelcomeNativeError { + if let value = value as? PigeonUserProfile { super.writeByte(128) super.writeValue(value.toList()) - } else if let value = value as? PigeonUserProfile { - super.writeByte(129) - super.writeValue(value.toList()) - } else if let value = value as? UserProfile { - super.writeByte(130) - super.writeValue(value.toList()) - } else if let value = value as? UserProfilesResult { - super.writeByte(131) - super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -187,7 +94,6 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) - func testFunction(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -211,21 +117,6 @@ class UserClientApiSetup { } else { fetchUserProfilesChannel.setMessageHandler(nil) } - let testFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.testFunction", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - testFunctionChannel.setMessageHandler { _, reply in - api.testFunction() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - testFunctionChannel.setMessageHandler(nil) - } } } /// Native calls Flutter diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 5200bf58..1e93d1ce 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -8,96 +8,6 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; -enum State { - success, - error, -} - -class OneWelcomeNativeError { - OneWelcomeNativeError({ - required this.code, - required this.message, - required this.details, - }); - - String code; - - String message; - - Map details; - - Object encode() { - return [ - code, - message, - details, - ]; - } - - static OneWelcomeNativeError decode(Object result) { - result as List; - return OneWelcomeNativeError( - code: result[0]! as String, - message: result[1]! as String, - details: (result[2] as Map?)!.cast(), - ); - } -} - -class UserProfile { - UserProfile({ - required this.profileId, - }); - - String profileId; - - Object encode() { - return [ - profileId, - ]; - } - - static UserProfile decode(Object result) { - result as List; - return UserProfile( - profileId: result[0]! as String, - ); - } -} - -class UserProfilesResult { - UserProfilesResult({ - required this.state, - this.success, - this.error, - }); - - State state; - - List? success; - - OneWelcomeNativeError? error; - - Object encode() { - return [ - state.index, - success, - error?.encode(), - ]; - } - - static UserProfilesResult decode(Object result) { - result as List; - return UserProfilesResult( - state: State.values[result[0]! as int], - success: (result[1] as List?)?.cast(), - error: result[2] != null - ? OneWelcomeNativeError.decode(result[2]! as List) - : null, - ); - } -} - class PigeonUserProfile { PigeonUserProfile({ required this.profileId, @@ -128,18 +38,9 @@ class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is OneWelcomeNativeError) { + if (value is PigeonUserProfile) { buffer.putUint8(128); writeValue(buffer, value.encode()); - } else if (value is PigeonUserProfile) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is UserProfile) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is UserProfilesResult) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -149,13 +50,7 @@ class _UserClientApiCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return OneWelcomeNativeError.decode(readValue(buffer)!); - case 129: return PigeonUserProfile.decode(readValue(buffer)!); - case 130: - return UserProfile.decode(readValue(buffer)!); - case 131: - return UserProfilesResult.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -199,33 +94,6 @@ class UserClientApi { return (replyList[0] as List?)!.cast(); } } - - Future testFunction() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.testFunction', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as UserProfilesResult?)!; - } - } } /// Native calls Flutter diff --git a/lib/user_client.dart b/lib/user_client.dart index f92c84aa..9e349e14 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,8 +1,10 @@ import 'dart:convert'; +import 'dart:ffi'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/model/registration_response.dart'; +import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/oneginiAppToWebSingleSignOn.dart'; diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart index 16ac236c..99baa115 100644 --- a/pigeons/userProfile.dart +++ b/pigeons/userProfile.dart @@ -15,42 +15,6 @@ import 'package:pigeon/pigeon.dart'; // )) // Error Class -class OneWelcomeNativeError { - String code; - String message; - Map details; - - OneWelcomeNativeError( - {required this.code, required this.message, required this.details}); -} - -// Return Objects -class UserProfile { - String profileId; - - UserProfile({required this.profileId}); -} - -// Results -enum State { - success, - error, -} - -// class Result { -// State state; -// OneWelcomeNativeError? error; - -// Result({required this.state}); -// } - -class UserProfilesResult { - State state; - List? success; - OneWelcomeNativeError? error; - - UserProfilesResult({required this.state}); -} class PigeonUserProfile { String profileId; @@ -64,9 +28,6 @@ class PigeonUserProfile { abstract class UserClientApi { @async List fetchUserProfiles(); - - @async - UserProfilesResult testFunction(); } /// Native calls Flutter From 4ece4a486456fd8d78f0867eedf0da9ba56670f7 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 23 Feb 2023 14:05:46 +0100 Subject: [PATCH 008/364] FP-20 WIP --- .../kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 8c30465f..02d67df8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -7,6 +7,7 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MethodChannel import javax.inject.Inject @@ -65,6 +66,7 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) // val a = Result.failure>(Exception("meee", Throwable("boop"))) - callback(a) + callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) + callback(Result.failure(Exception("meee", Throwable("boop")))) } } From 64684f1422cb545ab1e20b311467601f8985dd2e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 2 Mar 2023 11:25:32 +0100 Subject: [PATCH 009/364] FP-61: Move ChangePin into a useCase + tests --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 17 +---- .../sdk/flutter/OneginiMethodsWrapper.kt | 5 ++ .../sdk/flutter/useCases/ChangePinUseCase.kt | 27 +++++++ .../mobile/sdk/ChangePinUseCaseTests.kt | 75 +++++++++++++++++++ 4 files changed, 108 insertions(+), 16 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 9830503a..4e504c02 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -84,7 +84,7 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: Constants.METHOD_GET_UNAUTHENTICATED_RESOURCE -> oneginiMethodsWrapper.getUnauthenticatedResource(call, result) // Other - Constants.METHOD_CHANGE_PIN -> startChangePinFlow(result, client) + Constants.METHOD_CHANGE_PIN -> oneginiMethodsWrapper.changePin(result) Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> getAppToWebSingleSignOn(call.argument("url"), result, client) Constants.METHOD_GET_USER_PROFILES -> oneginiMethodsWrapper.getUserProfiles(result) Constants.METHOD_GET_ACCESS_TOKEN -> oneginiMethodsWrapper.getAccessToken(result) @@ -143,19 +143,4 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: } ) } - - fun startChangePinFlow(result: MethodChannel.Result, oneginiClient: OneginiClient) { - oneginiClient.userClient.changePin(object : OneginiChangePinHandler { - override fun onSuccess() { - result.success("Pin change successfully") - } - - override fun onError(error: OneginiChangePinError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) - } - }) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 9b8b0b33..6e4ff9a5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -14,6 +14,7 @@ class OneginiMethodsWrapper @Inject constructor( private val authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase, private val authenticateUserUseCase: AuthenticateUserUseCase, private val cancelCustomRegistrationActionUseCase: CancelCustomRegistrationActionUseCase, + private val changePinUseCase: ChangePinUseCase, private val deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase, private val deregisterUserUseCase: DeregisterUserUseCase, private val getAccessTokenUseCase: GetAccessTokenUseCase, @@ -150,4 +151,8 @@ class OneginiMethodsWrapper @Inject constructor( fun logout(result: MethodChannel.Result) { logoutUseCase(result) } + + fun changePin(result: MethodChannel.Result) { + changePinUseCase(result) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt new file mode 100644 index 00000000..a617dd15 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt @@ -0,0 +1,27 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import io.flutter.plugin.common.MethodChannel +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ChangePinUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(result: MethodChannel.Result) { + oneginiSDK.oneginiClient.userClient.changePin(object : OneginiChangePinHandler { + override fun onSuccess() { + result.success(null) + } + + override fun onError(error: OneginiChangePinError) { + SdkError( + code = error.errorType, + message = error.message + ).flutterError(result) + } + }) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt new file mode 100644 index 00000000..d1e56366 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -0,0 +1,75 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.client.OneginiClient +import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class ChangePinUseCaseTests { + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var clientMock: OneginiClient + + @Mock + lateinit var callMock: MethodCall + + @Mock + lateinit var resultMock: MethodChannel.Result + + @Mock + lateinit var oneginiChangePinError: OneginiChangePinError + + lateinit var changePinUseCase: ChangePinUseCase + + @Before + fun setup() { + changePinUseCase = ChangePinUseCase(oneginiSdk) + setupErrorMock() + } + + @Test + fun `When onSuccess is called on OneginiChangePinHandler, Then should succeed with Null `() { + whenever(oneginiSdk.oneginiClient.userClient.changePin(any())).thenAnswer { + it.getArgument(0).onSuccess() + } + + changePinUseCase(resultMock) + + verify(resultMock).success(null) + } + + @Test + fun `When onError is called on OneginiChangePinHandler, Then should fail with that error `() { + whenever(oneginiSdk.oneginiClient.userClient.changePin(any())).thenAnswer { + it.getArgument(0).onError(oneginiChangePinError) + } + + changePinUseCase(resultMock) + + val message = oneginiChangePinError.message + verify(resultMock).error(eq(oneginiChangePinError.errorType.toString()), eq(message), any()) + } + + private fun setupErrorMock() { + whenever(oneginiChangePinError.message).thenReturn("message") + whenever(oneginiChangePinError.errorType).thenReturn(1000) + } +} From c8811c6f223022e93dca77e1e7625e5c055b2df0 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 2 Mar 2023 11:48:48 +0100 Subject: [PATCH 010/364] FP-63: Android: Move validatePinWithPolicy into useCase + tests --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 23 +---- .../sdk/flutter/OneginiMethodsWrapper.kt | 7 +- .../useCases/ValidatePinWithPolicyUseCase.kt | 37 +++++++ .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 99 +++++++++++++++++++ 4 files changed, 143 insertions(+), 23 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 4e504c02..6b5c393f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -64,6 +64,7 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: Constants.METHOD_ACCEPT_PIN_AUTHENTICATION_REQUEST -> PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(call.argument("pin")?.toCharArray()) Constants.METHOD_DENY_PIN_AUTHENTICATION_REQUEST -> PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) + Constants.METHOD_VALIDATE_PIN_WITH_POLICY -> oneginiMethodsWrapper.validatePinWithPolicy(call, result) // Fingerprint Constants.METHOD_ACCEPT_FINGERPRINT_AUTHENTICATION_REQUEST -> FingerprintAuthenticationRequestHandler.fingerprintCallback?.acceptAuthenticationRequest() @@ -91,32 +92,10 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: Constants.METHOD_GET_AUTHENTICATED_USER_PROFILE -> oneginiMethodsWrapper.getAuthenticatedUserProfile(result) Constants.METHOD_GET_REDIRECT_URL -> oneginiMethodsWrapper.getRedirectUrl(result) - Constants.METHOD_VALIDATE_PIN_WITH_POLICY -> validatePinWithPolicy(call.argument("pin")?.toCharArray(), result, client) - else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } - private fun validatePinWithPolicy(pin: CharArray?, result: MethodChannel.Result, oneginiClient: OneginiClient) { - val nonNullPin = pin ?: return SdkError(ARGUMENT_NOT_CORRECT.code, ARGUMENT_NOT_CORRECT.message + " pin is null").flutterError(result) - - oneginiClient.userClient.validatePinWithPolicy( - nonNullPin, - object : OneginiPinValidationHandler { - override fun onSuccess() { - result.success(true) - } - - override fun onError(oneginiPinValidationError: OneginiPinValidationError) { - SdkError( - code = oneginiPinValidationError.errorType, - message = oneginiPinValidationError.message - ).flutterError(result) - } - } - ) - } - fun getAppToWebSingleSignOn(url: String?, result: MethodChannel.Result, oneginiClient: OneginiClient) { if (url == null) { SdkError(URL_CANT_BE_NULL).flutterError(result) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 6e4ff9a5..ba12514d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -37,7 +37,8 @@ class OneginiMethodsWrapper @Inject constructor( private val resourceHelper: ResourceHelper, private val setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase, private val startAppUseCase: StartAppUseCase, - private val submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase + private val submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase, + private val validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase, ) { fun registerUser(call: MethodCall, result: MethodChannel.Result) { @@ -148,6 +149,10 @@ class OneginiMethodsWrapper @Inject constructor( isAuthenticatorRegisteredUseCase(call, result) } + fun validatePinWithPolicy(call: MethodCall, result: MethodChannel.Result) { + validatePinWithPolicyUseCase(call, result) + } + fun logout(result: MethodChannel.Result) { logoutUseCase(result) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt new file mode 100644 index 00000000..7a0ea709 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt @@ -0,0 +1,37 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ValidatePinWithPolicyUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(call: MethodCall, result: MethodChannel.Result) { + val nonNullPin = call.argument("pin")?.toCharArray() ?: return SdkError( + OneWelcomeWrapperErrors.ARGUMENT_NOT_CORRECT.code, + OneWelcomeWrapperErrors.ARGUMENT_NOT_CORRECT.message + " pin is null" + ).flutterError(result) + + oneginiSDK.oneginiClient.userClient.validatePinWithPolicy( + nonNullPin, + object : OneginiPinValidationHandler { + override fun onSuccess() { + result.success(null) + } + + override fun onError(oneginiPinValidationError: OneginiPinValidationError) { + SdkError( + code = oneginiPinValidationError.errorType, + message = oneginiPinValidationError.message + ).flutterError(result) + } + } + ) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt new file mode 100644 index 00000000..5c49684c --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -0,0 +1,99 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.client.OneginiClient +import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class ValidatePinWithPolicyUseCaseTests { + + @Mock + lateinit var oneginiPinValidationErrorMock: OneginiPinValidationError + + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var clientMock: OneginiClient + @Mock + lateinit var callMock: MethodCall + + @Mock + lateinit var resultMock: MethodChannel.Result + + lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase + + @Before + fun attach() { + validatePinWithPolicyUseCase = ValidatePinWithPolicyUseCase(oneginiSdk) + } + + + @Test + fun `When supplying null as pin, Then should reject with ARGUMENT_NOT_CORRECT error`() { + whenever(callMock.argument("pin")).thenReturn(null) + + validatePinWithPolicyUseCase(callMock, resultMock) + + val message = ARGUMENT_NOT_CORRECT.message + " pin is null" + verify(resultMock).error(eq(ARGUMENT_NOT_CORRECT.code.toString()), eq(message), any()) + } + + @Test + fun `When pin is not null should call validatePinWithPolicy on the onegini sdk`() { + whenever(callMock.argument("pin")).thenReturn("14789") + + validatePinWithPolicyUseCase(callMock, resultMock) + + verify(oneginiSdk.oneginiClient.userClient).validatePinWithPolicy(eq("14789".toCharArray()), any()) + } + + @Test + fun `When oginini validatePinWithPolicy calls onSuccess on the handler, promise should resolve with null`() { + whenever(callMock.argument("pin")).thenReturn("14789") + whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { + it.getArgument(1).onSuccess() + } + + validatePinWithPolicyUseCase(callMock, resultMock) + + verify(resultMock).success(null) + } + + @Test + fun `When oginini validatePinWithPolicy calls onError on the handler, promise should reject with error from native sdk`() { + whenever(callMock.argument("pin")).thenReturn("14789") + whenPinValidationReturnedError() + + validatePinWithPolicyUseCase(callMock, resultMock) + + val message = oneginiPinValidationErrorMock.message + verify(resultMock).error(eq(oneginiPinValidationErrorMock.errorType.toString()), eq(message), any()) + } + + private fun whenPinValidationReturnedError() { + val errorCode = 111 + val errorMessage = "message" + whenever(oneginiPinValidationErrorMock.errorType).thenReturn(errorCode) + whenever(oneginiPinValidationErrorMock.message).thenReturn(errorMessage) + whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { + it.getArgument(1).onError(oneginiPinValidationErrorMock) + } + } +} From a450a0645f1211a2e55e443c5aa5e0e28b4fff3d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 2 Mar 2023 11:51:13 +0100 Subject: [PATCH 011/364] FP-63: Update example app to new validatePin api --- example/lib/screens/pin_request_screen.dart | 24 ++++++++++----------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index ace1e64e..e8f675b3 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -83,7 +83,7 @@ class _PinRequestScreenState extends State { ); } } else { - bool isSuccess = await Onegini.instance.userClient + await Onegini.instance.userClient .validatePinWithPolicy(pin) .catchError((error) { if (error is PlatformException) { @@ -91,18 +91,16 @@ class _PinRequestScreenState extends State { showFlutterToast(error.message); } }); - if (isSuccess != null && isSuccess) { - Navigator.of(context) - ..pop() - ..push( - MaterialPageRoute( - builder: (context) => PinRequestScreen( - confirmation: true, - previousCode: pin, - customAuthenticator: this.widget.customAuthenticator, - )), - ); - } + Navigator.of(context) + ..pop() + ..push( + MaterialPageRoute( + builder: (context) => PinRequestScreen( + confirmation: true, + previousCode: pin, + customAuthenticator: this.widget.customAuthenticator, + )), + ); } } From cb7ab23000b8874549eb6814b57b1824990a408e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 2 Mar 2023 11:57:36 +0100 Subject: [PATCH 012/364] FP-63: Change dart api for validatePinWithPolicy --- lib/user_client.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index 3c95ab26..fa486219 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -311,7 +311,7 @@ class UserClient { } } - Future validatePinWithPolicy(String pin) async { + Future validatePinWithPolicy(String pin) async { try { var success = await Onegini.instance.channel.invokeMethod( Constants.validatePinWithPolicy, {'pin': pin}); From d4536ed39e93b8ace3f49e6a532136c03099d5b1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 2 Mar 2023 14:05:50 +0100 Subject: [PATCH 013/364] FP-62: Android: Move SSO into a useCase and add Tests --- .../flutter/FlutterOneWelcomeSdkComponent.kt | 3 +- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 29 +--- .../sdk/flutter/OneginiMethodsWrapper.kt | 5 + .../mobile/sdk/flutter/facade/UriFacade.kt | 8 ++ .../sdk/flutter/facade/UriFacadeImpl.kt | 17 +++ .../mobile/sdk/flutter/module/FacadeModule.kt | 13 ++ .../GetAppToWebSingleSignOnUseCase.kt | 46 ++++++ .../GetAppToWebSingleSignOnUseCaseTests.kt | 135 ++++++++++++++++++ 8 files changed, 227 insertions(+), 29 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt index 7b452cbd..6f847e58 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt @@ -1,10 +1,11 @@ package com.onegini.mobile.sdk.flutter +import com.onegini.mobile.sdk.flutter.module.FacadeModule import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule import dagger.Component import javax.inject.Singleton -@Component(modules = [FlutterOneWelcomeSdkModule::class]) +@Component(modules = [FlutterOneWelcomeSdkModule::class, FacadeModule::class]) @Singleton interface FlutterOneWelcomeSdkComponent { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 6b5c393f..872c573a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -86,7 +86,7 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: // Other Constants.METHOD_CHANGE_PIN -> oneginiMethodsWrapper.changePin(result) - Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> getAppToWebSingleSignOn(call.argument("url"), result, client) + Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> oneginiMethodsWrapper.getAppToWebSingleSignOn(call, result) Constants.METHOD_GET_USER_PROFILES -> oneginiMethodsWrapper.getUserProfiles(result) Constants.METHOD_GET_ACCESS_TOKEN -> oneginiMethodsWrapper.getAccessToken(result) Constants.METHOD_GET_AUTHENTICATED_USER_PROFILE -> oneginiMethodsWrapper.getAuthenticatedUserProfile(result) @@ -95,31 +95,4 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } - - fun getAppToWebSingleSignOn(url: String?, result: MethodChannel.Result, oneginiClient: OneginiClient) { - if (url == null) { - SdkError(URL_CANT_BE_NULL).flutterError(result) - return - } - if (!Patterns.WEB_URL.matcher(url).matches()) { - SdkError(MALFORMED_URL).flutterError(result) - return - } - val targetUri: Uri = Uri.parse(url) - oneginiClient.userClient.getAppToWebSingleSignOn( - targetUri, - object : OneginiAppToWebSingleSignOnHandler { - override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { - result.success(Gson().toJson(mapOf("token" to oneginiAppToWebSingleSignOn.token, "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString()))) - } - - override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { - SdkError( - code = oneginiSingleSignOnError.errorType, - message = oneginiSingleSignOnError.message - ).flutterError(result) - } - } - ) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index ba12514d..5912591d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -27,6 +27,7 @@ class OneginiMethodsWrapper @Inject constructor( private val getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase, private val getResourceAnonymousUseCase: GetResourceAnonymousUseCase, private val getResourceUseCase: GetResourceUseCase, + private val getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase, private val getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase, private val getUserProfilesUseCase: GetUserProfilesUseCase, private val handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase, @@ -160,4 +161,8 @@ class OneginiMethodsWrapper @Inject constructor( fun changePin(result: MethodChannel.Result) { changePinUseCase(result) } + + fun getAppToWebSingleSignOn(call: MethodCall, result: MethodChannel.Result) { + getAppToWebSingleSignOnUseCase(call, result) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt new file mode 100644 index 00000000..f1101d65 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt @@ -0,0 +1,8 @@ +package com.onegini.mobile.sdk.flutter.facade + +import android.net.Uri + +interface UriFacade { + fun parse(string: String): Uri + fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt new file mode 100644 index 00000000..a1fa14a7 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt @@ -0,0 +1,17 @@ + +package com.onegini.mobile.sdk.flutter.facade + +import javax.inject.Singleton +import javax.inject.Inject +import android.net.Uri + +@Singleton +class UriFacadeImpl @Inject constructor() : UriFacade { + override fun parse(string: String): Uri { + return Uri.parse(string) + } + + override fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri { + return Uri.withAppendedPath(baseUri, pathSegment) + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt new file mode 100644 index 00000000..61b4ea37 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt @@ -0,0 +1,13 @@ +package com.onegini.mobile.sdk.flutter.module + +import com.onegini.mobile.sdk.flutter.facade.UriFacade +import com.onegini.mobile.sdk.flutter.facade.UriFacadeImpl +import dagger.Binds +import dagger.Module + +@Module +interface FacadeModule { + + @Binds + fun bindUriFacade(uriFacade: UriFacadeImpl): UriFacade +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt new file mode 100644 index 00000000..33586491 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import android.util.Patterns +import com.google.gson.Gson +import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError +import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.MALFORMED_URL +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.URL_CANT_BE_NULL +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.facade.UriFacade +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GetAppToWebSingleSignOnUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val uriFacade: UriFacade) { + operator fun invoke(call: MethodCall, result: MethodChannel.Result) { + val url = call.argument("url") ?: return SdkError(URL_CANT_BE_NULL).flutterError(result) + val targetUri = uriFacade.parse(url) + oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( + targetUri, + object : OneginiAppToWebSingleSignOnHandler { + override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { + result.success( + Gson().toJson( + mapOf( + "token" to oneginiAppToWebSingleSignOn.token, + "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString() + ) + ) + ) + } + + override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { + SdkError( + code = oneginiSingleSignOnError.errorType, + message = oneginiSingleSignOnError.message + ).flutterError(result) + } + } + ) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt new file mode 100644 index 00000000..0e565fa8 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt @@ -0,0 +1,135 @@ +package com.onegini.mobile.sdk + +import android.net.Uri +import com.google.gson.Gson +import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError +import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.facade.UriFacade +import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import junit.framework.TestCase.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class GetAppToWebSingleSignOnUseCaseTests { + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var resultMock: MethodChannel.Result + + @Mock + lateinit var callMock: MethodCall + + @Mock + private lateinit var uriFacade: UriFacade + + // We need to deep stub here to mock a uri object's .toString() as we cant pass a uriFacade into the OneginiAppToWebSingleSignOn + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private lateinit var oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn + + @Mock + private lateinit var oneginiAppToWebSingleSignOnError: OneginiAppToWebSingleSignOnError + + @Mock + private lateinit var parsedUri: Uri + + private val correctUri = "https://login-mobile.test.onegini.com/personal/dashboard" + private val mockedTokenString = "mockedToken" + private val mockedRedirectUrlString = "mockedRedirectUrl" + + lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase + @Before + fun setup() { + getAppToWebSingleSignOnUseCase = GetAppToWebSingleSignOnUseCase(oneginiSdk, uriFacade) + } + + @Test + fun `When GetAppToWebSingleSignOn is called without a url argument, Then should fail with URL_CANT_BE_NULL error`() { + whenCalledWithNullUrl() + + getAppToWebSingleSignOnUseCase(callMock, resultMock) + + val message = URL_CANT_BE_NULL.message + verify(resultMock).error(eq(URL_CANT_BE_NULL.code.toString()), eq(message), any()) + } + + @Test + fun `When oginini getAppToWebSingleSignOn calls onSuccess on the handler, Then promise should resolve with a map containing the content from the result`() { + whenCalledWithUrl() + mockParseUri(correctUri) + mockSingleSignOnObject() + whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { + it.getArgument(1).onSuccess(oneginiAppToWebSingleSignOn) + } + + getAppToWebSingleSignOnUseCase(callMock, resultMock) + + val argumentCaptor = argumentCaptor() + verify(resultMock).success(argumentCaptor.capture()) + // This will be reworked after FP-20 when we actually send the objects + val expectedResult = Gson().toJson( + mapOf( + "token" to oneginiAppToWebSingleSignOn.token, + "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString() + ) + ) + assertEquals(argumentCaptor.firstValue, expectedResult) + + } + + @Test + fun `When oginini getAppToWebSingleSignOn calls onError on the handler, Then result should fail with the error message and code`() { + mockParseUri(correctUri) + whenCalledWithUrl() + whenSSOReturnsError() + + getAppToWebSingleSignOnUseCase(callMock, resultMock) + + val message = oneginiAppToWebSingleSignOnError.message + verify(resultMock).error(eq(oneginiAppToWebSingleSignOnError.errorType.toString()), eq(message), any()) + } + + + + private fun mockSingleSignOnObject() { + whenever(oneginiAppToWebSingleSignOn.token).thenReturn(mockedTokenString) + whenever(oneginiAppToWebSingleSignOn.redirectUrl.toString()).thenReturn(mockedRedirectUrlString) + } + + private fun whenSSOReturnsError() { + whenever(oneginiAppToWebSingleSignOnError.errorType).thenReturn(1000) + whenever(oneginiAppToWebSingleSignOnError.message).thenReturn("message") + whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { + it.getArgument(1).onError(oneginiAppToWebSingleSignOnError) + } + } + + private fun mockParseUri(uri: String) { + whenever(uriFacade.parse(uri)).thenReturn(parsedUri) + } + + private fun whenCalledWithUrl() { + whenever(callMock.argument("url")).thenReturn(correctUri) + } + + private fun whenCalledWithNullUrl() { + whenever(callMock.argument("url")).thenReturn(null) + } + +} \ No newline at end of file From 1c2aedaf42222019c891afc297d48f27e48d1538 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 2 Mar 2023 14:37:57 +0100 Subject: [PATCH 014/364] FP-20 WIP --- .../mobile/sdk/flutter/OneginiPlugin.kt | 9 ++++--- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 22 ++++++++++------ ios/Classes/Pigeon.swift | 4 +-- lib/pigeon.dart | 2 +- lib/user_client.dart | 2 -- pigeons/userProfile.dart | 25 +++++++++++++++++-- pubspec.yaml | 2 +- test/user_client_test.dart | 2 +- 8 files changed, 48 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 02d67df8..dc72a666 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -5,6 +5,7 @@ import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.FlutterException @@ -64,9 +65,11 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { // Fixme limitation on failure platform exception structure; see // https://github.com/flutter/flutter/issues/120861 override fun fetchUserProfiles(callback: (Result>) -> Unit) { - val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) +// val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) // val a = Result.failure>(Exception("meee", Throwable("boop"))) - callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) - callback(Result.failure(Exception("meee", Throwable("boop")))) +// callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) + val b = mutableMapOf() + b["lol"] = "derp" + callback(Result.failure(FlutterError("meee", "", b))) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index bd8bce19..4f2a886c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.1), do not edit directly. +// Autogenerated from Pigeon (v9.0.2), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin @@ -6,7 +6,6 @@ package com.onegini.mobile.sdk.flutter.pigeonPlugin import android.util.Log import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BinaryMessenger -import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MessageCodec import io.flutter.plugin.common.StandardMessageCodec import java.io.ByteArrayOutputStream @@ -17,20 +16,27 @@ private fun wrapResult(result: Any?): List { } private fun wrapError(exception: Throwable): List { - if (exception is FlutterException) { + if (exception is FlutterError) { return listOf( exception.code, exception.message, exception.details ) + } else { + return listOf( + exception.javaClass.simpleName, + exception.toString(), + "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) + ) } - return listOf( - exception.javaClass.simpleName, - exception.toString(), - "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) - ) } +class FlutterError ( + val code: String, + override val message: String? = null, + val details: Any? = null +) : Throwable() + /** Generated class from Pigeon that represents data sent in messages. */ data class PigeonUserProfile ( val profileId: String, diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 27839eac..d5267484 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.1), do not edit directly. +// Autogenerated from Pigeon (v9.0.2), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -25,8 +25,8 @@ private func wrapError(_ error: Any) -> [Any?] { ] } return [ - "\(type(of: error))", "\(error)", + "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)" ] } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 1e93d1ce..dd84a4c9 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.1), do not edit directly. +// Autogenerated from Pigeon (v9.0.2), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import diff --git a/lib/user_client.dart b/lib/user_client.dart index 5f96899b..61614984 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,10 +1,8 @@ import 'dart:convert'; -import 'dart:ffi'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/model/registration_response.dart'; -import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/oneginiAppToWebSingleSignOn.dart'; diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart index 99baa115..8252aa1a 100644 --- a/pigeons/userProfile.dart +++ b/pigeons/userProfile.dart @@ -1,3 +1,4 @@ +import 'package:onegini/model/registration_response.dart'; import 'package:pigeon/pigeon.dart'; // @ConfigurePigeon(PigeonOptions( @@ -14,8 +15,7 @@ import 'package:pigeon/pigeon.dart'; // ), // )) -// Error Class - +/// Result objects class PigeonUserProfile { String profileId; bool isDefault; @@ -23,9 +23,30 @@ class PigeonUserProfile { PigeonUserProfile({required this.profileId, required this.isDefault}); } +class PigeonCustomInfo { + int status; + String data; + + PigeonCustomInfo({required this.status, required this.data}); +} + +// class PigeonRegistrationResponse + /// Flutter calls native @HostApi() abstract class UserClientApi { + // example one + @async + List fetchUserProfiles(); + + // todo removed buildcontext + RegistrationResponse registerUser(String? identityProviderId, List? scopes); + + +} + +@HostApi() +abstract class ResourceMethodApi { @async List fetchUserProfiles(); } diff --git a/pubspec.yaml b/pubspec.yaml index 673e3a37..6b1fdb8c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ dev_dependencies: git: url: git@github.com:flutter/packages.git path: packages/pigeon - ref: 4294185774d8b88989b6a21f9ad9cfc20be4af7b + ref: 43bfaaf55c0bd6b550bf2cb9af940a00b046bd07 flutter_test: sdk: flutter diff --git a/test/user_client_test.dart b/test/user_client_test.dart index a0431133..5b4eb553 100644 --- a/test/user_client_test.dart +++ b/test/user_client_test.dart @@ -729,7 +729,7 @@ void main() { () async { //arrange setupMethodChannel(Constants.authenticateUserImplicitly, - Future.value('{"profileId":"1234"}')); + Future.value('1234')); var result = await userClient.authenticateUserImplicitly("1234", null); From 115d2d5cbd9a3f2c3bcbbbeae383686641074e50 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 2 Mar 2023 17:00:54 +0100 Subject: [PATCH 015/364] FP-20 WIP got android setup almost going --- .../mobile/sdk/flutter/OneginiPlugin.kt | 17 +- .../mobile/sdk/flutter/PigeonInterface.kt | 44 +++++ .../mobile/sdk/flutter/helpers/SdkError.kt | 4 +- .../useCases/FetchUserProfilesUseCase.kt | 11 -- ios/Classes/Pigeon.swift | 112 +++++++++++- lib/pigeon.dart | 124 +++++++++++++- pigeons/README.md | 2 +- pigeons/onewelcomePigeonInterface.dart | 160 ++++++++++++++++++ 8 files changed, 428 insertions(+), 46 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt create mode 100644 pigeons/onewelcomePigeonInterface.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index dc72a666..73657ab7 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -2,19 +2,16 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender -import com.onegini.mobile.sdk.flutter.pigeonPlugin.PigeonUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel -import io.flutter.plugin.common.FlutterException import io.flutter.plugin.common.MethodChannel import javax.inject.Inject /** OneginiPlugin */ -class OneginiPlugin : FlutterPlugin, UserClientApi { +class OneginiPlugin : FlutterPlugin, PigeonInterface() { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it @@ -60,16 +57,4 @@ class OneginiPlugin : FlutterPlugin, UserClientApi { UserClientApi.setUp(binding.binaryMessenger, null) channel.setMethodCallHandler(null) } - - // Example function on how it could be initiated on Flutter send to Native - // Fixme limitation on failure platform exception structure; see - // https://github.com/flutter/flutter/issues/120861 - override fun fetchUserProfiles(callback: (Result>) -> Unit) { -// val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) -// val a = Result.failure>(Exception("meee", Throwable("boop"))) -// callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) - val b = mutableMapOf() - b["lol"] = "derp" - callback(Result.failure(FlutterError("meee", "", b))) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt new file mode 100644 index 00000000..d360b405 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -0,0 +1,44 @@ +package com.onegini.mobile.sdk.flutter + +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OneWelcomeUserProfile +import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi + +open class PigeonInterface: UserClientApi { + // Example function on how it could be initiated on Flutter send to Native + override fun fetchUserProfiles(callback: (Result>) -> Unit) { +// val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) +// val a = Result.failure>(Exception("meee", Throwable("boop"))) +// callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) + val b = mutableMapOf() + b["lol"] = "derp" + +// val c = Result.failure>(FlutterError("meee", "hallo", b)).exceptionOrNull() + +// callback(Result.failure(FlutterError("meee", "hallo", b))) + + + + val a = Result.success(listOf(OneWelcomeUserProfile("ghalo", true))) + temp(callback, a) + +// temp(callback, Result.failure(SdkError(2000, "hallo"))) + } + + fun temp(callback: (Result) -> Unit, result: Result) { + val potentialError = result.exceptionOrNull() + val potentialValue = result.getOrNull() + + if (potentialError != null && potentialError is SdkError) { + // error + callback(Result.failure(FlutterError(potentialError.code.toString(), potentialError.message, potentialError.details))) + } else if (potentialError != null) { + // for different passed error + } else if (result.isSuccess && potentialValue != null) { + callback(Result.success(potentialValue)) + } else { + // throw critical error + } + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index ba7782c4..2b4653ee 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -10,9 +10,9 @@ import io.flutter.plugin.common.MethodChannel import okhttp3.Response class SdkError: Exception { - private val code: Int + val code: Int override val message: String - private val details: MutableMap = mutableMapOf() + val details: MutableMap = mutableMapOf() // Only error codes constructor( diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt deleted file mode 100644 index f09468bc..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FetchUserProfilesUseCase.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -//import com.onegini.mobile.sdk.flutter.OneginiPlugin -//import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserProfile -// -//class fetchUserProfilesUseCase { -// -// fun fetchUserProfiles(keyword:String): List { -// return listOf() -// } -//} \ No newline at end of file diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index d5267484..8e72c351 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -31,16 +31,18 @@ private func wrapError(_ error: Any) -> [Any?] { ] } +/// Result objects +/// /// Generated class from Pigeon that represents data sent in messages. -struct PigeonUserProfile { +struct OneWelcomeUserProfile { var profileId: String var isDefault: Bool - static func fromList(_ list: [Any?]) -> PigeonUserProfile? { + static func fromList(_ list: [Any?]) -> OneWelcomeUserProfile? { let profileId = list[0] as! String let isDefault = list[1] as! Bool - return PigeonUserProfile( + return OneWelcomeUserProfile( profileId: profileId, isDefault: isDefault ) @@ -57,7 +59,7 @@ private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: - return PigeonUserProfile.fromList(self.readValue() as! [Any]) + return OneWelcomeUserProfile.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) } @@ -66,7 +68,7 @@ private class UserClientApiCodecReader: FlutterStandardReader { private class UserClientApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? PigeonUserProfile { + if let value = value as? OneWelcomeUserProfile { super.writeByte(128) super.writeValue(value.toList()) } else { @@ -93,7 +95,9 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { - func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) + func fetchUserProfiles(completion: @escaping (Result<[OneWelcomeUserProfile], Error>) -> Void) + func voidFunction(completion: @escaping (Result) -> Void) + func nullableStringFunction(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -117,9 +121,103 @@ class UserClientApiSetup { } else { fetchUserProfilesChannel.setMessageHandler(nil) } + let voidFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.voidFunction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + voidFunctionChannel.setMessageHandler { _, reply in + api.voidFunction() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + voidFunctionChannel.setMessageHandler(nil) + } + let nullableStringFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.nullableStringFunction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + nullableStringFunctionChannel.setMessageHandler { _, reply in + api.nullableStringFunction() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + nullableStringFunctionChannel.setMessageHandler(nil) + } + } +} +private class ResourceMethodApiCodecReader: FlutterStandardReader { + override func readValue(ofType type: UInt8) -> Any? { + switch type { + case 128: + return OneWelcomeUserProfile.fromList(self.readValue() as! [Any]) + default: + return super.readValue(ofType: type) + } + } +} + +private class ResourceMethodApiCodecWriter: FlutterStandardWriter { + override func writeValue(_ value: Any) { + if let value = value as? OneWelcomeUserProfile { + super.writeByte(128) + super.writeValue(value.toList()) + } else { + super.writeValue(value) + } + } +} + +private class ResourceMethodApiCodecReaderWriter: FlutterStandardReaderWriter { + override func reader(with data: Data) -> FlutterStandardReader { + return ResourceMethodApiCodecReader(data: data) + } + + override func writer(with data: NSMutableData) -> FlutterStandardWriter { + return ResourceMethodApiCodecWriter(data: data) + } +} + +class ResourceMethodApiCodec: FlutterStandardMessageCodec { + static let shared = ResourceMethodApiCodec(readerWriter: ResourceMethodApiCodecReaderWriter()) +} + +/// Generated protocol from Pigeon that represents a handler of messages from Flutter. +protocol ResourceMethodApi { + func fetchUserProfiles(completion: @escaping (Result<[OneWelcomeUserProfile], Error>) -> Void) +} + +/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. +class ResourceMethodApiSetup { + /// The codec used by ResourceMethodApi. + static var codec: FlutterStandardMessageCodec { ResourceMethodApiCodec.shared } + /// Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. + static func setUp(binaryMessenger: FlutterBinaryMessenger, api: ResourceMethodApi?) { + let fetchUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + fetchUserProfilesChannel.setMessageHandler { _, reply in + api.fetchUserProfiles() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + fetchUserProfilesChannel.setMessageHandler(nil) + } } } -/// Native calls Flutter +/// Native calls to Flutter /// /// Generated class from Pigeon that represents Flutter messages that can be called from Swift. class NativeCallFlutterApi { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dd84a4c9..4563c1da 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -8,8 +8,9 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; -class PigeonUserProfile { - PigeonUserProfile({ +/// Result objects +class OneWelcomeUserProfile { + OneWelcomeUserProfile({ required this.profileId, required this.isDefault, }); @@ -25,9 +26,9 @@ class PigeonUserProfile { ]; } - static PigeonUserProfile decode(Object result) { + static OneWelcomeUserProfile decode(Object result) { result as List; - return PigeonUserProfile( + return OneWelcomeUserProfile( profileId: result[0]! as String, isDefault: result[1]! as bool, ); @@ -38,7 +39,7 @@ class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is PigeonUserProfile) { + if (value is OneWelcomeUserProfile) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { @@ -50,7 +51,7 @@ class _UserClientApiCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return PigeonUserProfile.decode(readValue(buffer)!); + return OneWelcomeUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -68,7 +69,7 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future> fetchUserProfiles() async { + Future> fetchUserProfiles() async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fetchUserProfiles', codec, binaryMessenger: _binaryMessenger); @@ -91,12 +92,117 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as List?)!.cast(); + } + } + + Future voidFunction() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.voidFunction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future nullableStringFunction() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.nullableStringFunction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return (replyList[0] as String?); + } + } +} + +class _ResourceMethodApiCodec extends StandardMessageCodec { + const _ResourceMethodApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is OneWelcomeUserProfile) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return OneWelcomeUserProfile.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +class ResourceMethodApi { + /// Constructor for [ResourceMethodApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + ResourceMethodApi({BinaryMessenger? binaryMessenger}) + : _binaryMessenger = binaryMessenger; + final BinaryMessenger? _binaryMessenger; + + static const MessageCodec codec = _ResourceMethodApiCodec(); + + Future> fetchUserProfiles() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); } } } -/// Native calls Flutter +/// Native calls to Flutter abstract class NativeCallFlutterApi { static const MessageCodec codec = StandardMessageCodec(); diff --git a/pigeons/README.md b/pigeons/README.md index 48ba1f46..4ca2b0bc 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -3,7 +3,7 @@ Pidgeon is used within this project to enable type-save communication between th Command for code generation which is performed from top level: flutter pub run pigeon \ - --input pigeons/userProfile.dart \ + --input pigeons/onewelcomePigeonInterface.dart \ --dart_out lib/pigeon.dart \ --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ diff --git a/pigeons/onewelcomePigeonInterface.dart b/pigeons/onewelcomePigeonInterface.dart new file mode 100644 index 00000000..8f542994 --- /dev/null +++ b/pigeons/onewelcomePigeonInterface.dart @@ -0,0 +1,160 @@ +import 'package:pigeon/pigeon.dart'; + +// @ConfigurePigeon(PigeonOptions( +// dartOut: './../lib/pigeon.dart', +// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', +// kotlinOptions: KotlinOptions( +// // copyrightHeader: ['zero'], +// package: 'com.zero.flutter_pigeon_plugin', +// ), +// objcHeaderOut: 'ios/Runner/Pigeon.h', +// objcSourceOut: 'ios/Runner/Pigeon.m', +// objcOptions: ObjcOptions( +// prefix: 'FLT', +// ), +// )) + +/// Result objects +class OneWelcomeUserProfile { + String profileId; + bool isDefault; + + OneWelcomeUserProfile({required this.profileId, required this.isDefault}); +} + +class OneWelcomeCustomInfo { + int status; + String data; + + OneWelcomeCustomInfo({required this.status, required this.data}); +} + +class OneWelcomeIdentityProvider { + String id; + String name; + + OneWelcomeIdentityProvider({required this.id, required this.name}); +} + +class OneWelcomeAuthenticator { + String id; + String name; + + OneWelcomeAuthenticator({required this.id, required this.name}); +} + +class OneWelcomeAppToWebSingleSignOn { + String token; + String redirectUrl; + + OneWelcomeAppToWebSingleSignOn({required this.token, required this.redirectUrl}); +} + +class OneWelcomeRegistrationResponse { + OneWelcomeUserProfile userProfile; + OneWelcomeCustomInfo? customInfo; + + OneWelcomeRegistrationResponse({required this.userProfile, this.customInfo}); +} + +/// Flutter calls native +@HostApi() +abstract class UserClientApi { + // example one + @async + List fetchUserProfiles(); + + @async + void voidFunction(); + + @async + String? nullableStringFunction(); + // // todo removed buildcontext + // @async + // OneWelcomeRegistrationResponse registerUser(String? identityProviderId, List? scopes); + + // @async + // void handleRegisteredUserUrl(String? url, int signInType); + + // // todo removed buildcontext + // @async + // List getIdentityProviders(); + + // // removed boolean return + // @async + // void deregisterUser(String profileId); + + // // todo removed buildconext + // @async + // List getRegisteredAuthenticators(String profileId); + + // // todo removed buildconext + // @async + // List getAllAuthenticators(String profileId); + + // @async + // OneWelcomeUserProfile getAuthenticatedUserProfile(); + + // // todo removed build context + // @async + // OneWelcomeRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); + + // // todo removed context + // @async + // List getNotRegisteredAuthenticators(String profileId); + + // // todo removed context + // @async + // void changePin(); + + // // removed context and changed it into void instead of boolean + // @async + // void setPreferredAuthenticator(String authenticatorId); + + // // removed context and changed it into void instead of boolean + // @async + // void deregisterAuthenticator(String authenticatorId); + + // // removed context and changed it into void instead of boolean + // @async + // void logout(); + + // // todo investigate if string can be non null + // @async + // String? mobileAuthWithOtp(String data); + + // @async + // OneWelcomeAppToWebSingleSignOn getAppToWebSingleSignOn(String url); + + // @async + // String getAccessToken(); + + // @async + // String getRedirectUrl(); + + // @async + // List getUserProfiles(); + + // @async + // bool validatePinWithPolicy(); + + // @async + // bool authenticateDevice(List? scopes); + + // // todo update return value to object + // @async + // OneWelcomeUserProfile authenticateUserImplicitly(String profileId, List? scopes); +} + +@HostApi() +abstract class ResourceMethodApi { + @async + List fetchUserProfiles(); +} + +/// Native calls to Flutter +@FlutterApi() +abstract class NativeCallFlutterApi { + @async + String testEventFunction(String argument); +} From dec43e1abed993fef10dbe0c30fe2b591551c104 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 6 Mar 2023 12:06:04 +0100 Subject: [PATCH 016/364] FP-20 Interfaces final form; and setup for android completed --- .../mobile/sdk/flutter/PigeonInterface.kt | 53 +- .../mobile/sdk/flutter/helpers/SdkError.kt | 5 + .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 700 +++++++++++++++++- ios/Classes/Pigeon.swift | 530 ++++++++++++- lib/pigeon.dart | 684 ++++++++++++++++- lib/user_client.dart | 300 ++------ pigeons/README.md | 2 +- pigeons/onewelcome_pigeon_interface.dart | 151 ++++ 8 files changed, 2114 insertions(+), 311 deletions(-) create mode 100644 pigeons/onewelcome_pigeon_interface.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index d360b405..28f8ba71 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -4,41 +4,42 @@ import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OneWelcomeUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.GENERIC_ERROR open class PigeonInterface: UserClientApi { // Example function on how it could be initiated on Flutter send to Native override fun fetchUserProfiles(callback: (Result>) -> Unit) { -// val a = Result.success(listOf(PigeonUserProfile("ghalo", true))) -// val a = Result.failure>(Exception("meee", Throwable("boop"))) -// callback(Result.failure(FlutterException(CODE, MESSAGE, DETAILS))) - val b = mutableMapOf() - b["lol"] = "derp" - -// val c = Result.failure>(FlutterError("meee", "hallo", b)).exceptionOrNull() - -// callback(Result.failure(FlutterError("meee", "hallo", b))) - + val a = Result.success(listOf(OneWelcomeUserProfile("ghalo", true))) + flutterCallback(callback, a) +// val b = Result.failure>(SdkError(2000, "hallo")) +// flutterCallback(callback, b) + } - val a = Result.success(listOf(OneWelcomeUserProfile("ghalo", true))) - temp(callback, a) + override fun voidFunction(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } -// temp(callback, Result.failure(SdkError(2000, "hallo"))) + override fun nullableStringFunction(callback: (Result) -> Unit) { + TODO("Not yet implemented") } - fun temp(callback: (Result) -> Unit, result: Result) { - val potentialError = result.exceptionOrNull() - val potentialValue = result.getOrNull() + override fun nullableFetchUserProfiles(callback: (Result?>) -> Unit) { + val a = Result.success(null) + flutterCallback(callback, a) + } - if (potentialError != null && potentialError is SdkError) { - // error - callback(Result.failure(FlutterError(potentialError.code.toString(), potentialError.message, potentialError.details))) - } else if (potentialError != null) { - // for different passed error - } else if (result.isSuccess && potentialValue != null) { - callback(Result.success(potentialValue)) - } else { - // throw critical error - } + private fun flutterCallback(callback: (Result) -> Unit, result: Result) { + result.fold( + onFailure = { error -> + when (error) { + is SdkError -> callback(Result.failure(error.pigeonError())) + else -> callback(Result.failure(error)) + } + }, + onSuccess = { value -> + callback(Result.success(value)) + } + ) } } \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index 2b4653ee..b9ab64c8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -6,6 +6,7 @@ import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_BOD import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_HEADERS import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_STATUS_CODE import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_URL +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import io.flutter.plugin.common.MethodChannel import okhttp3.Response @@ -83,4 +84,8 @@ class SdkError: Exception { fun flutterError(result: MethodChannel.Result) { result.error(code.toString(), message, details) } + + fun pigeonError(): FlutterError { + return FlutterError(code.toString(), message, details) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 4f2a886c..b01bc706 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -37,18 +37,22 @@ class FlutterError ( val details: Any? = null ) : Throwable() -/** Generated class from Pigeon that represents data sent in messages. */ -data class PigeonUserProfile ( +/** + * Result objects + * + * Generated class from Pigeon that represents data sent in messages. + */ +data class OWUserProfile ( val profileId: String, val isDefault: Boolean ) { companion object { @Suppress("UNCHECKED_CAST") - fun fromList(list: List): PigeonUserProfile { + fun fromList(list: List): OWUserProfile { val profileId = list[0] as String val isDefault = list[1] as Boolean - return PigeonUserProfile(profileId, isDefault) + return OWUserProfile(profileId, isDefault) } } fun toList(): List { @@ -59,13 +63,150 @@ data class PigeonUserProfile ( } } +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWCustomInfo ( + val status: Long, + val data: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWCustomInfo { + val status = list[0].let { if (it is Int) it.toLong() else it as Long } + val data = list[1] as String + return OWCustomInfo(status, data) + } + } + fun toList(): List { + return listOf( + status, + data, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWIdentityProvider ( + val id: String, + val name: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWIdentityProvider { + val id = list[0] as String + val name = list[1] as String + return OWIdentityProvider(id, name) + } + } + fun toList(): List { + return listOf( + id, + name, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWAuthenticator ( + val id: String, + val name: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWAuthenticator { + val id = list[0] as String + val name = list[1] as String + return OWAuthenticator(id, name) + } + } + fun toList(): List { + return listOf( + id, + name, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWAppToWebSingleSignOn ( + val token: String, + val redirectUrl: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWAppToWebSingleSignOn { + val token = list[0] as String + val redirectUrl = list[1] as String + return OWAppToWebSingleSignOn(token, redirectUrl) + } + } + fun toList(): List { + return listOf( + token, + redirectUrl, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWRegistrationResponse ( + val userProfile: OWUserProfile, + val customInfo: OWCustomInfo? = null + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWRegistrationResponse { + val userProfile = OWUserProfile.fromList(list[0] as List) + val customInfo: OWCustomInfo? = (list[1] as? List)?.let { + OWCustomInfo.fromList(it) + } + return OWRegistrationResponse(userProfile, customInfo) + } + } + fun toList(): List { + return listOf( + userProfile?.toList(), + customInfo?.toList(), + ) + } +} + @Suppress("UNCHECKED_CAST") private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { 128.toByte() -> { return (readValue(buffer) as? List)?.let { - PigeonUserProfile.fromList(it) + OWAppToWebSingleSignOn.fromList(it) + } + } + 129.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWAuthenticator.fromList(it) + } + } + 130.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWCustomInfo.fromList(it) + } + } + 131.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWIdentityProvider.fromList(it) + } + } + 132.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWRegistrationResponse.fromList(it) + } + } + 133.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWUserProfile.fromList(it) } } else -> super.readValueOfType(type, buffer) @@ -73,10 +214,30 @@ private object UserClientApiCodec : StandardMessageCodec() { } override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { when (value) { - is PigeonUserProfile -> { + is OWAppToWebSingleSignOn -> { stream.write(128) writeValue(stream, value.toList()) } + is OWAuthenticator -> { + stream.write(129) + writeValue(stream, value.toList()) + } + is OWCustomInfo -> { + stream.write(130) + writeValue(stream, value.toList()) + } + is OWIdentityProvider -> { + stream.write(131) + writeValue(stream, value.toList()) + } + is OWRegistrationResponse -> { + stream.write(132) + writeValue(stream, value.toList()) + } + is OWUserProfile -> { + stream.write(133) + writeValue(stream, value.toList()) + } else -> super.writeValue(stream, value) } } @@ -88,7 +249,29 @@ private object UserClientApiCodec : StandardMessageCodec() { * Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface UserClientApi { - fun fetchUserProfiles(callback: (Result>) -> Unit) + fun fetchUserProfiles(callback: (Result>) -> Unit) + fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) + fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) + fun getIdentityProviders(callback: (Result>) -> Unit) + fun deregisterUser(profileId: String, callback: (Result) -> Unit) + fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) + fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) + fun getAuthenticatedUserProfile(callback: (Result) -> Unit) + fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) + fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) + fun changePin(callback: (Result) -> Unit) + fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) + fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) + fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) + fun logout(callback: (Result) -> Unit) + fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) + fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) + fun getAccessToken(callback: (Result) -> Unit) + fun getRedirectUrl(callback: (Result) -> Unit) + fun getUserProfiles(callback: (Result>) -> Unit) + fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) + fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) + fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) companion object { /** The codec used by UserClientApi. */ @@ -103,7 +286,506 @@ interface UserClientApi { if (api != null) { channel.setMessageHandler { _, reply -> var wrapped = listOf() - api.fetchUserProfiles() { result: Result> -> + api.fetchUserProfiles() { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val identityProviderIdArg = args[0] as? String + val scopesArg = args[1] as? List + api.registerUser(identityProviderIdArg, scopesArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val urlArg = args[0] as? String + val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } + api.handleRegisteredUserUrl(urlArg, signInTypeArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getIdentityProviders", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getIdentityProviders() { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterUser", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + api.deregisterUser(profileIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + api.getRegisteredAuthenticators(profileIdArg) { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + api.getAllAuthenticators(profileIdArg) { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getAuthenticatedUserProfile() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + val registeredAuthenticatorIdArg = args[1] as? String + api.authenticateUser(profileIdArg, registeredAuthenticatorIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + api.getNotRegisteredAuthenticators(profileIdArg) { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.changePin() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val authenticatorIdArg = args[0] as String + api.setPreferredAuthenticator(authenticatorIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val authenticatorIdArg = args[0] as String + api.deregisterAuthenticator(authenticatorIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerAuthenticator", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val authenticatorIdArg = args[0] as String + api.registerAuthenticator(authenticatorIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.logout", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.logout() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val dataArg = args[0] as String + api.mobileAuthWithOtp(dataArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val urlArg = args[0] as String + api.getAppToWebSingleSignOn(urlArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAccessToken", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getAccessToken() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRedirectUrl", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getRedirectUrl() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getUserProfiles", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getUserProfiles() { result: Result> -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val pinArg = args[0] as String + api.validatePinWithPolicy(pinArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateDevice", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val scopesArg = args[0] as? List + api.authenticateDevice(scopesArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val profileIdArg = args[0] as String + val scopesArg = args[1] as? List + api.authenticateUserImplicitly(profileIdArg, scopesArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + } + } +} +@Suppress("UNCHECKED_CAST") +private object ResourceMethodApiCodec : StandardMessageCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 128.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWUserProfile.fromList(it) + } + } + else -> super.readValueOfType(type, buffer) + } + } + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + when (value) { + is OWUserProfile -> { + stream.write(128) + writeValue(stream, value.toList()) + } + else -> super.writeValue(stream, value) + } + } +} + +/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ +interface ResourceMethodApi { + fun fetchUserProfiles(callback: (Result>) -> Unit) + + companion object { + /** The codec used by ResourceMethodApi. */ + val codec: MessageCodec by lazy { + ResourceMethodApiCodec + } + /** Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. */ + @Suppress("UNCHECKED_CAST") + fun setUp(binaryMessenger: BinaryMessenger, api: ResourceMethodApi?) { + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.fetchUserProfiles() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -121,7 +803,7 @@ interface UserClientApi { } } /** - * Native calls Flutter + * Native calls to Flutter * * Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. */ diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 8e72c351..d94bd7bb 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -34,15 +34,15 @@ private func wrapError(_ error: Any) -> [Any?] { /// Result objects /// /// Generated class from Pigeon that represents data sent in messages. -struct OneWelcomeUserProfile { +struct OWUserProfile { var profileId: String var isDefault: Bool - static func fromList(_ list: [Any?]) -> OneWelcomeUserProfile? { + static func fromList(_ list: [Any?]) -> OWUserProfile? { let profileId = list[0] as! String let isDefault = list[1] as! Bool - return OneWelcomeUserProfile( + return OWUserProfile( profileId: profileId, isDefault: isDefault ) @@ -55,11 +55,134 @@ struct OneWelcomeUserProfile { } } +/// Generated class from Pigeon that represents data sent in messages. +struct OWCustomInfo { + var status: Int32 + var data: String + + static func fromList(_ list: [Any?]) -> OWCustomInfo? { + let status = list[0] as! Int32 + let data = list[1] as! String + + return OWCustomInfo( + status: status, + data: data + ) + } + func toList() -> [Any?] { + return [ + status, + data, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWIdentityProvider { + var id: String + var name: String + + static func fromList(_ list: [Any?]) -> OWIdentityProvider? { + let id = list[0] as! String + let name = list[1] as! String + + return OWIdentityProvider( + id: id, + name: name + ) + } + func toList() -> [Any?] { + return [ + id, + name, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWAuthenticator { + var id: String + var name: String + + static func fromList(_ list: [Any?]) -> OWAuthenticator? { + let id = list[0] as! String + let name = list[1] as! String + + return OWAuthenticator( + id: id, + name: name + ) + } + func toList() -> [Any?] { + return [ + id, + name, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWAppToWebSingleSignOn { + var token: String + var redirectUrl: String + + static func fromList(_ list: [Any?]) -> OWAppToWebSingleSignOn? { + let token = list[0] as! String + let redirectUrl = list[1] as! String + + return OWAppToWebSingleSignOn( + token: token, + redirectUrl: redirectUrl + ) + } + func toList() -> [Any?] { + return [ + token, + redirectUrl, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWRegistrationResponse { + var userProfile: OWUserProfile + var customInfo: OWCustomInfo? = nil + + static func fromList(_ list: [Any?]) -> OWRegistrationResponse? { + let userProfile = OWUserProfile.fromList(list[0] as! [Any?])! + var customInfo: OWCustomInfo? = nil + if let customInfoList = list[1] as? [Any?] { + customInfo = OWCustomInfo.fromList(customInfoList) + } + + return OWRegistrationResponse( + userProfile: userProfile, + customInfo: customInfo + ) + } + func toList() -> [Any?] { + return [ + userProfile.toList(), + customInfo?.toList(), + ] + } +} + private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: - return OneWelcomeUserProfile.fromList(self.readValue() as! [Any]) + return OWAppToWebSingleSignOn.fromList(self.readValue() as! [Any]) + case 129: + return OWAuthenticator.fromList(self.readValue() as! [Any]) + case 130: + return OWCustomInfo.fromList(self.readValue() as! [Any]) + case 131: + return OWIdentityProvider.fromList(self.readValue() as! [Any]) + case 132: + return OWRegistrationResponse.fromList(self.readValue() as! [Any]) + case 133: + return OWUserProfile.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) } @@ -68,9 +191,24 @@ private class UserClientApiCodecReader: FlutterStandardReader { private class UserClientApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? OneWelcomeUserProfile { + if let value = value as? OWAppToWebSingleSignOn { super.writeByte(128) super.writeValue(value.toList()) + } else if let value = value as? OWAuthenticator { + super.writeByte(129) + super.writeValue(value.toList()) + } else if let value = value as? OWCustomInfo { + super.writeByte(130) + super.writeValue(value.toList()) + } else if let value = value as? OWIdentityProvider { + super.writeByte(131) + super.writeValue(value.toList()) + } else if let value = value as? OWRegistrationResponse { + super.writeByte(132) + super.writeValue(value.toList()) + } else if let value = value as? OWUserProfile { + super.writeByte(133) + super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -95,9 +233,29 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { - func fetchUserProfiles(completion: @escaping (Result<[OneWelcomeUserProfile], Error>) -> Void) - func voidFunction(completion: @escaping (Result) -> Void) - func nullableStringFunction(completion: @escaping (Result) -> Void) + func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) + func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) + func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) + func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) + func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) + func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) + func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) + func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) + func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) + func changePin(completion: @escaping (Result) -> Void) + func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) + func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) + func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) + func logout(completion: @escaping (Result) -> Void) + func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) + func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) + func getAccessToken(completion: @escaping (Result) -> Void) + func getRedirectUrl(completion: @escaping (Result) -> Void) + func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) + func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) + func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -121,10 +279,31 @@ class UserClientApiSetup { } else { fetchUserProfilesChannel.setMessageHandler(nil) } - let voidFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.voidFunction", binaryMessenger: binaryMessenger, codec: codec) + let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - voidFunctionChannel.setMessageHandler { _, reply in - api.voidFunction() { result in + registerUserChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let identityProviderIdArg = args[0] as? String + let scopesArg = args[1] as? [String] + api.registerUser(identityProviderId: identityProviderIdArg, scopes: scopesArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + registerUserChannel.setMessageHandler(nil) + } + let handleRegisteredUserUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + handleRegisteredUserUrlChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let urlArg = args[0] as? String + let signInTypeArg = args[1] as! Int32 + api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { case .success: reply(wrapResult(nil)) @@ -134,12 +313,78 @@ class UserClientApiSetup { } } } else { - voidFunctionChannel.setMessageHandler(nil) + handleRegisteredUserUrlChannel.setMessageHandler(nil) + } + let getIdentityProvidersChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getIdentityProviders", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getIdentityProvidersChannel.setMessageHandler { _, reply in + api.getIdentityProviders() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getIdentityProvidersChannel.setMessageHandler(nil) + } + let deregisterUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterUser", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + deregisterUserChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + api.deregisterUser(profileId: profileIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + deregisterUserChannel.setMessageHandler(nil) + } + let getRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + api.getRegisteredAuthenticators(profileId: profileIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getRegisteredAuthenticatorsChannel.setMessageHandler(nil) + } + let getAllAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAllAuthenticatorsChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + api.getAllAuthenticators(profileId: profileIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAllAuthenticatorsChannel.setMessageHandler(nil) } - let nullableStringFunctionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.nullableStringFunction", binaryMessenger: binaryMessenger, codec: codec) + let getAuthenticatedUserProfileChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - nullableStringFunctionChannel.setMessageHandler { _, reply in - api.nullableStringFunction() { result in + getAuthenticatedUserProfileChannel.setMessageHandler { _, reply in + api.getAuthenticatedUserProfile() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -149,7 +394,254 @@ class UserClientApiSetup { } } } else { - nullableStringFunctionChannel.setMessageHandler(nil) + getAuthenticatedUserProfileChannel.setMessageHandler(nil) + } + let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + authenticateUserChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + let registeredAuthenticatorIdArg = args[1] as? String + api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + authenticateUserChannel.setMessageHandler(nil) + } + let getNotRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getNotRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + api.getNotRegisteredAuthenticators(profileId: profileIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getNotRegisteredAuthenticatorsChannel.setMessageHandler(nil) + } + let changePinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.changePin", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + changePinChannel.setMessageHandler { _, reply in + api.changePin() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + changePinChannel.setMessageHandler(nil) + } + let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setPreferredAuthenticatorChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let authenticatorIdArg = args[0] as! String + api.setPreferredAuthenticator(authenticatorId: authenticatorIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setPreferredAuthenticatorChannel.setMessageHandler(nil) + } + let deregisterAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + deregisterAuthenticatorChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let authenticatorIdArg = args[0] as! String + api.deregisterAuthenticator(authenticatorId: authenticatorIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + deregisterAuthenticatorChannel.setMessageHandler(nil) + } + let registerAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + registerAuthenticatorChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let authenticatorIdArg = args[0] as! String + api.registerAuthenticator(authenticatorId: authenticatorIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + registerAuthenticatorChannel.setMessageHandler(nil) + } + let logoutChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.logout", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + logoutChannel.setMessageHandler { _, reply in + api.logout() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + logoutChannel.setMessageHandler(nil) + } + let mobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + mobileAuthWithOtpChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let dataArg = args[0] as! String + api.mobileAuthWithOtp(data: dataArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + mobileAuthWithOtpChannel.setMessageHandler(nil) + } + let getAppToWebSingleSignOnChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAppToWebSingleSignOnChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let urlArg = args[0] as! String + api.getAppToWebSingleSignOn(url: urlArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAppToWebSingleSignOnChannel.setMessageHandler(nil) + } + let getAccessTokenChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAccessToken", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAccessTokenChannel.setMessageHandler { _, reply in + api.getAccessToken() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAccessTokenChannel.setMessageHandler(nil) + } + let getRedirectUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRedirectUrl", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getRedirectUrlChannel.setMessageHandler { _, reply in + api.getRedirectUrl() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getRedirectUrlChannel.setMessageHandler(nil) + } + let getUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getUserProfiles", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getUserProfilesChannel.setMessageHandler { _, reply in + api.getUserProfiles() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getUserProfilesChannel.setMessageHandler(nil) + } + let validatePinWithPolicyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + validatePinWithPolicyChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let pinArg = args[0] as! String + api.validatePinWithPolicy(pin: pinArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + validatePinWithPolicyChannel.setMessageHandler(nil) + } + let authenticateDeviceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateDevice", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + authenticateDeviceChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let scopesArg = args[0] as? [String] + api.authenticateDevice(scopes: scopesArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + authenticateDeviceChannel.setMessageHandler(nil) + } + let authenticateUserImplicitlyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + authenticateUserImplicitlyChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let profileIdArg = args[0] as! String + let scopesArg = args[1] as? [String] + api.authenticateUserImplicitly(profileId: profileIdArg, scopes: scopesArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + authenticateUserImplicitlyChannel.setMessageHandler(nil) } } } @@ -157,7 +649,7 @@ private class ResourceMethodApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: - return OneWelcomeUserProfile.fromList(self.readValue() as! [Any]) + return OWUserProfile.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) } @@ -166,7 +658,7 @@ private class ResourceMethodApiCodecReader: FlutterStandardReader { private class ResourceMethodApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? OneWelcomeUserProfile { + if let value = value as? OWUserProfile { super.writeByte(128) super.writeValue(value.toList()) } else { @@ -191,7 +683,7 @@ class ResourceMethodApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol ResourceMethodApi { - func fetchUserProfiles(completion: @escaping (Result<[OneWelcomeUserProfile], Error>) -> Void) + func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 4563c1da..e6f9ac6c 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -9,8 +9,8 @@ import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Result objects -class OneWelcomeUserProfile { - OneWelcomeUserProfile({ +class OWUserProfile { + OWUserProfile({ required this.profileId, required this.isDefault, }); @@ -26,22 +26,169 @@ class OneWelcomeUserProfile { ]; } - static OneWelcomeUserProfile decode(Object result) { + static OWUserProfile decode(Object result) { result as List; - return OneWelcomeUserProfile( + return OWUserProfile( profileId: result[0]! as String, isDefault: result[1]! as bool, ); } } +class OWCustomInfo { + OWCustomInfo({ + required this.status, + required this.data, + }); + + int status; + + String data; + + Object encode() { + return [ + status, + data, + ]; + } + + static OWCustomInfo decode(Object result) { + result as List; + return OWCustomInfo( + status: result[0]! as int, + data: result[1]! as String, + ); + } +} + +class OWIdentityProvider { + OWIdentityProvider({ + required this.id, + required this.name, + }); + + String id; + + String name; + + Object encode() { + return [ + id, + name, + ]; + } + + static OWIdentityProvider decode(Object result) { + result as List; + return OWIdentityProvider( + id: result[0]! as String, + name: result[1]! as String, + ); + } +} + +class OWAuthenticator { + OWAuthenticator({ + required this.id, + required this.name, + }); + + String id; + + String name; + + Object encode() { + return [ + id, + name, + ]; + } + + static OWAuthenticator decode(Object result) { + result as List; + return OWAuthenticator( + id: result[0]! as String, + name: result[1]! as String, + ); + } +} + +class OWAppToWebSingleSignOn { + OWAppToWebSingleSignOn({ + required this.token, + required this.redirectUrl, + }); + + String token; + + String redirectUrl; + + Object encode() { + return [ + token, + redirectUrl, + ]; + } + + static OWAppToWebSingleSignOn decode(Object result) { + result as List; + return OWAppToWebSingleSignOn( + token: result[0]! as String, + redirectUrl: result[1]! as String, + ); + } +} + +class OWRegistrationResponse { + OWRegistrationResponse({ + required this.userProfile, + this.customInfo, + }); + + OWUserProfile userProfile; + + OWCustomInfo? customInfo; + + Object encode() { + return [ + userProfile.encode(), + customInfo?.encode(), + ]; + } + + static OWRegistrationResponse decode(Object result) { + result as List; + return OWRegistrationResponse( + userProfile: OWUserProfile.decode(result[0]! as List), + customInfo: result[1] != null + ? OWCustomInfo.decode(result[1]! as List) + : null, + ); + } +} + class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is OneWelcomeUserProfile) { + if (value is OWAppToWebSingleSignOn) { buffer.putUint8(128); writeValue(buffer, value.encode()); + } else if (value is OWAuthenticator) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else if (value is OWCustomInfo) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else if (value is OWIdentityProvider) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); + } else if (value is OWRegistrationResponse) { + buffer.putUint8(132); + writeValue(buffer, value.encode()); + } else if (value is OWUserProfile) { + buffer.putUint8(133); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -51,7 +198,17 @@ class _UserClientApiCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return OneWelcomeUserProfile.decode(readValue(buffer)!); + return OWAppToWebSingleSignOn.decode(readValue(buffer)!); + case 129: + return OWAuthenticator.decode(readValue(buffer)!); + case 130: + return OWCustomInfo.decode(readValue(buffer)!); + case 131: + return OWIdentityProvider.decode(readValue(buffer)!); + case 132: + return OWRegistrationResponse.decode(readValue(buffer)!); + case 133: + return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -69,7 +226,7 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future> fetchUserProfiles() async { + Future> fetchUserProfiles() async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fetchUserProfiles', codec, binaryMessenger: _binaryMessenger); @@ -92,13 +249,246 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as List?)!.cast(); + } + } + + Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.registerUser', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_identityProviderId, arg_scopes]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as OWRegistrationResponse?)!; + } + } + + Future handleRegisteredUserUrl(String? arg_url, int arg_signInType) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_url, arg_signInType]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future> getIdentityProviders() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getIdentityProviders', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); + } + } + + Future deregisterUser(String arg_profileId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.deregisterUser', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future> getRegisteredAuthenticators(String arg_profileId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); + } + } + + Future> getAllAuthenticators(String arg_profileId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getAllAuthenticators', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); + } + } + + Future getAuthenticatedUserProfile() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as OWUserProfile?)!; + } + } + + Future authenticateUser(String arg_profileId, String? arg_registeredAuthenticatorId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId, arg_registeredAuthenticatorId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as OWRegistrationResponse?)!; + } + } + + Future> getNotRegisteredAuthenticators(String arg_profileId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); } } - Future voidFunction() async { + Future changePin() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.voidFunction', codec, + 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send(null) as List?; @@ -118,9 +508,75 @@ class UserClientApi { } } - Future nullableStringFunction() async { + Future setPreferredAuthenticator(String arg_authenticatorId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_authenticatorId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future deregisterAuthenticator(String arg_authenticatorId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.deregisterAuthenticator', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_authenticatorId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future registerAuthenticator(String arg_authenticatorId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.registerAuthenticator', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_authenticatorId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future logout() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.nullableStringFunction', codec, + 'dev.flutter.pigeon.UserClientApi.logout', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send(null) as List?; @@ -135,17 +591,213 @@ class UserClientApi { message: replyList[1] as String?, details: replyList[2], ); + } else { + return; + } + } + + Future mobileAuthWithOtp(String arg_data) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_data]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); } else { return (replyList[0] as String?); } } + + Future getAppToWebSingleSignOn(String arg_url) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_url]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as OWAppToWebSingleSignOn?)!; + } + } + + Future getAccessToken() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getAccessToken', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as String?)!; + } + } + + Future getRedirectUrl() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getRedirectUrl', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as String?)!; + } + } + + Future> getUserProfiles() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.getUserProfiles', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as List?)!.cast(); + } + } + + Future validatePinWithPolicy(String arg_pin) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.validatePinWithPolicy', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_pin]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future authenticateDevice(List? arg_scopes) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.authenticateDevice', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_scopes]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future authenticateUserImplicitly(String arg_profileId, List? arg_scopes) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId, arg_scopes]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } } class _ResourceMethodApiCodec extends StandardMessageCodec { const _ResourceMethodApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is OneWelcomeUserProfile) { + if (value is OWUserProfile) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { @@ -157,7 +809,7 @@ class _ResourceMethodApiCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return OneWelcomeUserProfile.decode(readValue(buffer)!); + return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -174,7 +826,7 @@ class ResourceMethodApi { static const MessageCodec codec = _ResourceMethodApiCodec(); - Future> fetchUserProfiles() async { + Future> fetchUserProfiles() async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles', codec, binaryMessenger: _binaryMessenger); @@ -197,7 +849,7 @@ class ResourceMethodApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as List?)!.cast(); } } } diff --git a/lib/user_client.dart b/lib/user_client.dart index 3c95ab26..bb5c8010 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/model/registration_response.dart'; +import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/oneginiAppToWebSingleSignOn.dart'; @@ -11,162 +12,81 @@ import 'onegini.dart'; ///Сlass with basic methods available to the developer. class UserClient { + final api = UserClientApi(); ///Start registration flow. /// /// If [identityProviderId] is null, starts standard browser registration. /// Use your [scopes] for registration. By default it is "read". - Future registerUser( + Future registerUser( BuildContext? context, String? identityProviderId, List? scopes, ) async { Onegini.instance.setEventContext(context); - try { - var response = await Onegini.instance.channel - .invokeMethod(Constants.registerUser, { - 'scopes': scopes, - 'identityProviderId': identityProviderId, - }); - return registrationResponseFromJson(response); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return api.registerUser(identityProviderId, scopes); } /// Start browser Registration logic Future handleRegisteredUserUrl(BuildContext? context, String? url, {WebSignInType signInType = WebSignInType.insideApp}) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel - .invokeMethod(Constants.handleRegisteredUserUrl, { - 'url': url, - 'type': signInType.value, - }); + await api.handleRegisteredUserUrl(url, signInType.value); } /// Returns a list of available identity providers. - Future> getIdentityProviders( + Future> getIdentityProviders( BuildContext? context) async { Onegini.instance.setEventContext(context); - try { - var providers = await Onegini.instance.channel - .invokeMethod(Constants.getIdentityProvidersMethod); - return responseFromJson(providers); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + final providers = await api.getIdentityProviders(); + return providers.whereType().toList(); } /// Deletes the user. - Future deregisterUser(String profileId) async { - try { - var isSuccess = await Onegini.instance.channel - .invokeMethod(Constants.deregisterUserMethod, { - 'profileId': profileId, - }); - return isSuccess ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + Future deregisterUser(String profileId) async { + await api.deregisterUser(profileId); } /// Returns a list of authenticators registered and available to the user. - Future> getRegisteredAuthenticators( + Future> getRegisteredAuthenticators( BuildContext? context, String profileId) async { Onegini.instance.setEventContext(context); - try { - var authenticators = await Onegini.instance.channel - .invokeMethod(Constants.getRegisteredAuthenticators, { - 'profileId': profileId, - }); - return responseFromJson(authenticators); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + final registeredAuthenticators = await api.getRegisteredAuthenticators(profileId); + return registeredAuthenticators.whereType().toList(); } - Future> getAllAuthenticators( + Future> getAllAuthenticators( BuildContext? context, String profileId) async { Onegini.instance.setEventContext(context); - try { - var authenticators = await Onegini.instance.channel - .invokeMethod(Constants.getAllAuthenticators, { - 'profileId': profileId, - }); - return responseFromJson(authenticators); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + final allAuthenticators = await api.getAllAuthenticators(profileId); + return allAuthenticators.whereType().toList(); } - Future getAuthenticatedUserProfile() async { - try { - var userProfile = await Onegini.instance.channel - .invokeMethod(Constants.getAuthenticatedUserProfile); - return userProfileFromJson(userProfile); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + Future getAuthenticatedUserProfile() async { + return await api.getAuthenticatedUserProfile(); } /// Starts authentication flow. /// /// If [registeredAuthenticatorId] is null, starts authentication by default authenticator. /// Usually it is Pin authenticator. - Future authenticateUser( + Future authenticateUser( BuildContext? context, String profileId, String? registeredAuthenticatorId, ) async { Onegini.instance.setEventContext(context); - try { - var response = await Onegini.instance.channel - .invokeMethod(Constants.authenticateUser, { - 'registeredAuthenticatorId': registeredAuthenticatorId, - 'profileId': profileId, - }); - return registrationResponseFromJson(response); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + return await api.authenticateUser(profileId, registeredAuthenticatorId); } /// Returns a list of authenticators available to the user, but not yet registered. - Future> getNotRegisteredAuthenticators( + Future> getNotRegisteredAuthenticators( BuildContext? context, String profileId) async { - try { - var authenticators = await Onegini.instance.channel.invokeMethod( - Constants.getAllNotRegisteredAuthenticators, { - 'profileId': profileId, - }); - return responseFromJson(authenticators); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + final notRegisteredAuthenticators = await api.getNotRegisteredAuthenticators(profileId); + return notRegisteredAuthenticators.whereType().toList(); } /// Starts change pin flow. @@ -174,186 +94,86 @@ class UserClient { BuildContext? context, ) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel.invokeMethod(Constants.changePin); + + await api.changePin(); } /// Registers authenticator from [getNotRegisteredAuthenticators] list. Future registerAuthenticator( BuildContext? context, String authenticatorId) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel - .invokeMethod(Constants.registerAuthenticator, { - 'authenticatorId': authenticatorId, - }); + + await api.registerAuthenticator(authenticatorId); } ///Set preferred authenticator - Future setPreferredAuthenticator( + /// todo removed boolean return update docu + Future setPreferredAuthenticator( BuildContext? context, String authenticatorId) async { Onegini.instance.setEventContext(context); - try { - var data = await Onegini.instance.channel - .invokeMethod(Constants.setPreferredAuthenticator, { - 'authenticatorId': authenticatorId, - }); - return data; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + await api.setPreferredAuthenticator(authenticatorId); } - Future deregisterAuthenticator( + /// todo removed boolean return update docu + Future deregisterAuthenticator( BuildContext? context, String authenticatorId) async { Onegini.instance.setEventContext(context); - try { - var success = await Onegini.instance.channel - .invokeMethod(Constants.deregisterAuthenticator, { - 'authenticatorId': authenticatorId, - }); - return success ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + + await api.deregisterAuthenticator(authenticatorId); } ///Method for log out - Future logout() async { - try { - var isSuccess = - await Onegini.instance.channel.invokeMethod(Constants.logout); - return isSuccess ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + /// todo removed boolean return update docu + Future logout() async { + await api.logout(); } /// Starts mobile authentication on web by OTP. Future mobileAuthWithOtp(String data) async { - try { - var isSuccess = await Onegini.instance.channel - .invokeMethod(Constants.handleMobileAuthWithOtp, { - 'data': data, - }); - return isSuccess; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return await api.mobileAuthWithOtp(data); } /// Single sign on the user web page. - Future getAppToWebSingleSignOn( + Future getAppToWebSingleSignOn( String url) async { - try { - var oneginiAppToWebSingleSignOn = await Onegini.instance.channel - .invokeMethod(Constants.getAppToWebSingleSignOn, { - 'url': url, - }); - return oneginiAppToWebSingleSignOnFromJson(oneginiAppToWebSingleSignOn); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return await api.getAppToWebSingleSignOn(url); } // Get Access Token Future getAccessToken() async { - try { - return await Onegini.instance.channel - .invokeMethod(Constants.getAccessToken); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return await api.getAccessToken(); } // Redirect url Future getRedirectUrl() async { - try { - return await Onegini.instance.channel - .invokeMethod(Constants.getRedirectUrl); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return await api.getRedirectUrl(); } /// User profiles - Future> getUserProfiles() async { - try { - var profiles = await Onegini.instance.channel - .invokeMethod(Constants.getUserProfiles); - return List.from(json - .decode(profiles) - .map((profile) => UserProfile.fromJson(profile))); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + Future> getUserProfiles() async { + final userProfiles = await api.getUserProfiles(); + return userProfiles.whereType().toList(); } - Future validatePinWithPolicy(String pin) async { - try { - var success = await Onegini.instance.channel.invokeMethod( - Constants.validatePinWithPolicy, {'pin': pin}); - return success ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + /// todo removed boolean return update docu + Future validatePinWithPolicy(String pin) async { + await api.validatePinWithPolicy(pin); } - Future authenticateDevice(List? scopes) async { - try { - var success = await Onegini.instance.channel.invokeMethod( - Constants.authenticateDevice, {'scope': scopes}); - - return success ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + /// todo removed boolean return update docu + Future authenticateDevice(List? scopes) async { + await api.authenticateDevice(scopes); } - Future authenticateUserImplicitly( + /// todo removed string return update docu + Future authenticateUserImplicitly( String profileId, List? scopes) async { - try { - var userProfileId = await Onegini.instance.channel.invokeMethod( - Constants.authenticateUserImplicitly, - {'profileId': profileId, 'scopes': scopes}); - return userProfileId; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + await api.authenticateUserImplicitly(profileId, scopes); } } +// TODO We could also get rid of this but leave this for now. enum WebSignInType { insideApp, safari, diff --git a/pigeons/README.md b/pigeons/README.md index 4ca2b0bc..1413567b 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -3,7 +3,7 @@ Pidgeon is used within this project to enable type-save communication between th Command for code generation which is performed from top level: flutter pub run pigeon \ - --input pigeons/onewelcomePigeonInterface.dart \ + --input pigeons/onewelcome_pigeon_interface.dart \ --dart_out lib/pigeon.dart \ --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart new file mode 100644 index 00000000..aaad9d68 --- /dev/null +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -0,0 +1,151 @@ +import 'package:pigeon/pigeon.dart'; + +// @ConfigurePigeon(PigeonOptions( +// dartOut: './../lib/pigeon.dart', +// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', +// kotlinOptions: KotlinOptions( +// // copyrightHeader: ['zero'], +// package: 'com.zero.flutter_pigeon_plugin', +// ), +// objcHeaderOut: 'ios/Runner/Pigeon.h', +// objcSourceOut: 'ios/Runner/Pigeon.m', +// objcOptions: ObjcOptions( +// prefix: 'FLT', +// ), +// )) + +/// Result objects +class OWUserProfile { + String profileId; + bool isDefault; + + OWUserProfile({required this.profileId, required this.isDefault}); +} + +class OWCustomInfo { + int status; + String data; + + OWCustomInfo({required this.status, required this.data}); +} + +class OWIdentityProvider { + String id; + String name; + + OWIdentityProvider({required this.id, required this.name}); +} + +class OWAuthenticator { + String id; + String name; + + OWAuthenticator({required this.id, required this.name}); +} + +class OWAppToWebSingleSignOn { + String token; + String redirectUrl; + + OWAppToWebSingleSignOn({required this.token, required this.redirectUrl}); +} + +class OWRegistrationResponse { + OWUserProfile userProfile; + OWCustomInfo? customInfo; + + OWRegistrationResponse({required this.userProfile, this.customInfo}); +} + +/// Flutter calls native +@HostApi() +abstract class UserClientApi { + // example one + @async + List fetchUserProfiles(); + + @async + OWRegistrationResponse registerUser(String? identityProviderId, List? scopes); + + @async + void handleRegisteredUserUrl(String? url, int signInType); + + @async + List getIdentityProviders(); + + // removed boolean return + @async + void deregisterUser(String profileId); + + @async + List getRegisteredAuthenticators(String profileId); + + @async + List getAllAuthenticators(String profileId); + + @async + OWUserProfile getAuthenticatedUserProfile(); + + @async + OWRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); + + @async + List getNotRegisteredAuthenticators(String profileId); + + @async + void changePin(); + + // changed it into void instead of boolean + @async + void setPreferredAuthenticator(String authenticatorId); + + // changed it into void instead of boolean + @async + void deregisterAuthenticator(String authenticatorId); + + @async + void registerAuthenticator(String authenticatorId); + + // changed it into void instead of boolean + @async + void logout(); + + // todo investigate if string can be non null + @async + String? mobileAuthWithOtp(String data); + + @async + OWAppToWebSingleSignOn getAppToWebSingleSignOn(String url); + + @async + String getAccessToken(); + + @async + String getRedirectUrl(); + + @async + List getUserProfiles(); + + @async + void validatePinWithPolicy(String pin); + + @async + void authenticateDevice(List? scopes); + + // todo update return value to object + @async + void authenticateUserImplicitly(String profileId, List? scopes); +} + +@HostApi() +abstract class ResourceMethodApi { + @async + List fetchUserProfiles(); +} + +/// Native calls to Flutter +@FlutterApi() +abstract class NativeCallFlutterApi { + @async + String testEventFunction(String argument); +} From c5e96849d5835ed6a7adeed224a7c103d83d487f Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 6 Mar 2023 12:57:36 +0100 Subject: [PATCH 017/364] small fix interface --- .../mobile/sdk/flutter/PigeonInterface.kt | 97 +++++++++++++++-- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 98 +++++++++++------ ios/Classes/Pigeon.swift | 101 +++++++++-------- lib/pigeon.dart | 103 ++++++++++++------ pigeons/onewelcome_pigeon_interface.dart | 16 ++- 5 files changed, 287 insertions(+), 128 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 28f8ba71..c8d901c4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,32 +1,109 @@ package com.onegini.mobile.sdk.flutter import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OneWelcomeUserProfile import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.GENERIC_ERROR +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile open class PigeonInterface: UserClientApi { // Example function on how it could be initiated on Flutter send to Native - override fun fetchUserProfiles(callback: (Result>) -> Unit) { - val a = Result.success(listOf(OneWelcomeUserProfile("ghalo", true))) + override fun fetchUserProfiles(callback: (Result>) -> Unit) { + val a = Result.success(listOf(OWUserProfile("ghalo"))) flutterCallback(callback, a) // val b = Result.failure>(SdkError(2000, "hallo")) // flutterCallback(callback, b) } - override fun voidFunction(callback: (Result) -> Unit) { + override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { TODO("Not yet implemented") } - override fun nullableStringFunction(callback: (Result) -> Unit) { + override fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) { TODO("Not yet implemented") } - override fun nullableFetchUserProfiles(callback: (Result?>) -> Unit) { - val a = Result.success(null) - flutterCallback(callback, a) + override fun getIdentityProviders(callback: (Result>) -> Unit) { + TODO("Not yet implemented") + } + + override fun deregisterUser(profileId: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { + TODO("Not yet implemented") + } + + override fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) { + TODO("Not yet implemented") + } + + override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { + TODO("Not yet implemented") + } + + override fun changePin(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun logout(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getAccessToken(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getRedirectUrl(callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun getUserProfiles(callback: (Result>) -> Unit) { + TODO("Not yet implemented") + } + + override fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) { + TODO("Not yet implemented") + } + + override fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) { + TODO("Not yet implemented") } private fun flutterCallback(callback: (Result) -> Unit, result: Result) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index b01bc706..302f2496 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -43,22 +43,19 @@ class FlutterError ( * Generated class from Pigeon that represents data sent in messages. */ data class OWUserProfile ( - val profileId: String, - val isDefault: Boolean + val profileId: String ) { companion object { @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWUserProfile { val profileId = list[0] as String - val isDefault = list[1] as Boolean - return OWUserProfile(profileId, isDefault) + return OWUserProfile(profileId) } } fun toList(): List { return listOf( profileId, - isDefault, ) } } @@ -745,47 +742,84 @@ interface UserClientApi { } } } -@Suppress("UNCHECKED_CAST") -private object ResourceMethodApiCodec : StandardMessageCodec() { - override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { - return when (type) { - 128.toByte() -> { - return (readValue(buffer) as? List)?.let { - OWUserProfile.fromList(it) - } - } - else -> super.readValueOfType(type, buffer) - } - } - override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { - when (value) { - is OWUserProfile -> { - stream.write(128) - writeValue(stream, value.toList()) - } - else -> super.writeValue(stream, value) - } - } -} - /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface ResourceMethodApi { - fun fetchUserProfiles(callback: (Result>) -> Unit) + fun getResourceAnonymous(callback: (Result) -> Unit) + fun getResource(callback: (Result) -> Unit) + fun getResourceImplicit(callback: (Result) -> Unit) + fun getUnauthenticatedResource(callback: (Result) -> Unit) companion object { /** The codec used by ResourceMethodApi. */ val codec: MessageCodec by lazy { - ResourceMethodApiCodec + StandardMessageCodec() } /** Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. */ @Suppress("UNCHECKED_CAST") fun setUp(binaryMessenger: BinaryMessenger, api: ResourceMethodApi?) { run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", codec) if (api != null) { channel.setMessageHandler { _, reply -> var wrapped = listOf() - api.fetchUserProfiles() { result: Result> -> + api.getResourceAnonymous() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResource", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getResource() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getResourceImplicit() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.getUnauthenticatedResource() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index d94bd7bb..1162d0cd 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -36,21 +36,17 @@ private func wrapError(_ error: Any) -> [Any?] { /// Generated class from Pigeon that represents data sent in messages. struct OWUserProfile { var profileId: String - var isDefault: Bool static func fromList(_ list: [Any?]) -> OWUserProfile? { let profileId = list[0] as! String - let isDefault = list[1] as! Bool return OWUserProfile( - profileId: profileId, - isDefault: isDefault + profileId: profileId ) } func toList() -> [Any?] { return [ profileId, - isDefault, ] } } @@ -645,57 +641,23 @@ class UserClientApiSetup { } } } -private class ResourceMethodApiCodecReader: FlutterStandardReader { - override func readValue(ofType type: UInt8) -> Any? { - switch type { - case 128: - return OWUserProfile.fromList(self.readValue() as! [Any]) - default: - return super.readValue(ofType: type) - } - } -} - -private class ResourceMethodApiCodecWriter: FlutterStandardWriter { - override func writeValue(_ value: Any) { - if let value = value as? OWUserProfile { - super.writeByte(128) - super.writeValue(value.toList()) - } else { - super.writeValue(value) - } - } -} - -private class ResourceMethodApiCodecReaderWriter: FlutterStandardReaderWriter { - override func reader(with data: Data) -> FlutterStandardReader { - return ResourceMethodApiCodecReader(data: data) - } - - override func writer(with data: NSMutableData) -> FlutterStandardWriter { - return ResourceMethodApiCodecWriter(data: data) - } -} - -class ResourceMethodApiCodec: FlutterStandardMessageCodec { - static let shared = ResourceMethodApiCodec(readerWriter: ResourceMethodApiCodecReaderWriter()) -} - /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol ResourceMethodApi { - func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) + func getResourceAnonymous(completion: @escaping (Result) -> Void) + func getResource(completion: @escaping (Result) -> Void) + func getResourceImplicit(completion: @escaping (Result) -> Void) + func getUnauthenticatedResource(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class ResourceMethodApiSetup { /// The codec used by ResourceMethodApi. - static var codec: FlutterStandardMessageCodec { ResourceMethodApiCodec.shared } /// Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: ResourceMethodApi?) { - let fetchUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles", binaryMessenger: binaryMessenger, codec: codec) + let getResourceAnonymousChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", binaryMessenger: binaryMessenger) if let api = api { - fetchUserProfilesChannel.setMessageHandler { _, reply in - api.fetchUserProfiles() { result in + getResourceAnonymousChannel.setMessageHandler { _, reply in + api.getResourceAnonymous() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -705,7 +667,52 @@ class ResourceMethodApiSetup { } } } else { - fetchUserProfilesChannel.setMessageHandler(nil) + getResourceAnonymousChannel.setMessageHandler(nil) + } + let getResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResource", binaryMessenger: binaryMessenger) + if let api = api { + getResourceChannel.setMessageHandler { _, reply in + api.getResource() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getResourceChannel.setMessageHandler(nil) + } + let getResourceImplicitChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", binaryMessenger: binaryMessenger) + if let api = api { + getResourceImplicitChannel.setMessageHandler { _, reply in + api.getResourceImplicit() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getResourceImplicitChannel.setMessageHandler(nil) + } + let getUnauthenticatedResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", binaryMessenger: binaryMessenger) + if let api = api { + getUnauthenticatedResourceChannel.setMessageHandler { _, reply in + api.getUnauthenticatedResource() { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getUnauthenticatedResourceChannel.setMessageHandler(nil) } } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index e6f9ac6c..f362cc47 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -12,17 +12,13 @@ import 'package:flutter/services.dart'; class OWUserProfile { OWUserProfile({ required this.profileId, - required this.isDefault, }); String profileId; - bool isDefault; - Object encode() { return [ profileId, - isDefault, ]; } @@ -30,7 +26,6 @@ class OWUserProfile { result as List; return OWUserProfile( profileId: result[0]! as String, - isDefault: result[1]! as bool, ); } } @@ -793,29 +788,6 @@ class UserClientApi { } } -class _ResourceMethodApiCodec extends StandardMessageCodec { - const _ResourceMethodApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is OWUserProfile) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return OWUserProfile.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - class ResourceMethodApi { /// Constructor for [ResourceMethodApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default @@ -824,11 +796,11 @@ class ResourceMethodApi { : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = _ResourceMethodApiCodec(); + static const MessageCodec codec = StandardMessageCodec(); - Future> fetchUserProfiles() async { + Future getResourceAnonymous() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResourceMethodApi.fetchUserProfiles', codec, + 'dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send(null) as List?; @@ -843,13 +815,74 @@ class ResourceMethodApi { message: replyList[1] as String?, details: replyList[2], ); - } else if (replyList[0] == null) { + } else { + return (replyList[0] as String?); + } + } + + Future getResource() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.ResourceMethodApi.getResource', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as String?); + } + } + + Future getResourceImplicit() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return (replyList[0] as String?); + } + } + + Future getUnauthenticatedResource() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return (replyList[0] as String?); } } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index aaad9d68..44476371 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -17,9 +17,8 @@ import 'package:pigeon/pigeon.dart'; /// Result objects class OWUserProfile { String profileId; - bool isDefault; - OWUserProfile({required this.profileId, required this.isDefault}); + OWUserProfile({required this.profileId}); } class OWCustomInfo { @@ -60,7 +59,7 @@ class OWRegistrationResponse { /// Flutter calls native @HostApi() abstract class UserClientApi { - // example one + // example function @async List fetchUserProfiles(); @@ -140,7 +139,16 @@ abstract class UserClientApi { @HostApi() abstract class ResourceMethodApi { @async - List fetchUserProfiles(); + String? getResourceAnonymous(); + + @async + String? getResource(); + + @async + String? getResourceImplicit(); + + @async + String? getUnauthenticatedResource(); } /// Native calls to Flutter From 03ef344c89e1bf16ab48c4fad0cadf08c1103e96 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:11:37 +0100 Subject: [PATCH 018/364] FP-20: iOS: Reindent SwiftOneginiPlugin.swift --- ios/Classes/SwiftOneginiPlugin.swift | 200 +++++++++++++-------------- 1 file changed, 100 insertions(+), 100 deletions(-) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3bf0d018..5761f1cf 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -4,115 +4,115 @@ import UIKit extension FlutterError: Error {} public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { - static var flutterApi: NativeCallFlutterApi? - - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) - let eventChannel = FlutterEventChannel(name: "onegini_events", - binaryMessenger: registrar.messenger()) - let instance = SwiftOneginiPlugin() - registrar.addMethodCallDelegate(instance, channel: channel) - eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) - - // Init Pigeon communication - let messenger : FlutterBinaryMessenger = registrar.messenger() - let api : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() - UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) - - flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) - - // Example on call flutter function from native during start - flutterApi?.testEventFunction(argument: "we initilized the function", completion: {_ in }) - } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - Logger.log("call.method: \(call.method)", sender: self, logType: .log) - let _arg = call.arguments as! [String: Any]? - if ((_arg) != nil) { - for key in _arg!.keys { - Logger.log("key: " + key) - let val = _arg?[key] - Logger.log("value: " + String(describing: val)) - } - } + static var flutterApi: NativeCallFlutterApi? - switch call.method { - - // base - case Constants.Routes.startApp: startApp(call, result) - - // register - case Constants.Routes.registerUser: registerUser(call, result) - case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) - - case Constants.Routes.getIdentityProviders: getIdentityProviders(call, result) - case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) - case Constants.Routes.setPreferredAuthenticator: - setPreferredAuthenticator(call, result) - - case Constants.Routes.acceptPinRegistrationRequest: acceptPinRegistrationRequest(call, result) - case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) - case Constants.Routes.getRedirectUrl: getRedirectUrl(call, result) - - // custom registration - case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) - case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) + let eventChannel = FlutterEventChannel(name: "onegini_events", + binaryMessenger: registrar.messenger()) + let instance = SwiftOneginiPlugin() + registrar.addMethodCallDelegate(instance, channel: channel) + eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) - case Constants.Routes.deregisterUser: deregisterUser(call, result) + // Init Pigeon communication + let messenger : FlutterBinaryMessenger = registrar.messenger() + let api : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() + UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) - // auth - case Constants.Routes.registerAuthenticator: registerAuthenticator(call, result) - case Constants.Routes.authenticateUser: authenticateUser(call, result) - case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) - case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - - case Constants.Routes.getRegisteredAuthenticators: getRegisteredAuthenticators(call, result) - case Constants.Routes.getAllNotRegisteredAuthenticators: getAllNotRegisteredAuthenticators(call, result) - case Constants.Routes.getAllAuthenticators: getAllAuthenticators(call, result) - case Constants.Routes.deregisterAuthenticator: - deregisterAuthenticator(call, result) - - case Constants.Routes.acceptPinAuthenticationRequest: acceptPinAuthenticationRequest(call, result) - case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) - - case Constants.Routes.logout: logout(call, result) - - case Constants.Routes.validatePinWithPolicy: - validatePinWithPolicy(call, result) - case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) - case Constants.Routes.getUserProfiles: getUserProfiles(result) - case Constants.Routes.getAccessToken: getAccessToken(result) - - // fingerprint - case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) - case Constants.Routes.denyFingerprintAuthenticationRequest: denyFingerprintAuthenticationRequest(call, result) - case Constants.Routes.fingerprintFallbackToPin: fingerprintFallbackToPin(call, result) - - // otp - case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) - case Constants.Routes.acceptOtpAuthenticationRequest: acceptOtpAuthenticationRequest(call, result) - case Constants.Routes.denyOtpAuthenticationRequest: denyOtpAuthenticationRequest(call, result) + flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) - // resources - case Constants.Routes.getResourceAnonymous, Constants.Routes.getResource, Constants.Routes.getImplicitResource, Constants.Routes.unauthenticatedRequest: - getResource(call, result) - - // other - case Constants.Routes.changePin: changePin(call, result) - case Constants.Routes.getAppToWebSingleSignOn: getAppToWebSingleSignOn(call, result) - - default: do { - Logger.log("Method wasn't handled: " + call.method) - result(FlutterMethodNotImplemented) + // Example on call flutter function from native during start + flutterApi?.testEventFunction(argument: "we initilized the function", completion: {_ in }) } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + Logger.log("call.method: \(call.method)", sender: self, logType: .log) + let _arg = call.arguments as! [String: Any]? + if ((_arg) != nil) { + for key in _arg!.keys { + Logger.log("key: " + key) + let val = _arg?[key] + Logger.log("value: " + String(describing: val)) + } + } + + switch call.method { + + // base + case Constants.Routes.startApp: startApp(call, result) + + // register + case Constants.Routes.registerUser: registerUser(call, result) + case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) + + case Constants.Routes.getIdentityProviders: getIdentityProviders(call, result) + case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) + case Constants.Routes.setPreferredAuthenticator: + setPreferredAuthenticator(call, result) + + case Constants.Routes.acceptPinRegistrationRequest: acceptPinRegistrationRequest(call, result) + case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) + case Constants.Routes.getRedirectUrl: getRedirectUrl(call, result) + + // custom registration + case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) + case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) + + case Constants.Routes.deregisterUser: deregisterUser(call, result) + + // auth + case Constants.Routes.registerAuthenticator: registerAuthenticator(call, result) + case Constants.Routes.authenticateUser: authenticateUser(call, result) + case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) + case Constants.Routes.authenticateDevice: authenticateDevice(call, result) + + case Constants.Routes.getRegisteredAuthenticators: getRegisteredAuthenticators(call, result) + case Constants.Routes.getAllNotRegisteredAuthenticators: getAllNotRegisteredAuthenticators(call, result) + case Constants.Routes.getAllAuthenticators: getAllAuthenticators(call, result) + case Constants.Routes.deregisterAuthenticator: + deregisterAuthenticator(call, result) + + case Constants.Routes.acceptPinAuthenticationRequest: acceptPinAuthenticationRequest(call, result) + case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) + + case Constants.Routes.logout: logout(call, result) + + case Constants.Routes.validatePinWithPolicy: + validatePinWithPolicy(call, result) + case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) + case Constants.Routes.getUserProfiles: getUserProfiles(result) + case Constants.Routes.getAccessToken: getAccessToken(result) + + // fingerprint + case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) + case Constants.Routes.denyFingerprintAuthenticationRequest: denyFingerprintAuthenticationRequest(call, result) + case Constants.Routes.fingerprintFallbackToPin: fingerprintFallbackToPin(call, result) + + // otp + case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) + case Constants.Routes.acceptOtpAuthenticationRequest: acceptOtpAuthenticationRequest(call, result) + case Constants.Routes.denyOtpAuthenticationRequest: denyOtpAuthenticationRequest(call, result) + + // resources + case Constants.Routes.getResourceAnonymous, Constants.Routes.getResource, Constants.Routes.getImplicitResource, Constants.Routes.unauthenticatedRequest: + getResource(call, result) + + // other + case Constants.Routes.changePin: changePin(call, result) + case Constants.Routes.getAppToWebSingleSignOn: getAppToWebSingleSignOn(call, result) + + default: do { + Logger.log("Method wasn't handled: " + call.method) + result(FlutterMethodNotImplemented) + } + } } - } // Example function for Flutter -> Native functions and how to return a response or error func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) { -// let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) + // let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) - -// completion(.success([PigeonUserProfile(profileId: "boopios", isDefault: true)])) + + // completion(.success([PigeonUserProfile(profileId: "boopios", isDefault: true)])) } } From 763fb592082dd335535784d68b5f0b75eed50c49 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:13:41 +0100 Subject: [PATCH 019/364] FP-20: iOS: Add conversion functions for iOS->Pigeon types --- ios/Classes/SwiftOneginiPlugin.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 5761f1cf..e056950f 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -1,8 +1,34 @@ import Flutter import UIKit +import OneginiSDKiOS extension FlutterError: Error {} +extension OWUserProfile { + init(_ profile: UserProfile) { + self.profileId = profile.profileId + } + init(_ profile: ONGUserProfile) { + self.profileId = profile.profileId + } +} + +extension OWCustomInfo { + init(_ info: CustomInfo) { + status = Int32(info.status) + data = info.data + } + init(_ info: ONGCustomInfo) { + status = Int32(info.status) + data = info.data + } +} + +func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { + guard let info = info else { return nil } + return OWCustomInfo(status: Int32(info.status), data: info.data) +} + public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { static var flutterApi: NativeCallFlutterApi? From 6d63cac3dd3a8827c3ab65b487049fb32af5aee2 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:17:24 +0100 Subject: [PATCH 020/364] FP-20: Add validatePinWithPolicy Pigeon implementation --- .../NativeBridge/Handlers/PinHandler.swift | 21 +++++-------------- .../OneginiModuleSwift+Pin.swift | 8 +++---- 2 files changed, 8 insertions(+), 21 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 8034bbb5..bed146d9 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -1,16 +1,6 @@ import OneginiSDKiOS import Flutter -//MARK: - -protocol PinConnectorToPinHandler: AnyObject { - func onPinProvided(pin: String) - func onChangePinCalled(completion: @escaping (Bool, SdkError?) -> Void) - func onCancel() - func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) - func closeFlow() - func validatePinWithPolicy(pin: String, completion: @escaping (Bool, SdkError?) -> Void) -} - protocol PinHandlerToReceiverProtocol: class { func handlePin(pin: String?) } @@ -67,7 +57,7 @@ class PinHandler: NSObject { } //MARK: - -extension PinHandler : PinConnectorToPinHandler { +extension PinHandler { func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) { if(self.flow == nil){ self.flow = flow @@ -137,14 +127,13 @@ extension PinHandler : PinConnectorToPinHandler { processCancelAction() } - func validatePinWithPolicy(pin: String, completion: @escaping (Bool, SdkError?) -> Void) { + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in - guard let _error = error else { - completion(value, nil) + guard let error = error else { + completion(.success(())) return } - - completion(false, SdkError(code: _error.code, errorDescription: _error.localizedDescription)) + completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription))) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 16320d8c..c8a2e63a 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -20,11 +20,9 @@ extension OneginiModuleSwift { } } - func validatePinWithPolicy(_ pin: String, callback: @escaping FlutterResult) -> Void { - bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { - (value, error) -> Void in - - error != nil ? callback(SdkError.convertToFlutter(error)) : callback(value) + func validatePinWithPolicy(_ pin: String, completion: (Result) -> Void) { + bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in + completion(result) }) } } From 9df087dbb50e6b5535664f7a0053a132e8becfea Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:17:58 +0100 Subject: [PATCH 021/364] FP-20: getAuthenticatedUser Pigeon implementation --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 7 +++---- ios/Classes/SwiftOneginiPlugin.swift | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 9cc2544f..bbddb505 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -126,12 +126,11 @@ extension OneginiModuleSwift { } } - func getAuthenticatedUserProfile(callback: @escaping FlutterResult) { + func getAuthenticatedUserProfile() -> Result { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { - callback(SdkError.convertToFlutter(SdkError(.noUserProfileIsAuthenticated))) - return + return .failure(SdkError(.noUserProfileIsAuthenticated)) } - callback(String.stringify(json: ["profileId": profile.profileId])) + return .success(FPUserProfile(profile)) } func getAccessToken(callback: @escaping FlutterResult) { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index e056950f..edb5f619 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -105,7 +105,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.validatePinWithPolicy: validatePinWithPolicy(call, result) - case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) +// case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) case Constants.Routes.getUserProfiles: getUserProfiles(result) case Constants.Routes.getAccessToken: getAccessToken(result) From a2a1ff3bf29f15f6bce9a04251e08a5064be3720 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:18:19 +0100 Subject: [PATCH 022/364] GetAccessToken pigeon implementation --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 7 +++---- ios/Classes/SwiftOneginiPlugin.swift | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index bbddb505..05e7d1f2 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -133,11 +133,10 @@ extension OneginiModuleSwift { return .success(FPUserProfile(profile)) } - func getAccessToken(callback: @escaping FlutterResult) { + func getAccessToken() -> Result { guard let accessToken = ONGUserClient.sharedInstance().accessToken else { - callback(SdkError.convertToFlutter(SdkError(.noUserProfileIsAuthenticated))) - return + return .failure(SdkError(.noUserProfileIsAuthenticated)) } - callback(accessToken) + return .success(accessToken) } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index edb5f619..918f389b 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -107,7 +107,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { validatePinWithPolicy(call, result) // case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) case Constants.Routes.getUserProfiles: getUserProfiles(result) - case Constants.Routes.getAccessToken: getAccessToken(result) +// case Constants.Routes.getAccessToken: getAccessToken(result) // fingerprint case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) From 0fc23603c6d87e46c1d9466c2eb4ab1431351563 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:56:02 +0100 Subject: [PATCH 023/364] FP-20: Fixup example app with pigeon types --- example/ios/Podfile.lock | 2 +- example/lib/screens/login_screen.dart | 18 +++++------ example/lib/screens/pin_request_screen.dart | 24 +++++++-------- example/lib/screens/user_screen.dart | 33 ++++++++++----------- 4 files changed, 35 insertions(+), 42 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index d0defe9b..531de25e 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de + url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index eb0f02e8..bd6c2756 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -131,7 +131,7 @@ class _LoginScreenState extends State { }); } - Future> getUserProfiles() async { + Future> getUserProfiles() async { try { var userApi = UserClientApi(); var derp = await userApi.fetchUserProfiles(); @@ -151,13 +151,11 @@ class _LoginScreenState extends State { var userProfileId = await Onegini.instance.userClient .authenticateUserImplicitly(profileId, ["read"]); - if (userProfileId != null) { - var response = await Onegini.instance.resourcesMethods - .getResourceImplicit("user-id-decorated"); - var res = json.decode(response); + var response = await Onegini.instance.resourcesMethods + .getResourceImplicit("user-id-decorated"); + var res = json.decode(response); - returnString = json.decode(res["body"])["decorated_user_id"]; - } + returnString = json.decode(res["body"])["decorated_user_id"]; return returnString; } catch (err) { @@ -207,7 +205,7 @@ class _LoginScreenState extends State { SizedBox( height: 20, ), - FutureBuilder>( + FutureBuilder>( //userProfiles future: getUserProfiles(), builder: (context, userProfiles) { @@ -264,7 +262,7 @@ class _LoginScreenState extends State { ), FutureBuilder< List< - OneginiListResponse>>( + OWAuthenticator>>( future: Onegini .instance.userClient .getRegisteredAuthenticators( @@ -347,7 +345,7 @@ class _LoginScreenState extends State { SizedBox( height: 20, ), - FutureBuilder>( + FutureBuilder>( future: Onegini.instance.userClient .getIdentityProviders(context), builder: (BuildContext context, identityProviders) { diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index ace1e64e..e8f675b3 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -83,7 +83,7 @@ class _PinRequestScreenState extends State { ); } } else { - bool isSuccess = await Onegini.instance.userClient + await Onegini.instance.userClient .validatePinWithPolicy(pin) .catchError((error) { if (error is PlatformException) { @@ -91,18 +91,16 @@ class _PinRequestScreenState extends State { showFlutterToast(error.message); } }); - if (isSuccess != null && isSuccess) { - Navigator.of(context) - ..pop() - ..push( - MaterialPageRoute( - builder: (context) => PinRequestScreen( - confirmation: true, - previousCode: pin, - customAuthenticator: this.widget.customAuthenticator, - )), - ); - } + Navigator.of(context) + ..pop() + ..push( + MaterialPageRoute( + builder: (context) => PinRequestScreen( + confirmation: true, + previousCode: pin, + customAuthenticator: this.widget.customAuthenticator, + )), + ); } } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6a2b3410..6bf23872 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -11,6 +11,7 @@ import 'package:onegini_example/models/application_details.dart'; import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:onegini/pigeon.dart'; import '../main.dart'; import 'login_screen.dart'; @@ -28,8 +29,8 @@ class _UserScreenState extends State with RouteAware { int _currentIndex = 0; List _children; bool isContainNotRegisteredAuthenticators = true; - List registeredAuthenticators = []; - List notRegisteredAuthenticators = []; + List registeredAuthenticators = []; + List notRegisteredAuthenticators = []; String profileId = ""; void onTabTapped(int index) { @@ -89,7 +90,7 @@ class _UserScreenState extends State with RouteAware { .getRegisteredAuthenticators(context, this.profileId); } - Future> getAllSortAuthenticators() async { + Future> getAllSortAuthenticators() async { var allAuthenticators = await Onegini.instance.userClient .getAllAuthenticators(context, this.profileId); allAuthenticators.sort((a, b) { @@ -98,7 +99,7 @@ class _UserScreenState extends State with RouteAware { return allAuthenticators; } - Future> getNotRegisteredAuthenticators() async { + Future> getNotRegisteredAuthenticators() async { var authenticators = await Onegini.instance.userClient .getNotRegisteredAuthenticators(context, this.profileId); return authenticators; @@ -154,19 +155,17 @@ class _UserScreenState extends State with RouteAware { return; } - var isLogOut = await Onegini.instance.userClient + await Onegini.instance.userClient .deregisterUser(profileId) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); } }); - if (isLogOut != null && isLogOut) { - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => LoginScreen()), - ); - } + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => LoginScreen()), + ); } changePin(BuildContext context) { @@ -203,7 +202,7 @@ class _UserScreenState extends State with RouteAware { DrawerHeader( child: Container(), ), - FutureBuilder>( + FutureBuilder>( future: getAllSortAuthenticators(), builder: (BuildContext context, snapshot) { return ListView.builder( @@ -233,7 +232,7 @@ class _UserScreenState extends State with RouteAware { }); }, ), - FutureBuilder>( + FutureBuilder>( future: Onegini.instance.userClient .getRegisteredAuthenticators(context, this.profileId), builder: (BuildContext context, snapshot) { @@ -415,12 +414,10 @@ class Info extends StatefulWidget { class _InfoState extends State { Future getApplicationDetails() async { var response = ""; - var success = await Onegini.instance.userClient + await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - if (success != null && success) { - response = await Onegini.instance.resourcesMethods - .getResourceAnonymous("application-details"); - } + response = await Onegini.instance.resourcesMethods + .getResourceAnonymous("application-details"); var res = json.decode(response); return applicationDetailsFromJson(res["body"]); } From 2280395e76f8bf0d46de8dbd76d2dc5ef56f6303 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:59:13 +0100 Subject: [PATCH 024/364] Add pigeon function stubs --- .../NativeBridge/Handlers/PinHandler.swift | 11 +- .../OneginiModuleSwift+Auth.swift | 4 +- .../OneginiModuleSwift+Pin.swift | 2 +- .../SwiftOneginiPlugin+Auth.swift | 15 --- ios/Classes/SwiftOneginiPlugin.swift | 107 ++++++++++++++++-- 5 files changed, 109 insertions(+), 30 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index bed146d9..9919745a 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -1,6 +1,15 @@ import OneginiSDKiOS import Flutter +protocol PinConnectorToPinHandler: AnyObject { + func onPinProvided(pin: String) + func onChangePinCalled(completion: @escaping (Bool, SdkError?) -> Void) + func onCancel() + func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) + func closeFlow() + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) +} + protocol PinHandlerToReceiverProtocol: class { func handlePin(pin: String?) } @@ -57,7 +66,7 @@ class PinHandler: NSObject { } //MARK: - -extension PinHandler { +extension PinHandler: PinConnectorToPinHandler{ func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) { if(self.flow == nil){ self.flow = flow diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 05e7d1f2..8ee9d8e1 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -126,11 +126,11 @@ extension OneginiModuleSwift { } } - func getAuthenticatedUserProfile() -> Result { + func getAuthenticatedUserProfile() -> Result { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { return .failure(SdkError(.noUserProfileIsAuthenticated)) } - return .success(FPUserProfile(profile)) + return .success(OWUserProfile(profile)) } func getAccessToken() -> Result { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index c8a2e63a..77e1ad46 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -20,7 +20,7 @@ extension OneginiModuleSwift { } } - func validatePinWithPolicy(_ pin: String, completion: (Result) -> Void) { + func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in completion(result) }) diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index a902e4d3..7c6c7a31 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -154,13 +154,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: _pin) } - func validatePinWithPolicy(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _pin = _arg["pin"] as! String? else { - result(SdkError(.emptyInputValue).flutterError()) - return; - } - OneginiModuleSwift.sharedInstance.validatePinWithPolicy(_pin, callback: result) - } func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.cancelPinAuth() @@ -169,12 +162,4 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { func logout(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.logOut(callback:result) } - - func getAuthenticatedUserProfile(_ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile(callback: result) - } - - func getAccessToken(_ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.getAccessToken(callback: result) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 918f389b..791b5fd8 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -30,6 +30,101 @@ func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { + + + func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { + + } + + func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) { + + } + + func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { + + } + + func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { + + } + + func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + + } + + func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + + } + + func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile()) + } + + func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { + + } + + func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + + } + + func changePin(completion: @escaping (Result) -> Void) { + + } + + func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + + } + + func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + + } + + func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + + } + + func logout(completion: @escaping (Result) -> Void) { + + } + + func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { + + } + + func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { + + } + + func getAccessToken(completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getAccessToken()) + } + + func getRedirectUrl(completion: @escaping (Result) -> Void) { + + } + + func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { + + } + + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { + + } + + func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { + + } + + func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) { + + } + + // FIXME: Remove when deleted from api + func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { + + } + static var flutterApi: NativeCallFlutterApi? public static func register(with registrar: FlutterPluginRegistrar) { @@ -68,7 +163,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.startApp: startApp(call, result) // register - case Constants.Routes.registerUser: registerUser(call, result) +// case Constants.Routes.registerUser: registerUser(call, result) case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) case Constants.Routes.getIdentityProviders: getIdentityProviders(call, result) @@ -103,8 +198,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.logout: logout(call, result) - case Constants.Routes.validatePinWithPolicy: - validatePinWithPolicy(call, result) // case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) case Constants.Routes.getUserProfiles: getUserProfiles(result) // case Constants.Routes.getAccessToken: getAccessToken(result) @@ -133,12 +226,4 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } } } - - // Example function for Flutter -> Native functions and how to return a response or error - func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) { - // let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) - completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) - - // completion(.success([PigeonUserProfile(profileId: "boopios", isDefault: true)])) - } } From 83500478d733d0c5d232a0d3f1e937c33448890a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:03:21 +0100 Subject: [PATCH 025/364] Delete old pigeons interface file --- pigeons/onewelcomePigeonInterface.dart | 160 ------------------------- 1 file changed, 160 deletions(-) delete mode 100644 pigeons/onewelcomePigeonInterface.dart diff --git a/pigeons/onewelcomePigeonInterface.dart b/pigeons/onewelcomePigeonInterface.dart deleted file mode 100644 index 8f542994..00000000 --- a/pigeons/onewelcomePigeonInterface.dart +++ /dev/null @@ -1,160 +0,0 @@ -import 'package:pigeon/pigeon.dart'; - -// @ConfigurePigeon(PigeonOptions( -// dartOut: './../lib/pigeon.dart', -// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', -// kotlinOptions: KotlinOptions( -// // copyrightHeader: ['zero'], -// package: 'com.zero.flutter_pigeon_plugin', -// ), -// objcHeaderOut: 'ios/Runner/Pigeon.h', -// objcSourceOut: 'ios/Runner/Pigeon.m', -// objcOptions: ObjcOptions( -// prefix: 'FLT', -// ), -// )) - -/// Result objects -class OneWelcomeUserProfile { - String profileId; - bool isDefault; - - OneWelcomeUserProfile({required this.profileId, required this.isDefault}); -} - -class OneWelcomeCustomInfo { - int status; - String data; - - OneWelcomeCustomInfo({required this.status, required this.data}); -} - -class OneWelcomeIdentityProvider { - String id; - String name; - - OneWelcomeIdentityProvider({required this.id, required this.name}); -} - -class OneWelcomeAuthenticator { - String id; - String name; - - OneWelcomeAuthenticator({required this.id, required this.name}); -} - -class OneWelcomeAppToWebSingleSignOn { - String token; - String redirectUrl; - - OneWelcomeAppToWebSingleSignOn({required this.token, required this.redirectUrl}); -} - -class OneWelcomeRegistrationResponse { - OneWelcomeUserProfile userProfile; - OneWelcomeCustomInfo? customInfo; - - OneWelcomeRegistrationResponse({required this.userProfile, this.customInfo}); -} - -/// Flutter calls native -@HostApi() -abstract class UserClientApi { - // example one - @async - List fetchUserProfiles(); - - @async - void voidFunction(); - - @async - String? nullableStringFunction(); - // // todo removed buildcontext - // @async - // OneWelcomeRegistrationResponse registerUser(String? identityProviderId, List? scopes); - - // @async - // void handleRegisteredUserUrl(String? url, int signInType); - - // // todo removed buildcontext - // @async - // List getIdentityProviders(); - - // // removed boolean return - // @async - // void deregisterUser(String profileId); - - // // todo removed buildconext - // @async - // List getRegisteredAuthenticators(String profileId); - - // // todo removed buildconext - // @async - // List getAllAuthenticators(String profileId); - - // @async - // OneWelcomeUserProfile getAuthenticatedUserProfile(); - - // // todo removed build context - // @async - // OneWelcomeRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); - - // // todo removed context - // @async - // List getNotRegisteredAuthenticators(String profileId); - - // // todo removed context - // @async - // void changePin(); - - // // removed context and changed it into void instead of boolean - // @async - // void setPreferredAuthenticator(String authenticatorId); - - // // removed context and changed it into void instead of boolean - // @async - // void deregisterAuthenticator(String authenticatorId); - - // // removed context and changed it into void instead of boolean - // @async - // void logout(); - - // // todo investigate if string can be non null - // @async - // String? mobileAuthWithOtp(String data); - - // @async - // OneWelcomeAppToWebSingleSignOn getAppToWebSingleSignOn(String url); - - // @async - // String getAccessToken(); - - // @async - // String getRedirectUrl(); - - // @async - // List getUserProfiles(); - - // @async - // bool validatePinWithPolicy(); - - // @async - // bool authenticateDevice(List? scopes); - - // // todo update return value to object - // @async - // OneWelcomeUserProfile authenticateUserImplicitly(String profileId, List? scopes); -} - -@HostApi() -abstract class ResourceMethodApi { - @async - List fetchUserProfiles(); -} - -/// Native calls to Flutter -@FlutterApi() -abstract class NativeCallFlutterApi { - @async - String testEventFunction(String argument); -} From 071c329570dc296859d7b3cbd1169da16dd021ca Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:56:02 +0100 Subject: [PATCH 026/364] FP-20: Fixup example app with pigeon types --- example/ios/Podfile.lock | 2 +- example/lib/screens/login_screen.dart | 18 +++++------ example/lib/screens/pin_request_screen.dart | 24 +++++++-------- example/lib/screens/user_screen.dart | 33 ++++++++++----------- 4 files changed, 35 insertions(+), 42 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index d0defe9b..531de25e 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de + url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index eb0f02e8..bd6c2756 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -131,7 +131,7 @@ class _LoginScreenState extends State { }); } - Future> getUserProfiles() async { + Future> getUserProfiles() async { try { var userApi = UserClientApi(); var derp = await userApi.fetchUserProfiles(); @@ -151,13 +151,11 @@ class _LoginScreenState extends State { var userProfileId = await Onegini.instance.userClient .authenticateUserImplicitly(profileId, ["read"]); - if (userProfileId != null) { - var response = await Onegini.instance.resourcesMethods - .getResourceImplicit("user-id-decorated"); - var res = json.decode(response); + var response = await Onegini.instance.resourcesMethods + .getResourceImplicit("user-id-decorated"); + var res = json.decode(response); - returnString = json.decode(res["body"])["decorated_user_id"]; - } + returnString = json.decode(res["body"])["decorated_user_id"]; return returnString; } catch (err) { @@ -207,7 +205,7 @@ class _LoginScreenState extends State { SizedBox( height: 20, ), - FutureBuilder>( + FutureBuilder>( //userProfiles future: getUserProfiles(), builder: (context, userProfiles) { @@ -264,7 +262,7 @@ class _LoginScreenState extends State { ), FutureBuilder< List< - OneginiListResponse>>( + OWAuthenticator>>( future: Onegini .instance.userClient .getRegisteredAuthenticators( @@ -347,7 +345,7 @@ class _LoginScreenState extends State { SizedBox( height: 20, ), - FutureBuilder>( + FutureBuilder>( future: Onegini.instance.userClient .getIdentityProviders(context), builder: (BuildContext context, identityProviders) { diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index ace1e64e..e8f675b3 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -83,7 +83,7 @@ class _PinRequestScreenState extends State { ); } } else { - bool isSuccess = await Onegini.instance.userClient + await Onegini.instance.userClient .validatePinWithPolicy(pin) .catchError((error) { if (error is PlatformException) { @@ -91,18 +91,16 @@ class _PinRequestScreenState extends State { showFlutterToast(error.message); } }); - if (isSuccess != null && isSuccess) { - Navigator.of(context) - ..pop() - ..push( - MaterialPageRoute( - builder: (context) => PinRequestScreen( - confirmation: true, - previousCode: pin, - customAuthenticator: this.widget.customAuthenticator, - )), - ); - } + Navigator.of(context) + ..pop() + ..push( + MaterialPageRoute( + builder: (context) => PinRequestScreen( + confirmation: true, + previousCode: pin, + customAuthenticator: this.widget.customAuthenticator, + )), + ); } } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6a2b3410..6bf23872 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -11,6 +11,7 @@ import 'package:onegini_example/models/application_details.dart'; import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:onegini/pigeon.dart'; import '../main.dart'; import 'login_screen.dart'; @@ -28,8 +29,8 @@ class _UserScreenState extends State with RouteAware { int _currentIndex = 0; List _children; bool isContainNotRegisteredAuthenticators = true; - List registeredAuthenticators = []; - List notRegisteredAuthenticators = []; + List registeredAuthenticators = []; + List notRegisteredAuthenticators = []; String profileId = ""; void onTabTapped(int index) { @@ -89,7 +90,7 @@ class _UserScreenState extends State with RouteAware { .getRegisteredAuthenticators(context, this.profileId); } - Future> getAllSortAuthenticators() async { + Future> getAllSortAuthenticators() async { var allAuthenticators = await Onegini.instance.userClient .getAllAuthenticators(context, this.profileId); allAuthenticators.sort((a, b) { @@ -98,7 +99,7 @@ class _UserScreenState extends State with RouteAware { return allAuthenticators; } - Future> getNotRegisteredAuthenticators() async { + Future> getNotRegisteredAuthenticators() async { var authenticators = await Onegini.instance.userClient .getNotRegisteredAuthenticators(context, this.profileId); return authenticators; @@ -154,19 +155,17 @@ class _UserScreenState extends State with RouteAware { return; } - var isLogOut = await Onegini.instance.userClient + await Onegini.instance.userClient .deregisterUser(profileId) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); } }); - if (isLogOut != null && isLogOut) { - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => LoginScreen()), - ); - } + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => LoginScreen()), + ); } changePin(BuildContext context) { @@ -203,7 +202,7 @@ class _UserScreenState extends State with RouteAware { DrawerHeader( child: Container(), ), - FutureBuilder>( + FutureBuilder>( future: getAllSortAuthenticators(), builder: (BuildContext context, snapshot) { return ListView.builder( @@ -233,7 +232,7 @@ class _UserScreenState extends State with RouteAware { }); }, ), - FutureBuilder>( + FutureBuilder>( future: Onegini.instance.userClient .getRegisteredAuthenticators(context, this.profileId), builder: (BuildContext context, snapshot) { @@ -415,12 +414,10 @@ class Info extends StatefulWidget { class _InfoState extends State { Future getApplicationDetails() async { var response = ""; - var success = await Onegini.instance.userClient + await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - if (success != null && success) { - response = await Onegini.instance.resourcesMethods - .getResourceAnonymous("application-details"); - } + response = await Onegini.instance.resourcesMethods + .getResourceAnonymous("application-details"); var res = json.decode(response); return applicationDetailsFromJson(res["body"]); } From 4efd448255dc775daf02378ddca887a6b626b17c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:18:44 +0100 Subject: [PATCH 027/364] FP-20: Remove testing lines --- example/lib/screens/login_screen.dart | 4 ---- 1 file changed, 4 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index bd6c2756..0a6f654e 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -133,10 +133,6 @@ class _LoginScreenState extends State { Future> getUserProfiles() async { try { - var userApi = UserClientApi(); - var derp = await userApi.fetchUserProfiles(); - print(derp[0].profileId); - var profiles = await Onegini.instance.userClient.getUserProfiles(); return profiles; } catch (err) { From 5bebd13f00ec3577ad3cf100f1d58d3d5fa523a4 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:19:03 +0100 Subject: [PATCH 028/364] FP-20: iOS: Implement pigeon getUserProfiles --- ios/Classes/NativeBridge/OneginiModuleSwift.swift | 8 ++------ .../PluginExtensions/SwiftOneginiPlugin+Other.swift | 5 ----- ios/Classes/SwiftOneginiPlugin.swift | 6 +----- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index d9a56605..5b1470ed 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -61,13 +61,9 @@ public class OneginiModuleSwift: NSObject, ConnectorToFlutterBridgeProtocol, Flu } } - func getUserProfiles(callback: @escaping FlutterResult) { + func getUserProfiles() -> Result<[OWUserProfile], Error> { let profiles = ONGUserClient.sharedInstance().userProfiles() - let value: [[String: String?]] = profiles.compactMap({ ["profileId": $0.profileId] }) - - let data = String.stringify(json: value) - - callback(data) + return .success(profiles.compactMap({OWUserProfile($0)})) } public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift index dddc6ab9..bc995d81 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift @@ -5,7 +5,6 @@ import Flutter protocol OneginiPluginOtherProtocol { func changePin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func getAppToWebSingleSignOn(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func getUserProfiles(_ result: @escaping FlutterResult) -> Void } extension SwiftOneginiPlugin: OneginiPluginOtherProtocol { @@ -17,9 +16,5 @@ extension SwiftOneginiPlugin: OneginiPluginOtherProtocol { guard let _arg = call.arguments as! [String: Any]?, let _path = _arg["url"] as! String? else { return; } OneginiModuleSwift.sharedInstance.runSingleSignOn(_path, callback: result) } - - func getUserProfiles(_ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.getUserProfiles(callback: result) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 791b5fd8..4a38ea4e 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -105,7 +105,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getUserProfiles()) } func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { @@ -198,10 +198,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.logout: logout(call, result) -// case Constants.Routes.getAuthenticatedUserProfile: getAuthenticatedUserProfile(result) - case Constants.Routes.getUserProfiles: getUserProfiles(result) -// case Constants.Routes.getAccessToken: getAccessToken(result) - // fingerprint case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) case Constants.Routes.denyFingerprintAuthenticationRequest: denyFingerprintAuthenticationRequest(call, result) From 0e4de9321434d843b1aa5cb9749de0547a20952b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:33:25 +0100 Subject: [PATCH 029/364] FP-20: Add fields to OWAuthenticator type --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 13 +++++++++++-- ios/Classes/Pigeon.swift | 14 +++++++++++++- lib/pigeon.dart | 15 +++++++++++++++ pigeons/onewelcome_pigeon_interface.dart | 18 ++++++++++++++---- 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 302f2496..7f466aad 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -107,7 +107,10 @@ data class OWIdentityProvider ( /** Generated class from Pigeon that represents data sent in messages. */ data class OWAuthenticator ( val id: String, - val name: String + val name: String, + val isRegistered: Boolean, + val isPreferred: Boolean, + val authenticatorType: Long ) { companion object { @@ -115,13 +118,19 @@ data class OWAuthenticator ( fun fromList(list: List): OWAuthenticator { val id = list[0] as String val name = list[1] as String - return OWAuthenticator(id, name) + val isRegistered = list[2] as Boolean + val isPreferred = list[3] as Boolean + val authenticatorType = list[4].let { if (it is Int) it.toLong() else it as Long } + return OWAuthenticator(id, name, isRegistered, isPreferred, authenticatorType) } } fun toList(): List { return listOf( id, name, + isRegistered, + isPreferred, + authenticatorType, ) } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 1162d0cd..54464e0e 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -99,20 +99,32 @@ struct OWIdentityProvider { struct OWAuthenticator { var id: String var name: String + var isRegistered: Bool + var isPreferred: Bool + var authenticatorType: Int32 static func fromList(_ list: [Any?]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String + let isRegistered = list[2] as! Bool + let isPreferred = list[3] as! Bool + let authenticatorType = list[4] as! Int32 return OWAuthenticator( id: id, - name: name + name: name, + isRegistered: isRegistered, + isPreferred: isPreferred, + authenticatorType: authenticatorType ) } func toList() -> [Any?] { return [ id, name, + isRegistered, + isPreferred, + authenticatorType, ] } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index f362cc47..50730eb9 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -86,16 +86,28 @@ class OWAuthenticator { OWAuthenticator({ required this.id, required this.name, + required this.isRegistered, + required this.isPreferred, + required this.authenticatorType, }); String id; String name; + bool isRegistered; + + bool isPreferred; + + int authenticatorType; + Object encode() { return [ id, name, + isRegistered, + isPreferred, + authenticatorType, ]; } @@ -104,6 +116,9 @@ class OWAuthenticator { return OWAuthenticator( id: result[0]! as String, name: result[1]! as String, + isRegistered: result[2]! as bool, + isPreferred: result[3]! as bool, + authenticatorType: result[4]! as int, ); } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 44476371..203d6c2b 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -38,8 +38,16 @@ class OWIdentityProvider { class OWAuthenticator { String id; String name; - - OWAuthenticator({required this.id, required this.name}); + bool isRegistered; + bool isPreferred; + int authenticatorType; + + OWAuthenticator( + {required this.id, + required this.name, + required this.isRegistered, + required this.isPreferred, + required this.authenticatorType}); } class OWAppToWebSingleSignOn { @@ -64,7 +72,8 @@ abstract class UserClientApi { List fetchUserProfiles(); @async - OWRegistrationResponse registerUser(String? identityProviderId, List? scopes); + OWRegistrationResponse registerUser( + String? identityProviderId, List? scopes); @async void handleRegisteredUserUrl(String? url, int signInType); @@ -86,7 +95,8 @@ abstract class UserClientApi { OWUserProfile getAuthenticatedUserProfile(); @async - OWRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); + OWRegistrationResponse authenticateUser( + String profileId, String? registeredAuthenticatorId); @async List getNotRegisteredAuthenticators(String profileId); From c436e4845a7a237fde982e0e2be83727445f48dc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:36:41 +0100 Subject: [PATCH 030/364] FP-20: iOS: Implement getAllAuthenticators --- .../OneginiModuleSwift+Register.swift | 13 ++++--------- .../SwiftOneginiPlugin+Auth.swift | 15 --------------- ios/Classes/SwiftOneginiPlugin.swift | 13 +++++++++++-- 3 files changed, 15 insertions(+), 26 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 5b61c292..7f91777b 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -126,19 +126,14 @@ extension OneginiModuleSwift { callback(String.stringify(json: authenticators)) } - func getAllAuthenticators(_ profileId: String, callback: @escaping FlutterResult) -> Void { + func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - callback(SdkError.convertToFlutter(SdkError(.userProfileDoesNotExist))) - return + return .failure(SdkError(.userProfileDoesNotExist)) } - // get all authenticators let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) - - // convert list to list of objects with id and name - let authenticators: [[String: String]] = allAuthenticators.compactMap({ ["id" : $0.identifier, "name": $0.name] }) - - callback(String.stringify(json: authenticators)) + + return .success(allAuthenticators.compactMap({OWAuthenticator($0)})) } func getRedirectUrl(callback: @escaping FlutterResult) -> Void { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 7c6c7a31..192d09f0 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -10,7 +10,6 @@ protocol OneginiPluginAuthProtocol { func getRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func getAllNotRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func getAllAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -104,20 +103,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId, callback: result) } - func getAllAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId, callback: result) - } - func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { result(SdkError(.methodArgumentNotFound).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 4a38ea4e..2e86c4d2 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -24,6 +24,16 @@ extension OWCustomInfo { } } +extension OWAuthenticator { + init(_ authenticator: ONGAuthenticator) { + id = authenticator.identifier + name = authenticator.name + isPreferred = authenticator.isPreferred + isRegistered = authenticator.isRegistered + authenticatorType = Int32(authenticator.type.rawValue) + } +} + func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } return OWCustomInfo(status: Int32(info.status), data: info.data) @@ -53,7 +63,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId)) } func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { @@ -189,7 +199,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.getRegisteredAuthenticators: getRegisteredAuthenticators(call, result) case Constants.Routes.getAllNotRegisteredAuthenticators: getAllNotRegisteredAuthenticators(call, result) - case Constants.Routes.getAllAuthenticators: getAllAuthenticators(call, result) case Constants.Routes.deregisterAuthenticator: deregisterAuthenticator(call, result) From 13e388640578319db1e25220469f0b1976985336 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:41:24 +0100 Subject: [PATCH 031/364] FP-20: Implement getRegisteredAuthenticators with pigeon --- .../OneginiModuleSwift+Register.swift | 14 +++----------- .../SwiftOneginiPlugin+Auth.swift | 15 --------------- ios/Classes/SwiftOneginiPlugin.swift | 3 +-- 3 files changed, 4 insertions(+), 28 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 7f91777b..31214e25 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -97,18 +97,12 @@ extension OneginiModuleSwift { } } - func getRegisteredAuthenticators(_ profileId: String, callback: @escaping FlutterResult) { + func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - callback(SdkError.convertToFlutter(SdkError(.userProfileDoesNotExist))) - return + return .failure(SdkError(.userProfileDoesNotExist)) } - let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) - - let authenticators: [[String: String]] = registeredAuthenticators.compactMap({ ["id" : $0.identifier, "name": $0.name] }) - - let data = String.stringify(json: authenticators) - callback(data) + return .success(registeredAuthenticators.compactMap({OWAuthenticator($0)})) } func getNotRegisteredAuthenticators(_ profileId: String, callback: @escaping FlutterResult) -> Void { @@ -130,9 +124,7 @@ extension OneginiModuleSwift { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { return .failure(SdkError(.userProfileDoesNotExist)) } - let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) - return .success(allAuthenticators.compactMap({OWAuthenticator($0)})) } diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 192d09f0..f2b9fa42 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -8,7 +8,6 @@ protocol OneginiPluginAuthProtocol { func authenticateUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func getRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func getAllNotRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) @@ -75,20 +74,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - func getRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId, callback: result) - } - func getAllNotRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { result(SdkError(.methodArgumentNotFound).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 2e86c4d2..d42f6b80 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -59,7 +59,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId)) } func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { @@ -197,7 +197,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - case Constants.Routes.getRegisteredAuthenticators: getRegisteredAuthenticators(call, result) case Constants.Routes.getAllNotRegisteredAuthenticators: getAllNotRegisteredAuthenticators(call, result) case Constants.Routes.deregisterAuthenticator: deregisterAuthenticator(call, result) From 91b78169e6101fd1edaf306b501c1247d9b5a4df Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:45:20 +0100 Subject: [PATCH 032/364] FP-20: Pigeon implement getNotRegisteredAuthenticators --- .../OneginiModuleSwift+Register.swift | 13 +++---------- .../SwiftOneginiPlugin+Auth.swift | 15 --------------- ios/Classes/SwiftOneginiPlugin.swift | 3 +-- 3 files changed, 4 insertions(+), 27 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 31214e25..6490794d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -105,19 +105,12 @@ extension OneginiModuleSwift { return .success(registeredAuthenticators.compactMap({OWAuthenticator($0)})) } - func getNotRegisteredAuthenticators(_ profileId: String, callback: @escaping FlutterResult) -> Void { + func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - callback(SdkError.convertToFlutter(SdkError(.userProfileDoesNotExist))) - return + return .failure(SdkError(.userProfileDoesNotExist)) } - - // get not registered authenticators let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) - - // convert list to list of objects with id and name - let authenticators: [[String: String]] = notRegisteredAuthenticators.compactMap({ ["id" : $0.identifier, "name": $0.name] }) - - callback(String.stringify(json: authenticators)) + return .success(notRegisteredAuthenticators.compactMap({OWAuthenticator($0)})) } func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index f2b9fa42..c059e15f 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -8,7 +8,6 @@ protocol OneginiPluginAuthProtocol { func authenticateUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func getAllNotRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -74,20 +73,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - func getAllNotRegisteredAuthenticators(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId, callback: result) - } - func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { result(SdkError(.methodArgumentNotFound).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index d42f6b80..a9bb80b7 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -75,7 +75,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId)) } func changePin(completion: @escaping (Result) -> Void) { @@ -197,7 +197,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - case Constants.Routes.getAllNotRegisteredAuthenticators: getAllNotRegisteredAuthenticators(call, result) case Constants.Routes.deregisterAuthenticator: deregisterAuthenticator(call, result) From f15cd9bebb8d36e98477d3f7b0b482084d91e326 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:52:44 +0100 Subject: [PATCH 033/364] FP-20: iOS: Pigeon implement getIdentityProviders --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 14 +++----------- .../SwiftOneginiPlugin+Register.swift | 6 ------ ios/Classes/SwiftOneginiPlugin.swift | 10 ++++++++-- 3 files changed, 11 insertions(+), 19 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 8ee9d8e1..4c14b13d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -4,17 +4,9 @@ import Flutter extension OneginiModuleSwift { - func identityProviders(callback: @escaping FlutterResult) { - let _providers = ONGClient.sharedInstance().userClient.identityProviders() - let jsonData = _providers.compactMap { (identityProvider) -> [String: Any]? in - var data = [String: Any]() - data["id"] = identityProvider.identifier - data["name"] = identityProvider.name - return data - } - - let data = String.stringify(json: jsonData) - callback(data) + func getIdentityProviders() -> Result<[OWIdentityProvider], Error> { + let providers = ONGClient.sharedInstance().userClient.identityProviders() + return .success(providers.compactMap({OWIdentityProvider($0)})) } func logOut(callback: @escaping FlutterResult) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index e4d1a600..60ebe32e 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -9,8 +9,6 @@ enum WebSignInType: Int { protocol OneginiPluginRegisterProtocol { - func getIdentityProviders(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func registerUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func handleRegisteredProcessUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -31,10 +29,6 @@ extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { func getRedirectUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.getRedirectUrl(callback: result) } - - func getIdentityProviders(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.identityProviders(callback: result) - } func registerUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { return; } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index a9bb80b7..78e5f913 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -34,6 +34,13 @@ extension OWAuthenticator { } } +extension OWIdentityProvider { + init(_ identityProvider: ONGIdentityProvider) { + id = identityProvider.identifier + name = identityProvider.name + } +} + func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } return OWCustomInfo(status: Int32(info.status), data: info.data) @@ -51,7 +58,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getIdentityProviders()) } func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { @@ -176,7 +183,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // case Constants.Routes.registerUser: registerUser(call, result) case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) - case Constants.Routes.getIdentityProviders: getIdentityProviders(call, result) case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) case Constants.Routes.setPreferredAuthenticator: setPreferredAuthenticator(call, result) From bc19a9bb1b222fe6b95c2dc43e92cf2a909bd500 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:55:21 +0100 Subject: [PATCH 034/364] FP-20: iOS: pigeon update validatePinWithPolicy implementation --- ios/Classes/NativeBridge/Handlers/PinHandler.swift | 4 ++-- .../ModuleExtensions/OneginiModuleSwift+Pin.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 9919745a..59bf9425 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -7,7 +7,7 @@ protocol PinConnectorToPinHandler: AnyObject { func onCancel() func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) func closeFlow() - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) } protocol PinHandlerToReceiverProtocol: class { @@ -136,7 +136,7 @@ extension PinHandler: PinConnectorToPinHandler{ processCancelAction() } - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in guard let error = error else { completion(.success(())) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 77e1ad46..d18a8f6d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -20,7 +20,7 @@ extension OneginiModuleSwift { } } - func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { + func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in completion(result) }) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 78e5f913..a2d439da 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -126,7 +126,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.validatePinWithPolicy(pin) { result in + completion(result) + } } func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { From 54be4fc643fed700a3751daea457d6cd3ed92346 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:57:55 +0100 Subject: [PATCH 035/364] FP-20: iOS: pigeon implement getRedirectUrl --- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 4 ++-- .../PluginExtensions/SwiftOneginiPlugin+Register.swift | 4 ---- ios/Classes/SwiftOneginiPlugin.swift | 3 +-- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 6490794d..8828b38b 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -121,8 +121,8 @@ extension OneginiModuleSwift { return .success(allAuthenticators.compactMap({OWAuthenticator($0)})) } - func getRedirectUrl(callback: @escaping FlutterResult) -> Void { - callback(ONGClient.sharedInstance().configModel.redirectURL) + func getRedirectUrl() -> Result { + return .success(ONGClient.sharedInstance().configModel.redirectURL) } } diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index 60ebe32e..5bc44dd6 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -21,14 +21,10 @@ protocol OneginiPluginRegisterProtocol { func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func deregisterUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func getRedirectUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { - func getRedirectUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.getRedirectUrl(callback: result) - } func registerUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { return; } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index a2d439da..401f01d7 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -118,7 +118,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getRedirectUrl(completion: @escaping (Result) -> Void) { - + completion(OneginiModuleSwift.sharedInstance.getRedirectUrl()) } func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { @@ -191,7 +191,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.acceptPinRegistrationRequest: acceptPinRegistrationRequest(call, result) case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) - case Constants.Routes.getRedirectUrl: getRedirectUrl(call, result) // custom registration case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) From f4175eb4e8b344bdd8bf43a37bd3584d9b96d912 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 17:56:16 +0100 Subject: [PATCH 036/364] FP-20: Pigeon implement AuthenticateUser --- .../NativeBridge/Handlers/LoginHandler.swift | 20 +++++---- .../OneginiModuleSwift+Auth.swift | 44 +++++-------------- .../SwiftOneginiPlugin+Auth.swift | 24 ---------- ios/Classes/SwiftOneginiPlugin.swift | 22 +++++++++- 4 files changed, 41 insertions(+), 69 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 840ad10b..9b29963b 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -3,7 +3,7 @@ import Flutter //MARK: - protocol BridgeToLoginHandlerProtocol: LoginHandlerToPinHanlderProtocol { - func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (ONGUserProfile?, SdkError?) -> Void) + func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (Result) -> Void) } protocol LoginHandlerToPinHanlderProtocol: class { @@ -14,7 +14,7 @@ protocol LoginHandlerToPinHanlderProtocol: class { class LoginHandler: NSObject, PinHandlerToReceiverProtocol { var pinChallenge: ONGPinChallenge? var customChallange: ONGCustomAuthFinishAuthenticationChallenge? - var loginCompletion: ((ONGUserProfile?, SdkError?) -> Void)? + var loginCompletion: ((Result) -> Void)? unowned var pinHandler: PinConnectorToPinHandler? @@ -47,7 +47,7 @@ class LoginHandler: NSObject, PinHandlerToReceiverProtocol { //MARK: - extension LoginHandler : BridgeToLoginHandlerProtocol { - func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (ONGUserProfile?, SdkError?) -> Void) { + func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (Result) -> Void) { loginCompletion = completion ONGUserClient.sharedInstance().authenticateUser(profile, authenticator: authenticator, delegate: self) } @@ -59,14 +59,14 @@ extension LoginHandler: ONGAuthenticationDelegate { pinChallenge = challenge let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) - if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue , challenge.previousFailureCount < challenge.maxFailureCount { // 9009 + if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue, challenge.previousFailureCount < challenge.maxFailureCount { // 9009 pinHandler?.handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) return } pinHandler?.handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) - guard let _ = pinError else { return } + guard let pinError = pinError else { return } guard challenge.maxFailureCount == challenge.previousFailureCount else { return } @@ -74,7 +74,7 @@ extension LoginHandler: ONGAuthenticationDelegate { pinHandler?.closeFlow() pinHandler?.onCancel() - loginCompletion?(nil, pinError) + loginCompletion?(.failure((FlutterError(pinError)))) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishAuthenticationChallenge) { @@ -97,7 +97,9 @@ extension LoginHandler: ONGAuthenticationDelegate { pinChallenge = nil customChallange = nil - loginCompletion?(userProfile, nil) + loginCompletion?(.success( + OWRegistrationResponse(userProfile: OWUserProfile(userProfile), + customInfo: toOWCustomInfo(customAuthInfo)))) pinHandler?.closeFlow() } @@ -109,10 +111,10 @@ extension LoginHandler: ONGAuthenticationDelegate { pinHandler?.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { - loginCompletion?(nil, SdkError(.loginCanceled)) + loginCompletion?(.failure(FlutterError(.loginCanceled))) } else { let mappedError = ErrorMapper().mapError(error) - loginCompletion?(nil, mappedError) + loginCompletion?(.failure(FlutterError(mappedError))) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 4c14b13d..54b0538f 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -15,23 +15,6 @@ extension OneginiModuleSwift { } } - func authenticateUserPin(_ profileId: String, completion: @escaping FlutterResult) -> Void { - guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { - completion(SdkError(.noUserProfileIsAuthenticated).flutterError()) - return - } - - bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: nil, completion: { - (userProfile, error) -> Void in - guard let userProfile = userProfile else { - completion(SdkError.convertToFlutter(error)) - return - } - - completion(String.stringify(json: [Constants.Keys.userProfile: [Constants.Keys.profileId: userProfile.profileId]])) - }) - } - public func authenticateUserImplicitly(_ profileId: String, _ scopes: [String]?, _ completion: @escaping FlutterResult) { guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { @@ -61,27 +44,20 @@ extension OneginiModuleSwift { error != nil ? callback(SdkError.convertToFlutter(error)) : callback(String.stringify(json: result ?? [])) }) } - - func authenticateWithRegisteredAuthentication(profileId: String, registeredAuthenticatorId: String, completion: @escaping FlutterResult) { + + func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { + guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { - completion(SdkError(.noUserProfileIsAuthenticated).flutterError()) + completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) return } - - guard let registeredAuthenticator = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile).first(where: { $0.identifier == registeredAuthenticatorId }) else { - completion(SdkError(.authenticatorNotFound).flutterError()) - return - } - - bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: registeredAuthenticator) { - (userProfile, error) -> Void in - guard let userProfile = userProfile else { - completion(SdkError.convertToFlutter(error)) - return - } - - completion(String.stringify(json: [Constants.Keys.userProfile: [Constants.Keys.profileId: userProfile.profileId]])) + + let authenticator = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile).first(where: { $0.identifier == authenticatorId }) + + bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in + completion(result) } + } func setPreferredAuthenticator(_ identifierId: String, completion: @escaping FlutterResult) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index c059e15f..19ee8b02 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -5,7 +5,6 @@ import Flutter protocol OneginiPluginAuthProtocol { func registerAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func authenticateUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) @@ -28,29 +27,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.registerAuthenticator(_authenticator, callback: result) } - func authenticateUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let registeredAuthenticatorId = arg["registeredAuthenticatorId"] as? String else { - // auth with pin - Logger.log("use pin for auth") - OneginiModuleSwift.sharedInstance.authenticateUserPin(profileId, completion: result) - return - } - - // auth with provider - Logger.log("use provider for auth") - OneginiModuleSwift.sharedInstance.authenticateWithRegisteredAuthentication(profileId: profileId, registeredAuthenticatorId: registeredAuthenticatorId, completion: result) - } - func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { result(SdkError(.methodArgumentNotFound).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 401f01d7..39ea673b 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -4,6 +4,17 @@ import OneginiSDKiOS extension FlutterError: Error {} +extension FlutterError { + convenience init(_ error: OneWelcomeWrapperError) { + let flutterError = SdkError(error).flutterError() + self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) + } + convenience init(_ error: SdkError) { + let flutterError = error.flutterError() + self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) + } +} + extension OWUserProfile { init(_ profile: UserProfile) { self.profileId = profile.profileId @@ -46,6 +57,12 @@ func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { return OWCustomInfo(status: Int32(info.status), data: info.data) } +func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { + guard let info = info else { return nil } + return OWCustomInfo(status: Int32(info.status), data: info.data) +} + + public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { @@ -78,7 +95,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorId: registeredAuthenticatorId) { result in + completion(result.mapError{$0}) + } } func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { @@ -200,7 +219,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // auth case Constants.Routes.registerAuthenticator: registerAuthenticator(call, result) - case Constants.Routes.authenticateUser: authenticateUser(call, result) case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) From 2480ed7386b13d0bb5d99b278baa5751507238a1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 17:59:03 +0100 Subject: [PATCH 037/364] FP-20: Throw FlutterError in implemetned functions We need to throw a flutterError instead of an Error or SdkError so this gets handled correctly in the generated code by pigeon. This commit does that :^). --- .../NativeBridge/Handlers/PinHandler.swift | 6 +++--- .../OneginiModuleSwift+Auth.swift | 11 ++++++----- .../OneginiModuleSwift+Pin.swift | 2 +- .../OneginiModuleSwift+Register.swift | 14 +++++++------- .../NativeBridge/OneginiModuleSwift.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 18 +++++++++--------- 6 files changed, 27 insertions(+), 26 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 59bf9425..833dfb5e 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -7,7 +7,7 @@ protocol PinConnectorToPinHandler: AnyObject { func onCancel() func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) func closeFlow() - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) } protocol PinHandlerToReceiverProtocol: class { @@ -136,13 +136,13 @@ extension PinHandler: PinConnectorToPinHandler{ processCancelAction() } - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in guard let error = error else { completion(.success(())) return } - completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription))) + completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 54b0538f..4db14187 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -4,7 +4,7 @@ import Flutter extension OneginiModuleSwift { - func getIdentityProviders() -> Result<[OWIdentityProvider], Error> { + func getIdentityProviders() -> Result<[OWIdentityProvider], FlutterError> { let providers = ONGClient.sharedInstance().userClient.identityProviders() return .success(providers.compactMap({OWIdentityProvider($0)})) } @@ -86,6 +86,7 @@ extension OneginiModuleSwift { // Deregister Authenticator bridgeConnector.toAuthenticatorsHandler.deregisterAuthenticator(profile, identifierId) { value, error in guard error == nil else { + // FIXME: use Result and make this FlutterError completion(SdkError.convertToFlutter(error)) return } @@ -94,16 +95,16 @@ extension OneginiModuleSwift { } } - func getAuthenticatedUserProfile() -> Result { + func getAuthenticatedUserProfile() -> Result { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { - return .failure(SdkError(.noUserProfileIsAuthenticated)) + return .failure(FlutterError(.noUserProfileIsAuthenticated)) } return .success(OWUserProfile(profile)) } - func getAccessToken() -> Result { + func getAccessToken() -> Result { guard let accessToken = ONGUserClient.sharedInstance().accessToken else { - return .failure(SdkError(.noUserProfileIsAuthenticated)) + return .failure(FlutterError(.noUserProfileIsAuthenticated)) } return .success(accessToken) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index d18a8f6d..862dfde0 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -20,7 +20,7 @@ extension OneginiModuleSwift { } } - func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { + func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in completion(result) }) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 8828b38b..9f739d35 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -97,31 +97,31 @@ extension OneginiModuleSwift { } } - func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { + func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(SdkError(.userProfileDoesNotExist)) + return .failure(FlutterError(.userProfileDoesNotExist)) } let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) return .success(registeredAuthenticators.compactMap({OWAuthenticator($0)})) } - func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { + func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(SdkError(.userProfileDoesNotExist)) + return .failure(FlutterError(.userProfileDoesNotExist)) } let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) return .success(notRegisteredAuthenticators.compactMap({OWAuthenticator($0)})) } - func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], Error> { + func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(SdkError(.userProfileDoesNotExist)) + return .failure(FlutterError(.userProfileDoesNotExist)) } let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) return .success(allAuthenticators.compactMap({OWAuthenticator($0)})) } - func getRedirectUrl() -> Result { + func getRedirectUrl() -> Result { return .success(ONGClient.sharedInstance().configModel.redirectURL) } } diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index 5b1470ed..e86ef028 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -61,7 +61,7 @@ public class OneginiModuleSwift: NSObject, ConnectorToFlutterBridgeProtocol, Flu } } - func getUserProfiles() -> Result<[OWUserProfile], Error> { + func getUserProfiles() -> Result<[OWUserProfile], FlutterError> { let profiles = ONGUserClient.sharedInstance().userProfiles() return .success(profiles.compactMap({OWUserProfile($0)})) } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 39ea673b..9fa9f0d0 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -75,7 +75,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getIdentityProviders()) + completion(OneginiModuleSwift.sharedInstance.getIdentityProviders().mapError{$0}) } func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { @@ -83,15 +83,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId)) + completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError{$0}) } func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId)) + completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError{$0}) } func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile()) + completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError{$0}) } func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { @@ -101,7 +101,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId)) + completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError{$0}) } func changePin(completion: @escaping (Result) -> Void) { @@ -133,20 +133,20 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getAccessToken(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAccessToken()) + completion(OneginiModuleSwift.sharedInstance.getAccessToken().mapError{$0}) } func getRedirectUrl(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRedirectUrl()) + completion(OneginiModuleSwift.sharedInstance.getRedirectUrl().mapError{$0}) } func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getUserProfiles()) + completion(OneginiModuleSwift.sharedInstance.getUserProfiles().mapError{$0}) } func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.validatePinWithPolicy(pin) { result in - completion(result) + completion(result.mapError{$0}) } } From 4a0c749a9b07551dd82cdb53cb0759c1eb3cf180 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:19:57 +0100 Subject: [PATCH 038/364] FP-20: iOS: pigeon registeruser and wip handleRegisteredUserUrl --- .../Handlers/RegistrationHandler.swift | 25 +++++++++-------- .../OneginiModuleSwift+Register.swift | 26 +++++------------ .../SwiftOneginiPlugin+Register.swift | 28 +------------------ ios/Classes/SwiftOneginiPlugin.swift | 6 ++-- 4 files changed, 26 insertions(+), 59 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index a814fd5b..1632b2d6 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -1,7 +1,7 @@ import OneginiSDKiOS protocol RegistrationConnectorToHandlerProtocol: RegistrationHandlerToPinHanlderProtocol { - func signUp(_ providerId: String?, scopes: [String]?, completion: @escaping (Bool, ONGUserProfile?, ONGCustomInfo?, SdkError?) -> Void) + func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func processRedirectURL(url: String, webSignInType: WebSignInType) func cancelBrowserRegistration() func logout(completion: @escaping (SdkError?) -> Void) @@ -29,7 +29,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, Pi var logoutUserHandler = LogoutHandler() var deregisterUserHandler = DeregisterUserHandler() - var signUpCompletion: ((Bool, ONGUserProfile?, ONGCustomInfo?, SdkError?) -> Void)? + var signUpCompletion: ((Result) -> Void)? unowned var pinHandler: PinConnectorToPinHandler? @@ -75,7 +75,8 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, Pi func handleRedirectURL(url: URL?) { Logger.log("handleRedirectURL url: \(url?.absoluteString ?? "nil")", sender: self) guard let browserRegistrationChallenge = self.browserRegistrationChallenge else { - signUpCompletion?(false, nil, nil, SdkError(.genericError)) + //FIXME: Registration not in progress error here + signUpCompletion?(.failure(FlutterError(.genericError))) return } @@ -111,9 +112,8 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, Pi } } -//MARK:- extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { - func signUp(_ providerId: String?, scopes: [String]?, completion: @escaping (Bool, ONGUserProfile?, ONGCustomInfo?, SdkError?) -> Void) { + func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { signUpCompletion = completion var identityProvider = identityProviders().first(where: { $0.identifier == providerId}) @@ -136,12 +136,12 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { func processRedirectURL(url: String, webSignInType: WebSignInType) { guard let url = URL.init(string: url) else { - signUpCompletion?(false, nil, nil, SdkError(.providedUrlIncorrect)) + signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return } if webSignInType != .insideApp && !UIApplication.shared.canOpenURL(url) { - signUpCompletion?(false, nil, nil, SdkError(.providedUrlIncorrect)) + signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return } @@ -187,7 +187,10 @@ extension RegistrationHandler: ONGRegistrationDelegate { createPinChallenge = nil customRegistrationChallenge = nil pinHandler?.closeFlow() - signUpCompletion?(true, userProfile, info, nil) + + signUpCompletion?(.success( + OWRegistrationResponse(userProfile: OWUserProfile(userProfile), + customInfo: toOWCustomInfo(info)))) } func userClient(_: ONGUserClient, didReceiveCustomRegistrationInitChallenge challenge: ONGCustomRegistrationChallenge) { @@ -203,7 +206,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { Logger.log("didReceiveCustomRegistrationFinish ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge - var result = makeCustomInfoResponse(challenge) + let result = makeCustomInfoResponse(challenge) sendCustomRegistrationNotification(CustomRegistrationNotification.finishRegistration, result) } @@ -215,10 +218,10 @@ extension RegistrationHandler: ONGRegistrationDelegate { pinHandler?.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { - signUpCompletion?(false, nil, nil, SdkError(.registrationCancelled)) + signUpCompletion?(.failure(FlutterError(.registrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - signUpCompletion?(false, nil, nil, mappedError) + signUpCompletion?(.failure(FlutterError(mappedError))) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 9f739d35..bfcac53d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -2,6 +2,11 @@ import Foundation import OneginiSDKiOS import Flutter +enum WebSignInType: Int { + case insideApp = 0 + case safari +} + extension OneginiModuleSwift { func deregisterUser(profileId: String, callback: @escaping FlutterResult) { @@ -10,25 +15,8 @@ extension OneginiModuleSwift { } } - func registerUser(_ identityProviderId: String? = nil, scopes: [String]? = nil, callback: @escaping FlutterResult) -> Void { - - bridgeConnector.toRegistrationConnector.registrationHandler.signUp(identityProviderId, scopes: scopes) { (_, userProfile, userInfo, error) -> Void in - guard let userProfile = userProfile else { - callback(SdkError.convertToFlutter(error)) - return - } - - var result = Dictionary() - result["userProfile"] = ["profileId": userProfile.profileId] - - guard let userInfo = userInfo else { - callback(String.stringify(json: result)) - return - } - - result["customInfo"] = ["status": userInfo.status, "data": userInfo.data] - callback(String.stringify(json: result)) - } + func registerUser(_ identityProviderId: String? = nil, scopes: [String]? = nil, completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationConnector.registrationHandler.registerUser(identityProviderId, scopes: scopes, completion: completion) } func handleRegisteredProcessUrl(_ url: String, webSignInType: WebSignInType) -> Void { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index 5bc44dd6..a1164e7a 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -2,15 +2,9 @@ import Foundation import OneginiSDKiOS import Flutter -enum WebSignInType: Int { - case insideApp = 0 - case safari -} -protocol OneginiPluginRegisterProtocol { - func registerUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func handleRegisteredProcessUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void +protocol OneginiPluginRegisterProtocol { func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -26,26 +20,6 @@ protocol OneginiPluginRegisterProtocol { extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { - func registerUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { return; } - let identifier = arg["identityProviderId"] as? String - let scopes = arg["scopes"] as? [String] - OneginiModuleSwift.sharedInstance.registerUser(identifier, scopes: scopes, callback: result) - } - - func handleRegisteredProcessUrl(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { return } - let url = arg["url"] as? String - let typeValue = arg["type"] as? Int - - var type: WebSignInType = .insideApp - if let _typeValue = typeValue, let value = WebSignInType.init(rawValue: _typeValue) { - type = value - } - OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url ?? "", webSignInType: type) - result(nil) - } - func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 9fa9f0d0..ba9a4aae 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -68,10 +68,13 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.registerUser(identityProviderId, scopes: scopes) { result in + completion(result.mapError{$0}) + } } func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url ?? "", webSignInType: type) } func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { @@ -201,7 +204,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.startApp: startApp(call, result) // register -// case Constants.Routes.registerUser: registerUser(call, result) case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) From ab99f4e31502db7456b799d29bedd7189de9e4cf Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:21:35 +0100 Subject: [PATCH 039/364] FP-20: Pigeon: update handleRegisteredUserUrl non-nullable String arg. --- .../com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 4 ++-- ios/Classes/Pigeon.swift | 4 ++-- lib/pigeon.dart | 2 +- pigeons/onewelcome_pigeon_interface.dart | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 7f466aad..82da01d2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -257,7 +257,7 @@ private object UserClientApiCodec : StandardMessageCodec() { interface UserClientApi { fun fetchUserProfiles(callback: (Result>) -> Unit) fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) - fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) + fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) fun deregisterUser(profileId: String, callback: (Result) -> Unit) fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) @@ -334,7 +334,7 @@ interface UserClientApi { channel.setMessageHandler { message, reply -> var wrapped = listOf() val args = message as List - val urlArg = args[0] as? String + val urlArg = args[0] as String val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } api.handleRegisteredUserUrl(urlArg, signInTypeArg) { result: Result -> val error = result.exceptionOrNull() diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 54464e0e..fd46f6d6 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -243,7 +243,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { protocol UserClientApi { func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) @@ -309,7 +309,7 @@ class UserClientApiSetup { if let api = api { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let urlArg = args[0] as? String + let urlArg = args[0] as! String let signInTypeArg = args[1] as! Int32 api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 50730eb9..8a9829db 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -290,7 +290,7 @@ class UserClientApi { } } - Future handleRegisteredUserUrl(String? arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 203d6c2b..586127b7 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -76,7 +76,7 @@ abstract class UserClientApi { String? identityProviderId, List? scopes); @async - void handleRegisteredUserUrl(String? url, int signInType); + void handleRegisteredUserUrl(String url, int signInType); @async List getIdentityProviders(); From 729b009f05d32c73479f8ab9be1cc8ad5ec4df28 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 12:56:02 +0100 Subject: [PATCH 040/364] FP-20 Test setup for android including async function --- .../sdk/flutter/OneginiMethodsWrapper.kt | 6 +- .../mobile/sdk/flutter/PigeonInterface.kt | 140 ++++++++++--- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 48 ++++- .../GetAuthenticatedUserProfileUseCase.kt | 18 +- .../useCases/GetIdentityProvidersUseCase.kt | 24 +-- .../flutter/useCases/RegistrationUseCase.kt | 45 ++-- ...GetAuthenticatedUserProfileUseCaseTests.kt | 58 +++--- .../sdk/GetIdentityProvidersUseCaseTests.kt | 6 +- .../mobile/sdk/RegistrationUseCaseTests.kt | 193 +++++++++--------- ios/Classes/Pigeon.swift | 42 +++- lib/pigeon.dart | 50 ++++- pigeons/onewelcome_pigeon_interface.dart | 8 +- 12 files changed, 432 insertions(+), 206 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 9b8b0b33..1b55c45f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -40,7 +40,7 @@ class OneginiMethodsWrapper @Inject constructor( ) { fun registerUser(call: MethodCall, result: MethodChannel.Result) { - registrationUseCase(call, result) +// registrationUseCase(call, result) } fun respondCustomRegistrationAction( @@ -60,7 +60,7 @@ class OneginiMethodsWrapper @Inject constructor( } fun getIdentityProviders(result: MethodChannel.Result) { - getIdentityProvidersUseCase(result) +// getIdentityProvidersUseCase(result) } fun getAccessToken(result: MethodChannel.Result) { @@ -72,7 +72,7 @@ class OneginiMethodsWrapper @Inject constructor( } fun getAuthenticatedUserProfile(result: MethodChannel.Result) { - getAuthenticatedUserProfileUseCase(result) +// getAuthenticatedUserProfileUseCase(result) } fun getUserProfiles(result: MethodChannel.Result) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index c8d901c4..c26b7a34 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,5 +1,6 @@ package com.onegini.mobile.sdk.flutter +import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn @@ -7,8 +8,91 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile +import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase +import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase +import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase +import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUseCase +import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetImplicitResourceUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetResourceAnonymousUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetResourceUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetUnauthenticatedResourceUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase +import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase +import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase +import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase +import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase +import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase +import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUseCase +import javax.inject.Inject + +//private val getIdentityProvidersUseCase: GetIdentityProvidersUseCase +open class PigeonInterface : UserClientApi { + @Inject + lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase + @Inject + lateinit var authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase + @Inject + lateinit var authenticateUserUseCase: AuthenticateUserUseCase + @Inject + lateinit var cancelCustomRegistrationActionUseCase: CancelCustomRegistrationActionUseCase + @Inject + lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase + @Inject + lateinit var deregisterUserUseCase: DeregisterUserUseCase + @Inject + lateinit var getAccessTokenUseCase: GetAccessTokenUseCase + @Inject + lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase + @Inject + lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase + @Inject + lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase + @Inject + lateinit var getImplicitResourceUseCase: GetImplicitResourceUseCase + @Inject + lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase + @Inject + lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase + @Inject + lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase + @Inject + lateinit var getResourceAnonymousUseCase: GetResourceAnonymousUseCase + @Inject + lateinit var getResourceUseCase: GetResourceUseCase + @Inject + lateinit var getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase + @Inject + lateinit var getUserProfilesUseCase: GetUserProfilesUseCase + @Inject + lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase + @Inject + lateinit var isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase + @Inject + lateinit var logoutUseCase: LogoutUseCase + @Inject + lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase + @Inject + lateinit var registrationUseCase: RegistrationUseCase + @Inject + lateinit var resourceHelper: ResourceHelper + @Inject + lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase + @Inject + lateinit var startAppUseCase: StartAppUseCase + @Inject + lateinit var submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase -open class PigeonInterface: UserClientApi { // Example function on how it could be initiated on Flutter send to Native override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(OWUserProfile("ghalo"))) @@ -19,91 +103,101 @@ open class PigeonInterface: UserClientApi { } override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { - TODO("Not yet implemented") + registrationUseCase(identityProviderId, scopes, callback) +// flutterCallback(callback, result) } override fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getIdentityProviders(callback: (Result>) -> Unit) { - TODO("Not yet implemented") + val result = getIdentityProvidersUseCase() + flutterCallback(callback, result) } override fun deregisterUser(profileId: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun changePin(callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun logout(callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getAccessToken(callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getRedirectUrl(callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun getUserProfiles(callback: (Result>) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") } override fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) { - TODO("Not yet implemented") +// TODO("Not yet implemented") + } + + override fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { +// TODO("Not yet implemented") } private fun flutterCallback(callback: (Result) -> Unit, result: Result) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 302f2496..c3c1b392 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -63,14 +63,14 @@ data class OWUserProfile ( /** Generated class from Pigeon that represents data sent in messages. */ data class OWCustomInfo ( val status: Long, - val data: String + val data: String? = null ) { companion object { @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWCustomInfo { val status = list[0].let { if (it is Int) it.toLong() else it as Long } - val data = list[1] as String + val data = list[1] as? String return OWCustomInfo(status, data) } } @@ -269,6 +269,8 @@ interface UserClientApi { fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) + fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) + fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) companion object { /** The codec used by UserClientApi. */ @@ -739,6 +741,48 @@ interface UserClientApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val identityProviderIdArg = args[0] as String + val dataArg = args[1] as? String + api.submitCustomRegistrationAction(identityProviderIdArg, dataArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val identityProviderIdArg = args[0] as String + val errorArg = args[1] as String + api.cancelCustomRegistrationAction(identityProviderIdArg, errorArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt index 2c9e256b..c544ecbf 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt @@ -1,22 +1,18 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.errors.wrapperError -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject import javax.inject.Singleton @Singleton class GetAuthenticatedUserProfileUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - if (authenticatedUserProfile != null) { - val json = Gson().toJson(mapOf("profileId" to authenticatedUserProfile.profileId)) - result.success(json) - } else { - result.wrapperError(NO_USER_PROFILE_IS_AUTHENTICATED) - } + operator fun invoke(): Result { + return when (val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile) { + null -> Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) + else -> Result.success(OWUserProfile(authenticatedUserProfile.profileId)) } + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt index b710e9ae..3b96ee91 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt @@ -1,24 +1,20 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.GsonBuilder -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.flutter.OneginiSDK -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import javax.inject.Inject import javax.inject.Singleton @Singleton class GetIdentityProvidersUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - val gson = GsonBuilder().serializeNulls().create() - val identityProviders = oneginiSDK.oneginiClient.userClient.identityProviders - val providers: ArrayList> = ArrayList() - for (identityProvider in identityProviders) { - val map = mutableMapOf() - map["id"] = identityProvider.id - map["name"] = identityProvider.name - providers.add(map) - } - result.success(gson.toJson(providers)) + operator fun invoke(): Result> { + val identityProviders = oneginiSDK.oneginiClient.userClient.identityProviders + val providers: MutableList = mutableListOf() + + for (identityProvider in identityProviders) { + providers.add(OWIdentityProvider(identityProvider.id, identityProvider.name)) } + + return Result.success(providers) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index 5ebe757a..ae593367 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -1,7 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiRegistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiRegistrationError import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider @@ -10,22 +8,24 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile + import javax.inject.Inject import javax.inject.Singleton @Singleton class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val identityProviderId = call.argument("identityProviderId") - val scopes = call.argument>("scopes") ?: ArrayList() + operator fun invoke(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { val identityProvider = getIdentityProviderById(identityProviderId) if (identityProviderId != null && identityProvider == null) { - SdkError(IDENTITY_PROVIDER_NOT_FOUND).flutterError(result) - return + callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) } - register(identityProvider, scopes.toArray(arrayOfNulls(scopes.size)), result) + + val registerScopes = scopes?.toTypedArray() ?: emptyArray() + + register(identityProvider, registerScopes, callback) } private fun getIdentityProviderById(identityProviderId: String?): OneginiIdentityProvider? { @@ -41,20 +41,27 @@ class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK return foundIdentityProvider } - private fun register(identityProvider: OneginiIdentityProvider?, scopes: Array, result: MethodChannel.Result) { + private fun register(identityProvider: OneginiIdentityProvider?, scopes: Array?, callback: (Result) -> Unit) { oneginiSDK.oneginiClient.userClient.registerUser(identityProvider, scopes, object : OneginiRegistrationHandler { override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) { - val userProfileJson = mapOf("profileId" to userProfile.profileId, "isDefault" to userProfile.isDefault) - val customInfoJson = mapOf("data" to customInfo?.data, "status" to customInfo?.status) - val returnedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - result.success(returnedResult) + val user = OWUserProfile(userProfile.profileId) + + when (customInfo) { + null -> callback(Result.success(OWRegistrationResponse(user))) + else -> { + val info = OWCustomInfo(customInfo.status.toLong(), customInfo.data) + callback(Result.success(OWRegistrationResponse(user, info))) + } + } } override fun onError(oneginiRegistrationError: OneginiRegistrationError) { - SdkError( - code = oneginiRegistrationError.errorType, - message = oneginiRegistrationError.message - ).flutterError(result) + callback(Result.failure( + SdkError( + code = oneginiRegistrationError.errorType, + message = oneginiRegistrationError.message + ).pigeonError()) + ) } }) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index 6b6d083c..f066b87e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -1,54 +1,54 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.errors.wrapperError +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetAuthenticatedUserProfileUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase - @Before - fun attach() { - getAuthenticatedUserProfileUseCase = GetAuthenticatedUserProfileUseCase(oneginiSdk) - } + lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase + + @Before + fun attach() { + getAuthenticatedUserProfileUseCase = GetAuthenticatedUserProfileUseCase(oneginiSdk) + } - @Test - fun `When no user is authenticated, Then should reject with NO_USER_PROFILE_IS_AUTHENTICATED`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) + @Test + fun `When no user is authenticated, Then should reject with NO_USER_PROFILE_IS_AUTHENTICATED`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - getAuthenticatedUserProfileUseCase(resultSpy) + val result = getAuthenticatedUserProfileUseCase() - verify(resultSpy).wrapperError(NO_USER_PROFILE_IS_AUTHENTICATED) + when (val error = result.exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) + } + else -> fail("Test failed as no sdk error was passed") } + } - @Test - fun `When a user is authenticated, Then should return the userProfile as JSON`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + @Test + fun `When a user is authenticated, Then should return the userProfile as JSON`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - getAuthenticatedUserProfileUseCase(resultSpy) + val result = getAuthenticatedUserProfileUseCase().getOrNull() - val expectedResult = Gson().toJson(mapOf("profileId" to "QWERTY")) - - verify(resultSpy).success(eq(expectedResult)) - } -} \ No newline at end of file + Assert.assertEquals(result?.profileId, "QWERTY") + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt index 4b0659fb..2c41d53a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt @@ -40,7 +40,7 @@ class GetIdentityProvidersUseCaseTests { fun `should return empty list when sdk return empty set`() { whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(emptySet()) - getIdentityProvidersUseCase(resultSpy) + getIdentityProvidersUseCase() val expectedResult = Gson().toJson(emptyArray>()) verify(resultSpy).success(expectedResult) @@ -54,10 +54,10 @@ class GetIdentityProvidersUseCaseTests { whenever(oneginiIdentityProviderSecondMock.id).thenReturn("secondId") whenever(oneginiIdentityProviderSecondMock.name).thenReturn("secondName") - getIdentityProvidersUseCase(resultSpy) + getIdentityProvidersUseCase() val expectedArray = arrayOf(mapOf("id" to "firstId", "name" to "firstName"), mapOf("id" to "secondId", "name" to "secondName")) val expectedResult = Gson().toJson(expectedArray) verify(resultSpy).success(expectedResult) } -} \ No newline at end of file +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index cb59cc6e..77fa8dcc 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -1,7 +1,6 @@ package com.onegini.mobile.sdk import com.google.common.truth.Truth.assertThat -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiRegistrationHandler import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider @@ -9,143 +8,145 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.ArgumentMatchers.any import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.* @RunWith(MockitoJUnitRunner::class) class RegistrationUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var callbackSpy: (Result) -> Unit - @Mock - lateinit var oneginiIdentityProviderMock: OneginiIdentityProvider + @Mock + lateinit var callMock: MethodCall - lateinit var registrationUseCase: RegistrationUseCase + @Mock + lateinit var oneginiIdentityProviderMock: OneginiIdentityProvider - @Before - fun attach() { - registrationUseCase = RegistrationUseCase(oneginiSdk) - } - - @Test - fun `should call result success with identity provider id as a param when given identity provider id is null`() { - whenever(callMock.argument("identityProviderId")).thenReturn(null) - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read")) - whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNull(), eq(arrayOf("read")), any())).thenAnswer { - it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) - } + lateinit var registrationUseCase: RegistrationUseCase - registrationUseCase(callMock, resultSpy) + @Before + fun attach() { + registrationUseCase = RegistrationUseCase(oneginiSdk) + } - val userProfileJson = mapOf("profileId" to "QWERTY", "isDefault" to false) - val customInfoJson = mapOf("data" to "", "status" to 0) - val expectedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - - verify(resultSpy).success(expectedResult) + @Test + fun `should call result success with identity provider id as a param when given identity provider id is null`() { + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(emptySet()) + whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNull(), eq(arrayOf("read")), any())).thenAnswer { + it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - @Test - fun `should match the IDs with the identity provider id as a parameter when the given ID is found in the SDK identity providers`() { - val setOfIdentityProviders = setOf(oneginiIdentityProviderMock) - - whenever(oneginiIdentityProviderMock.id).thenReturn("testId") - whenever(callMock.argument("identityProviderId")).thenReturn("testId") - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read")) - whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOfIdentityProviders) + registrationUseCase(null, listOf("read"), callbackSpy) - registrationUseCase(callMock, resultSpy) - - argumentCaptor { - verify(oneginiSdk.oneginiClient.userClient).registerUser(capture(), eq(arrayOf("read")), any()) - assertThat(firstValue.id).isEqualTo("testId") - } + argumentCaptor>().apply { + verify(callbackSpy, times(1)).invoke(capture()) + val testUser = OWUserProfile("QWERTY") + val testInfo = OWCustomInfo(0, "") + Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) } + } - @Test - fun `should return error when the given ID is not found in the SDK identity providers`() { - val setOfIdentityProviders = setOf(oneginiIdentityProviderMock) + @Test + fun `should match the IDs with the identity provider id as a parameter when the given ID is found in the SDK identity providers`() { + val testProviderId = "testId" + val testScopes = listOf("read") + val setOfIdentityProviders = setOf(oneginiIdentityProviderMock) - whenever(oneginiIdentityProviderMock.id).thenReturn("test") - whenever(callMock.argument("identityProviderId")).thenReturn("testId") - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read")) - whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOfIdentityProviders) + whenever(oneginiIdentityProviderMock.id).thenReturn(testProviderId) + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOfIdentityProviders) - registrationUseCase(callMock, resultSpy) + registrationUseCase(testProviderId, testScopes, callbackSpy) - verify(resultSpy).error(eq(IDENTITY_PROVIDER_NOT_FOUND.code.toString()), eq(IDENTITY_PROVIDER_NOT_FOUND.message), any()) + argumentCaptor { + verify(oneginiSdk.oneginiClient.userClient).registerUser(capture(), eq(arrayOf("read")), any()) + assertThat(firstValue.id).isEqualTo(testProviderId) } + } - @Test - fun `should call result success with identity provider id as a param when given identity provider id is found in SDK identity providers`() { - val setOfIdentityProviders = setOf(oneginiIdentityProviderMock) + @Test + fun `should return error when the given ID is not found in the SDK identity providers`() { + whenever(oneginiIdentityProviderMock.id).thenReturn("id") + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderMock)) - whenever(oneginiIdentityProviderMock.id).thenReturn("testId") - whenever(callMock.argument("identityProviderId")).thenReturn("testId") - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read")) - whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOfIdentityProviders) - whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNotNull(), eq(arrayOf("read")), any())).thenAnswer { - it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) - } + registrationUseCase("differentId", listOf("read"), callbackSpy) - registrationUseCase(callMock, resultSpy) + argumentCaptor>().apply { + verify(callbackSpy, times(1)).invoke(capture()) - val userProfileJson = mapOf("profileId" to "QWERTY", "isDefault" to false) - val customInfoJson = mapOf("data" to "", "status" to 0) - val expectedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - verify(resultSpy).success(expectedResult) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.message, IDENTITY_PROVIDER_NOT_FOUND.message) + Assert.assertEquals(error.code, IDENTITY_PROVIDER_NOT_FOUND.code.toString()) + } + else -> fail("Test failed as no sdk error was passed") + } + } + } + + @Test + fun `should call result success with identity provider id as a param when given identity provider id is found in SDK identity providers`() { + whenever(oneginiIdentityProviderMock.id).thenReturn("testId") + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderMock)) + whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNotNull(), eq(arrayOf("read")), any())).thenAnswer { + it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - @Test - fun `should call 'registerUser' method once when given identity provider id is null`() { - whenever(callMock.argument("identityProviderId")).thenReturn(null) - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read")) - - registrationUseCase(callMock, resultSpy) + registrationUseCase("testId", listOf("read"), callbackSpy) - verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), eq(arrayOf("read")), any()) + argumentCaptor>().apply { + verify(callbackSpy, times(1)).invoke(capture()) + val testUser = OWUserProfile("QWERTY") + val testInfo = OWCustomInfo(0, "") + Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) } + } - @Test - fun `should scopes param be array of two scopes when given scopes contains two strings`() { - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read", "write")) + @Test + fun `should call 'registerUser' method once when given identity provider id is null`() { + registrationUseCase(null, listOf("read"), callbackSpy) - registrationUseCase(callMock, resultSpy) + verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), eq(arrayOf("read")), any()) + } - argumentCaptor> { - verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) - assertThat(firstValue.size).isEqualTo(2) - assertThat(firstValue).isEqualTo(arrayOf("read", "write")) - } - } + @Test + fun `should scopes param be array of two scopes when given scopes contains two strings`() { + registrationUseCase(null, listOf("read", "write"), callbackSpy) - @Test - fun `should scopes param be array of zero lengths when given scopes is null`() { - whenever(callMock.argument>("scopes")).thenReturn(null) + argumentCaptor> { + verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) + assertThat(firstValue.size).isEqualTo(2) + assertThat(firstValue).isEqualTo(arrayOf("read", "write")) + } + } - registrationUseCase(callMock, resultSpy) + @Test + fun `should scopes param be array of zero lengths when given scopes is null`() { + registrationUseCase(null, null, callbackSpy) - argumentCaptor> { - verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) - assertThat(firstValue).isEmpty() - } + argumentCaptor> { + verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) + assertThat(firstValue).isEmpty() } -} \ No newline at end of file + } +} diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 1162d0cd..7c96523c 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -54,11 +54,11 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { var status: Int32 - var data: String + var data: String? = nil static func fromList(_ list: [Any?]) -> OWCustomInfo? { let status = list[0] as! Int32 - let data = list[1] as! String + let data = list[1] as? String return OWCustomInfo( status: status, @@ -252,6 +252,8 @@ protocol UserClientApi { func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) + func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) + func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -639,6 +641,42 @@ class UserClientApiSetup { } else { authenticateUserImplicitlyChannel.setMessageHandler(nil) } + let submitCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + submitCustomRegistrationActionChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let identityProviderIdArg = args[0] as! String + let dataArg = args[1] as? String + api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + submitCustomRegistrationActionChannel.setMessageHandler(nil) + } + let cancelCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + cancelCustomRegistrationActionChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let identityProviderIdArg = args[0] as! String + let errorArg = args[1] as! String + api.cancelCustomRegistrationAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + cancelCustomRegistrationActionChannel.setMessageHandler(nil) + } } } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. diff --git a/lib/pigeon.dart b/lib/pigeon.dart index f362cc47..10afc724 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -33,12 +33,12 @@ class OWUserProfile { class OWCustomInfo { OWCustomInfo({ required this.status, - required this.data, + this.data, }); int status; - String data; + String? data; Object encode() { return [ @@ -51,7 +51,7 @@ class OWCustomInfo { result as List; return OWCustomInfo( status: result[0]! as int, - data: result[1]! as String, + data: result[1] as String?, ); } } @@ -786,6 +786,50 @@ class UserClientApi { return; } } + + Future submitCustomRegistrationAction(String arg_identityProviderId, String? arg_data) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_identityProviderId, arg_data]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future cancelCustomRegistrationAction(String arg_identityProviderId, String arg_error) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_identityProviderId, arg_error]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } } class ResourceMethodApi { diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 44476371..882971e7 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -23,7 +23,7 @@ class OWUserProfile { class OWCustomInfo { int status; - String data; + String? data; OWCustomInfo({required this.status, required this.data}); } @@ -134,6 +134,12 @@ abstract class UserClientApi { // todo update return value to object @async void authenticateUserImplicitly(String profileId, List? scopes); + + @async + void submitCustomRegistrationAction(String identityProviderId, String? data); + + @async + void cancelCustomRegistrationAction(String identityProviderId, String error); } @HostApi() From 0c83003cd3420b234b60b7a4257259b76a251f5a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:21:35 +0100 Subject: [PATCH 041/364] FP-20: Pigeon: update handleRegisteredUserUrl non-nullable String arg. --- .../com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 4 ++-- ios/Classes/Pigeon.swift | 4 ++-- lib/pigeon.dart | 2 +- pigeons/onewelcome_pigeon_interface.dart | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index c3c1b392..a60e9d7d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -248,7 +248,7 @@ private object UserClientApiCodec : StandardMessageCodec() { interface UserClientApi { fun fetchUserProfiles(callback: (Result>) -> Unit) fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) - fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) + fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) fun deregisterUser(profileId: String, callback: (Result) -> Unit) fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) @@ -327,7 +327,7 @@ interface UserClientApi { channel.setMessageHandler { message, reply -> var wrapped = listOf() val args = message as List - val urlArg = args[0] as? String + val urlArg = args[0] as String val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } api.handleRegisteredUserUrl(urlArg, signInTypeArg) { result: Result -> val error = result.exceptionOrNull() diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 7c96523c..9e8d5a82 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -231,7 +231,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { protocol UserClientApi { func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) @@ -299,7 +299,7 @@ class UserClientApiSetup { if let api = api { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let urlArg = args[0] as? String + let urlArg = args[0] as! String let signInTypeArg = args[1] as! Int32 api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 10afc724..1c087848 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -275,7 +275,7 @@ class UserClientApi { } } - Future handleRegisteredUserUrl(String? arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 882971e7..aa68bd58 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -67,7 +67,7 @@ abstract class UserClientApi { OWRegistrationResponse registerUser(String? identityProviderId, List? scopes); @async - void handleRegisteredUserUrl(String? url, int signInType); + void handleRegisteredUserUrl(String url, int signInType); @async List getIdentityProviders(); From 88aec2e833ab89f4d3b71d2477bed80c2322c951 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:45:02 +0100 Subject: [PATCH 042/364] FP-20: Update handleRegisteredUserUrl api --- lib/user_client.dart | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index bb5c8010..d5372e5b 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -13,6 +13,7 @@ import 'onegini.dart'; ///Сlass with basic methods available to the developer. class UserClient { final api = UserClientApi(); + ///Start registration flow. /// /// If [identityProviderId] is null, starts standard browser registration. @@ -27,7 +28,7 @@ class UserClient { } /// Start browser Registration logic - Future handleRegisteredUserUrl(BuildContext? context, String? url, + Future handleRegisteredUserUrl(BuildContext? context, String url, {WebSignInType signInType = WebSignInType.insideApp}) async { Onegini.instance.setEventContext(context); await api.handleRegisteredUserUrl(url, signInType.value); @@ -52,7 +53,8 @@ class UserClient { BuildContext? context, String profileId) async { Onegini.instance.setEventContext(context); - final registeredAuthenticators = await api.getRegisteredAuthenticators(profileId); + final registeredAuthenticators = + await api.getRegisteredAuthenticators(profileId); return registeredAuthenticators.whereType().toList(); } @@ -85,7 +87,8 @@ class UserClient { /// Returns a list of authenticators available to the user, but not yet registered. Future> getNotRegisteredAuthenticators( BuildContext? context, String profileId) async { - final notRegisteredAuthenticators = await api.getNotRegisteredAuthenticators(profileId); + final notRegisteredAuthenticators = + await api.getNotRegisteredAuthenticators(profileId); return notRegisteredAuthenticators.whereType().toList(); } @@ -135,8 +138,7 @@ class UserClient { } /// Single sign on the user web page. - Future getAppToWebSingleSignOn( - String url) async { + Future getAppToWebSingleSignOn(String url) async { return await api.getAppToWebSingleSignOn(url); } From f936ecc781288a5ce0f00f92032dd6d43abf12fb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:45:02 +0100 Subject: [PATCH 043/364] FP-20: Update handleRegisteredUserUrl api --- lib/user_client.dart | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index bb5c8010..d5372e5b 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -13,6 +13,7 @@ import 'onegini.dart'; ///Сlass with basic methods available to the developer. class UserClient { final api = UserClientApi(); + ///Start registration flow. /// /// If [identityProviderId] is null, starts standard browser registration. @@ -27,7 +28,7 @@ class UserClient { } /// Start browser Registration logic - Future handleRegisteredUserUrl(BuildContext? context, String? url, + Future handleRegisteredUserUrl(BuildContext? context, String url, {WebSignInType signInType = WebSignInType.insideApp}) async { Onegini.instance.setEventContext(context); await api.handleRegisteredUserUrl(url, signInType.value); @@ -52,7 +53,8 @@ class UserClient { BuildContext? context, String profileId) async { Onegini.instance.setEventContext(context); - final registeredAuthenticators = await api.getRegisteredAuthenticators(profileId); + final registeredAuthenticators = + await api.getRegisteredAuthenticators(profileId); return registeredAuthenticators.whereType().toList(); } @@ -85,7 +87,8 @@ class UserClient { /// Returns a list of authenticators available to the user, but not yet registered. Future> getNotRegisteredAuthenticators( BuildContext? context, String profileId) async { - final notRegisteredAuthenticators = await api.getNotRegisteredAuthenticators(profileId); + final notRegisteredAuthenticators = + await api.getNotRegisteredAuthenticators(profileId); return notRegisteredAuthenticators.whereType().toList(); } @@ -135,8 +138,7 @@ class UserClient { } /// Single sign on the user web page. - Future getAppToWebSingleSignOn( - String url) async { + Future getAppToWebSingleSignOn(String url) async { return await api.getAppToWebSingleSignOn(url); } From ea946860f64b5a4f33e45277636ea35e82067c5c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 12:48:29 +0100 Subject: [PATCH 044/364] FP-20: pigeon: Impl. processRedirectURL --- .../Handlers/RegistrationHandler.swift | 16 ++++++++++++---- .../OneginiModuleSwift+Register.swift | 9 +++------ ios/Classes/SwiftOneginiPlugin.swift | 5 ++--- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 1632b2d6..ad620db7 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -2,7 +2,7 @@ import OneginiSDKiOS protocol RegistrationConnectorToHandlerProtocol: RegistrationHandlerToPinHanlderProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func processRedirectURL(url: String, webSignInType: WebSignInType) + func processRedirectURL(url: String, webSignInType: Int) -> Result func cancelBrowserRegistration() func logout(completion: @escaping (SdkError?) -> Void) func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) @@ -20,6 +20,11 @@ protocol CustomRegistrationNotificationReceiverProtocol: class { func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) } +enum WebSignInType: Int { + case insideApp = 0 + case safari +} + class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, PinHandlerToReceiverProtocol, RegistrationHandlerToPinHanlderProtocol { var createPinChallenge: ONGCreatePinChallenge? @@ -134,18 +139,21 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { deregisterUserHandler.deregister(profileId: profileId, completion: completion) } - func processRedirectURL(url: String, webSignInType: WebSignInType) { + func processRedirectURL(url: String, webSignInType: Int) -> Result { + let webSignInType = WebSignInType(rawValue: webSignInType) ?? .insideApp guard let url = URL.init(string: url) else { + //FIXME: This doesn't seem right, we're canceling the whole registration here??? signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) - return + return .failure(FlutterError(.providedUrlIncorrect)) } if webSignInType != .insideApp && !UIApplication.shared.canOpenURL(url) { signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) - return + return .failure(FlutterError(.providedUrlIncorrect)) } presentBrowserUserRegistrationView(registrationUserURL: url, webSignInType: webSignInType) + return .success(()) } func submitCustomRegistrationSuccess(_ data: String?) { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index bfcac53d..9702f448 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -2,10 +2,7 @@ import Foundation import OneginiSDKiOS import Flutter -enum WebSignInType: Int { - case insideApp = 0 - case safari -} + extension OneginiModuleSwift { @@ -19,8 +16,8 @@ extension OneginiModuleSwift { bridgeConnector.toRegistrationConnector.registrationHandler.registerUser(identityProviderId, scopes: scopes, completion: completion) } - func handleRegisteredProcessUrl(_ url: String, webSignInType: WebSignInType) -> Void { - bridgeConnector.toRegistrationConnector.registrationHandler.processRedirectURL(url: url, webSignInType: webSignInType) + func handleRegisteredProcessUrl(_ url: String, webSignInType: Int) -> Result { + return bridgeConnector.toRegistrationConnector.registrationHandler.processRedirectURL(url: url, webSignInType: webSignInType) } public func handleDeepLinkCallbackUrl(_ url: URL) -> Bool { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index ba9a4aae..861ed766 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -73,8 +73,8 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } } - func handleRegisteredUserUrl(url: String?, signInType: Int32, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url ?? "", webSignInType: type) + func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url, webSignInType: Int(signInType)).mapError({$0})) } func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { @@ -204,7 +204,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.startApp: startApp(call, result) // register - case Constants.Routes.handleRegisteredUserUrl: handleRegisteredProcessUrl(call, result) case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) case Constants.Routes.setPreferredAuthenticator: From fc7c0e823b1faa3e3af3a5bee915d2fbc4c5a573 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 13:07:00 +0100 Subject: [PATCH 045/364] FP-20: iOS: Pigeon implement logout --- ios/Classes/NativeBridge/Handlers/LogoutHandler.swift | 10 +++++----- .../NativeBridge/Handlers/RegistrationHandler.swift | 7 ------- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 6 ++---- .../PluginExtensions/SwiftOneginiPlugin+Auth.swift | 6 ------ ios/Classes/SwiftOneginiPlugin.swift | 7 +++---- 5 files changed, 10 insertions(+), 26 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift index 98dbe2dc..3ceec44e 100644 --- a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift @@ -2,25 +2,25 @@ import UIKit import OneginiSDKiOS protocol LogoutHandlerProtocol: AnyObject { - func logout(completion: @escaping (SdkError?) -> Void) + func logout(completion: @escaping (Result) -> Void) } class LogoutHandler: LogoutHandlerProtocol { - func logout(completion: @escaping ( SdkError?) -> Void) { + func logout(completion: @escaping (Result) -> Void) { let userClient = ONGUserClient.sharedInstance() if userClient.authenticatedUserProfile() != nil { userClient.logoutUser { _, error in if let error = error { let mappedError = ErrorMapper().mapError(error) - completion(mappedError) + completion(.failure(FlutterError(mappedError))) } else { - completion(nil) + completion(.success(())) } } } else { - completion(SdkError(.noUserProfileIsAuthenticated)) + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) } } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index ad620db7..944d23a0 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -4,7 +4,6 @@ protocol RegistrationConnectorToHandlerProtocol: RegistrationHandlerToPinHanlder func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func processRedirectURL(url: String, webSignInType: Int) -> Result func cancelBrowserRegistration() - func logout(completion: @escaping (SdkError?) -> Void) func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) func identityProviders() -> Array func submitCustomRegistrationSuccess(_ data: String?) @@ -31,8 +30,6 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, Pi var browserRegistrationChallenge: ONGBrowserRegistrationChallenge? var customRegistrationChallenge: ONGCustomRegistrationChallenge? var browserConntroller: BrowserHandlerProtocol? - - var logoutUserHandler = LogoutHandler() var deregisterUserHandler = DeregisterUserHandler() var signUpCompletion: ((Result) -> Void)? @@ -131,10 +128,6 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) } - func logout(completion: @escaping (SdkError?) -> Void) { - logoutUserHandler.logout(completion: completion) - } - func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) { deregisterUserHandler.deregister(profileId: profileId, completion: completion) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 4db14187..a260c8bd 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -9,10 +9,8 @@ extension OneginiModuleSwift { return .success(providers.compactMap({OWIdentityProvider($0)})) } - func logOut(callback: @escaping FlutterResult) { - bridgeConnector.toLogoutUserHandler.logout { error in - error != nil ? callback(error?.flutterError()) : callback(true) - } + func logOut(callback: @escaping (Result) -> Void) { + bridgeConnector.toLogoutUserHandler.logout(completion: callback) } public func authenticateUserImplicitly(_ profileId: String, _ scopes: [String]?, diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 19ee8b02..632127fb 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -13,8 +13,6 @@ protocol OneginiPluginAuthProtocol { func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func deregisterAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func logout(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - } //MARK: - OneginiPluginAuthProtocol @@ -89,8 +87,4 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.cancelPinAuth() } - - func logout(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.logOut(callback:result) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 861ed766..065cbe15 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -67,7 +67,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.registerUser(identityProviderId, scopes: scopes) { result in completion(result.mapError{$0}) } @@ -124,7 +123,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func logout(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.logOut(){ result in + completion(result.mapError{$0}) + } } func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { @@ -229,8 +230,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.acceptPinAuthenticationRequest: acceptPinAuthenticationRequest(call, result) case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) - case Constants.Routes.logout: logout(call, result) - // fingerprint case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) case Constants.Routes.denyFingerprintAuthenticationRequest: denyFingerprintAuthenticationRequest(call, result) From c4746df1a742a8315d28ce8f7941242a6e607cfb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 13:13:02 +0100 Subject: [PATCH 046/364] FP-20: iOS: Pigeon: Implement deregisterUser --- .../Handlers/DeregisterUserHandler.swift | 10 +++++----- .../Handlers/RegistrationHandler.swift | 4 ++-- .../OneginiModuleSwift+Register.swift | 6 ++---- .../SwiftOneginiPlugin+Register.swift | 15 --------------- ios/Classes/SwiftOneginiPlugin.swift | 6 +++--- 5 files changed, 12 insertions(+), 29 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift index 90a39097..fc0ceea5 100644 --- a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift @@ -2,22 +2,22 @@ import UIKit import OneginiSDKiOS protocol DeregisterUserHandlerProtocol: AnyObject { - func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) + func deregister(profileId: String, completion: @escaping (Result) -> Void) } class DeregisterUserHandler: DeregisterUserHandlerProtocol { - func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) { + func deregister(profileId: String, completion: @escaping (Result) -> Void) { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - completion(SdkError(.userProfileDoesNotExist)) + completion(.failure(FlutterError(.userProfileDoesNotExist))) return } ONGUserClient.sharedInstance().deregisterUser(profile) { _, error in if let error = error { let mappedError = ErrorMapper().mapError(error) - completion(mappedError) + completion(.failure(FlutterError(mappedError))) } else { - completion(nil) + completion(.success(())) } } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 944d23a0..61b75461 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -4,7 +4,7 @@ protocol RegistrationConnectorToHandlerProtocol: RegistrationHandlerToPinHanlder func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func processRedirectURL(url: String, webSignInType: Int) -> Result func cancelBrowserRegistration() - func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) + func deregister(profileId: String, completion: @escaping (Result) -> Void) func identityProviders() -> Array func submitCustomRegistrationSuccess(_ data: String?) func cancelCustomRegistration(_ error: String) @@ -128,7 +128,7 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) } - func deregister(profileId: String, completion: @escaping (SdkError?) -> Void) { + func deregister(profileId: String, completion: @escaping (Result) -> Void) { deregisterUserHandler.deregister(profileId: profileId, completion: completion) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 9702f448..65da56c7 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -6,10 +6,8 @@ import Flutter extension OneginiModuleSwift { - func deregisterUser(profileId: String, callback: @escaping FlutterResult) { - bridgeConnector.toDeregisterUserHandler.deregister(profileId: profileId) { error in - error != nil ? callback(SdkError.convertToFlutter(error)) : callback(true) - } + func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toDeregisterUserHandler.deregister(profileId: profileId, completion: completion) } func registerUser(_ identityProviderId: String? = nil, scopes: [String]? = nil, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index a1164e7a..cddf597e 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -13,8 +13,6 @@ protocol OneginiPluginRegisterProtocol { func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - - func deregisterUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } @@ -44,18 +42,5 @@ extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(_error) } - func deregisterUser(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.deregisterUser(profileId: profileId, callback:result) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 065cbe15..3eb974ed 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -81,7 +81,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.deregisterUser(profileId: profileId) { result in + completion(result.mapError{$0}) + } } func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { @@ -217,8 +219,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) - case Constants.Routes.deregisterUser: deregisterUser(call, result) - // auth case Constants.Routes.registerAuthenticator: registerAuthenticator(call, result) case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) From d448fcf4e7efc1afb8394965c64a57c26e301a74 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 13:18:17 +0100 Subject: [PATCH 047/364] FP-20: iOS: Pigeon implement changePin --- ios/Classes/NativeBridge/Handlers/PinHandler.swift | 14 +++++++------- .../ModuleExtensions/OneginiModuleSwift+Pin.swift | 8 ++------ .../SwiftOneginiPlugin+Other.swift | 5 ----- ios/Classes/SwiftOneginiPlugin.swift | 5 +++-- 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 833dfb5e..f079693a 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -3,7 +3,7 @@ import Flutter protocol PinConnectorToPinHandler: AnyObject { func onPinProvided(pin: String) - func onChangePinCalled(completion: @escaping (Bool, SdkError?) -> Void) + func onChangePinCalled(completion: @escaping (Result) -> Void) func onCancel() func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) func closeFlow() @@ -30,7 +30,7 @@ class PinHandler: NSObject { var flow: PinFlow? var mode: PINEntryMode? var pinEntryToVerify = Array() - var changePinCompletion: ((Bool, SdkError?) -> Void)? + var changePinCompletion: ((Result) -> Void)? unowned var pinReceiver: PinHandlerToReceiverProtocol? unowned var notificationReceiver: PinNotificationReceiverProtocol? @@ -127,7 +127,7 @@ extension PinHandler: PinConnectorToPinHandler{ processPin(pinEntry: pinArray) } - func onChangePinCalled(completion: @escaping (Bool, SdkError?) -> Void) { + func onChangePinCalled(completion: @escaping (Result) -> Void) { changePinCompletion = completion ONGUserClient.sharedInstance().changePin(self) } @@ -213,11 +213,11 @@ extension PinHandler: ONGChangePinDelegate { let mappedError = ErrorMapper().mapError(error) if error.code == ONGGenericError.actionCancelled.rawValue { - changePinCompletion?(false, SdkError(.changingPinCancelled)) + changePinCompletion?(.failure(FlutterError(.changingPinCancelled))) } else if error.code == ONGGenericError.userDeregistered.rawValue { - changePinCompletion?(false, mappedError) + changePinCompletion?(.failure(FlutterError(mappedError))) } else { - changePinCompletion?(false, mappedError) + changePinCompletion?(.failure(FlutterError(mappedError))) } } @@ -225,6 +225,6 @@ extension PinHandler: ONGChangePinDelegate { Logger.log("didChangePinForUser", sender: self) createPinChallenge = nil closeFlow() - changePinCompletion?(true, nil) + changePinCompletion?(.success(())) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 862dfde0..09f93f59 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -12,12 +12,8 @@ extension OneginiModuleSwift { bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin) } - func changePin(callback: @escaping FlutterResult) -> Void { - bridgeConnector.toPinHandlerConnector.pinHandler.onChangePinCalled() { - (_, error) -> Void in - - error != nil ? callback(SdkError.convertToFlutter(error)) : callback(true) - } + func changePin(completion: @escaping (Result) -> Void) { + bridgeConnector.toPinHandlerConnector.pinHandler.onChangePinCalled(completion: completion) } func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift index bc995d81..d238b07c 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift @@ -3,15 +3,10 @@ import OneginiSDKiOS import Flutter protocol OneginiPluginOtherProtocol { - func changePin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func getAppToWebSingleSignOn(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } extension SwiftOneginiPlugin: OneginiPluginOtherProtocol { - func changePin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.changePin(callback: result) - } - func getAppToWebSingleSignOn(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let _arg = call.arguments as! [String: Any]?, let _path = _arg["url"] as! String? else { return; } OneginiModuleSwift.sharedInstance.runSingleSignOn(_path, callback: result) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3eb974ed..aedaf2f7 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -109,7 +109,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func changePin(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.changePin() { result in + completion(result.mapError{$0}) + } } func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { @@ -245,7 +247,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { getResource(call, result) // other - case Constants.Routes.changePin: changePin(call, result) case Constants.Routes.getAppToWebSingleSignOn: getAppToWebSingleSignOn(call, result) default: do { From 7c04650a8e4ab5cfad467b91fddf59d4b3886cfb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 13:31:05 +0100 Subject: [PATCH 048/364] FP-20: iOS: Pigeon: implement getAppToWebSingleSignOn --- .../Handlers/AppToWebHandler.swift | 22 ++++++------------- .../OneginiModuleSwift+Auth.swift | 11 ++++------ .../SwiftOneginiPlugin+Other.swift | 15 ------------- ios/Classes/SwiftOneginiPlugin.swift | 7 +++--- 4 files changed, 14 insertions(+), 41 deletions(-) delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift diff --git a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift index 84a29a69..6618f0ff 100644 --- a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift @@ -3,25 +3,17 @@ import OneginiSDKiOS //MARK: - protocol AppToWebHandlerProtocol: AnyObject { - func signInAppToWeb(targetURL: URL?, completion: @escaping (Dictionary?, SdkError?) -> Void) + func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) } //MARK: - class AppToWebHandler: AppToWebHandlerProtocol { - func signInAppToWeb(targetURL: URL?, completion: @escaping (Dictionary?, SdkError?) -> Void) { - guard let _targetURL = targetURL else { - completion(nil, SdkError(.providedUrlIncorrect)) - return - } - - ONGUserClient.sharedInstance() - .appToWebSingleSignOn(withTargetUrl: _targetURL) { (url, token, error) in - if let _url = url, let _token = token { - completion(["token": _token, "redirectUrl": _url.absoluteString ], nil) - } else if let _error = error { - // Handle error - let sdkError = SdkError(code: OneWelcomeWrapperError.genericError.rawValue, errorDescription: _error.localizedDescription) - completion(nil, sdkError) + func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) { + ONGUserClient.sharedInstance().appToWebSingleSignOn(withTargetUrl: targetURL) { (url, token, error) in + if let url = url, let token = token { + completion(.success(OWAppToWebSingleSignOn(token: token, redirectUrl: url.absoluteString))) + } else if let error = error { + completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index a260c8bd..b4769c93 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -31,16 +31,13 @@ extension OneginiModuleSwift { } } - func runSingleSignOn(_ path: String?, callback: @escaping FlutterResult) -> Void { + func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { - guard let _path = path, let _url = URL(string: _path) else { - callback(SdkError(.providedUrlIncorrect)) + guard let url = URL(string: path) else { + completion(.failure(FlutterError(.providedUrlIncorrect))) return } - - bridgeConnector.toAppToWebHandler.signInAppToWeb(targetURL: _url, completion: { (result, error) in - error != nil ? callback(SdkError.convertToFlutter(error)) : callback(String.stringify(json: result ?? [])) - }) + bridgeConnector.toAppToWebHandler.signInAppToWeb(targetURL: url, completion: completion) } func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift deleted file mode 100644 index d238b07c..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Other.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - -protocol OneginiPluginOtherProtocol { - func getAppToWebSingleSignOn(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void -} - -extension SwiftOneginiPlugin: OneginiPluginOtherProtocol { - func getAppToWebSingleSignOn(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _path = _arg["url"] as! String? else { return; } - OneginiModuleSwift.sharedInstance.runSingleSignOn(_path, callback: result) - } -} - diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index aedaf2f7..16d4886f 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -137,7 +137,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.runSingleSignOn(url) { result in + completion(result.mapError{$0}) + } } func getAccessToken(completion: @escaping (Result) -> Void) { @@ -246,9 +248,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.getResourceAnonymous, Constants.Routes.getResource, Constants.Routes.getImplicitResource, Constants.Routes.unauthenticatedRequest: getResource(call, result) - // other - case Constants.Routes.getAppToWebSingleSignOn: getAppToWebSingleSignOn(call, result) - default: do { Logger.log("Method wasn't handled: " + call.method) result(FlutterMethodNotImplemented) From c03e95b4f37b06062c895543413fbe407c5ab845 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 6 Mar 2023 13:33:25 +0100 Subject: [PATCH 049/364] FP-20: Add fields to OWAuthenticator type --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 13 +++++++++++-- ios/Classes/Pigeon.swift | 14 +++++++++++++- lib/pigeon.dart | 15 +++++++++++++++ pigeons/onewelcome_pigeon_interface.dart | 18 ++++++++++++++---- 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index a60e9d7d..b7beb083 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -107,7 +107,10 @@ data class OWIdentityProvider ( /** Generated class from Pigeon that represents data sent in messages. */ data class OWAuthenticator ( val id: String, - val name: String + val name: String, + val isRegistered: Boolean, + val isPreferred: Boolean, + val authenticatorType: Long ) { companion object { @@ -115,13 +118,19 @@ data class OWAuthenticator ( fun fromList(list: List): OWAuthenticator { val id = list[0] as String val name = list[1] as String - return OWAuthenticator(id, name) + val isRegistered = list[2] as Boolean + val isPreferred = list[3] as Boolean + val authenticatorType = list[4].let { if (it is Int) it.toLong() else it as Long } + return OWAuthenticator(id, name, isRegistered, isPreferred, authenticatorType) } } fun toList(): List { return listOf( id, name, + isRegistered, + isPreferred, + authenticatorType, ) } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 9e8d5a82..12e3357f 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -99,20 +99,32 @@ struct OWIdentityProvider { struct OWAuthenticator { var id: String var name: String + var isRegistered: Bool + var isPreferred: Bool + var authenticatorType: Int32 static func fromList(_ list: [Any?]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String + let isRegistered = list[2] as! Bool + let isPreferred = list[3] as! Bool + let authenticatorType = list[4] as! Int32 return OWAuthenticator( id: id, - name: name + name: name, + isRegistered: isRegistered, + isPreferred: isPreferred, + authenticatorType: authenticatorType ) } func toList() -> [Any?] { return [ id, name, + isRegistered, + isPreferred, + authenticatorType, ] } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 1c087848..57320734 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -86,16 +86,28 @@ class OWAuthenticator { OWAuthenticator({ required this.id, required this.name, + required this.isRegistered, + required this.isPreferred, + required this.authenticatorType, }); String id; String name; + bool isRegistered; + + bool isPreferred; + + int authenticatorType; + Object encode() { return [ id, name, + isRegistered, + isPreferred, + authenticatorType, ]; } @@ -104,6 +116,9 @@ class OWAuthenticator { return OWAuthenticator( id: result[0]! as String, name: result[1]! as String, + isRegistered: result[2]! as bool, + isPreferred: result[3]! as bool, + authenticatorType: result[4]! as int, ); } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index aa68bd58..ee5ff2d3 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -38,8 +38,16 @@ class OWIdentityProvider { class OWAuthenticator { String id; String name; - - OWAuthenticator({required this.id, required this.name}); + bool isRegistered; + bool isPreferred; + int authenticatorType; + + OWAuthenticator( + {required this.id, + required this.name, + required this.isRegistered, + required this.isPreferred, + required this.authenticatorType}); } class OWAppToWebSingleSignOn { @@ -64,7 +72,8 @@ abstract class UserClientApi { List fetchUserProfiles(); @async - OWRegistrationResponse registerUser(String? identityProviderId, List? scopes); + OWRegistrationResponse registerUser( + String? identityProviderId, List? scopes); @async void handleRegisteredUserUrl(String url, int signInType); @@ -86,7 +95,8 @@ abstract class UserClientApi { OWUserProfile getAuthenticatedUserProfile(); @async - OWRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); + OWRegistrationResponse authenticateUser( + String profileId, String? registeredAuthenticatorId); @async List getNotRegisteredAuthenticators(String profileId); From 3c44abfecb2477c43796b06cf555be390f3df9b5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 14:31:52 +0100 Subject: [PATCH 050/364] FP-20: iOS: Pigeon: Implement registerAuthenticator --- .../Handlers/AuthenticatorsHandler.swift | 26 +++++++++---------- .../OneginiModuleSwift+Register.swift | 24 ++--------------- .../SwiftOneginiPlugin+Auth.swift | 8 ------ ios/Classes/SwiftOneginiPlugin.swift | 5 ++-- 4 files changed, 18 insertions(+), 45 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 96dfb7a0..bc267d81 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -3,7 +3,7 @@ import OneginiSDKiOS //MARK: - protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { - func registerAuthenticator(_ userProfile: ONGUserProfile,_ authenticator: ONGAuthenticator, _ completion: @escaping (Bool, SdkError?) -> Void) + func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Bool, SdkError?) -> Void) func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Bool, SdkError?) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array @@ -19,7 +19,7 @@ protocol AuthenticatorsNotificationReceiverProtocol: class { class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { var pinChallenge: ONGPinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? - var registrationCompletion: ((Bool, SdkError?) -> Void)? + var registrationCompletion: ((Result) -> Void)? var deregistrationCompletion: ((Bool, SdkError?) -> Void)? unowned var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? @@ -65,17 +65,17 @@ class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { //MARK: - BridgeToAuthenticatorsHandlerProtocol extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { - func registerAuthenticator(_ userProfile: ONGUserProfile, _ authenticator: ONGAuthenticator,_ completion: @escaping (Bool, SdkError?) -> Void) { - guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticator.identifier}) else { - completion(false, SdkError(.authenticatorNotFound)) + func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { + guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - - if(authenticator.isRegistered == true) { - completion(false, SdkError(.authenticatorNotFound)) + + // We don't have to check if the authenticator is already registered as the sdk will do that for us. + guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile).first(where: { $0.identifier == authenticatorId }) else { + completion(.failure(FlutterError(.authenticatorNotFound))) return } - registrationCompletion = completion; ONGUserClient.sharedInstance().register(authenticator, delegate: self) } @@ -140,7 +140,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { Logger.log("[AUTH] userClient didReceive ONGCustomAuthFinishRegistrationChallenge", sender: self) // TODO: Will need to check it in the future - registrationCompletion!(true, nil) + registrationCompletion?(.success(())) customAuthChallenge = challenge BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) } @@ -149,16 +149,16 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender:self) BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { - registrationCompletion!(false, SdkError(.authenticatorRegistrationCancelled)) + registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - registrationCompletion!(false, mappedError) + registrationCompletion?(.failure(FlutterError(mappedError))) } } func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) - registrationCompletion?(true, nil) + registrationCompletion?(.success(())) BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 65da56c7..8ab2f1ba 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -56,28 +56,8 @@ extension OneginiModuleSwift { bridgeConnector.toRegistrationConnector.registrationHandler.cancelBrowserRegistration() } - func registerAuthenticator(_ authenticatorId: String, callback: @escaping FlutterResult) { - guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { - callback(SdkError.convertToFlutter(SdkError(.noUserProfileIsAuthenticated))) - return - } - - let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) - - guard let authenticator = notRegisteredAuthenticators.first(where: { $0.identifier == authenticatorId }) else { - callback(SdkError.convertToFlutter(SdkError(.authenticatorNotFound))) - return - } - - bridgeConnector.toAuthenticatorsHandler.registerAuthenticator(profile, authenticator) { - (_ , error) -> Void in - - if let _error = error { - callback(SdkError.convertToFlutter(_error)) - } else { - callback(nil) - } - } + func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toAuthenticatorsHandler.registerAuthenticator(authenticatorId, completion) } func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 632127fb..7f29f3a5 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -4,7 +4,6 @@ import Flutter protocol OneginiPluginAuthProtocol { - func registerAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) @@ -17,13 +16,6 @@ protocol OneginiPluginAuthProtocol { //MARK: - OneginiPluginAuthProtocol extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { - func registerAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _authenticator = _arg["authenticatorId"] as! String? else { - result(SdkError(.emptyInputValue).flutterError()) - return - } - OneginiModuleSwift.sharedInstance.registerAuthenticator(_authenticator, callback: result) - } func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let arg = call.arguments as? [String: Any] else { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 16d4886f..2f153d3d 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -123,7 +123,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.registerAuthenticator(authenticatorId) { result in + completion(result.mapError{$0}) + } } func logout(completion: @escaping (Result) -> Void) { @@ -224,7 +226,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) // auth - case Constants.Routes.registerAuthenticator: registerAuthenticator(call, result) case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) From e402d8c73487b33074ee414e695d234e9abf4608 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 14:50:21 +0100 Subject: [PATCH 051/364] FP-20: iOS: Pigeon: implement setPreferredAuthenticator --- .../Handlers/AuthenticatorsHandler.swift | 11 ++++++----- .../OneginiModuleSwift+Auth.swift | 15 +++------------ .../SwiftOneginiPlugin+Auth.swift | 17 ----------------- ios/Classes/SwiftOneginiPlugin.swift | 6 +++--- 4 files changed, 12 insertions(+), 37 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index bc267d81..32046d59 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -5,7 +5,7 @@ import OneginiSDKiOS protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Bool, SdkError?) -> Void) - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Bool, SdkError?) -> Void) + func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? { get } @@ -95,19 +95,20 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { ONGUserClient.sharedInstance().deregister(authenticator, delegate: self) } - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Bool, SdkError?) -> Void) { + func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { - completion(false, SdkError(.authenticatorNotFound)) + completion(.failure(FlutterError(.authenticatorNotFound))) return } + // FIXME: Doesnt the sdk give us an error by itself? if(!authenticator.isRegistered) { - completion(false, SdkError(.authenticatorNotRegistered)) + completion(.failure(FlutterError(.authenticatorNotRegistered))) return } ONGUserClient.sharedInstance().preferredAuthenticator = authenticator - completion(true, nil) + completion(.success(())) } func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index b4769c93..0ff3fcf4 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -55,21 +55,12 @@ extension OneginiModuleSwift { } - func setPreferredAuthenticator(_ identifierId: String, completion: @escaping FlutterResult) { + func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { - completion(SdkError.convertToFlutter(SdkError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - - // Preferred Authenticator - bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId) { value, error in - guard error == nil else { - completion(SdkError.convertToFlutter(error)) - return - } - - completion(value) - } + bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) } func deregisterAuthenticator(_ identifierId: String, completion: @escaping FlutterResult) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 7f29f3a5..901efa0f 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -5,9 +5,6 @@ import Flutter protocol OneginiPluginAuthProtocol { func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - - func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) - func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func deregisterAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -39,20 +36,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - func setPreferredAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let authenticatorId = arg["authenticatorId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId, completion: result) - } - func deregisterAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void { guard let arg = call.arguments as? [String: Any] else { result(SdkError(.methodArgumentNotFound).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 2f153d3d..3655bfbd 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -115,7 +115,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId) { result in + completion(result.mapError{$0}) + } } func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { @@ -215,8 +217,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // register case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) - case Constants.Routes.setPreferredAuthenticator: - setPreferredAuthenticator(call, result) case Constants.Routes.acceptPinRegistrationRequest: acceptPinRegistrationRequest(call, result) case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) From 8ce15e948f4af0c8ebea81f4db73d0b9afdc7560 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 7 Mar 2023 15:01:54 +0100 Subject: [PATCH 052/364] FP-20: iOS: Pigeon: Implement deregisterAuthenticator --- .../Handlers/AuthenticatorsHandler.swift | 18 +++++++++--------- .../OneginiModuleSwift+Auth.swift | 16 +++------------- .../SwiftOneginiPlugin+Auth.swift | 15 --------------- ios/Classes/SwiftOneginiPlugin.swift | 8 ++++---- 4 files changed, 16 insertions(+), 41 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 32046d59..a5522d52 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -4,7 +4,7 @@ import OneginiSDKiOS //MARK: - protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Bool, SdkError?) -> Void) + func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool @@ -20,7 +20,7 @@ class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { var pinChallenge: ONGPinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? var registrationCompletion: ((Result) -> Void)? - var deregistrationCompletion: ((Bool, SdkError?) -> Void)? + var deregistrationCompletion: ((Result) -> Void)? unowned var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? @@ -80,14 +80,14 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { ONGUserClient.sharedInstance().register(authenticator, delegate: self) } - func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Bool, SdkError?) -> Void) { + func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { - completion(false, SdkError(.authenticatorNotFound)) + completion(.failure(FlutterError(.authenticatorNotFound))) return } if(authenticator.isRegistered != true) { - completion(false, SdkError(.authenticatorNotRegistered)) + completion(.failure(FlutterError(.authenticatorNotRegistered))) return } @@ -168,23 +168,23 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { func userClient(_: ONGUserClient, didDeregister _: ONGAuthenticator, forUser _: ONGUserProfile) { Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) - deregistrationCompletion!(true, nil) + deregistrationCompletion?(.success(())) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthDeregistrationChallenge) { Logger.log("[AUTH] userClient didReceive ONGCustomAuthDeregistrationChallenge", sender: self) - deregistrationCompletion!(true, nil) + deregistrationCompletion?(.success(())) } func userClient(_: ONGUserClient, didFailToDeregister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) //BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { - deregistrationCompletion?(false, SdkError(.authenticatorDeregistrationCancelled)) + deregistrationCompletion?(.failure(FlutterError(.authenticatorDeregistrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - deregistrationCompletion?(false, mappedError) + deregistrationCompletion?(.failure(FlutterError(mappedError))) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 0ff3fcf4..533a9b5d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -63,22 +63,12 @@ extension OneginiModuleSwift { bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) } - func deregisterAuthenticator(_ identifierId: String, completion: @escaping FlutterResult) { + func deregisterAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { - completion(SdkError.convertToFlutter(SdkError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - - // Deregister Authenticator - bridgeConnector.toAuthenticatorsHandler.deregisterAuthenticator(profile, identifierId) { value, error in - guard error == nil else { - // FIXME: use Result and make this FlutterError - completion(SdkError.convertToFlutter(error)) - return - } - - completion(value) - } + bridgeConnector.toAuthenticatorsHandler.deregisterAuthenticator(profile, identifierId, completion) } func getAuthenticatedUserProfile() -> Result { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index 901efa0f..c67646b6 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -7,7 +7,6 @@ protocol OneginiPluginAuthProtocol { func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func deregisterAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } @@ -36,20 +35,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - func deregisterAuthenticator(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let authenticatorId = arg["authenticatorId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId, completion: result) - } - func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let _arg = call.arguments as! [String: Any]?, let _pin = _arg["pin"] as! String? else { result(SdkError(.emptyInputValue).flutterError()) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3655bfbd..3ddd024b 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -121,7 +121,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId) { result in + completion(result.mapError{$0}) + } } func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { @@ -228,9 +230,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // auth case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - - case Constants.Routes.deregisterAuthenticator: - deregisterAuthenticator(call, result) + case Constants.Routes.acceptPinAuthenticationRequest: acceptPinAuthenticationRequest(call, result) case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) From 34340cf0dce6454ae441817306687a0f47e46440 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:48:11 +0100 Subject: [PATCH 053/364] FP-20 Updated pigeon interface to also contain the callback methods --- .../sdk/flutter/OneginiMethodsWrapper.kt | 36 +-- .../mobile/sdk/flutter/PigeonInterface.kt | 97 +++++-- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 245 ++++++++++++++++ ios/Classes/Pigeon.swift | 215 ++++++++++++++ .../onegini_custom_registration_callback.dart | 30 +- .../onegini_fingerprint_callback.dart | 12 +- .../onegini_otp_accept_deny_callback.dart | 10 +- .../onegini_pin_authentication_callback.dart | 13 +- .../onegini_pin_registration_callback.dart | 13 +- .../onegini_registration_callback.dart | 7 +- lib/pigeon.dart | 270 ++++++++++++++++++ lib/user_client.dart | 58 +++- pigeons/onewelcomePigeonInterface.dart | 160 ----------- pigeons/onewelcome_pigeon_interface.dart | 42 +++ pigeons/userProfile.dart | 59 ---- 15 files changed, 951 insertions(+), 316 deletions(-) delete mode 100644 pigeons/onewelcomePigeonInterface.dart delete mode 100644 pigeons/userProfile.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 1b55c45f..69734570 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -46,17 +46,17 @@ class OneginiMethodsWrapper @Inject constructor( fun respondCustomRegistrationAction( call: MethodCall, result: MethodChannel.Result) { - submitCustomRegistrationActionUseCase(result, call) +// submitCustomRegistrationActionUseCase(result, call) } fun cancelCustomRegistrationAction( call: MethodCall, result: MethodChannel.Result) { - cancelCustomRegistrationActionUseCase(result, call) +// cancelCustomRegistrationActionUseCase(result, call) } fun handleRegisteredUrl(call: MethodCall) { - handleRegisteredUrlUseCase(call) +// handleRegisteredUrlUseCase(call) } fun getIdentityProviders(result: MethodChannel.Result) { @@ -64,7 +64,7 @@ class OneginiMethodsWrapper @Inject constructor( } fun getAccessToken(result: MethodChannel.Result) { - getAccessTokenUseCase(result) +// getAccessTokenUseCase(result) } fun cancelBrowserRegistration() { @@ -76,7 +76,7 @@ class OneginiMethodsWrapper @Inject constructor( } fun getUserProfiles(result: MethodChannel.Result) { - getUserProfilesUseCase(result) +// getUserProfilesUseCase(result) } fun startApp(call: MethodCall, result: MethodChannel.Result) { @@ -84,51 +84,51 @@ class OneginiMethodsWrapper @Inject constructor( } fun getRegisteredAuthenticators(call: MethodCall, result: MethodChannel.Result) { - getRegisteredAuthenticatorsUseCase(call, result) +// getRegisteredAuthenticatorsUseCase(call, result) } fun getNotRegisteredAuthenticators(call: MethodCall, result: MethodChannel.Result) { - getNotRegisteredAuthenticatorsUseCase(call, result) +// getNotRegisteredAuthenticatorsUseCase(call, result) } fun setPreferredAuthenticator(call: MethodCall, result: MethodChannel.Result) { - setPreferredAuthenticatorUseCase(call, result) +// setPreferredAuthenticatorUseCase(call, result) } fun deregisterUser(call: MethodCall, result: MethodChannel.Result) { - deregisterUserUseCase(call, result) +// deregisterUserUseCase(call, result) } fun deregisterAuthenticator(call: MethodCall, result: MethodChannel.Result) { - deregisterAuthenticatorUseCase(call, result) +// deregisterAuthenticatorUseCase(call, result) } fun registerAuthenticator(call: MethodCall, result: MethodChannel.Result) { - registerAuthenticatorUseCase(call, result) +// registerAuthenticatorUseCase(call, result) } fun getAllAuthenticators(call: MethodCall, result: MethodChannel.Result) { - getAllAuthenticatorsUseCase(call, result) +// getAllAuthenticatorsUseCase(call, result) } fun getRedirectUrl(result: MethodChannel.Result) { - getRedirectUrlUseCase(result) +// getRedirectUrlUseCase(result) } fun authenticateUser(call: MethodCall, result: MethodChannel.Result) { - authenticateUserUseCase(call, result) +// authenticateUserUseCase(call, result) } fun authenticateDevice(call: MethodCall, result: MethodChannel.Result){ - authenticateDeviceUseCase(call, result) +// authenticateDeviceUseCase(call, result) } fun authenticateUserImplicitly(call: MethodCall, result: MethodChannel.Result){ - authenticateUserImplicitlyUseCase(call, result) +// authenticateUserImplicitlyUseCase(call, result) } fun getResourceAnonymous(call: MethodCall, result: MethodChannel.Result){ - getResourceAnonymousUseCase(call, result, resourceHelper) +// getResourceAnonymousUseCase(call, result, resourceHelper) } fun getResource(call: MethodCall, result: MethodChannel.Result){ @@ -148,6 +148,6 @@ class OneginiMethodsWrapper @Inject constructor( } fun logout(result: MethodChannel.Result) { - logoutUseCase(result) +// logoutUseCase(result) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index c26b7a34..e0ab7450 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -93,7 +93,7 @@ open class PigeonInterface : UserClientApi { @Inject lateinit var submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase - // Example function on how it could be initiated on Flutter send to Native + // FIXME REMOVE ME AT THE END; Example function on how it could be initiated on Flutter send to Native override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(OWUserProfile("ghalo"))) flutterCallback(callback, a) @@ -104,11 +104,11 @@ open class PigeonInterface : UserClientApi { override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { registrationUseCase(identityProviderId, scopes, callback) -// flutterCallback(callback, result) } - override fun handleRegisteredUserUrl(url: String?, signInType: Long, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + override fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) { + val result = handleRegisteredUrlUseCase(url, signInType) + flutterCallback(callback, result) } override fun getIdentityProviders(callback: (Result>) -> Unit) { @@ -117,27 +117,31 @@ open class PigeonInterface : UserClientApi { } override fun deregisterUser(profileId: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + deregisterUserUseCase(profileId, callback) } override fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { -// TODO("Not yet implemented") + val result = getRegisteredAuthenticatorsUseCase(profileId) + flutterCallback(callback, result) } override fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) { -// TODO("Not yet implemented") + val result = getAllAuthenticatorsUseCase(profileId) + flutterCallback(callback, result) } override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + val result = getAuthenticatedUserProfileUseCase() + flutterCallback(callback, result) } override fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + authenticateUserUseCase(profileId, registeredAuthenticatorId, callback) } override fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { -// TODO("Not yet implemented") + val result = getNotRegisteredAuthenticatorsUseCase(profileId) + flutterCallback(callback, result) } override fun changePin(callback: (Result) -> Unit) { @@ -145,19 +149,20 @@ open class PigeonInterface : UserClientApi { } override fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + val result = setPreferredAuthenticatorUseCase(authenticatorId) + flutterCallback(callback, result) } override fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + deregisterAuthenticatorUseCase(authenticatorId, callback) } override fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + registerAuthenticatorUseCase(authenticatorId, callback) } override fun logout(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + logoutUseCase(callback) } override fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) { @@ -169,15 +174,18 @@ open class PigeonInterface : UserClientApi { } override fun getAccessToken(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + val result = getAccessTokenUseCase() + flutterCallback(callback, result) } override fun getRedirectUrl(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + val result = getRedirectUrlUseCase() + flutterCallback(callback, result) } override fun getUserProfiles(callback: (Result>) -> Unit) { -// TODO("Not yet implemented") + val result = getUserProfilesUseCase() + flutterCallback(callback, result) } override fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) { @@ -185,18 +193,67 @@ open class PigeonInterface : UserClientApi { } override fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + authenticateDeviceUseCase(scopes, callback) } override fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + authenticateUserImplicitlyUseCase(profileId, scopes, callback) } override fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + submitCustomRegistrationActionUseCase(identityProviderId, data, callback) } override fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { + cancelCustomRegistrationActionUseCase(identityProviderId, error, callback) + } + + // Callback functions + override fun submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun submitCustomRegistrationErrorAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun fingerprintAcceptAuthenticationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun pinAcceptAuthenticationRequest(pin: String?, callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) { +// TODO("Not yet implemented") + } + + override fun cancelBrowserRegistration(callback: (Result) -> Unit) { // TODO("Not yet implemented") } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index b7beb083..5133a91d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -280,6 +280,24 @@ interface UserClientApi { fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) + /** Custom Registration Callbacks */ + fun submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) + fun submitCustomRegistrationErrorAction(identityProviderId: String, error: String, callback: (Result) -> Unit) + /** Fingerprint Callbacks */ + fun fingerprintFallbackToPin(callback: (Result) -> Unit) + fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) + fun fingerprintAcceptAuthenticationRequest(callback: (Result) -> Unit) + /** OTP Callbacks */ + fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) + fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) + /** Pin Authentication Callbacks */ + fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) + fun pinAcceptAuthenticationRequest(pin: String?, callback: (Result) -> Unit) + /** Pin Registration Callbacks */ + fun pinDenyRegistrationRequest(callback: (Result) -> Unit) + fun pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) + /** Browser Registration Callbacks */ + fun cancelBrowserRegistration(callback: (Result) -> Unit) companion object { /** The codec used by UserClientApi. */ @@ -792,6 +810,233 @@ interface UserClientApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val identityProviderIdArg = args[0] as String + val dataArg = args[1] as? String + api.submitCustomRegistrationSuccessAction(identityProviderIdArg, dataArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val identityProviderIdArg = args[0] as String + val errorArg = args[1] as String + api.submitCustomRegistrationErrorAction(identityProviderIdArg, errorArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.fingerprintFallbackToPin() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.fingerprintDenyAuthenticationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.fingerprintAcceptAuthenticationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.otpDenyAuthenticationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.otpAcceptAuthenticationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.pinDenyAuthenticationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val pinArg = args[0] as? String + api.pinAcceptAuthenticationRequest(pinArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.pinDenyRegistrationRequest() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val pinArg = args[0] as? String + val isCustomAuthenticatorArg = args[1] as Boolean + api.pinAcceptRegistrationRequest(pinArg, isCustomAuthenticatorArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.cancelBrowserRegistration() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } } } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 12e3357f..125e3b28 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -266,6 +266,24 @@ protocol UserClientApi { func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) + /// Custom Registration Callbacks + func submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) + func submitCustomRegistrationErrorAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) + /// Fingerprint Callbacks + func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) + func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) + func fingerprintAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) + /// OTP Callbacks + func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) + func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) + /// Pin Authentication Callbacks + func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) + func pinAcceptAuthenticationRequest(pin: String?, completion: @escaping (Result) -> Void) + /// Pin Registration Callbacks + func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) + func pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) + /// Browser Registration Callbacks + func cancelBrowserRegistration(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -689,6 +707,203 @@ class UserClientApiSetup { } else { cancelCustomRegistrationActionChannel.setMessageHandler(nil) } + /// Custom Registration Callbacks + let submitCustomRegistrationSuccessActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + submitCustomRegistrationSuccessActionChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let identityProviderIdArg = args[0] as! String + let dataArg = args[1] as? String + api.submitCustomRegistrationSuccessAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + submitCustomRegistrationSuccessActionChannel.setMessageHandler(nil) + } + let submitCustomRegistrationErrorActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + submitCustomRegistrationErrorActionChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let identityProviderIdArg = args[0] as! String + let errorArg = args[1] as! String + api.submitCustomRegistrationErrorAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + submitCustomRegistrationErrorActionChannel.setMessageHandler(nil) + } + /// Fingerprint Callbacks + let fingerprintFallbackToPinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + fingerprintFallbackToPinChannel.setMessageHandler { _, reply in + api.fingerprintFallbackToPin() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + fingerprintFallbackToPinChannel.setMessageHandler(nil) + } + let fingerprintDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + fingerprintDenyAuthenticationRequestChannel.setMessageHandler { _, reply in + api.fingerprintDenyAuthenticationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + fingerprintDenyAuthenticationRequestChannel.setMessageHandler(nil) + } + let fingerprintAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + fingerprintAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in + api.fingerprintAcceptAuthenticationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + fingerprintAcceptAuthenticationRequestChannel.setMessageHandler(nil) + } + /// OTP Callbacks + let otpDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + otpDenyAuthenticationRequestChannel.setMessageHandler { _, reply in + api.otpDenyAuthenticationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + otpDenyAuthenticationRequestChannel.setMessageHandler(nil) + } + let otpAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + otpAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in + api.otpAcceptAuthenticationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + otpAcceptAuthenticationRequestChannel.setMessageHandler(nil) + } + /// Pin Authentication Callbacks + let pinDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pinDenyAuthenticationRequestChannel.setMessageHandler { _, reply in + api.pinDenyAuthenticationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pinDenyAuthenticationRequestChannel.setMessageHandler(nil) + } + let pinAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pinAcceptAuthenticationRequestChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let pinArg = args[0] as? String + api.pinAcceptAuthenticationRequest(pin: pinArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pinAcceptAuthenticationRequestChannel.setMessageHandler(nil) + } + /// Pin Registration Callbacks + let pinDenyRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pinDenyRegistrationRequestChannel.setMessageHandler { _, reply in + api.pinDenyRegistrationRequest() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pinDenyRegistrationRequestChannel.setMessageHandler(nil) + } + let pinAcceptRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let pinArg = args[0] as? String + let isCustomAuthenticatorArg = args[1] as! Bool + api.pinAcceptRegistrationRequest(pin: pinArg, isCustomAuthenticator: isCustomAuthenticatorArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pinAcceptRegistrationRequestChannel.setMessageHandler(nil) + } + /// Browser Registration Callbacks + let cancelBrowserRegistrationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + cancelBrowserRegistrationChannel.setMessageHandler { _, reply in + api.cancelBrowserRegistration() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + cancelBrowserRegistrationChannel.setMessageHandler(nil) + } } } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. diff --git a/lib/callbacks/onegini_custom_registration_callback.dart b/lib/callbacks/onegini_custom_registration_callback.dart index eaf43071..f5692326 100644 --- a/lib/callbacks/onegini_custom_registration_callback.dart +++ b/lib/callbacks/onegini_custom_registration_callback.dart @@ -1,25 +1,13 @@ -import 'package:onegini/constants/constants.dart'; - -import '../onegini.dart'; +import 'package:onegini/pigeon.dart'; class OneginiCustomRegistrationCallback { - Future submitSuccessAction(String identityProviderId, String? data) async { - await Onegini.instance.channel.invokeMethod( - Constants.submitCustomRegistrationAction, - { - 'identityProviderId': identityProviderId, - 'data': data - } - ); - } + final api = UserClientApi(); + + Future submitSuccessAction(String identityProviderId, String? data) async { + await api.submitCustomRegistrationAction(identityProviderId, data); + } - Future submitErrorAction(String identityProviderId, String error) async { - await Onegini.instance.channel.invokeMethod( - Constants.cancelCustomRegistrationAction, - { - 'identityProviderId': identityProviderId, - 'error': error, - } - ); - } + Future submitErrorAction(String identityProviderId, String error) async { + await api.cancelCustomRegistrationAction(identityProviderId, error); + } } diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index ae105f5c..2368be51 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; -import 'package:onegini/constants/constants.dart'; +import 'package:onegini/pigeon.dart'; import '../onegini.dart'; @@ -9,18 +9,17 @@ import '../onegini.dart'; /// /// Use this callback when user want authenticate by fingerprint. class OneginiFingerprintCallback { + final api = UserClientApi(); /// Changes the authentication method from fingerprint to PIN. Future fallbackToPin() async { - await Onegini.instance.channel - .invokeMethod(Constants.fingerprintFallbackToPin); + await api.fingerprintFallbackToPin(); } /// Cancels authentication request. /// /// Used when a user has canceled a authentication by fingerprint. Future denyAuthenticationRequest() async { - await Onegini.instance.channel - .invokeMethod(Constants.denyFingerprintAuthenticationRequest); + await api.fingerprintDenyAuthenticationRequest(); } /// Accept fingerprint request. @@ -28,7 +27,6 @@ class OneginiFingerprintCallback { /// Use this method when you want start scanning fingerprint. Future acceptAuthenticationRequest(BuildContext? context) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel - .invokeMethod(Constants.acceptFingerprintAuthenticationRequest); + await api.fingerprintAcceptAuthenticationRequest(); } } diff --git a/lib/callbacks/onegini_otp_accept_deny_callback.dart b/lib/callbacks/onegini_otp_accept_deny_callback.dart index 3184e89c..4a769c11 100644 --- a/lib/callbacks/onegini_otp_accept_deny_callback.dart +++ b/lib/callbacks/onegini_otp_accept_deny_callback.dart @@ -1,20 +1,22 @@ import 'package:flutter/material.dart'; import 'package:onegini/constants/constants.dart'; +import 'package:onegini/pigeon.dart'; import '../onegini.dart'; /// A callback for mobile authentication with OTP class OneginiOtpAcceptDenyCallback { + final api = UserClientApi(); + /// Cancels OTP authentication. Future denyAuthenticationRequest() async { - await Onegini.instance.channel - .invokeMethod(Constants.denyOtpAuthenticationRequest); + await api.otpDenyAuthenticationRequest(); } /// Accepts OTP authentication. Future acceptAuthenticationRequest(BuildContext? context) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel - .invokeMethod(Constants.acceptOtpAuthenticationRequest); + + await api.otpAcceptAuthenticationRequest(); } } diff --git a/lib/callbacks/onegini_pin_authentication_callback.dart b/lib/callbacks/onegini_pin_authentication_callback.dart index 19297b2f..38111157 100644 --- a/lib/callbacks/onegini_pin_authentication_callback.dart +++ b/lib/callbacks/onegini_pin_authentication_callback.dart @@ -1,23 +1,22 @@ import 'package:flutter/material.dart'; -import 'package:onegini/constants/constants.dart'; +import 'package:onegini/pigeon.dart'; import '../onegini.dart'; /// A callback for pin AUTHENTICATION. class OneginiPinAuthenticationCallback { + final api = UserClientApi(); + /// Cancels pin authentication. Future denyAuthenticationRequest() async { - await Onegini.instance.channel - .invokeMethod(Constants.denyPinAuthenticationRequest); + await api.pinDenyAuthenticationRequest(); } /// Accepts pin authentication and sent [pin] to the OneginiSdk. Future acceptAuthenticationRequest(BuildContext? context, {String? pin}) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel.invokeMethod( - Constants.acceptPinAuthenticationRequest, { - 'pin': pin, - }); + + await api.pinAcceptAuthenticationRequest(pin); } } diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index 6101c3e3..63c602ce 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -1,14 +1,14 @@ import 'package:flutter/material.dart'; -import 'package:onegini/constants/constants.dart'; +import 'package:onegini/pigeon.dart'; import '../onegini.dart'; /// A callback for pin REGISTRATION. class OneginiPinRegistrationCallback { + final api = UserClientApi(); /// Cancels pin registration request. Future denyAuthenticationRequest() async { - await Onegini.instance.channel - .invokeMethod(Constants.denyPinRegistrationRequest); + await api.pinDenyRegistrationRequest(); } /// Accepts pin registration and sent [pin] to the OneginiSdk. @@ -16,10 +16,7 @@ class OneginiPinRegistrationCallback { Future acceptAuthenticationRequest(BuildContext? context, {String? pin, bool isCustomAuthenticator = false}) async { Onegini.instance.setEventContext(context); - await Onegini.instance.channel - .invokeMethod(Constants.acceptPinRegistrationRequest, { - 'pin': pin, - 'isCustomAuth': isCustomAuthenticator ? "true" : null, - }); + + await api.pinAcceptRegistrationRequest(pin, isCustomAuthenticator); } } diff --git a/lib/callbacks/onegini_registration_callback.dart b/lib/callbacks/onegini_registration_callback.dart index 25ff687d..60188aa0 100644 --- a/lib/callbacks/onegini_registration_callback.dart +++ b/lib/callbacks/onegini_registration_callback.dart @@ -1,12 +1,13 @@ -import 'package:onegini/constants/constants.dart'; +import 'package:onegini/pigeon.dart'; import '../onegini.dart'; /// A callback for registration. class OneginiRegistrationCallback { + final api = UserClientApi(); + /// Cancels registration action. Future cancelBrowserRegistration() async { - await Onegini.instance.channel - .invokeMethod(Constants.cancelRegistrationMethod); + await api.cancelBrowserRegistration(); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 57320734..baae72e9 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -845,6 +845,276 @@ class UserClientApi { return; } } + + /// Custom Registration Callbacks + Future submitCustomRegistrationSuccessAction(String arg_identityProviderId, String? arg_data) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_identityProviderId, arg_data]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future submitCustomRegistrationErrorAction(String arg_identityProviderId, String arg_error) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_identityProviderId, arg_error]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + /// Fingerprint Callbacks + Future fingerprintFallbackToPin() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future fingerprintDenyAuthenticationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future fingerprintAcceptAuthenticationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + /// OTP Callbacks + Future otpDenyAuthenticationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future otpAcceptAuthenticationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + /// Pin Authentication Callbacks + Future pinDenyAuthenticationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future pinAcceptAuthenticationRequest(String? arg_pin) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_pin]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + /// Pin Registration Callbacks + Future pinDenyRegistrationRequest() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future pinAcceptRegistrationRequest(String? arg_pin, bool arg_isCustomAuthenticator) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_pin, arg_isCustomAuthenticator]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + /// Browser Registration Callbacks + Future cancelBrowserRegistration() async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } } class ResourceMethodApi { diff --git a/lib/user_client.dart b/lib/user_client.dart index d5372e5b..91d36032 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,13 +1,9 @@ -import 'dart:convert'; - import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/model/registration_response.dart'; import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/oneginiAppToWebSingleSignOn.dart'; -import 'model/onegini_list_response.dart'; import 'onegini.dart'; ///Сlass with basic methods available to the developer. @@ -24,7 +20,7 @@ class UserClient { List? scopes, ) async { Onegini.instance.setEventContext(context); - return api.registerUser(identityProviderId, scopes); + return await api.registerUser(identityProviderId, scopes); } /// Start browser Registration logic @@ -98,7 +94,9 @@ class UserClient { ) async { Onegini.instance.setEventContext(context); - await api.changePin(); + // todo use api once the branch is merged that puts this in an usecase on android + // await api.changePin(); + await Onegini.instance.channel.invokeMethod(Constants.changePin); } /// Registers authenticator from [getNotRegisteredAuthenticators] list. @@ -134,12 +132,43 @@ class UserClient { /// Starts mobile authentication on web by OTP. Future mobileAuthWithOtp(String data) async { - return await api.mobileAuthWithOtp(data); + // todo use api once the branch is merged that puts this in an usecase on android + // return await api.mobileAuthWithOtp(data); + try { + var isSuccess = await Onegini.instance.channel + .invokeMethod(Constants.handleMobileAuthWithOtp, { + 'data': data, + }); + return isSuccess; + } on TypeError catch (error) { + throw PlatformException( + code: Constants.wrapperTypeError.code.toString(), + message: Constants.wrapperTypeError.message, + stacktrace: error.stackTrace?.toString()); + } } /// Single sign on the user web page. Future getAppToWebSingleSignOn(String url) async { - return await api.getAppToWebSingleSignOn(url); + // todo use api once the branch is merged that puts this in an usecase on android + // return await api.getAppToWebSingleSignOn(url); + try { + var oneginiAppToWebSingleSignOn = await Onegini.instance.channel + .invokeMethod(Constants.getAppToWebSingleSignOn, { + 'url': url, + }); + + var oldAppToWeb = oneginiAppToWebSingleSignOnFromJson(oneginiAppToWebSingleSignOn); + var token = oldAppToWeb.token != null ? oldAppToWeb.token.toString() : ""; + var redirectUrl = oldAppToWeb.redirectUrl != null ? oldAppToWeb.redirectUrl.toString() : ""; + + return OWAppToWebSingleSignOn(token: token, redirectUrl: redirectUrl); + } on TypeError catch (error) { + throw PlatformException( + code: Constants.wrapperTypeError.code.toString(), + message: Constants.wrapperTypeError.message, + stacktrace: error.stackTrace?.toString()); + } } // Get Access Token @@ -160,7 +189,18 @@ class UserClient { /// todo removed boolean return update docu Future validatePinWithPolicy(String pin) async { - await api.validatePinWithPolicy(pin); + // todo use api once the branch is merged that puts this in an usecase on android + // await api.validatePinWithPolicy(pin); + try { + var success = await Onegini.instance.channel.invokeMethod( + Constants.validatePinWithPolicy, {'pin': pin}); + return success ?? false; + } on TypeError catch (error) { + throw PlatformException( + code: Constants.wrapperTypeError.code.toString(), + message: Constants.wrapperTypeError.message, + stacktrace: error.stackTrace?.toString()); + } } /// todo removed boolean return update docu diff --git a/pigeons/onewelcomePigeonInterface.dart b/pigeons/onewelcomePigeonInterface.dart deleted file mode 100644 index 8f542994..00000000 --- a/pigeons/onewelcomePigeonInterface.dart +++ /dev/null @@ -1,160 +0,0 @@ -import 'package:pigeon/pigeon.dart'; - -// @ConfigurePigeon(PigeonOptions( -// dartOut: './../lib/pigeon.dart', -// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', -// kotlinOptions: KotlinOptions( -// // copyrightHeader: ['zero'], -// package: 'com.zero.flutter_pigeon_plugin', -// ), -// objcHeaderOut: 'ios/Runner/Pigeon.h', -// objcSourceOut: 'ios/Runner/Pigeon.m', -// objcOptions: ObjcOptions( -// prefix: 'FLT', -// ), -// )) - -/// Result objects -class OneWelcomeUserProfile { - String profileId; - bool isDefault; - - OneWelcomeUserProfile({required this.profileId, required this.isDefault}); -} - -class OneWelcomeCustomInfo { - int status; - String data; - - OneWelcomeCustomInfo({required this.status, required this.data}); -} - -class OneWelcomeIdentityProvider { - String id; - String name; - - OneWelcomeIdentityProvider({required this.id, required this.name}); -} - -class OneWelcomeAuthenticator { - String id; - String name; - - OneWelcomeAuthenticator({required this.id, required this.name}); -} - -class OneWelcomeAppToWebSingleSignOn { - String token; - String redirectUrl; - - OneWelcomeAppToWebSingleSignOn({required this.token, required this.redirectUrl}); -} - -class OneWelcomeRegistrationResponse { - OneWelcomeUserProfile userProfile; - OneWelcomeCustomInfo? customInfo; - - OneWelcomeRegistrationResponse({required this.userProfile, this.customInfo}); -} - -/// Flutter calls native -@HostApi() -abstract class UserClientApi { - // example one - @async - List fetchUserProfiles(); - - @async - void voidFunction(); - - @async - String? nullableStringFunction(); - // // todo removed buildcontext - // @async - // OneWelcomeRegistrationResponse registerUser(String? identityProviderId, List? scopes); - - // @async - // void handleRegisteredUserUrl(String? url, int signInType); - - // // todo removed buildcontext - // @async - // List getIdentityProviders(); - - // // removed boolean return - // @async - // void deregisterUser(String profileId); - - // // todo removed buildconext - // @async - // List getRegisteredAuthenticators(String profileId); - - // // todo removed buildconext - // @async - // List getAllAuthenticators(String profileId); - - // @async - // OneWelcomeUserProfile getAuthenticatedUserProfile(); - - // // todo removed build context - // @async - // OneWelcomeRegistrationResponse authenticateUser(String profileId, String? registeredAuthenticatorId); - - // // todo removed context - // @async - // List getNotRegisteredAuthenticators(String profileId); - - // // todo removed context - // @async - // void changePin(); - - // // removed context and changed it into void instead of boolean - // @async - // void setPreferredAuthenticator(String authenticatorId); - - // // removed context and changed it into void instead of boolean - // @async - // void deregisterAuthenticator(String authenticatorId); - - // // removed context and changed it into void instead of boolean - // @async - // void logout(); - - // // todo investigate if string can be non null - // @async - // String? mobileAuthWithOtp(String data); - - // @async - // OneWelcomeAppToWebSingleSignOn getAppToWebSingleSignOn(String url); - - // @async - // String getAccessToken(); - - // @async - // String getRedirectUrl(); - - // @async - // List getUserProfiles(); - - // @async - // bool validatePinWithPolicy(); - - // @async - // bool authenticateDevice(List? scopes); - - // // todo update return value to object - // @async - // OneWelcomeUserProfile authenticateUserImplicitly(String profileId, List? scopes); -} - -@HostApi() -abstract class ResourceMethodApi { - @async - List fetchUserProfiles(); -} - -/// Native calls to Flutter -@FlutterApi() -abstract class NativeCallFlutterApi { - @async - String testEventFunction(String argument); -} diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index ee5ff2d3..5fceac27 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -150,6 +150,48 @@ abstract class UserClientApi { @async void cancelCustomRegistrationAction(String identityProviderId, String error); + + /// Custom Registration Callbacks + @async + void submitCustomRegistrationSuccessAction(String identityProviderId, String? data); + + @async + void submitCustomRegistrationErrorAction(String identityProviderId, String error); + + /// Fingerprint Callbacks + @async + void fingerprintFallbackToPin(); + + @async + void fingerprintDenyAuthenticationRequest(); + + @async + void fingerprintAcceptAuthenticationRequest(); + + /// OTP Callbacks + @async + void otpDenyAuthenticationRequest(); + + @async + void otpAcceptAuthenticationRequest(); + + /// Pin Authentication Callbacks + @async + void pinDenyAuthenticationRequest(); + + @async + void pinAcceptAuthenticationRequest(String? pin); + + /// Pin Registration Callbacks + @async + void pinDenyRegistrationRequest(); + + @async + void pinAcceptRegistrationRequest(String? pin, bool isCustomAuthenticator); + + /// Browser Registration Callbacks + @async + void cancelBrowserRegistration(); } @HostApi() diff --git a/pigeons/userProfile.dart b/pigeons/userProfile.dart deleted file mode 100644 index 8252aa1a..00000000 --- a/pigeons/userProfile.dart +++ /dev/null @@ -1,59 +0,0 @@ -import 'package:onegini/model/registration_response.dart'; -import 'package:pigeon/pigeon.dart'; - -// @ConfigurePigeon(PigeonOptions( -// dartOut: './../lib/pigeon.dart', -// kotlinOut: 'android/src/main/kotlin/com/zero/flutter_pigeon_plugin/Pigeon.kt', -// kotlinOptions: KotlinOptions( -// // copyrightHeader: ['zero'], -// package: 'com.zero.flutter_pigeon_plugin', -// ), -// objcHeaderOut: 'ios/Runner/Pigeon.h', -// objcSourceOut: 'ios/Runner/Pigeon.m', -// objcOptions: ObjcOptions( -// prefix: 'FLT', -// ), -// )) - -/// Result objects -class PigeonUserProfile { - String profileId; - bool isDefault; - - PigeonUserProfile({required this.profileId, required this.isDefault}); -} - -class PigeonCustomInfo { - int status; - String data; - - PigeonCustomInfo({required this.status, required this.data}); -} - -// class PigeonRegistrationResponse - -/// Flutter calls native -@HostApi() -abstract class UserClientApi { - // example one - @async - List fetchUserProfiles(); - - // todo removed buildcontext - RegistrationResponse registerUser(String? identityProviderId, List? scopes); - - -} - -@HostApi() -abstract class ResourceMethodApi { - @async - List fetchUserProfiles(); -} - -/// Native calls Flutter -@FlutterApi() -abstract class NativeCallFlutterApi { - @async - String testEventFunction(String argument); -} From 8304918695cf6f8658dd5034a551e39cda9327bf Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:49:58 +0100 Subject: [PATCH 054/364] FP-20 Update custom registration callback methods --- .../providers/CustomRegistrationAction.kt | 4 ++-- .../providers/CustomRegistrationActionImpl.kt | 20 +++++++++++-------- .../CustomTwoStepRegistrationActionImpl.kt | 20 +++++++++++-------- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt index eb774e8f..a978cb31 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt @@ -8,7 +8,7 @@ interface CustomRegistrationAction { fun getIdProvider(): String - fun returnSuccess(result: String?, resultChannel: MethodChannel.Result) + fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) - fun returnError(exception: Exception?, resultChannel: MethodChannel.Result) + fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 075b66c4..119b7eee 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -10,8 +10,6 @@ import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel import com.onegini.mobile.sdk.flutter.models.OneginiEvent -import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -import io.flutter.plugin.common.MethodChannel class CustomRegistrationActionImpl(private val providerId: String) : OneginiCustomRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null @@ -35,19 +33,25 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust return providerId } - override fun returnSuccess(result: String?, resultChannel: MethodChannel.Result) { + override fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) { when (callback) { - null -> SdkError(REGISTRATION_NOT_IN_PROGRESS).flutterError(resultChannel) - else -> this.callback?.returnSuccess(result) + null -> pigeonChannel(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + else -> { + this.callback?.returnSuccess(result) + pigeonChannel(Result.success(Unit)) + } } callback = null } - override fun returnError(exception: Exception?, resultChannel: MethodChannel.Result) { + override fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) { when (callback) { - null -> SdkError(REGISTRATION_NOT_IN_PROGRESS).flutterError(resultChannel) - else -> this.callback?.returnError(exception) + null -> pigeonChannel(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + else -> { + this.callback?.returnError(exception) + pigeonChannel(Result.success(Unit)) + } } callback = null diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 5b0cc9ba..31ca0dff 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -11,8 +11,6 @@ import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel import com.onegini.mobile.sdk.flutter.models.OneginiEvent -import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -import io.flutter.plugin.common.MethodChannel class CustomTwoStepRegistrationActionImpl(private val providerId: String) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null @@ -41,19 +39,25 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg return providerId } - override fun returnSuccess(result: String?, resultChannel: MethodChannel.Result) { + override fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) { when (callback) { - null -> SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).flutterError(resultChannel) - else -> this.callback?.returnSuccess(result) + null -> pigeonChannel(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + else -> { + this.callback?.returnSuccess(result) + pigeonChannel(Result.success(Unit)) + } } callback = null } - override fun returnError(exception: Exception?, resultChannel: MethodChannel.Result) { + override fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) { when (callback) { - null -> SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).flutterError(resultChannel) - else -> this.callback?.returnError(exception) + null -> pigeonChannel(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + else -> { + this.callback?.returnError(exception) + pigeonChannel(Result.success(Unit)) + } } callback = null From 2392bb1b6dc0af28199c4b892b238eb0c28e1d72 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:50:28 +0100 Subject: [PATCH 055/364] FP-20 Update authenticatedevice use case to pigeon --- .../useCases/AuthenticateDeviceUseCase.kt | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateDeviceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateDeviceUseCase.kt index 781800c6..c77ab73d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateDeviceUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateDeviceUseCase.kt @@ -4,27 +4,30 @@ import com.onegini.mobile.sdk.android.handlers.OneginiDeviceAuthenticationHandle import com.onegini.mobile.sdk.android.handlers.error.OneginiDeviceAuthenticationError import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class AuthenticateDeviceUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val scope = call.argument>("scope") - oneginiSDK.oneginiClient.deviceClient.authenticateDevice(scope?.toArray(arrayOfNulls(scope.size)), object : OneginiDeviceAuthenticationHandler { - override fun onSuccess() { - result.success(true) - } + operator fun invoke(scopes: List?, callback: (Result) -> Unit) { + val sdkScopes: Array? = scopes?.toTypedArray() - override fun onError(error: OneginiDeviceAuthenticationError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) - } - } + oneginiSDK.oneginiClient.deviceClient.authenticateDevice(sdkScopes, object : OneginiDeviceAuthenticationHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } + + override fun onError(error: OneginiDeviceAuthenticationError) { + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) ) + } } + ) + } } From 1c1419819da8b80395a534b55804a938f51153c6 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:50:53 +0100 Subject: [PATCH 056/364] FP-20 Update AuthenticateUserImplicitlyUseCase.kt to pigeon --- .../AuthenticateUserImplicitlyUseCase.kt | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt index 302ab380..b33610d1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt @@ -3,26 +3,22 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiImplicitAuthenticationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiImplicitTokenRequestError import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.METHOD_ARGUMENT_NOT_FOUND import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton -class AuthenticateUserImplicitlyUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, - private val getUserProfileUseCase: GetUserProfileUseCase) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - val scopes = call.argument>("scopes") - +class AuthenticateUserImplicitlyUseCase @Inject constructor( + private val oneginiSDK: OneginiSDK, + private val getUserProfileUseCase: GetUserProfileUseCase +) { + operator fun invoke(profileId: String, scopes: List?, callback: (Result) -> Unit) { + // TODO replace this logic with result val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return callback(Result.failure(error.pigeonError())) } oneginiSDK.oneginiClient.userClient.authenticateUserImplicitly( @@ -30,14 +26,18 @@ class AuthenticateUserImplicitlyUseCase @Inject constructor(private val oneginiS scopes?.toTypedArray(), object : OneginiImplicitAuthenticationHandler { override fun onSuccess(profile: UserProfile) { - result.success(userProfile.profileId) + callback(Result.success(Unit)) } override fun onError(error: OneginiImplicitTokenRequestError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) } } ) From 116556625d78b3ea29e5b1d9fed01cdf16a506bf Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:51:33 +0100 Subject: [PATCH 057/364] FP-20 Update AuthenticateUserUseCase.kt to pigeon --- .../useCases/AuthenticateUserUseCase.kt | 56 +++++++++++-------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 5c9edbb0..e0d15517 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator @@ -9,8 +8,9 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject import javax.inject.Singleton @@ -19,22 +19,18 @@ class AuthenticateUserUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("registeredAuthenticatorId") - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - + operator fun invoke(profileId: String, authenticatorId: String?, callback: (Result) -> Unit) { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return callback(Result.failure(error)) } val authenticator = getRegisteredAuthenticatorById(authenticatorId, userProfile) when { - authenticatorId != null && authenticator == null -> SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) - else -> authenticate(userProfile, authenticator, result) + authenticatorId != null && authenticator == null -> callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) + else -> authenticate(userProfile, authenticator, callback) } } @@ -49,29 +45,41 @@ class AuthenticateUserUseCase @Inject constructor( return null } - private fun authenticate(userProfile: UserProfile, authenticator: OneginiAuthenticator?, result: MethodChannel.Result) { + private fun authenticate( + userProfile: UserProfile, + authenticator: OneginiAuthenticator?, + callback: (Result) -> Unit + ) { if (authenticator == null) { - oneginiSDK.oneginiClient.userClient.authenticateUser(userProfile, getOneginiAuthenticationHandler(result)) + oneginiSDK.oneginiClient.userClient.authenticateUser(userProfile, getOneginiAuthenticationHandler(callback)) } else { - oneginiSDK.oneginiClient.userClient.authenticateUser(userProfile, authenticator, getOneginiAuthenticationHandler(result)) + oneginiSDK.oneginiClient.userClient.authenticateUser(userProfile, authenticator, getOneginiAuthenticationHandler(callback)) } } - private fun getOneginiAuthenticationHandler(result: MethodChannel.Result): OneginiAuthenticationHandler { + private fun getOneginiAuthenticationHandler(callback: (Result) -> Unit): OneginiAuthenticationHandler { return object : OneginiAuthenticationHandler { override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) { - //todo check unit tests - val userProfileJson = mapOf("profileId" to userProfile.profileId, "isDefault" to userProfile.isDefault) - val customInfoJson = mapOf("data" to customInfo?.data, "status" to customInfo?.status) - val returnedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - result.success(returnedResult) + val owProfile = OWUserProfile(userProfile.profileId) + + when (customInfo) { + null -> callback(Result.success(OWRegistrationResponse(owProfile))) + else -> { + val owCustomInfo = OWCustomInfo(customInfo.status.toLong(), customInfo.data) + callback(Result.success(OWRegistrationResponse(owProfile, owCustomInfo))) + } + } } override fun onError(error: OneginiAuthenticationError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) } } } From 3527ade3b891f036adc0abf684171edbf698d3e4 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:51:55 +0100 Subject: [PATCH 058/364] FP-20 Update CancelCustomRegistrationActionUseCase.kt to pigeon --- .../CancelCustomRegistrationActionUseCase.kt | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt index 94231e53..a7f66b9f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt @@ -3,24 +3,15 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.IDENTITY_PROVIDER_NOT_FOUND import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class CancelCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result, call: MethodCall) { - val idProvider: String? = call.argument("identityProviderId") - - when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == idProvider }) { - null -> SdkError(IDENTITY_PROVIDER_NOT_FOUND).flutterError(result) - else -> { - when (val error: String? = call.argument("error")) { - null -> action.returnError(null, result) - else -> action.returnError(Exception(error), result) - } - } + operator fun invoke(identityProviderId: String, error: String, callback: (Result) -> Unit) { + when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { + null -> callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) + else -> action.returnError(Exception(error), callback) } } } From 407d35defdd04db26acd1fd6f5d89e59073d5ced Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:52:24 +0100 Subject: [PATCH 059/364] FP-20 update DeregisterAuthenticatorUseCase.kt to pigeon --- .../DeregisterAuthenticatorUseCase.kt | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt index eadedd41..9d31e6ec 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt @@ -7,33 +7,32 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("authenticatorId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - + operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).flutterError(result) + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) val authenticator = getAuthenticatorById(authenticatorId, userProfile) - ?: return SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) + ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(authenticator, object : OneginiAuthenticatorDeregistrationHandler { override fun onSuccess() { - result.success(true) + callback(Result.success(Unit)) } override fun onError(oneginiAuthenticatorDeregistrationError: OneginiAuthenticatorDeregistrationError) { - SdkError( - code = oneginiAuthenticatorDeregistrationError.errorType, - message = oneginiAuthenticatorDeregistrationError.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = oneginiAuthenticatorDeregistrationError.errorType, + message = oneginiAuthenticatorDeregistrationError.message + ).pigeonError() + ) + ) } } ) @@ -49,5 +48,4 @@ class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: } return authenticator } - } From d1c101f0d66132fe0f86e045b4211a656a43f0ae Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:52:47 +0100 Subject: [PATCH 060/364] fp-20 update DeregisterUserUseCase.kt to pigeon --- .../flutter/useCases/DeregisterUserUseCase.kt | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt index 2aeb1f95..c1207bc5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt @@ -2,11 +2,8 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiDeregisterUserProfileHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiDeregistrationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @@ -15,26 +12,28 @@ class DeregisterUserUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) + operator fun invoke(profileId: String, callback: (Result) -> Unit) { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return callback(Result.failure(error.pigeonError())) } oneginiSDK.oneginiClient.userClient.deregisterUser(userProfile, object : OneginiDeregisterUserProfileHandler { override fun onSuccess() { - result.success(true) + callback(Result.success(Unit)) } override fun onError(oneginiDeregistrationError: OneginiDeregistrationError) { - SdkError( - code = oneginiDeregistrationError.errorType, - message = oneginiDeregistrationError.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = oneginiDeregistrationError.errorType, + message = oneginiDeregistrationError.message + ).pigeonError() + ) + ) } }) } From 90bd02e249d26e3af4c8ac80aee567c1ec15946a Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:53:17 +0100 Subject: [PATCH 061/364] fp-20 update GetAccessTokenUseCase.kt to pigeon --- .../sdk/flutter/useCases/GetAccessTokenUseCase.kt | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt index 1c0de5a2..c81c39d4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt @@ -2,18 +2,17 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.errors.wrapperError -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton class GetAccessTokenUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - oneginiSDK.oneginiClient.userClient.accessToken?.let { token -> - result.success(token) - return - } - result.wrapperError(NO_USER_PROFILE_IS_AUTHENTICATED) + operator fun invoke(): Result { + oneginiSDK.oneginiClient.userClient.accessToken?.let { token -> + return Result.success(token) } + + return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) + } } From d4bc9a38de334c8035f51947cb28deb7e0ff9f32 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:53:38 +0100 Subject: [PATCH 062/364] fp-20 update GetAllAuthenticatorsUseCase.kt to pigeon --- .../useCases/GetAllAuthenticatorsUseCase.kt | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt index 3639c73a..215bbae8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt @@ -1,11 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.GsonBuilder -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import javax.inject.Inject import javax.inject.Singleton @@ -14,30 +11,28 @@ class GetAllAuthenticatorsUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - + operator fun invoke(profileId: String): Result> { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return Result.failure(error) } - val gson = GsonBuilder().serializeNulls().create() val allAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - val authenticators: ArrayList> = ArrayList() + val authenticators = mutableListOf() + for (auth in allAuthenticators) { - val map = mutableMapOf() - map["id"] = auth.id - map["name"] = auth.name + val authenticator = OWAuthenticator( + auth.id, + auth.name, + auth.isRegistered, + auth.isPreferred, + auth.type.toLong() + ) - /* TODO Extend this callback with additional attributes - * type, isPreferred, isRegistered - * https://onewelcome.atlassian.net/browse/FP-46 - */ - authenticators.add(map) + authenticators.add(authenticator) } - result.success(gson.toJson(authenticators)) + + return Result.success(authenticators) } } From 9dd6774b5c411c80985043a26210ee82fc9ce457 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:54:08 +0100 Subject: [PATCH 063/364] fp-20 update GetNotRegisteredAuthenticatorsUseCase.kt to pigeon --- .../GetNotRegisteredAuthenticatorsUseCase.kt | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt index e3ccb984..332d5d88 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt @@ -4,6 +4,7 @@ import com.google.gson.GsonBuilder import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import javax.inject.Inject @@ -14,30 +15,26 @@ class GetNotRegisteredAuthenticatorsUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - + operator fun invoke(profileId: String): Result> { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return Result.failure(error) } - val gson = GsonBuilder().serializeNulls().create() val notRegisteredAuthenticators = oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(userProfile) - val authenticators: ArrayList> = ArrayList() + val authenticators = mutableListOf() for (auth in notRegisteredAuthenticators) { - val map = mutableMapOf() - map["id"] = auth.id - map["name"] = auth.name + val authenticator = OWAuthenticator( + auth.id, + auth.name, + auth.isRegistered, + auth.isPreferred, + auth.type.toLong() + ) - /* TODO Extend this callback with additional attributes - * type, isPreferred, isRegistered - * https://onewelcome.atlassian.net/browse/FP-46 - */ - authenticators.add(map) + authenticators.add(authenticator) } - result.success(gson.toJson(authenticators)) + return Result.success(authenticators) } } From 718059e6064411cc0560cca24fb363f1c3b3a3d5 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:54:31 +0100 Subject: [PATCH 064/364] fp-20 update GetRedirectUrlUseCase.kt to pigeon --- .../mobile/sdk/flutter/useCases/GetRedirectUrlUseCase.kt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRedirectUrlUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRedirectUrlUseCase.kt index 1946cc59..24494f1f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRedirectUrlUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRedirectUrlUseCase.kt @@ -1,13 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.OneginiSDK -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class GetRedirectUrlUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - result.success(oneginiSDK.oneginiClient.configModel.redirectUri) + operator fun invoke(): Result { + return Result.success(oneginiSDK.oneginiClient.configModel.redirectUri) } } From 61580208f85f36010b00b13463d68590b5dbb6a9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:54:50 +0100 Subject: [PATCH 065/364] fp-20 update GetRegisteredAuthenticatorsUseCase.kt to pigeon --- .../GetRegisteredAuthenticatorsUseCase.kt | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt index 6d63464c..3016299e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt @@ -1,11 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.GsonBuilder -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import javax.inject.Inject import javax.inject.Singleton @@ -14,30 +11,28 @@ class GetRegisteredAuthenticatorsUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val profileId = call.argument("profileId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - + operator fun invoke(profileId: String): Result> { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return error.flutterError(result) + return Result.failure(error) } - val gson = GsonBuilder().serializeNulls().create() val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - val authenticators: ArrayList> = ArrayList() + val authenticators = mutableListOf() + for (registeredAuthenticator in registeredAuthenticators) { - val map = mutableMapOf() - map["id"] = registeredAuthenticator.id - map["name"] = registeredAuthenticator.name + val authenticator = OWAuthenticator( + registeredAuthenticator.id, + registeredAuthenticator.name, + registeredAuthenticator.isRegistered, + registeredAuthenticator.isPreferred, + registeredAuthenticator.type.toLong() + ) - /* TODO Extend this callback with additional attributes - * type, isPreferred, isRegistered - * https://onewelcome.atlassian.net/browse/FP-46 - */ - authenticators.add(map) + authenticators.add(authenticator) } - result.success(gson.toJson(authenticators)) + + return Result.success(authenticators) } } From 5af5b760bc2e9b4bca090f6d96c20e9bf61f1e4e Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:55:10 +0100 Subject: [PATCH 066/364] dp-20 update HandleRegisteredUrlUseCase.kt to pigeon --- .../sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt index 2432f76f..b6819646 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt @@ -3,20 +3,18 @@ package com.onegini.mobile.sdk.flutter.useCases import android.content.Context import android.content.Intent import android.net.Uri -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.activity.ActivityWebView -import io.flutter.plugin.common.MethodCall import javax.inject.Inject import javax.inject.Singleton @Singleton class HandleRegisteredUrlUseCase @Inject constructor(private val context: Context, private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall) { - val url = call.argument("url") ?: "" - val isInAppBrowser = call.argument("type") - val intent = prepareIntentBasedOnType(isInAppBrowser, context, url) + operator fun invoke(url: String, signInType: Long): Result { + val intent = prepareIntentBasedOnType(signInType.toInt(), context, url) context.startActivity(intent) + + return Result.success(Unit) } private fun prepareIntentBasedOnType(type: Int?, context: Context, url: String): Intent { From 253358057795f102634e927144562b4ace353fae Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:55:31 +0100 Subject: [PATCH 067/364] fp-20 update LogoutUseCase.kt to pigeon --- .../sdk/flutter/useCases/LogoutUseCase.kt | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/LogoutUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/LogoutUseCase.kt index dbf6523f..99273303 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/LogoutUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/LogoutUseCase.kt @@ -4,24 +4,27 @@ import com.onegini.mobile.sdk.android.handlers.OneginiLogoutHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiLogoutError import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class LogoutUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - oneginiSDK.oneginiClient.userClient.logout(object : OneginiLogoutHandler { - override fun onSuccess() { - result.success(true) - } + operator fun invoke(callback: (Result) -> Unit) { + oneginiSDK.oneginiClient.userClient.logout(object : OneginiLogoutHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } - override fun onError(error: OneginiLogoutError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) - } - }) - } + override fun onError(error: OneginiLogoutError) { + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) + } + }) + } } From 2dc2da7ee430b5d7bfd67c2352cad77e95bfcdcb Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:56:00 +0100 Subject: [PATCH 068/364] fpp-20 update RegistrationUseCase.kt to pigeon --- .../onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index ae593367..721f25d6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -23,7 +23,7 @@ class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) } - val registerScopes = scopes?.toTypedArray() ?: emptyArray() + val registerScopes = scopes?.toTypedArray() register(identityProvider, registerScopes, callback) } From c40354ff30e438763beab264d523e13b3d406f75 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:56:27 +0100 Subject: [PATCH 069/364] fp-20 update GetUserProfilesUseCase.kt to pigeon --- .../useCases/GetUserProfilesUseCase.kt | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt index cc08836c..09bc13b9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt @@ -1,33 +1,29 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneginiSDK -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject import javax.inject.Singleton @Singleton -class GetUserProfilesUseCase @Inject constructor (private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - val userProfiles = oneginiSDK.oneginiClient.userClient.userProfiles - val userProfileArray = getUserProfileArray(userProfiles) - result.success(Gson().toJson(userProfileArray)) - } +class GetUserProfilesUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(): Result> { + val userProfiles = oneginiSDK.oneginiClient.userClient.userProfiles + val userProfileList = getUserProfileArray(userProfiles) + return Result.success(userProfileList) + } + + private fun getUserProfileArray(userProfiles: Set?): List { + val userProfileList = mutableListOf() - private fun getUserProfileArray(userProfiles: Set?): ArrayList> { - val userProfileArray: ArrayList> = ArrayList() - if (userProfiles != null) { - for (userProfile in userProfiles) { - if (userProfile != null) { - val map = mutableMapOf() - map["isDefault"] = userProfile.isDefault - map["profileId"] = userProfile.profileId - userProfileArray.add(map) - } - } + if (userProfiles != null) { + for (userProfile in userProfiles) { + if (userProfile != null) { + userProfileList.add(OWUserProfile(userProfile.profileId)) } - return userProfileArray + } } + return userProfileList + } } From 63baf7f662d23ba91804b1612ff69883f7adced8 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:56:45 +0100 Subject: [PATCH 070/364] fp-20 update RegisterAuthenticatorUseCase.kt to pigeon --- .../useCases/RegisterAuthenticatorUseCase.kt | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt index 9ceefbac..3a49abca 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator @@ -9,46 +8,47 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class RegisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("authenticatorId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) + operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { + val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).flutterError(result) + val authenticator = getAuthenticatorById(authenticatorId, authenticatedUserProfile) + ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) - val authenticator = getAuthenticatorById(authenticatorId, authenticatedUserProfile) - ?: return SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) + oneginiSDK.oneginiClient.userClient.registerAuthenticator(authenticator, object : OneginiAuthenticatorRegistrationHandler { + override fun onSuccess(customInfo: CustomInfo?) { + callback(Result.success(Unit)) + } - oneginiSDK.oneginiClient.userClient.registerAuthenticator(authenticator, object : OneginiAuthenticatorRegistrationHandler { - override fun onSuccess(customInfo: CustomInfo?) { - result.success(Gson().toJson(customInfo)) - } - - override fun onError(oneginiAuthenticatorRegistrationError: OneginiAuthenticatorRegistrationError) { - SdkError( - code = oneginiAuthenticatorRegistrationError.errorType, - message = oneginiAuthenticatorRegistrationError.message - ).flutterError(result) - } - } + override fun onError(oneginiAuthenticatorRegistrationError: OneginiAuthenticatorRegistrationError) { + callback( + Result.failure( + SdkError( + code = oneginiAuthenticatorRegistrationError.errorType, + message = oneginiAuthenticatorRegistrationError.message + ).pigeonError() + ) ) + } } + ) + } + + private fun getAuthenticatorById(authenticatorId: String?, authenticatedUserProfile: UserProfile): OneginiAuthenticator? { + var authenticator: OneginiAuthenticator? = null - private fun getAuthenticatorById(authenticatorId: String?, authenticatedUserProfile: UserProfile): OneginiAuthenticator? { - var authenticator: OneginiAuthenticator? = null - val notRegisteredAuthenticators = oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(authenticatedUserProfile) - for (auth in notRegisteredAuthenticators) { - if (auth.id == authenticatorId) { - authenticator = auth - } - } - return authenticator + // We don't have to check if the authenticator is already registered as the sdk will do that for us. + val allAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(authenticatedUserProfile) + for (auth in allAuthenticators) { + if (auth.id == authenticatorId) { + authenticator = auth + } } + return authenticator + } } From cdc1f3a51612357a7f6851c061ed4586ba9f48ea Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:57:05 +0100 Subject: [PATCH 071/364] fp-20 update SetPreferredAuthenticatorUseCase.kt to pigeon --- .../SetPreferredAuthenticatorUseCase.kt | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 2b85abb5..28300973 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -5,35 +5,31 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton -class SetPreferredAuthenticatorUseCase @Inject constructor (private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("authenticatorId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) +class SetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(authenticatorId: String): Result { - val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).flutterError(result) + val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) - val authenticator = getAuthenticatorById(authenticatorId, userProfile) - ?: return SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) + val authenticator = getAuthenticatorById(authenticatorId, userProfile) + ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND)) - oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) - result.success(true) - } + oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) + return Result.success(Unit) + } - private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { - var authenticator: OneginiAuthenticator? = null - val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - for (registeredAuthenticator in registeredAuthenticators) { - if (registeredAuthenticator.id == authenticatorId) { - authenticator = registeredAuthenticator - } - } - return authenticator + private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { + var authenticator: OneginiAuthenticator? = null + val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) + for (registeredAuthenticator in registeredAuthenticators) { + if (registeredAuthenticator.id == authenticatorId) { + authenticator = registeredAuthenticator + } } + return authenticator + } } From d162ec1facdb3c6b8363e9b80121b07dc567eadc Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 10:57:44 +0100 Subject: [PATCH 072/364] fp-20 update SubmitCustomRegistrationActionUseCase.kt to pigeon --- .../SubmitCustomRegistrationActionUseCase.kt | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt index 0b91e91e..38bfc472 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt @@ -3,20 +3,15 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.IDENTITY_PROVIDER_NOT_FOUND import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class SubmitCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result, call: MethodCall) { - val idProvider: String? = call.argument("identityProviderId") - val token: String? = call.argument("data") - - when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == idProvider }) { - null -> SdkError(IDENTITY_PROVIDER_NOT_FOUND).flutterError(result) - else -> action.returnSuccess(token, result) + operator fun invoke(identityProviderId: String, data: String?, callback: (Result) -> Unit) { + when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { + null -> callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) + else -> action.returnSuccess(data, callback) } } } From e835790e26afa9b3c3d358f9d9b18336221167b3 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 11:11:59 +0100 Subject: [PATCH 073/364] fp-20 removed duplicate pigeon interface calls for custom registration --- .../mobile/sdk/flutter/PigeonInterface.kt | 10 +--- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 46 +------------------ ios/Classes/Pigeon.swift | 42 +---------------- lib/pigeon.dart | 46 +------------------ pigeons/onewelcome_pigeon_interface.dart | 8 +--- 5 files changed, 6 insertions(+), 146 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index e0ab7450..1bb72993 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -200,6 +200,7 @@ open class PigeonInterface : UserClientApi { authenticateUserImplicitlyUseCase(profileId, scopes, callback) } + // Callback functions override fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { submitCustomRegistrationActionUseCase(identityProviderId, data, callback) } @@ -208,15 +209,6 @@ open class PigeonInterface : UserClientApi { cancelCustomRegistrationActionUseCase(identityProviderId, error, callback) } - // Callback functions - override fun submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { -// TODO("Not yet implemented") - } - - override fun submitCustomRegistrationErrorAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") - } - override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { // TODO("Not yet implemented") } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 5133a91d..6bcada3c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -278,11 +278,9 @@ interface UserClientApi { fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) + /** Custom Registration Callbacks */ fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) - /** Custom Registration Callbacks */ - fun submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) - fun submitCustomRegistrationErrorAction(identityProviderId: String, error: String, callback: (Result) -> Unit) /** Fingerprint Callbacks */ fun fingerprintFallbackToPin(callback: (Result) -> Unit) fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) @@ -810,48 +808,6 @@ interface UserClientApi { channel.setMessageHandler(null) } } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction", codec) - if (api != null) { - channel.setMessageHandler { message, reply -> - var wrapped = listOf() - val args = message as List - val identityProviderIdArg = args[0] as String - val dataArg = args[1] as? String - api.submitCustomRegistrationSuccessAction(identityProviderIdArg, dataArg) { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - reply.reply(wrapResult(null)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction", codec) - if (api != null) { - channel.setMessageHandler { message, reply -> - var wrapped = listOf() - val args = message as List - val identityProviderIdArg = args[0] as String - val errorArg = args[1] as String - api.submitCustomRegistrationErrorAction(identityProviderIdArg, errorArg) { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - reply.reply(wrapResult(null)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", codec) if (api != null) { diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 125e3b28..dac4f828 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -264,11 +264,9 @@ protocol UserClientApi { func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) + /// Custom Registration Callbacks func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) - /// Custom Registration Callbacks - func submitCustomRegistrationSuccessAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) - func submitCustomRegistrationErrorAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) /// Fingerprint Callbacks func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) @@ -671,6 +669,7 @@ class UserClientApiSetup { } else { authenticateUserImplicitlyChannel.setMessageHandler(nil) } + /// Custom Registration Callbacks let submitCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in @@ -707,43 +706,6 @@ class UserClientApiSetup { } else { cancelCustomRegistrationActionChannel.setMessageHandler(nil) } - /// Custom Registration Callbacks - let submitCustomRegistrationSuccessActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - submitCustomRegistrationSuccessActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let identityProviderIdArg = args[0] as! String - let dataArg = args[1] as? String - api.submitCustomRegistrationSuccessAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in - switch result { - case .success: - reply(wrapResult(nil)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - submitCustomRegistrationSuccessActionChannel.setMessageHandler(nil) - } - let submitCustomRegistrationErrorActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - submitCustomRegistrationErrorActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let identityProviderIdArg = args[0] as! String - let errorArg = args[1] as! String - api.submitCustomRegistrationErrorAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in - switch result { - case .success: - reply(wrapResult(nil)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - submitCustomRegistrationErrorActionChannel.setMessageHandler(nil) - } /// Fingerprint Callbacks let fingerprintFallbackToPinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index baae72e9..ce678404 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -802,6 +802,7 @@ class UserClientApi { } } + /// Custom Registration Callbacks Future submitCustomRegistrationAction(String arg_identityProviderId, String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, @@ -846,51 +847,6 @@ class UserClientApi { } } - /// Custom Registration Callbacks - Future submitCustomRegistrationSuccessAction(String arg_identityProviderId, String? arg_data) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationSuccessAction', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_data]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future submitCustomRegistrationErrorAction(String arg_identityProviderId, String arg_error) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationErrorAction', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_error]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - /// Fingerprint Callbacks Future fingerprintFallbackToPin() async { final BasicMessageChannel channel = BasicMessageChannel( diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 5fceac27..5e97aa00 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -145,19 +145,13 @@ abstract class UserClientApi { @async void authenticateUserImplicitly(String profileId, List? scopes); + /// Custom Registration Callbacks @async void submitCustomRegistrationAction(String identityProviderId, String? data); @async void cancelCustomRegistrationAction(String identityProviderId, String error); - /// Custom Registration Callbacks - @async - void submitCustomRegistrationSuccessAction(String identityProviderId, String? data); - - @async - void submitCustomRegistrationErrorAction(String identityProviderId, String error); - /// Fingerprint Callbacks @async void fingerprintFallbackToPin(); From 30e350600c2df7d854bbd2663cb2b492e1ce6bfc Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 11:37:31 +0100 Subject: [PATCH 074/364] FP-20 Updated interface regarding callbacks again and implemented some callback functions on android for pigeon --- .../mobile/sdk/flutter/PigeonInterface.kt | 29 ++++++++++++++----- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 8 ++--- ios/Classes/Pigeon.swift | 8 ++--- .../onegini_otp_accept_deny_callback.dart | 1 - .../onegini_pin_authentication_callback.dart | 3 +- .../onegini_pin_registration_callback.dart | 4 +-- lib/pigeon.dart | 4 +-- pigeons/onewelcome_pigeon_interface.dart | 4 +-- 8 files changed, 36 insertions(+), 25 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 1bb72993..6f161b19 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,5 +1,9 @@ package com.onegini.mobile.sdk.flutter +import com.onegini.mobile.sdk.flutter.constants.Constants +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi @@ -210,38 +214,49 @@ open class PigeonInterface : UserClientApi { } override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + FingerprintAuthenticationRequestHandler.fingerprintCallback?.fallbackToPin() + callback(Result.success(Unit)) } override fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + FingerprintAuthenticationRequestHandler.fingerprintCallback?.denyAuthenticationRequest() + callback(Result.success(Unit)) } override fun fingerprintAcceptAuthenticationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + FingerprintAuthenticationRequestHandler.fingerprintCallback?.acceptAuthenticationRequest() + callback(Result.success(Unit)) } override fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() + callback(Result.success(Unit)) } override fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + MobileAuthOtpRequestHandler.CALLBACK?.acceptAuthenticationRequest() + callback(Result.success(Unit)) } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { // TODO("Not yet implemented") } - override fun pinAcceptAuthenticationRequest(pin: String?, callback: (Result) -> Unit) { + override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { // TODO("Not yet implemented") + PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { // TODO("Not yet implemented") } - override fun pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) { + override fun pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) { // TODO("Not yet implemented") } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 6bcada3c..832b8be8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -290,10 +290,10 @@ interface UserClientApi { fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) /** Pin Authentication Callbacks */ fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) - fun pinAcceptAuthenticationRequest(pin: String?, callback: (Result) -> Unit) + fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) /** Pin Registration Callbacks */ fun pinDenyRegistrationRequest(callback: (Result) -> Unit) - fun pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) + fun pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) /** Browser Registration Callbacks */ fun cancelBrowserRegistration(callback: (Result) -> Unit) @@ -922,7 +922,7 @@ interface UserClientApi { channel.setMessageHandler { message, reply -> var wrapped = listOf() val args = message as List - val pinArg = args[0] as? String + val pinArg = args[0] as String api.pinAcceptAuthenticationRequest(pinArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -960,7 +960,7 @@ interface UserClientApi { channel.setMessageHandler { message, reply -> var wrapped = listOf() val args = message as List - val pinArg = args[0] as? String + val pinArg = args[0] as String val isCustomAuthenticatorArg = args[1] as Boolean api.pinAcceptRegistrationRequest(pinArg, isCustomAuthenticatorArg) { result: Result -> val error = result.exceptionOrNull() diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index dac4f828..eef8bfd5 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -276,10 +276,10 @@ protocol UserClientApi { func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) /// Pin Authentication Callbacks func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) - func pinAcceptAuthenticationRequest(pin: String?, completion: @escaping (Result) -> Void) + func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) /// Pin Registration Callbacks func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) - func pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) + func pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) /// Browser Registration Callbacks func cancelBrowserRegistration(completion: @escaping (Result) -> Void) } @@ -803,7 +803,7 @@ class UserClientApiSetup { if let api = api { pinAcceptAuthenticationRequestChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let pinArg = args[0] as? String + let pinArg = args[0] as! String api.pinAcceptAuthenticationRequest(pin: pinArg) { result in switch result { case .success: @@ -836,7 +836,7 @@ class UserClientApiSetup { if let api = api { pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let pinArg = args[0] as? String + let pinArg = args[0] as! String let isCustomAuthenticatorArg = args[1] as! Bool api.pinAcceptRegistrationRequest(pin: pinArg, isCustomAuthenticator: isCustomAuthenticatorArg) { result in switch result { diff --git a/lib/callbacks/onegini_otp_accept_deny_callback.dart b/lib/callbacks/onegini_otp_accept_deny_callback.dart index 4a769c11..3ced9b01 100644 --- a/lib/callbacks/onegini_otp_accept_deny_callback.dart +++ b/lib/callbacks/onegini_otp_accept_deny_callback.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:onegini/constants/constants.dart'; import 'package:onegini/pigeon.dart'; import '../onegini.dart'; diff --git a/lib/callbacks/onegini_pin_authentication_callback.dart b/lib/callbacks/onegini_pin_authentication_callback.dart index 38111157..d4ae17f9 100644 --- a/lib/callbacks/onegini_pin_authentication_callback.dart +++ b/lib/callbacks/onegini_pin_authentication_callback.dart @@ -13,8 +13,7 @@ class OneginiPinAuthenticationCallback { } /// Accepts pin authentication and sent [pin] to the OneginiSdk. - Future acceptAuthenticationRequest(BuildContext? context, - {String? pin}) async { + Future acceptAuthenticationRequest(BuildContext? context, String pin) async { Onegini.instance.setEventContext(context); await api.pinAcceptAuthenticationRequest(pin); diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index 63c602ce..8679ef16 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -12,9 +12,7 @@ class OneginiPinRegistrationCallback { } /// Accepts pin registration and sent [pin] to the OneginiSdk. - /// Method also passes [isCustomAuthenticator] as `true` or `null`. - Future acceptAuthenticationRequest(BuildContext? context, - {String? pin, bool isCustomAuthenticator = false}) async { + Future acceptAuthenticationRequest(BuildContext? context, String pin, [bool isCustomAuthenticator=false]) async { Onegini.instance.setEventContext(context); await api.pinAcceptRegistrationRequest(pin, isCustomAuthenticator); diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ce678404..85ddd78c 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -982,7 +982,7 @@ class UserClientApi { } } - Future pinAcceptAuthenticationRequest(String? arg_pin) async { + Future pinAcceptAuthenticationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); @@ -1027,7 +1027,7 @@ class UserClientApi { } } - Future pinAcceptRegistrationRequest(String? arg_pin, bool arg_isCustomAuthenticator) async { + Future pinAcceptRegistrationRequest(String arg_pin, bool arg_isCustomAuthenticator) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest', codec, binaryMessenger: _binaryMessenger); diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 5e97aa00..19dc3222 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -174,14 +174,14 @@ abstract class UserClientApi { void pinDenyAuthenticationRequest(); @async - void pinAcceptAuthenticationRequest(String? pin); + void pinAcceptAuthenticationRequest(String pin); /// Pin Registration Callbacks @async void pinDenyRegistrationRequest(); @async - void pinAcceptRegistrationRequest(String? pin, bool isCustomAuthenticator); + void pinAcceptRegistrationRequest(String pin, bool isCustomAuthenticator); /// Browser Registration Callbacks @async From 31f47b9be23f0fcf6b8ba1b99dbe1be2af94c90c Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 11:51:46 +0100 Subject: [PATCH 075/364] fp-20 update example app to new method params regarding pin accept callbacks both authentication and register --- .../com/onegini/mobile/sdk/flutter/PigeonInterface.kt | 8 ++++++-- example/lib/screens/pin_screen.dart | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 6f161b19..e76e838f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -244,12 +244,15 @@ open class PigeonInterface : UserClientApi { } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + PinRequestHandler.CALLBACK?.denyAuthenticationRequest() + callback(Result.success(Unit)) } override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) + callback(Result.success(Unit)) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { @@ -258,6 +261,7 @@ open class PigeonInterface : UserClientApi { override fun pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) { // TODO("Not yet implemented") + PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { diff --git a/example/lib/screens/pin_screen.dart b/example/lib/screens/pin_screen.dart index c5e78a0c..f557a828 100644 --- a/example/lib/screens/pin_screen.dart +++ b/example/lib/screens/pin_screen.dart @@ -66,7 +66,7 @@ class _PinScreenState extends State { pin += element; }); OneginiPinAuthenticationCallback() - .acceptAuthenticationRequest(context, pin: pin) + .acceptAuthenticationRequest(context, pin) .catchError((error) { if (error is PlatformException) { setState(() => {isLoading = false}); From f67598a7809534fdf26839c502fc41a27604f495 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 8 Mar 2023 12:00:03 +0100 Subject: [PATCH 076/364] FP-20 Update pigeon interface with removed iscustomauthenticator param --- .../mobile/sdk/flutter/PigeonInterface.kt | 19 +++++++++++++------ .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 5 ++--- example/lib/screens/pin_request_screen.dart | 2 +- ios/Classes/Pigeon.swift | 5 ++--- .../onegini_pin_registration_callback.dart | 4 ++-- lib/pigeon.dart | 4 ++-- pigeons/onewelcome_pigeon_interface.dart | 2 +- 7 files changed, 23 insertions(+), 18 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index e76e838f..b32341a5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,8 +1,10 @@ package com.onegini.mobile.sdk.flutter import com.onegini.mobile.sdk.flutter.constants.Constants +import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -245,27 +247,32 @@ open class PigeonInterface : UserClientApi { override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { // TODO NEEDS OWN USE CASE - PinRequestHandler.CALLBACK?.denyAuthenticationRequest() + PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() callback(Result.success(Unit)) } override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { // TODO NEEDS OWN USE CASE - PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) + PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) callback(Result.success(Unit)) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + PinRequestHandler.CALLBACK?.denyAuthenticationRequest() + callback(Result.success(Unit)) } - override fun pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + override fun pinAcceptRegistrationRequest(pin: String, callback: (Result) -> Unit) { + // TODO NEEDS OWN USE CASE PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) + callback(Result.success(Unit)) } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE + BrowserRegistrationRequestHandler.onRegistrationCanceled() + callback(Result.success(Unit)) } private fun flutterCallback(callback: (Result) -> Unit, result: Result) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 832b8be8..a7a054dc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -293,7 +293,7 @@ interface UserClientApi { fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) /** Pin Registration Callbacks */ fun pinDenyRegistrationRequest(callback: (Result) -> Unit) - fun pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Boolean, callback: (Result) -> Unit) + fun pinAcceptRegistrationRequest(pin: String, callback: (Result) -> Unit) /** Browser Registration Callbacks */ fun cancelBrowserRegistration(callback: (Result) -> Unit) @@ -961,8 +961,7 @@ interface UserClientApi { var wrapped = listOf() val args = message as List val pinArg = args[0] as String - val isCustomAuthenticatorArg = args[1] as Boolean - api.pinAcceptRegistrationRequest(pinArg, isCustomAuthenticatorArg) { result: Result -> + api.pinAcceptRegistrationRequest(pinArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index e8f675b3..e45f2ce6 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -65,7 +65,7 @@ class _PinRequestScreenState extends State { if (widget.confirmation) { if (pin == widget.previousCode) { OneginiPinRegistrationCallback() - .acceptAuthenticationRequest(context, pin: pin) + .acceptAuthenticationRequest(context, pin) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index eef8bfd5..46adf461 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -279,7 +279,7 @@ protocol UserClientApi { func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) /// Pin Registration Callbacks func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) - func pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) + func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) /// Browser Registration Callbacks func cancelBrowserRegistration(completion: @escaping (Result) -> Void) } @@ -837,8 +837,7 @@ class UserClientApiSetup { pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in let args = message as! [Any?] let pinArg = args[0] as! String - let isCustomAuthenticatorArg = args[1] as! Bool - api.pinAcceptRegistrationRequest(pin: pinArg, isCustomAuthenticator: isCustomAuthenticatorArg) { result in + api.pinAcceptRegistrationRequest(pin: pinArg) { result in switch result { case .success: reply(wrapResult(nil)) diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index 8679ef16..9c104f36 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -12,9 +12,9 @@ class OneginiPinRegistrationCallback { } /// Accepts pin registration and sent [pin] to the OneginiSdk. - Future acceptAuthenticationRequest(BuildContext? context, String pin, [bool isCustomAuthenticator=false]) async { + Future acceptAuthenticationRequest(BuildContext? context, String pin) async { Onegini.instance.setEventContext(context); - await api.pinAcceptRegistrationRequest(pin, isCustomAuthenticator); + await api.pinAcceptRegistrationRequest(pin); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 85ddd78c..1a2b65ba 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1027,12 +1027,12 @@ class UserClientApi { } } - Future pinAcceptRegistrationRequest(String arg_pin, bool arg_isCustomAuthenticator) async { + Future pinAcceptRegistrationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_pin, arg_isCustomAuthenticator]) as List?; + await channel.send([arg_pin]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 19dc3222..8740dbd8 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -181,7 +181,7 @@ abstract class UserClientApi { void pinDenyRegistrationRequest(); @async - void pinAcceptRegistrationRequest(String pin, bool isCustomAuthenticator); + void pinAcceptRegistrationRequest(String pin); /// Browser Registration Callbacks @async From ac33aa5bb4c403a115fc36890877872a046b50f2 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 14:16:15 +0100 Subject: [PATCH 077/364] FP-20: iOS: Pigeon: Implement pinAcceptRegistrationRequest dirty --- .../ModuleExtensions/OneginiModuleSwift+Pin.swift | 4 ++-- .../PluginExtensions/SwiftOneginiPlugin+Register.swift | 8 -------- ios/Classes/SwiftOneginiPlugin.swift | 10 ++++++---- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 09f93f59..36cde794 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -8,8 +8,8 @@ extension OneginiModuleSwift { bridgeConnector.toPinHandlerConnector.pinHandler.onCancel() } - func submitPinAction(_ flow: String, action: String, pin: String, isCustomAuth: Bool = false) -> Void { - bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin) + func submitPinAction(_ flow: String, action: String, pin: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin, completion: completion) } func changePin(completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index cddf597e..3e84e3c0 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -7,8 +7,6 @@ import Flutter protocol OneginiPluginRegisterProtocol { func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - - func acceptPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func denyPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -22,12 +20,6 @@ extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() } - func acceptPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _pin = _arg["pin"] as! String? else { return; } - - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: _pin) - } - func denyPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.cancelPinAuth() } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 7a97bf3d..1f5d4d4c 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -64,6 +64,7 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { + func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { } @@ -96,7 +97,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } - func pinAcceptAuthenticationRequest(pin: String?, completion: @escaping (Result) -> Void) { + func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { } @@ -104,8 +105,10 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } - func pinAcceptRegistrationRequest(pin: String?, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) { - + func pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: pin, completion: completion) + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 + completion(.success(())) } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { @@ -266,7 +269,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) - case Constants.Routes.acceptPinRegistrationRequest: acceptPinRegistrationRequest(call, result) case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) // custom registration From 3c2e0f09d0ec039ea6363c71f91bb9217c227271 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 14:17:24 +0100 Subject: [PATCH 078/364] FP-20: Update some method calls for submitPin --- .../NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 36cde794..53686abb 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -9,7 +9,7 @@ extension OneginiModuleSwift { } func submitPinAction(_ flow: String, action: String, pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin, completion: completion) + bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin) } func changePin(completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 1f5d4d4c..a58beb08 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -65,6 +65,7 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { + func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { } @@ -105,7 +106,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } - func pinAcceptRegistrationRequest(pin: String, isCustomAuthenticator: Bool, completion: @escaping (Result) -> Void) { + func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: pin, completion: completion) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) From 07ec06a703c2878ef1ecc12977513a9e19ed6e65 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 14:22:50 +0100 Subject: [PATCH 079/364] FP-20: iOS: Pigeon: dirty implement pinAcceptAuthenticationRequest --- .../PluginExtensions/SwiftOneginiPlugin+Auth.swift | 10 ---------- ios/Classes/SwiftOneginiPlugin.swift | 6 +++--- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index c67646b6..fbc64bb2 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -5,7 +5,6 @@ import Flutter protocol OneginiPluginAuthProtocol { func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } @@ -35,15 +34,6 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - func acceptPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _pin = _arg["pin"] as! String? else { - result(SdkError(.emptyInputValue).flutterError()) - return - } - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: _pin) - } - - func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { OneginiModuleSwift.sharedInstance.cancelPinAuth() } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index a58beb08..da4224d2 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -99,7 +99,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: pin, completion: completion) + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 + completion(.success(())) } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { @@ -280,8 +282,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - - case Constants.Routes.acceptPinAuthenticationRequest: acceptPinAuthenticationRequest(call, result) case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) // fingerprint From 2d457b5e0aff57e2b1996d8335a4585d9a663cbb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 14:45:39 +0100 Subject: [PATCH 080/364] FP-20: iOS: Pigeon: implement pinDeny methods dirty --- .../PluginExtensions/SwiftOneginiPlugin+Auth.swift | 5 ----- .../SwiftOneginiPlugin+Register.swift | 5 ----- ios/Classes/SwiftOneginiPlugin.swift | 12 ++++++------ 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift index fbc64bb2..0cac6fea 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift @@ -5,7 +5,6 @@ import Flutter protocol OneginiPluginAuthProtocol { func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } @@ -33,8 +32,4 @@ extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { let _scopes = _arg["scope"] as? [String] OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) } - - func denyPinAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.cancelPinAuth() - } } diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index 3e84e3c0..670e89ce 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -7,7 +7,6 @@ import Flutter protocol OneginiPluginRegisterProtocol { func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func denyPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -20,10 +19,6 @@ extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() } - func denyPinRegistrationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.cancelPinAuth() - } - func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let args = call.arguments as? [String: Any] else { return; } // FIXME: Throw exception here OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(args["data"] as? String) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index da4224d2..52b61a0b 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -95,7 +95,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.cancelPinAuth() + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 + completion(.success(())) } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { @@ -105,7 +107,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.cancelPinAuth() + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 + completion(.success(())) } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { @@ -272,8 +276,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) - case Constants.Routes.denyPinRegistrationRequest: denyPinRegistrationRequest(call, result) - // custom registration case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) @@ -281,8 +283,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // auth case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - - case Constants.Routes.denyPinAuthenticationRequest: denyPinAuthenticationRequest(call, result) // fingerprint case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) From 4da28ae4935ed5856a0a7e77395568ea4315322f Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 14:56:03 +0100 Subject: [PATCH 081/364] FP-20: iOS, Pigeon: Dirty implementation cancelBrowserRegistration --- .../PluginExtensions/SwiftOneginiPlugin+Register.swift | 5 ----- ios/Classes/SwiftOneginiPlugin.swift | 10 ++++------ 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index 670e89ce..ff531dc6 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -5,8 +5,6 @@ import Flutter protocol OneginiPluginRegisterProtocol { - - func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void @@ -15,9 +13,6 @@ protocol OneginiPluginRegisterProtocol { extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { - func cancelBrowserRegistration(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() - } func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let args = call.arguments as? [String: Any] else { return; } // FIXME: Throw exception here diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 52b61a0b..62ce4523 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -119,7 +119,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + completion(.success(())) } func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { @@ -271,11 +273,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // base case Constants.Routes.startApp: startApp(call, result) - - // register - - case Constants.Routes.cancelBrowserRegistration: cancelBrowserRegistration(call, result) - + // custom registration case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) From effc042a82ffe40c67ad56b1e50d96b1f8b3adbd Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 15:01:44 +0100 Subject: [PATCH 082/364] FP-20: iOS, Pigeon: Implement submitCustomRegistrationAction dirty --- .../PluginExtensions/SwiftOneginiPlugin+Register.swift | 6 ------ ios/Classes/SwiftOneginiPlugin.swift | 5 +++-- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift index ff531dc6..cc357eb3 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift @@ -6,7 +6,6 @@ import Flutter protocol OneginiPluginRegisterProtocol { - func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } @@ -14,11 +13,6 @@ protocol OneginiPluginRegisterProtocol { extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { - func submitCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let args = call.arguments as? [String: Any] else { return; } // FIXME: Throw exception here - OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(args["data"] as? String) - } - func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let _arg = call.arguments as! [String: Any]?, let _error = _arg["error"] as! String? else { return; } OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(_error) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 62ce4523..6a8dfdde 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -67,7 +67,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + completion(.success(())) } func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { @@ -275,7 +277,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { case Constants.Routes.startApp: startApp(call, result) // custom registration - case Constants.Routes.submitCustomRegistrationAction: submitCustomRegistrationAction(call, result) case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) // auth From ed711659d0d451288acbff859feb6b08cbfdee2c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 15:19:03 +0100 Subject: [PATCH 083/364] FP-20: iOS, Pigeon: implement fingerprint methods --- .../SwiftOneginiPlugin+Register.swift | 22 ----------------- ios/Classes/SwiftOneginiPlugin.swift | 24 +++++++++---------- 2 files changed, 12 insertions(+), 34 deletions(-) delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift deleted file mode 100644 index cc357eb3..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Register.swift +++ /dev/null @@ -1,22 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - - - -protocol OneginiPluginRegisterProtocol { - - func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - -} - -extension SwiftOneginiPlugin: OneginiPluginRegisterProtocol { - - - func cancelCustomRegistrationAction(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _error = _arg["error"] as! String? else { return; } - OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(_error) - } - -} - diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 6a8dfdde..1aec910b 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -73,19 +73,27 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + completion(.success(())) } func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) { - + Logger.log("fingerprintFallbackToPin is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success(())) } func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - + Logger.log("fingerprintDenyAuthenticationRequest is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success(())) } func fingerprintAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - + Logger.log("fingerprintAcceptAuthenticationRequest is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success(())) } func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { @@ -275,19 +283,11 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // base case Constants.Routes.startApp: startApp(call, result) - - // custom registration - case Constants.Routes.cancelCustomRegistrationAction: cancelCustomRegistrationAction(call, result) // auth case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - // fingerprint - case Constants.Routes.acceptFingerprintAuthenticationRequest: acceptFingerprintAuthenticationRequest(call, result) - case Constants.Routes.denyFingerprintAuthenticationRequest: denyFingerprintAuthenticationRequest(call, result) - case Constants.Routes.fingerprintFallbackToPin: fingerprintFallbackToPin(call, result) - // otp case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) case Constants.Routes.acceptOtpAuthenticationRequest: acceptOtpAuthenticationRequest(call, result) From dceb043d0310b8c4aa9a47b20565b241432072bf Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 15:52:00 +0100 Subject: [PATCH 084/364] FP-20: iOS, Pigeon: implement AuthenticateDevice/user --- .../Handlers/ResourcesHandler.swift | 21 +++++------ .../OneginiModuleSwift+Auth.swift | 14 ++------ .../OneginiModuleSwift+Resources.swift | 7 ++-- .../SwiftOneginiPlugin+Auth.swift | 35 ------------------- ios/Classes/SwiftOneginiPlugin.swift | 12 +++---- 5 files changed, 22 insertions(+), 67 deletions(-) delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index c75d06bc..665eb3bc 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -4,8 +4,8 @@ import OneginiSDKiOS typealias FlutterDataCallback = (Any?, SdkError?) -> Void protocol FetchResourcesHandlerProtocol: AnyObject { - func authenticateDevice(_ scopes: [String]?, completion: @escaping (Bool, SdkError?) -> Void) - func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) + func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) + func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool, parameters: [String: Any], completion: @escaping FlutterDataCallback) func fetchSimpleResources(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) func fetchAnonymousResource(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) @@ -16,25 +16,26 @@ protocol FetchResourcesHandlerProtocol: AnyObject { //MARK: - class ResourcesHandler: FetchResourcesHandlerProtocol { - func authenticateDevice(_ scopes: [String]?, completion: @escaping (Bool, SdkError?) -> Void) { + func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { Logger.log("authenticateDevice", sender: self) - ONGDeviceClient.sharedInstance().authenticateDevice(scopes) { success, error in + ONGDeviceClient.sharedInstance().authenticateDevice(scopes) { _, error in if let error = error { - let mappedError = ErrorMapper().mapError(error) - completion(success, mappedError) + let mappedError = FlutterError(ErrorMapper().mapError(error)) + completion(.failure(mappedError)) } else { - completion(success, nil) + completion(.success(())) } } } - func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) { + func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) { Logger.log("authenticateImplicitly", sender: self) ONGUserClient.sharedInstance().implicitlyAuthenticateUser(profile, scopes: scopes) { success, error in if success { - completion(.success(profile.profileId)) + completion(.success(())) } else { - let mappedError = error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError) + // This error construction is obviously not good, but it will work for now till we refactor this later + let mappedError = FlutterError(error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError)) completion(.failure(mappedError)) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 533a9b5d..4efd0042 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -14,21 +14,13 @@ extension OneginiModuleSwift { } public func authenticateUserImplicitly(_ profileId: String, _ scopes: [String]?, - _ completion: @escaping FlutterResult) { + completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { - completion(SdkError(.noUserProfileIsAuthenticated).flutterError()) + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - bridgeConnector.toResourceFetchHandler.authenticateUserImplicitly(profile, scopes: scopes) { - result -> Void in - switch result { - case .success(let response): - completion(response) - case .failure(let error): - completion(error.flutterError()) - } - } + bridgeConnector.toResourceFetchHandler.authenticateUserImplicitly(profile, scopes: scopes, completion: completion) } func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift index cb2dd15f..a0fa7601 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift @@ -4,11 +4,8 @@ import Flutter extension OneginiModuleSwift { - public func authenticateDevice(_ scopes: [String]?, callback: @escaping FlutterResult) -> Void { - bridgeConnector.toResourceFetchHandler.authenticateDevice(scopes) { - (data, error) -> Void in - error != nil ? callback(error?.flutterError()) : callback(data) - } + public func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { + bridgeConnector.toResourceFetchHandler.authenticateDevice(scopes, completion: completion) } public func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool = true, parameters: [String: Any], diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift deleted file mode 100644 index 0cac6fea..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Auth.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - -protocol OneginiPluginAuthProtocol { - - func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - -} - -//MARK: - OneginiPluginAuthProtocol -extension SwiftOneginiPlugin: OneginiPluginAuthProtocol { - - func authenticateUserImplicitly(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let arg = call.arguments as? [String: Any] else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - guard let profileId = arg["profileId"] as? String else { - result(SdkError(.methodArgumentNotFound).flutterError()) - return - } - - let scopes = arg["scopes"] as? [String] - - OneginiModuleSwift.sharedInstance.authenticateUserImplicitly(profileId, scopes, result) - } - - func authenticateDevice(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]? else { return } - let _scopes = _arg["scope"] as? [String] - OneginiModuleSwift.sharedInstance.authenticateDevice(_scopes, callback: result) - } -} diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 1aec910b..6937ab05 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -235,11 +235,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.authenticateDevice(scopes) { result in + completion(result.mapError{$0}) + } } func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.authenticateUserImplicitly(profileId, scopes) { result in + completion(result.mapError{$0}) + } } // FIXME: Remove when deleted from api @@ -284,10 +288,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // base case Constants.Routes.startApp: startApp(call, result) - // auth - case Constants.Routes.authenticateUserImplicitly: authenticateUserImplicitly(call, result) - case Constants.Routes.authenticateDevice: authenticateDevice(call, result) - // otp case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) case Constants.Routes.acceptOtpAuthenticationRequest: acceptOtpAuthenticationRequest(call, result) From af873a9036d717790db256c058041f12f4415238 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 16:02:27 +0100 Subject: [PATCH 085/364] FP-20: iOS, Pigeon: Implement deny/acceptAuthenticationRequestOtp --- .../ModuleExtensions/OneginiModuleSwift+OTP.swift | 4 ++-- .../PluginExtensions/SwiftOneginiPlugin+Otp.swift | 10 ---------- ios/Classes/SwiftOneginiPlugin.swift | 10 ++++++---- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index db7b776e..4c25554a 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -46,12 +46,12 @@ extension OneginiModuleSwift { } } - func acceptMobileAuthConfirmation(callback: @escaping FlutterResult) -> Void { + func acceptMobileAuthConfirmation() -> Void { bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleMobileAuthConfirmation(cancelled: false) } @objc - func denyMobileAuthConfirmation(callback: @escaping FlutterResult) -> Void { + func denyMobileAuthConfirmation() -> Void { bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleMobileAuthConfirmation(cancelled: true) } } diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Otp.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Otp.swift index 39b0ef7e..57eed7f9 100644 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Otp.swift +++ b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Otp.swift @@ -4,8 +4,6 @@ import Flutter protocol OneginiPluginOtpProtocol { func handleMobileAuthWithOtp(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func acceptOtpAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func denyOtpAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } extension SwiftOneginiPlugin: OneginiPluginOtpProtocol { @@ -14,13 +12,5 @@ extension SwiftOneginiPlugin: OneginiPluginOtpProtocol { OneginiModuleSwift.sharedInstance.otpQRResourceCodeConfirmation(code: _data, callback: result) } - - func acceptOtpAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.acceptMobileAuthConfirmation(callback: result) - } - - func denyOtpAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - OneginiModuleSwift.sharedInstance.denyMobileAuthConfirmation(callback: result) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 6937ab05..309bbe87 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -97,11 +97,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.denyMobileAuthConfirmation() + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + completion(.success(())) } func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.acceptMobileAuthConfirmation() + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + completion(.success(())) } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { @@ -290,8 +294,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // otp case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) - case Constants.Routes.acceptOtpAuthenticationRequest: acceptOtpAuthenticationRequest(call, result) - case Constants.Routes.denyOtpAuthenticationRequest: denyOtpAuthenticationRequest(call, result) // resources case Constants.Routes.getResourceAnonymous, Constants.Routes.getResource, Constants.Routes.getImplicitResource, Constants.Routes.unauthenticatedRequest: From c90ef857c13b5f74539f3a3a5a55302e34f26871 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 16:56:50 +0100 Subject: [PATCH 086/364] FP-20: iOS, Pigeon: Remove fingerprint wrapper file --- .../SwiftOneginiPlugin+Fingerprint.swift | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Fingerprint.swift diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Fingerprint.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Fingerprint.swift deleted file mode 100644 index cdc5830e..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Fingerprint.swift +++ /dev/null @@ -1,24 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - -protocol OneginiPluginFingerprintProtocol { - func acceptFingerprintAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func denyFingerprintAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void - func fingerprintFallbackToPin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void -} - -extension SwiftOneginiPlugin: OneginiPluginFingerprintProtocol { - func acceptFingerprintAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - Logger.log("[NOT IMPLEMENTED] acceptFingerprintAuthenticationRequest") - } - - func denyFingerprintAuthenticationRequest(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - Logger.log("[NOT IMPLEMENTED] denyFingerprintAuthenticationRequest") - } - - func fingerprintFallbackToPin(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - Logger.log("[NOT IMPLEMENTED] fingerprintFallbackToPin") - } -} - From 4164e4fd4bc8a94795d82ae59fd4910c5f7e8631 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 8 Mar 2023 16:59:26 +0100 Subject: [PATCH 087/364] FP-20: iOS, Pigeon: Remove most constants --- ios/Classes/Constants.swift | 53 +------------------------------------ 1 file changed, 1 insertion(+), 52 deletions(-) diff --git a/ios/Classes/Constants.swift b/ios/Classes/Constants.swift index 982df2d0..341ae2fe 100644 --- a/ios/Classes/Constants.swift +++ b/ios/Classes/Constants.swift @@ -3,66 +3,15 @@ import Foundation enum Constants { enum Routes { - // onegini methods static let startApp = "startApp" - - // Submit CustomRegistration Actions - static let submitCustomRegistrationAction = "submitCustomRegistrationAction" - static let cancelCustomRegistrationAction = "cancelCustomRegistrationAction" - - // registration - static let registerUser = "registerUser" - static let cancelBrowserRegistration = "cancelBrowserRegistration" - static let getIdentityProviders = "getIdentityProviders" - static let denyPinRegistrationRequest = "denyPinRegistrationRequest" - static let acceptPinRegistrationRequest = "acceptPinRegistrationRequest" - static let deregisterUser = "deregisterUser" - static let handleRegisteredUserUrl = "handleRegisteredUserUrl" - static let getRedirectUrl = "getRedirectUrl" - //authentication - static let authenticateUser = "authenticateUser" - static let authenticateDevice = "authenticateDevice" - static let authenticateUserImplicitly = "authenticateUserImplicitly" - static let getAccessToken = "getAccessToken" - static let getAllNotRegisteredAuthenticators = "getAllNotRegisteredAuthenticators" - static let getRegisteredAuthenticators = "getRegisteredAuthenticators" - static let getAllAuthenticators = "getAllAuthenticators" - static let registerAuthenticator = "registerAuthenticator" - static let denyPinAuthenticationRequest = "denyPinAuthenticationRequest" - static let acceptPinAuthenticationRequest = "acceptPinAuthenticationRequest" - static let logout = "logout"; - static let validatePinWithPolicy = "validatePinWithPolicy" - static let setPreferredAuthenticator = "setPreferredAuthenticator" - static let deregisterAuthenticator = "deregisterAuthenticator" - - //fingerprint - static let acceptFingerprintAuthenticationRequest = "acceptFingerprintAuthenticationRequest" - static let denyFingerprintAuthenticationRequest = "denyFingerprintAuthenticationRequest" - static let fingerprintFallbackToPin = "fingerprintFallbackToPin" - //otp static let handleMobileAuthWithOtp = "handleMobileAuthWithOtp" - static let acceptOtpAuthenticationRequest = "acceptOtpAuthenticationRequest" - static let denyOtpAuthenticationRequest = "denyOtpAuthenticationRequest" - + //resources static let getResourceAnonymous = "getResourceAnonymous" static let getResource = "getResource" static let getImplicitResource = "getImplicitResource" static let unauthenticatedRequest = "getUnauthenticatedResource" - - static let eventHandleRegisteredUrl = "eventHandleRegisteredUrl" - - //Other - static let getAppToWebSingleSignOn = "getAppToWebSingleSignOn" - static let changePin = "changePin" - static let getUserProfiles = "getUserProfiles" - static let getAuthenticatedUserProfile = "getAuthenticatedUserProfile" - } - - enum Keys { - static let userProfile = "userProfile" - static let profileId = "profileId" } } From c0436128e1aefeeccd700512ecb7f32a87e70452 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:43:37 +0100 Subject: [PATCH 088/364] fp-20 added test specific error code --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../sdk/RegisterAuthenticatorUseCaseTests.kt | 75 +++++++++++++------ 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index c4511060..c869e221 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -22,4 +22,5 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), REGISTRATION_NOT_IN_PROGRESS(8034, "No registration in progress for the given Identity Provider"), + UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index 80a530b2..1ea55e57 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -9,9 +9,11 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -20,7 +22,9 @@ import org.mockito.Mock import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -41,6 +45,9 @@ class RegisterAuthenticatorUseCaseTests { @Mock lateinit var oneginiAuthenticatorRegistrationErrorMock: OneginiAuthenticatorRegistrationError + @Mock + lateinit var callbackMock: (Result) -> Unit + @Spy lateinit var resultSpy: MethodChannel.Result @@ -51,44 +58,64 @@ class RegisterAuthenticatorUseCaseTests { } @Test - fun `should return error when authenticatedUserProfile is null`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") + fun `When no user is authenticated, Then it should return error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - registerAuthenticatorUseCase(callMock, resultSpy) - - val message = NO_USER_PROFILE_IS_AUTHENTICATED.message - verify(resultSpy).error(eq(NO_USER_PROFILE_IS_AUTHENTICATED.code.toString()), eq(message), any()) + registerAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test fun `When authenticator id is not recognised, Then it should return error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") - registerAuthenticatorUseCase(callMock, resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) + registerAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test - fun `should return error when getNotRegisteredAuthenticators method returns empty set`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") + fun `When the user has an empty set of authenticators, Then an error should be returned`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - registerAuthenticatorUseCase(callMock, resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) + registerAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test fun `should return CustomInfo class with status and data as a params when given authenticator id found in getNotRegisteredAuthenticators method`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) whenever(oneginiAuthenticatorMock.id).thenReturn("test") @@ -96,9 +123,13 @@ class RegisterAuthenticatorUseCaseTests { it.getArgument(1).onSuccess(CustomInfo(0, "data")) } - registerAuthenticatorUseCase(callMock, resultSpy) + registerAuthenticatorUseCase("test", callbackMock) - verify(resultSpy).success(Gson().toJson(CustomInfo(0, "data"))) +// fixme +// argumentCaptor>().apply { +// verify(callbackMock, times(1)).invoke(capture()) +// Assert.assertEquals(firstValue.getOrNull(), Unit) +// } } @Test @@ -113,9 +144,9 @@ class RegisterAuthenticatorUseCaseTests { it.getArgument(1).onError(oneginiAuthenticatorRegistrationErrorMock) } - registerAuthenticatorUseCase(callMock, resultSpy) +// registerAuthenticatorUseCase(callMock, resultSpy) val message = oneginiAuthenticatorRegistrationErrorMock.message verify(resultSpy).error(eq(oneginiAuthenticatorRegistrationErrorMock.errorType.toString()), eq(message), any()) } -} \ No newline at end of file +} From 1958ba2a1294a38db08a0baab7ee132e03c83793 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:44:03 +0100 Subject: [PATCH 089/364] fp-20 update AuthenticateUserUseCase.kt test case for pigeon --- .../mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index e0d15517..9d71aa4a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -23,7 +23,7 @@ class AuthenticateUserUseCase @Inject constructor( val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return callback(Result.failure(error)) + return callback(Result.failure(error.pigeonError())) } val authenticator = getRegisteredAuthenticatorById(authenticatorId, userProfile) From b7a5ef087e8d6b97bd02e7ef932e55929b20019b Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:44:43 +0100 Subject: [PATCH 090/364] fp-20 updated AuthenticateDeviceUseCaseTests.kt for pigeon --- .../sdk/AuthenticateDeviceUseCaseTests.kt | 101 ++++++++++-------- 1 file changed, 55 insertions(+), 46 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt index 6d35a87b..e69290df 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt @@ -3,81 +3,90 @@ package com.onegini.mobile.sdk import com.google.common.truth.Truth import com.onegini.mobile.sdk.android.handlers.OneginiDeviceAuthenticationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiDeviceAuthenticationError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.ArgumentMatchers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.isNull +import org.mockito.kotlin.times import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever@RunWith(MockitoJUnitRunner::class) +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) class AuthenticateDeviceUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var oneginiDeviceAuthenticationErrorMock: OneginiDeviceAuthenticationError + @Mock + lateinit var oneginiDeviceAuthenticationErrorMock: OneginiDeviceAuthenticationError - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var callbackMock: (Result) -> Unit - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase - lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase + @Before + fun attach() { + authenticateDeviceUseCase = AuthenticateDeviceUseCase(oneginiSdk) + } - @Before - fun attach() { - authenticateDeviceUseCase = AuthenticateDeviceUseCase(oneginiSdk) + @Test + fun `When the sdk returns an Authentication error, Then it should return an`() { + whenever(oneginiDeviceAuthenticationErrorMock.errorType).thenReturn(OneginiDeviceAuthenticationError.GENERAL_ERROR) + whenever(oneginiDeviceAuthenticationErrorMock.message).thenReturn("General error") + whenever(oneginiSdk.oneginiClient.deviceClient.authenticateDevice(isNull(), any())).thenAnswer { + it.getArgument(1).onError(oneginiDeviceAuthenticationErrorMock) } + authenticateDeviceUseCase(null, callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) - @Test - fun `should return error when sdk returned authentication error`() { - whenever(callMock.argument>("scope")).thenReturn(null) - whenever(oneginiDeviceAuthenticationErrorMock.errorType).thenReturn(OneginiDeviceAuthenticationError.GENERAL_ERROR) - whenever(oneginiDeviceAuthenticationErrorMock.message).thenReturn("General error") - whenever(oneginiSdk.oneginiClient.deviceClient.authenticateDevice(isNull(), any())).thenAnswer { - it.getArgument(1).onError(oneginiDeviceAuthenticationErrorMock) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), OneginiDeviceAuthenticationError.GENERAL_ERROR) + Assert.assertEquals(error.message, "General error") } - authenticateDeviceUseCase(callMock, resultSpy) + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } - val message = oneginiDeviceAuthenticationErrorMock.message - verify(resultSpy).error(eq(oneginiDeviceAuthenticationErrorMock.errorType.toString()), eq(message), any()) + @Test + fun `When the authentications goes successful, Then it should return resolve successfully`() { + whenever(oneginiSdk.oneginiClient.deviceClient.authenticateDevice(eq(arrayOf("test")), any())).thenAnswer { + it.getArgument(1).onSuccess() } - @Test - fun `should return success when SDK returned authentication success`() { - whenever(callMock.argument>("scope")).thenReturn(arrayListOf("test")) - whenever(oneginiSdk.oneginiClient.deviceClient.authenticateDevice(eq(arrayOf("test")), any())).thenAnswer { - it.getArgument(1).onSuccess() - } - authenticateDeviceUseCase(callMock, resultSpy) + authenticateDeviceUseCase(listOf("test"), callbackMock) - verify(resultSpy).success(true) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) } + } - @Test - fun `should scopes param be array of two scopes when given scopes contains two strings`() { - whenever(callMock.argument>("scope")).thenReturn(arrayListOf("read", "write")) + @Test + fun `When two scopes are passed, Then the native sdk should also respond with two scopes`() { + authenticateDeviceUseCase(listOf("read", "write"), callbackMock) - authenticateDeviceUseCase(callMock, resultSpy) - - argumentCaptor> { - verify(oneginiSdk.oneginiClient.deviceClient).authenticateDevice(capture(), ArgumentMatchers.any()) - Truth.assertThat(firstValue.size).isEqualTo(2) - Truth.assertThat(firstValue).isEqualTo(arrayOf("read", "write")) - } + argumentCaptor>().apply { + verify(oneginiSdk.oneginiClient.deviceClient).authenticateDevice(capture(), ArgumentMatchers.any()) + Truth.assertThat(firstValue.size).isEqualTo(2) + Truth.assertThat(firstValue).isEqualTo(arrayOf("read", "write")) } - -} \ No newline at end of file + } +} From 457f5a8b03c8ef3b5d1e2262f9a34b6ccfdb4caa Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:46:18 +0100 Subject: [PATCH 091/364] fp-20 update AuthenticateUserImplicitlyUseCaseTests.kt for pigeon --- .../AuthenticateUserImplicitlyUseCaseTests.kt | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt index b32fa45d..e5234788 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt @@ -6,25 +6,25 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiImplicitTokenRequest import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.ArgumentMatchers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.isNull +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -import java.util.ArrayList @RunWith(MockitoJUnitRunner::class) class AuthenticateUserImplicitlyUseCaseTests { @@ -36,12 +36,10 @@ class AuthenticateUserImplicitlyUseCaseTests { lateinit var oneginiImplicitTokenRequestErrorMock: OneginiImplicitTokenRequestError @Mock - lateinit var callMock: MethodCall - - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var callbackMock: (Result) -> Unit lateinit var authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase + @Before fun attach() { val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) @@ -50,9 +48,6 @@ class AuthenticateUserImplicitlyUseCaseTests { @Test fun `should return error when the sdk returns authentication error`() { - whenever(callMock.argument>("scopes")).thenReturn(null) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiImplicitTokenRequestErrorMock.errorType).thenReturn(GENERIC_ERROR.code) @@ -61,51 +56,66 @@ class AuthenticateUserImplicitlyUseCaseTests { it.getArgument(2).onError(oneginiImplicitTokenRequestErrorMock) } - authenticateUserImplicitlyUseCase(callMock, resultSpy) + authenticateUserImplicitlyUseCase("QWERTY", null, callbackMock) - verify(resultSpy).error( - GENERIC_ERROR.code.toString(), GENERIC_ERROR.message, - mutableMapOf("code" to GENERIC_ERROR.code.toString(), "message" to GENERIC_ERROR.message) - ) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), GENERIC_ERROR.code) + Assert.assertEquals(error.message, GENERIC_ERROR.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test - fun `should return error when the userProfileId is not a registered users`() { - whenever(callMock.argument>("scopes")).thenReturn(null) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + fun `When the userProfileId is not a registered users, Then an error should be returned`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf()) - authenticateUserImplicitlyUseCase(callMock, resultSpy) + authenticateUserImplicitlyUseCase("QWERTY", null, callbackMock) - verify(resultSpy).error( - USER_PROFILE_DOES_NOT_EXIST.code.toString(), USER_PROFILE_DOES_NOT_EXIST.message, - mutableMapOf("code" to USER_PROFILE_DOES_NOT_EXIST.code.toString(), "message" to USER_PROFILE_DOES_NOT_EXIST.message) - ) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test - fun `should return success when the SDK returns success`() { - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("test")) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - + fun `When the implicit authentications goes successfully, Then the function should resolve with success`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.authenticateUserImplicitly(eq(UserProfile("QWERTY")), eq(arrayOf("test")), any())).thenAnswer { + whenever( + oneginiSdk.oneginiClient.userClient.authenticateUserImplicitly( + eq(UserProfile("QWERTY")), + eq(arrayOf("test")), + any() + ) + ).thenAnswer { it.getArgument(2).onSuccess(UserProfile("QWERTY")) } - authenticateUserImplicitlyUseCase(callMock, resultSpy) + authenticateUserImplicitlyUseCase("QWERTY", listOf("test"), callbackMock) - verify(resultSpy).success(eq("QWERTY")) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) + } } @Test - fun `should scopes param be array of two scopes when given scopes contains two strings`() { - whenever(callMock.argument>("scopes")).thenReturn(arrayListOf("read", "write")) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - + fun `When given scopes contains two strings, Then scopes param should be array of two scopes`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - authenticateUserImplicitlyUseCase(callMock, resultSpy) + authenticateUserImplicitlyUseCase("QWERTY", listOf("read", "write"), callbackMock) argumentCaptor> { verify(oneginiSdk.oneginiClient.userClient).authenticateUserImplicitly(eq(UserProfile("QWERTY")), capture(), ArgumentMatchers.any()) From 7230bbb1ae6c91cc2b104289e66d7813d495e998 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:47:01 +0100 Subject: [PATCH 092/364] fp-20 update AuthenticateUserUseCaseTests.kt for pigeon --- .../sdk/AuthenticateUserUseCaseTests.kt | 103 +++++++++++------- 1 file changed, 61 insertions(+), 42 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index 1f0b103d..fa8106ad 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -1,7 +1,5 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson -import com.onegini.mobile.sdk.android.client.UserClient import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator @@ -9,19 +7,24 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -30,11 +33,8 @@ class AuthenticateUserUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Spy - lateinit var resultSpy: MethodChannel.Result - @Mock - lateinit var callMock: MethodCall + lateinit var callbackMock: (Result) -> Unit @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator @@ -51,51 +51,63 @@ class AuthenticateUserUseCaseTests { } @Test - fun `when the given authenticator id is null and a valid ProfileId is passed, Then it should call result success with UserProfile and CustomInfo as json`() { - whenever(callMock.argument("registeredAuthenticatorId")).thenReturn(null) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + fun `When the given authenticator id is null and a valid ProfileId is passed, Then it should call result success with UserProfile and CustomInfo as json`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.authenticateUser(eq(UserProfile("QWERTY")), any())).thenAnswer { it.getArgument(1).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - authenticateUserUseCase(callMock, resultSpy) + authenticateUserUseCase("QWERTY", null, callbackMock) - val userProfileJson = mapOf("profileId" to "QWERTY", "isDefault" to false) - val customInfoJson = mapOf("data" to "", "status" to 0) - val expectedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - verify(resultSpy).success(expectedResult) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + val testUser = OWUserProfile("QWERTY") + val testInfo = OWCustomInfo(0, "") + Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) + } } @Test fun `When the requested UserProfileId is not registered, Then it should call result error`() { - whenever(callMock.argument("registeredAuthenticatorId")).thenReturn(null) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - authenticateUserUseCase(callMock, resultSpy) + authenticateUserUseCase("QWERTY", null, callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) - val message = USER_PROFILE_DOES_NOT_EXIST.message - verify(resultSpy).error(eq(USER_PROFILE_DOES_NOT_EXIST.code.toString()), eq(message), any()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test fun `When the given authenticator id is not found, Then it should return an error`() { - whenever(callMock.argument("registeredAuthenticatorId")).thenReturn("TEST") - whenever(callMock.argument("profileId")).thenReturn("QWERTY") whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - authenticateUserUseCase(callMock, resultSpy) + authenticateUserUseCase("QWERTY", "TEST", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } } @Test fun `When the given authenticator id is found and a valid ProfileId is passed, Then it should call result success with with UserProfile and CustomInfo as json`() { - whenever(callMock.argument("registeredAuthenticatorId")).thenReturn("TEST") - whenever(callMock.argument("profileId")).thenReturn("QWERTY") whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiAuthenticatorMock.id).thenReturn("TEST") whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( @@ -113,18 +125,18 @@ class AuthenticateUserUseCaseTests { it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - authenticateUserUseCase(callMock, resultSpy) + authenticateUserUseCase("QWERTY", "TEST", callbackMock) - val userProfileJson = mapOf("profileId" to "QWERTY", "isDefault" to false) - val customInfoJson = mapOf("data" to "", "status" to 0) - val expectedResult = Gson().toJson(mapOf("userProfile" to userProfileJson, "customInfo" to customInfoJson)) - verify(resultSpy).success(expectedResult) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + val testUser = OWUserProfile("QWERTY") + val testInfo = OWCustomInfo(0, "") + Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) + } } @Test fun `When authenticateUser return error, Then it should call result error`() { - whenever(callMock.argument("registeredAuthenticatorId")).thenReturn(null) - whenever(callMock.argument("profileId")).thenReturn("QWERTY") whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiAuthenticationErrorMock.errorType).thenReturn(OneginiAuthenticationError.GENERAL_ERROR) whenever(oneginiAuthenticationErrorMock.message).thenReturn("General error") @@ -132,10 +144,17 @@ class AuthenticateUserUseCaseTests { it.getArgument(1).onError(oneginiAuthenticationErrorMock) } - authenticateUserUseCase(callMock, resultSpy) - - val message = oneginiAuthenticationErrorMock.message - verify(resultSpy).error(eq(oneginiAuthenticationErrorMock.errorType.toString()), eq(message), any()) + authenticateUserUseCase("QWERTY", null, callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiAuthenticationErrorMock.errorType) + Assert.assertEquals(error.message, oneginiAuthenticationErrorMock.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } } - -} \ No newline at end of file +} From b2f28d5c266cd5dce5ba6d931c0c465592ae8465 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:47:58 +0100 Subject: [PATCH 093/364] fp-20 update DeregisterAuthenticatorUseCaseTests.kt for pigeon --- .../DeregisterAuthenticatorUseCaseTests.kt | 189 +++++++++++------- 1 file changed, 116 insertions(+), 73 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt index 752869c4..355af5a9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt @@ -6,110 +6,153 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class DeregisterAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - @Mock - lateinit var oneginiAuthenticatorMock: OneginiAuthenticator + @Mock + lateinit var callbackMock: (Result) -> Unit - @Mock - lateinit var oneginiAuthenticatorDeregistrationErrorMock: OneginiAuthenticatorDeregistrationError + @Mock + lateinit var oneginiAuthenticatorDeregistrationErrorMock: OneginiAuthenticatorDeregistrationError - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase - lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase - @Before - fun attach() { - deregisterAuthenticatorUseCase = DeregisterAuthenticatorUseCase(oneginiSdk) - } + @Before + fun attach() { + deregisterAuthenticatorUseCase = DeregisterAuthenticatorUseCase(oneginiSdk) + } - @Test - fun `When no user is authenticated, Then it should return error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) + @Test + fun `When no user is authenticated, Then it should return error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - deregisterAuthenticatorUseCase(callMock, resultSpy) + deregisterAuthenticatorUseCase("test", callbackMock) - val message = NO_USER_PROFILE_IS_AUTHENTICATED.message - verify(resultSpy).error(eq(NO_USER_PROFILE_IS_AUTHENTICATED.code.toString()), eq(message), any()) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } - - @Test - fun `When the given authenticator id is not found within the registered authenticators of the authenticated user, Then it should return an error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") - - deregisterAuthenticatorUseCase(callMock, resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) + } + + @Test + fun `When the given authenticator id is not found within the registered authenticators of the authenticated user, Then it should return an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") + + deregisterAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } + } - @Test - fun `When getRegisteredAuthenticators method returns empty set, Then an error should be returned`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + @Test + fun `When getRegisteredAuthenticators method returns empty set, Then an error should be returned`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - deregisterAuthenticatorUseCase(callMock, resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) - } + deregisterAuthenticatorUseCase("test", callbackMock) - @Test - fun `When getRegisteredAuthenticators finds an authenticator for a authenticated user, Then it should return true`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { - it.getArgument(1).onSuccess() + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } + + @Test + fun `When getRegisteredAuthenticators finds an authenticator for a authenticated user, Then it should return true`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { + it.getArgument(1).onSuccess() + } - deregisterAuthenticatorUseCase(callMock, resultSpy) + deregisterAuthenticatorUseCase("test", callbackMock) - verify(resultSpy).success(eq(true)) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) + } + } + + @Test + fun `When deregisterAuthenticator method returns error, Then the function should return an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorDeregistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorDeregistrationError.GENERAL_ERROR) + whenever(oneginiAuthenticatorDeregistrationErrorMock.message).thenReturn("General error") + whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { + it.getArgument(1).onError(oneginiAuthenticatorDeregistrationErrorMock) } - @Test - fun `When deregisterAuthenticator method returns error, Then the function should return an error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") - whenever(oneginiAuthenticatorDeregistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorDeregistrationError.GENERAL_ERROR) - whenever(oneginiAuthenticatorDeregistrationErrorMock.message).thenReturn("General error") - whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { - it.getArgument(1).onError(oneginiAuthenticatorDeregistrationErrorMock) - } - - deregisterAuthenticatorUseCase(callMock, resultSpy) + deregisterAuthenticatorUseCase("test", callbackMock) - val message = oneginiAuthenticatorDeregistrationErrorMock.message - verify(resultSpy).error(eq(oneginiAuthenticatorDeregistrationErrorMock.errorType.toString()), eq(message), any()) - }} \ No newline at end of file + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiAuthenticatorDeregistrationErrorMock.errorType) + Assert.assertEquals(error.message, oneginiAuthenticatorDeregistrationErrorMock.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } +} From 9ae64acbe8ee25a6d3b4a6a811072d747f938931 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:48:51 +0100 Subject: [PATCH 094/364] fp-20 update DeregisterUserUseCaseTests.kt for pigeon --- .../mobile/sdk/DeregisterUserUseCaseTests.kt | 109 ++++++++++-------- 1 file changed, 62 insertions(+), 47 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt index 6dc4bc07..047ca7ef 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt @@ -5,82 +5,97 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiDeregistrationError import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class DeregisterUserUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var oneginiDeregistrationErrorMock: OneginiDeregistrationError + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var oneginiDeregistrationErrorMock: OneginiDeregistrationError - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock + lateinit var callbackMock: (Result) -> Unit - lateinit var deregisterUserUseCase: DeregisterUserUseCase + lateinit var deregisterUserUseCase: DeregisterUserUseCase - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - deregisterUserUseCase = DeregisterUserUseCase(oneginiSdk, getUserProfileUseCase) - } + @Before + fun attach() { + val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) + deregisterUserUseCase = DeregisterUserUseCase(oneginiSdk, getUserProfileUseCase) + } + + @Test + fun `When the user is not recognised, Then it should return error`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - @Test - fun `When the user is not recognised, Then it should return error`() { - whenever(callMock.argument("profileId")).thenReturn("ABCDEF") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - deregisterUserUseCase(callMock, resultSpy) + deregisterUserUseCase("ABCDEF", callbackMock) - val message = USER_PROFILE_DOES_NOT_EXIST.message - verify(resultSpy).error(eq(USER_PROFILE_DOES_NOT_EXIST.code.toString()), eq(message), any()) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } } + } - @Test - fun `When user deregisters successfully, Then it should return true`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + @Test + fun `When user deregisters successfully, Then it should resolve successfully`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.deregisterUser(eq(UserProfile("QWERTY")), any())).thenAnswer { - it.getArgument(1).onSuccess() - } + whenever(oneginiSdk.oneginiClient.userClient.deregisterUser(eq(UserProfile("QWERTY")), any())).thenAnswer { + it.getArgument(1).onSuccess() + } - deregisterUserUseCase(callMock, resultSpy) + deregisterUserUseCase("QWERTY", callbackMock) - verify(resultSpy).success(true) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) } + } - @Test - fun `When deregister method return an error, Then the wrapper function should return error`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.deregisterUser(eq(UserProfile("QWERTY")), any())).thenAnswer { - it.getArgument(1).onError(oneginiDeregistrationErrorMock) - } - whenever(oneginiDeregistrationErrorMock.errorType).thenReturn(OneginiDeregistrationError.GENERAL_ERROR) - whenever(oneginiDeregistrationErrorMock.message).thenReturn("General error") + @Test + fun `When deregister method return an error, Then the wrapper function should return error`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + whenever(oneginiSdk.oneginiClient.userClient.deregisterUser(eq(UserProfile("QWERTY")), any())).thenAnswer { + it.getArgument(1).onError(oneginiDeregistrationErrorMock) + } + whenever(oneginiDeregistrationErrorMock.errorType).thenReturn(OneginiDeregistrationError.GENERAL_ERROR) + whenever(oneginiDeregistrationErrorMock.message).thenReturn("General error") - deregisterUserUseCase(callMock, resultSpy) + deregisterUserUseCase("QWERTY", callbackMock) - val message = oneginiDeregistrationErrorMock.message - verify(resultSpy).error(eq(oneginiDeregistrationErrorMock.errorType.toString()), eq(message), any()) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiDeregistrationErrorMock.errorType) + Assert.assertEquals(error.message, oneginiDeregistrationErrorMock.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } } -} \ No newline at end of file + } +} From 27342920d542f262785cf85626f1328d6554ce12 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:49:31 +0100 Subject: [PATCH 095/364] fp-20 update GetAccessTokenUseCaseTests.kt for pigeon --- .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 53 ++++++++++--------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index 7b54c529..5682be5f 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -2,49 +2,50 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.errors.wrapperError +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetAccessTokenUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - lateinit var getAccessTokenUseCase: GetAccessTokenUseCase - @Before - fun attach() { - getAccessTokenUseCase = GetAccessTokenUseCase(oneginiSdk) - } + lateinit var getAccessTokenUseCase: GetAccessTokenUseCase - @Test - fun `When the accessToken is null, Then should error with NO_USER_PROFILE_IS_AUTHENTICATED`() { - whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn(null) + @Before + fun attach() { + getAccessTokenUseCase = GetAccessTokenUseCase(oneginiSdk) + } - getAccessTokenUseCase(resultSpy) + @Test + fun `When the accessToken is null, Then should error with NO_USER_PROFILE_IS_AUTHENTICATED`() { + whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn(null) - verify(resultSpy).wrapperError(NO_USER_PROFILE_IS_AUTHENTICATED) + when (val error = getAccessTokenUseCase().exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } + } - @Test - fun `When the accessToken exists, Then should return the accessToken`() { - whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn("test access token") + @Test + fun `When the accessToken exists, Then should return the accessToken`() { + whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn("test access token") - getAccessTokenUseCase(resultSpy) + val result = getAccessTokenUseCase() - verify(resultSpy).success(eq("test access token")) - } -} \ No newline at end of file + Assert.assertEquals(result.getOrNull(), "test access token") + } +} From 1b0d728d89ff2eedd410d13dd24af7475687eb25 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:50:02 +0100 Subject: [PATCH 096/364] fp-20 update GetAllAuthenticatorsUseCaseTests.kt for pigeon --- .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 57 +++++++++++-------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index 39a79fd8..69bf3da9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -1,24 +1,22 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) @@ -32,8 +30,6 @@ class GetAllAuthenticatorsUseCaseTests { @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - @Spy - lateinit var resultSpy: MethodChannel.Result lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase @@ -44,39 +40,50 @@ class GetAllAuthenticatorsUseCaseTests { } @Test - fun `When an unknown or unregistered profileId is given then an error should be thrown`() { + fun `When an unknown or unregistered profileId is given, Then an error should be thrown`() { whenever(callMock.argument("profileId")).thenReturn("QWERTY") whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("ABCDEF"))) - getAllAuthenticatorsUseCase(callMock, resultSpy) - - val message = USER_PROFILE_DOES_NOT_EXIST.message - verify(resultSpy).error(eq(USER_PROFILE_DOES_NOT_EXIST.code.toString()), eq(message), any()) + when (val error = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } @Test - fun `When getAllAuthenticators method return empty set then the function should return empty`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + fun `When getAllAuthenticators method return empty set, Then the function should return empty`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(UserProfile("QWERTY"))).thenReturn(emptySet()) - getAllAuthenticatorsUseCase(callMock, resultSpy) + val result = getAllAuthenticatorsUseCase("QWERTY") - val expectedResult = Gson().toJson(emptyArray>()) - verify(resultSpy).success(expectedResult) + Assert.assertEquals(result.getOrNull(), mutableListOf>()) } @Test - fun `When a registered profileId is given and getAllAuthenticatorsUseCase contains authenticators then an array of maps should be returned`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + fun `When a registered profileId is given and getAllAuthenticatorsUseCase contains authenticators, Then an array of maps should be returned`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(UserProfile("QWERTY"))).thenReturn(setOf(oneginiAuthenticatorMock)) whenever(oneginiAuthenticatorMock.name).thenReturn("test") whenever(oneginiAuthenticatorMock.id).thenReturn("test") - - getAllAuthenticatorsUseCase(callMock, resultSpy) - - val expectedResult = Gson().toJson(arrayOf(mapOf("id" to "test", "name" to "test"))) - verify(resultSpy).success(expectedResult) + whenever(oneginiAuthenticatorMock.isRegistered).thenReturn(true) + whenever(oneginiAuthenticatorMock.isPreferred).thenReturn(true) + whenever(oneginiAuthenticatorMock.type).thenReturn(5) + + val result = getAllAuthenticatorsUseCase("QWERTY") + + when (val authenticator = result.getOrNull()?.first()) { + is OWAuthenticator -> { + Assert.assertEquals(authenticator.id, "test") + Assert.assertEquals(authenticator.name, "test") + Assert.assertEquals(authenticator.isRegistered, true) + Assert.assertEquals(authenticator.isPreferred, true) + Assert.assertEquals(authenticator.authenticatorType, 5) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } } From 2e519aac28ad9d19e8dc6492cafaa59b01d82764 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:50:33 +0100 Subject: [PATCH 097/364] fp-20 update GetIdentityProvidersUseCaseTests.kt for pigeon --- .../sdk/GetIdentityProvidersUseCaseTests.kt | 80 ++++++++++--------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt index 2c41d53a..77f3f9ce 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt @@ -1,63 +1,71 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetIdentityProvidersUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var oneginiIdentityProviderFirstMock: OneginiIdentityProvider + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var oneginiIdentityProviderSecondMock: OneginiIdentityProvider + @Mock + lateinit var oneginiIdentityProviderFirstMock: OneginiIdentityProvider - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock + lateinit var oneginiIdentityProviderSecondMock: OneginiIdentityProvider - lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase - @Before - fun attach() { - getIdentityProvidersUseCase = GetIdentityProvidersUseCase(oneginiSdk) - } + lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase - @Test - fun `should return empty list when sdk return empty set`() { - whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(emptySet()) + @Before + fun attach() { + getIdentityProvidersUseCase = GetIdentityProvidersUseCase(oneginiSdk) + } - getIdentityProvidersUseCase() + @Test + fun `When the sdk returns an empty set, Then it should return an empty list`() { + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(emptySet()) - val expectedResult = Gson().toJson(emptyArray>()) - verify(resultSpy).success(expectedResult) - } + val result = getIdentityProvidersUseCase() + + Assert.assertEquals(result.getOrNull(), mutableListOf>()) + } - @Test - fun `should return list of identity providers when user have available identity providers`() { - whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderFirstMock, oneginiIdentityProviderSecondMock)) - whenever(oneginiIdentityProviderFirstMock.id).thenReturn("firstId") - whenever(oneginiIdentityProviderFirstMock.name).thenReturn("firstName") - whenever(oneginiIdentityProviderSecondMock.id).thenReturn("secondId") - whenever(oneginiIdentityProviderSecondMock.name).thenReturn("secondName") + @Test + fun `When the user has available identity providers, Then it should return list of identity providers`() { + whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn( + setOf( + oneginiIdentityProviderFirstMock, + oneginiIdentityProviderSecondMock + ) + ) + whenever(oneginiIdentityProviderFirstMock.id).thenReturn("firstId") + whenever(oneginiIdentityProviderFirstMock.name).thenReturn("firstName") + whenever(oneginiIdentityProviderSecondMock.id).thenReturn("secondId") + whenever(oneginiIdentityProviderSecondMock.name).thenReturn("secondName") - getIdentityProvidersUseCase() + val result = getIdentityProvidersUseCase() - val expectedArray = arrayOf(mapOf("id" to "firstId", "name" to "firstName"), mapOf("id" to "secondId", "name" to "secondName")) - val expectedResult = Gson().toJson(expectedArray) - verify(resultSpy).success(expectedResult) + when (val identityProviders = result.getOrNull()) { + is List -> { + Assert.assertEquals(identityProviders[0].id, "firstId") + Assert.assertEquals(identityProviders[0].name, "firstName") + Assert.assertEquals(identityProviders[1].id, "secondId") + Assert.assertEquals(identityProviders[1].name, "secondName") + } + else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } + } } From 3f2260ef851c9f9a0217e16fe73c6c55375eef3e Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:51:28 +0100 Subject: [PATCH 098/364] fp-20 update GetNotRegisteredAuthenticatorsUseCaseTests.kt for pigeon --- ...NotRegisteredAuthenticatorsUseCaseTests.kt | 128 ++++++++++-------- 1 file changed, 73 insertions(+), 55 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 0be606ee..1cd1be2c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -1,87 +1,105 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetNotRegisteredAuthenticatorsUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator - @Mock - lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator + @Mock + lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - @Mock - lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator + lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase - @Spy - lateinit var resultSpy: MethodChannel.Result + @Before + fun attach() { + val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) + getNotRegisteredAuthenticatorsUseCase = GetNotRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) + } - lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - getNotRegisteredAuthenticatorsUseCase = GetNotRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) - } - - @Test - fun `When there are no Unregistered Authenticators then an empty set should be returned`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + @Test + fun `When there are no Unregistered Authenticators, Then an empty set should be returned`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - getNotRegisteredAuthenticatorsUseCase(callMock, resultSpy) + val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") - val expectedResult = Gson().toJson(emptyArray>()) - verify(resultSpy).success(expectedResult) - } + Assert.assertEquals(result.getOrNull(), mutableListOf>()) + } - @Test - fun `When the UserProfile is not found then an error should be returned`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + @Test + fun `When the UserProfile is not found, Then an error should be returned`() { + val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") - getNotRegisteredAuthenticatorsUseCase(callMock, resultSpy) - - val message = USER_PROFILE_DOES_NOT_EXIST.message - verify(resultSpy).error(eq(USER_PROFILE_DOES_NOT_EXIST.code.toString()), eq(message), any()) + when (val error = result.exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } - - @Test - fun `When a valid UserProfile is given and multiple not registered authenticators are found then getNotRegisteredAuthenticators should return a non-empty set`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorFirstMock, oneginiAuthenticatorSecondMock)) - whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") - whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") - whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") - whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") - - getNotRegisteredAuthenticatorsUseCase(callMock, resultSpy) - - val expectedArray = arrayOf(mapOf("id" to "firstId", "name" to "firstName"), mapOf("id" to "secondId", "name" to "secondName")) - val expectedResult = Gson().toJson(expectedArray) - verify(resultSpy).success(expectedResult) + } + + @Test + fun `When a valid UserProfile is given and multiple not registered authenticators are found, Then getNotRegisteredAuthenticators should return a non-empty set`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorFirstMock, + oneginiAuthenticatorSecondMock + ) + ) + whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") + whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") + whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(false) + whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) + whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) + + whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") + whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") + whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(false) + whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) + whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) + + val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") + + when (val authenticators = result.getOrNull()) { + is List -> { + Assert.assertEquals(authenticators[0].id, "firstId") + Assert.assertEquals(authenticators[0].name, "firstName") + Assert.assertEquals(authenticators[0].isRegistered, false) + Assert.assertEquals(authenticators[0].isPreferred, true) + Assert.assertEquals(authenticators[0].authenticatorType, 5) + + Assert.assertEquals(authenticators[1].id, "secondId") + Assert.assertEquals(authenticators[1].name, "secondName") + Assert.assertEquals(authenticators[1].isRegistered, false) + Assert.assertEquals(authenticators[1].isPreferred, false) + Assert.assertEquals(authenticators[1].authenticatorType, 6) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } + } } From b91544ff770b6c8a3ff29e3bfa3f7b914613ed19 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:52:06 +0100 Subject: [PATCH 099/364] fp-20 update GetUserProfilesUseCaseTests.kt for pigeon --- .../mobile/sdk/GetUserProfilesUseCaseTests.kt | 73 +++++++++---------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt index 2f19cd6d..223f9b1b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt @@ -1,65 +1,64 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase -import io.flutter.plugin.common.MethodChannel +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetUserProfilesUseCaseTests { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var clientMock: OneginiClient - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var getUserProfilesUseCase: GetUserProfilesUseCase - lateinit var getUserProfilesUseCase: GetUserProfilesUseCase - @Before - fun attach() { - getUserProfilesUseCase = GetUserProfilesUseCase(oneginiSdk) - } - - @Test - fun `should return empty set when SDK returns empty set`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) + @Before + fun attach() { + getUserProfilesUseCase = GetUserProfilesUseCase(oneginiSdk) + } - getUserProfilesUseCase(resultSpy) + @Test + fun `When the SDK returns an empty set, Then it should return an empty set`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - verify(resultSpy).success(Gson().toJson(emptySet())) - } + val result = getUserProfilesUseCase() - @Test - fun `should return single UserProfile when SDK returns one UserProfile`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + Assert.assertEquals(result.getOrNull(), mutableListOf>()) + } - getUserProfilesUseCase(resultSpy) + @Test + fun `When the SDK returns one UserProfile, Then it should return single UserProfile`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - val expectedResult = Gson().toJson(setOf(mapOf( "isDefault" to false, "profileId" to "QWERTY"))) - verify(resultSpy).success(eq(expectedResult)) - } + val result = getUserProfilesUseCase() + Assert.assertEquals(result.getOrNull()?.first()?.profileId, "QWERTY") + } - @Test - fun `should return UserProfile set when SDK returns set of UserProfile`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"), UserProfile("ASDFGH"))) + @Test + fun `When the SDK returns a set of UserProfiles, Then it should return this UserProfile set`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"), UserProfile("ASDFGH"))) - getUserProfilesUseCase(resultSpy) + val result = getUserProfilesUseCase() - val expectedResult = Gson().toJson(setOf(mapOf("isDefault" to false, "profileId" to "QWERTY"),mapOf("isDefault" to false, "profileId" to "ASDFGH"))) - verify(resultSpy).success(eq(expectedResult)) + when (val userProfiles = result.getOrNull()) { + is List -> { + Assert.assertEquals(userProfiles[0].profileId, "QWERTY") + Assert.assertEquals(userProfiles[1].profileId, "ASDFGH") + } + else -> junit.framework.Assert.fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } -} \ No newline at end of file + } +} From 0603e68cda29a361dc108da168e7d5bd82c2b1a9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:53:13 +0100 Subject: [PATCH 100/364] fp-20 update LogoutUseCaseTests.kt for pigeon --- .../onegini/mobile/sdk/LogoutUseCaseTests.kt | 83 +++++++++++-------- 1 file changed, 50 insertions(+), 33 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt index 1efad556..e29d4f0c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt @@ -3,63 +3,80 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiLogoutHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiLogoutError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any -import org.mockito.kotlin.eq +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class LogoutUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var oneginiLogoutError: OneginiLogoutError + @Mock + lateinit var clientMock: OneginiClient - @Spy - lateinit var resultSpy: MethodChannel.Result + @Mock + lateinit var oneginiLogoutError: OneginiLogoutError - lateinit var logoutUseCase: LogoutUseCase - @Before - fun attach() { - logoutUseCase = LogoutUseCase(oneginiSdk) + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var logoutUseCase: LogoutUseCase + + @Before + fun attach() { + logoutUseCase = LogoutUseCase(oneginiSdk) + } + + @Test + fun `When SDK return success, Then it should resolve successfully`() { + whenever(oneginiSdk.oneginiClient.userClient.logout(any())).thenAnswer { + it.getArgument(0).onSuccess() } - @Test - fun `should return true when SDK return success`() { - whenever(oneginiSdk.oneginiClient.userClient.logout(any())).thenAnswer { - it.getArgument(0).onSuccess() - } + logoutUseCase(callbackMock) - logoutUseCase(resultSpy) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) + } + } - verify(resultSpy).success(true) + @Test + fun `When the SDK returns an error, Then it should return the same error`() { + whenever(oneginiLogoutError.errorType).thenReturn(OneginiLogoutError.GENERAL_ERROR) + whenever(oneginiLogoutError.message).thenReturn("General error") + whenever(oneginiSdk.oneginiClient.userClient.logout(any())).thenAnswer { + it.getArgument(0).onError(oneginiLogoutError) } - @Test - fun `should return error when SDK return error`() { - whenever(oneginiLogoutError.errorType).thenReturn(OneginiLogoutError.GENERAL_ERROR) - whenever(oneginiLogoutError.message).thenReturn("General error") - whenever(oneginiSdk.oneginiClient.userClient.logout(any())).thenAnswer { - it.getArgument(0).onError(oneginiLogoutError) - } + logoutUseCase(callbackMock) - logoutUseCase(resultSpy) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) - val message = oneginiLogoutError.message - verify(resultSpy).error(eq(oneginiLogoutError.errorType.toString()), eq(message), any()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiLogoutError.errorType) + Assert.assertEquals(error.message, oneginiLogoutError.message) + } + else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + } } -} \ No newline at end of file + } +} From 49c82f37a1b9851f14fc01da1c148fb19bfbd728 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:53:46 +0100 Subject: [PATCH 101/364] fp-20 update GetRedirectUrlUseCaseTests.kt --- .../mobile/sdk/GetRedirectUrlUseCaseTests.kt | 56 +++++++++---------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt index 86ab00a1..d34e095b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt @@ -4,54 +4,50 @@ import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase -import io.flutter.plugin.common.MethodChannel +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetRedirectUrlUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var oneginiClientConfigModelMock: OneginiClientConfigModel + @Mock + lateinit var oneginiClientConfigModelMock: OneginiClientConfigModel - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase - lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase - @Before - fun attach() { - getRedirectUrlUseCase = GetRedirectUrlUseCase(oneginiSdk) - whenever(oneginiSdk.oneginiClient.configModel).thenReturn(oneginiClientConfigModelMock) - } + @Before + fun attach() { + getRedirectUrlUseCase = GetRedirectUrlUseCase(oneginiSdk) + whenever(oneginiSdk.oneginiClient.configModel).thenReturn(oneginiClientConfigModelMock) + } - @Test - fun `When redirectUri is an empty string, Then call success with empty string`() { - whenever(oneginiClientConfigModelMock.redirectUri).thenReturn("") + @Test + fun `When redirectUri is an empty string, Then call success with empty string`() { + whenever(oneginiClientConfigModelMock.redirectUri).thenReturn("") - getRedirectUrlUseCase(resultSpy) + val result = getRedirectUrlUseCase() - verify(resultSpy).success("") - } + Assert.assertEquals(result.getOrNull(), "") + } - @Test - fun `When redirectUri is a non-empty string, Then call sucess with that string`() { - whenever(oneginiClientConfigModelMock.redirectUri).thenReturn("http://test.com") + @Test + fun `When redirectUri is a non-empty string, Then call sucess with that string`() { + whenever(oneginiClientConfigModelMock.redirectUri).thenReturn("http://test.com") - getRedirectUrlUseCase(resultSpy) + val result = getRedirectUrlUseCase() - verify(resultSpy).success("http://test.com") - } -} \ No newline at end of file + Assert.assertEquals(result.getOrNull(), "http://test.com") + } +} From cdab3d84bcc6394ec6bae3f0e6de7e34a4c01896 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 11:55:06 +0100 Subject: [PATCH 102/364] fp-20 update GetRegisteredAuthenticatorsUseCaseTests.kt for pigeon --- ...GetRegisteredAuthenticatorsUseCaseTests.kt | 75 +++++++++++-------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index b03a49a6..df1f18c3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -1,25 +1,23 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) @@ -34,15 +32,9 @@ class GetRegisteredAuthenticatorsUseCaseTests { @Mock lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator - @Mock - lateinit var callMock: MethodCall - @Mock lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - @Spy - lateinit var resultSpy: MethodChannel.Result - lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase @Before fun attach() { @@ -52,43 +44,62 @@ class GetRegisteredAuthenticatorsUseCaseTests { @Test fun `should return empty list when sdk return empty set`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - getRegisteredAuthenticatorsUseCase(callMock, resultSpy) + val result = getRegisteredAuthenticatorsUseCase("QWERTY") - val expectedResult = Gson().toJson(emptyArray>()) - verify(resultSpy).success(expectedResult) + Assert.assertEquals(result.getOrNull(), mutableListOf>()) } @Test - fun `should return error when UserProfile is null`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - + fun `When UserProfile is null, Then it should return an error`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - getRegisteredAuthenticatorsUseCase(callMock, resultSpy) + val result = getRegisteredAuthenticatorsUseCase("QWERTY") - val message = USER_PROFILE_DOES_NOT_EXIST.message - verify(resultSpy).error(eq(USER_PROFILE_DOES_NOT_EXIST.code.toString()), eq(message), any()) + when (val error = result.exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } @Test - fun `should return list of registered authenticators when getRegisteredAuthenticators method returns not empty set`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") + fun `When getRegisteredAuthenticators method returns not empty set, Then it should return list of registered authenticators `() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorFirstMock, oneginiAuthenticatorSecondMock)) whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") + whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(true) + whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) + whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) + whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") - - getRegisteredAuthenticatorsUseCase(callMock, resultSpy) - - val expectedArray = arrayOf(mapOf("id" to "firstId", "name" to "firstName"), mapOf("id" to "secondId", "name" to "secondName")) - val expectedResult = Gson().toJson(expectedArray) - verify(resultSpy).success(expectedResult) + whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(true) + whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) + whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) + + val result = getRegisteredAuthenticatorsUseCase("QWERTY") + + when (val authenticators = result.getOrNull()) { + is List -> { + Assert.assertEquals(authenticators[0].id, "firstId") + Assert.assertEquals(authenticators[0].name, "firstName") + Assert.assertEquals(authenticators[0].isRegistered, true) + Assert.assertEquals(authenticators[0].isPreferred, true) + Assert.assertEquals(authenticators[0].authenticatorType, 5) + + Assert.assertEquals(authenticators[1].id, "secondId") + Assert.assertEquals(authenticators[1].name, "secondName") + Assert.assertEquals(authenticators[1].isRegistered, true) + Assert.assertEquals(authenticators[1].isPreferred, false) + Assert.assertEquals(authenticators[1].authenticatorType, 6) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } -} \ No newline at end of file +} From 123d209023bc4823023faf58b4f64cdff5fab508 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 12:00:28 +0100 Subject: [PATCH 103/364] fp-20 update RegistrationUseCaseTests.kt for pigeon --- .../sdk/RegisterAuthenticatorUseCaseTests.kt | 203 +++++++++--------- .../mobile/sdk/RegistrationUseCaseTests.kt | 28 ++- 2 files changed, 113 insertions(+), 118 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index 1ea55e57..a1b903be 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError @@ -11,15 +10,13 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor @@ -31,122 +28,124 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class RegisterAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var oneginiAuthenticatorMock: OneginiAuthenticator + @Mock + lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - @Mock - lateinit var oneginiAuthenticatorRegistrationErrorMock: OneginiAuthenticatorRegistrationError + @Mock + lateinit var oneginiAuthenticatorRegistrationErrorMock: OneginiAuthenticatorRegistrationError - @Mock - lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var callbackMock: (Result) -> Unit - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase - lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase - @Before - fun attach() { - registerAuthenticatorUseCase = RegisterAuthenticatorUseCase(oneginiSdk) - } + @Before + fun attach() { + registerAuthenticatorUseCase = RegisterAuthenticatorUseCase(oneginiSdk) + } - @Test - fun `When no user is authenticated, Then it should return error`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - registerAuthenticatorUseCase("test", callbackMock) - - argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } - } - } + @Test + fun `When no user is authenticated, Then it should return error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) + + registerAuthenticatorUseCase("test", callbackMock) - @Test - fun `When authenticator id is not recognised, Then it should return error`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") - - registerAuthenticatorUseCase("test", callbackMock) - - argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } - - @Test - fun `When the user has an empty set of authenticators, Then an error should be returned`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - - registerAuthenticatorUseCase("test", callbackMock) - - argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } + } + + @Test + fun `When authenticator id is not recognised, Then it should return error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) + whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") + + registerAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } + } - @Test - fun `should return CustomInfo class with status and data as a params when given authenticator id found in getNotRegisteredAuthenticators method`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { - it.getArgument(1).onSuccess(CustomInfo(0, "data")) - } + @Test + fun `When the user has an empty set of authenticators, Then an error should be returned`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - registerAuthenticatorUseCase("test", callbackMock) + registerAuthenticatorUseCase("test", callbackMock) -// fixme -// argumentCaptor>().apply { -// verify(callbackMock, times(1)).invoke(capture()) -// Assert.assertEquals(firstValue.getOrNull(), Unit) -// } + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } + + @Test + fun `should return CustomInfo class with status and data as a params when given authenticator id found in getNotRegisteredAuthenticators method`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) + whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { + it.getArgument(1).onSuccess(CustomInfo(0, "data")) } - @Test - fun `should return error when registerAuthenticator method returns error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") - whenever(oneginiAuthenticatorRegistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorRegistrationError.GENERAL_ERROR) - whenever(oneginiAuthenticatorRegistrationErrorMock.message).thenReturn("General error") - whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { - it.getArgument(1).onError(oneginiAuthenticatorRegistrationErrorMock) - } + registerAuthenticatorUseCase("test", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) + } + } + + @Test + fun `should return error when registerAuthenticator method returns error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) + whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorRegistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorRegistrationError.GENERAL_ERROR) + whenever(oneginiAuthenticatorRegistrationErrorMock.message).thenReturn("General error") + whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { + it.getArgument(1).onError(oneginiAuthenticatorRegistrationErrorMock) + } -// registerAuthenticatorUseCase(callMock, resultSpy) + registerAuthenticatorUseCase("test", callbackMock) - val message = oneginiAuthenticatorRegistrationErrorMock.message - verify(resultSpy).error(eq(oneginiAuthenticatorRegistrationErrorMock.errorType.toString()), eq(message), any()) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), OneginiAuthenticatorRegistrationError.GENERAL_ERROR) + Assert.assertEquals(error.message, "General error") + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } } + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 77fa8dcc..a4293b8b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -13,7 +13,6 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase -import io.flutter.plugin.common.MethodCall import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before @@ -35,10 +34,7 @@ class RegistrationUseCaseTests { lateinit var clientMock: OneginiClient @Mock - lateinit var callbackSpy: (Result) -> Unit - - @Mock - lateinit var callMock: MethodCall + lateinit var callbackMock: (Result) -> Unit @Mock lateinit var oneginiIdentityProviderMock: OneginiIdentityProvider @@ -51,16 +47,16 @@ class RegistrationUseCaseTests { } @Test - fun `should call result success with identity provider id as a param when given identity provider id is null`() { + fun `when given identity provider id is null, Then it should resolve with success with identity provider id as a param`() { whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(emptySet()) whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNull(), eq(arrayOf("read")), any())).thenAnswer { it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - registrationUseCase(null, listOf("read"), callbackSpy) + registrationUseCase(null, listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackSpy, times(1)).invoke(capture()) + verify(callbackMock, times(1)).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) @@ -76,7 +72,7 @@ class RegistrationUseCaseTests { whenever(oneginiIdentityProviderMock.id).thenReturn(testProviderId) whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOfIdentityProviders) - registrationUseCase(testProviderId, testScopes, callbackSpy) + registrationUseCase(testProviderId, testScopes, callbackMock) argumentCaptor { verify(oneginiSdk.oneginiClient.userClient).registerUser(capture(), eq(arrayOf("read")), any()) @@ -89,10 +85,10 @@ class RegistrationUseCaseTests { whenever(oneginiIdentityProviderMock.id).thenReturn("id") whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderMock)) - registrationUseCase("differentId", listOf("read"), callbackSpy) + registrationUseCase("differentId", listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackSpy, times(1)).invoke(capture()) + verify(callbackMock, times(1)).invoke(capture()) when (val error = firstValue.exceptionOrNull()) { is FlutterError -> { @@ -112,10 +108,10 @@ class RegistrationUseCaseTests { it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - registrationUseCase("testId", listOf("read"), callbackSpy) + registrationUseCase("testId", listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackSpy, times(1)).invoke(capture()) + verify(callbackMock, times(1)).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) @@ -124,14 +120,14 @@ class RegistrationUseCaseTests { @Test fun `should call 'registerUser' method once when given identity provider id is null`() { - registrationUseCase(null, listOf("read"), callbackSpy) + registrationUseCase(null, listOf("read"), callbackMock) verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), eq(arrayOf("read")), any()) } @Test fun `should scopes param be array of two scopes when given scopes contains two strings`() { - registrationUseCase(null, listOf("read", "write"), callbackSpy) + registrationUseCase(null, listOf("read", "write"), callbackMock) argumentCaptor> { verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) @@ -142,7 +138,7 @@ class RegistrationUseCaseTests { @Test fun `should scopes param be array of zero lengths when given scopes is null`() { - registrationUseCase(null, null, callbackSpy) + registrationUseCase(null, null, callbackMock) argumentCaptor> { verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) From 31237841d7edc8e0377bee76256cbc24c719d4cf Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 12:01:20 +0100 Subject: [PATCH 104/364] fp-20 update SetPreferredAuthenticatorUseCaseTests.kt for pigeon --- .../SetPreferredAuthenticatorUseCaseTests.kt | 111 ++++++++---------- 1 file changed, 51 insertions(+), 60 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index 12616757..1e03bb85 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -5,88 +5,79 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any import org.mockito.kotlin.eq -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class SetPreferredAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var oneginiAuthenticatorMock: OneginiAuthenticator + @Mock + lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase - lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase + @Before + fun attach() { + setPreferredAuthenticatorUseCase = SetPreferredAuthenticatorUseCase(oneginiSdk) + } - @Before - fun attach() { - setPreferredAuthenticatorUseCase = SetPreferredAuthenticatorUseCase(oneginiSdk) - } - - @Test - fun `When no user is authenticated then return an error`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - setPreferredAuthenticatorUseCase(callMock, resultSpy) - - val message = NO_USER_PROFILE_IS_AUTHENTICATED.message - verify(resultSpy).error(eq(NO_USER_PROFILE_IS_AUTHENTICATED.code.toString()), eq(message), any()) - } - - @Test - fun `When an authenticator id is null then an error should be thrown`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - - setPreferredAuthenticatorUseCase(callMock, resultSpy) - - val message = METHOD_ARGUMENT_NOT_FOUND.message - verify(resultSpy).error(eq(METHOD_ARGUMENT_NOT_FOUND.code.toString()), eq(message), any()) - } - - @Test - fun `When an authenticator id is given that is not related to the authenticated user then an error should be thrown`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - - setPreferredAuthenticatorUseCase(callMock, resultSpy) + @Test + fun `When no user is authenticated, Then return an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) + when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } + } - @Test - fun `should return success with authenticator id as a param when given authenticator id found in getRegisteredAuthenticators method`() { - whenever(callMock.argument("authenticatorId")).thenReturn("test") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + @Test + fun `When an authenticator id is given that is not related to the authenticated user, Then an error should be thrown`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - setPreferredAuthenticatorUseCase(callMock, resultSpy) + setPreferredAuthenticatorUseCase("test") - verify(resultSpy).success(eq(true)) + when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { + is SdkError -> { + Assert.assertEquals(error.code, AUTHENTICATOR_NOT_FOUND.code) + Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } + } + + @Test + fun `When the given authenticator id is found and registered, Then it should resolve with success`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + whenever(oneginiAuthenticatorMock.id).thenReturn("test") + + val result = setPreferredAuthenticatorUseCase("test") + + Assert.assertEquals(result.getOrNull(), Unit) + } } From 66a8280f746f7538daf6ec58b82541a16d78c40c Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 12:04:35 +0100 Subject: [PATCH 105/364] fp-20 added empty line at end of file --- .../kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index b32341a5..190d173a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -288,4 +288,4 @@ open class PigeonInterface : UserClientApi { } ) } -} \ No newline at end of file +} From ac24c32b632a821dbff46839b28d12850625a261 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 12:22:06 +0100 Subject: [PATCH 106/364] fp-20 update method mappers to only contain the functions that we left out for now using pigeon --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 37 ------ .../sdk/flutter/OneginiMethodsWrapper.kt | 106 +----------------- .../mobile/sdk/flutter/OneginiPlugin.kt | 3 +- 3 files changed, 3 insertions(+), 143 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 9830503a..6f3fbca3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -39,45 +39,12 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { - // Custom Registration Callbacks - Constants.METHOD_SUBMIT_CUSTOM_REGISTRATION_ACTION -> oneginiMethodsWrapper.respondCustomRegistrationAction(call, result) - Constants.METHOD_CANCEL_CUSTOM_REGISTRATION_ACTION -> oneginiMethodsWrapper.cancelCustomRegistrationAction(call, result) - - //Register - Constants.METHOD_REGISTER_USER -> oneginiMethodsWrapper.registerUser(call, result) - Constants.METHOD_HANDLE_REGISTERED_URL -> oneginiMethodsWrapper.handleRegisteredUrl(call) - Constants.METHOD_GET_IDENTITY_PROVIDERS -> oneginiMethodsWrapper.getIdentityProviders(result) - Constants.METHOD_CANCEL_BROWSER_REGISTRATION -> oneginiMethodsWrapper.cancelBrowserRegistration() - Constants.METHOD_ACCEPT_PIN_REGISTRATION_REQUEST -> PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(call.argument("pin")?.toCharArray()) - Constants.METHOD_DENY_PIN_REGISTRATION_REQUEST -> PinRequestHandler.CALLBACK?.denyAuthenticationRequest() - Constants.METHOD_DEREGISTER_USER -> oneginiMethodsWrapper.deregisterUser(call, result) - - // Authenticate - Constants.METHOD_REGISTER_AUTHENTICATOR -> oneginiMethodsWrapper.registerAuthenticator(call, result) - Constants.METHOD_GET_REGISTERED_AUTHENTICATORS -> oneginiMethodsWrapper.getRegisteredAuthenticators(call, result) - Constants.METHOD_AUTHENTICATE_USER -> oneginiMethodsWrapper.authenticateUser(call, result) - Constants.METHOD_GET_ALL_AUTHENTICATORS -> oneginiMethodsWrapper.getAllAuthenticators(call, result) - Constants.METHOD_GET_ALL_NOT_REGISTERED_AUTHENTICATORS -> oneginiMethodsWrapper.getNotRegisteredAuthenticators(call, result) - Constants.METHOD_SET_PREFERRED_AUTHENTICATOR -> oneginiMethodsWrapper.setPreferredAuthenticator(call, result) - Constants.METHOD_DEREGISTER_AUTHENTICATOR -> oneginiMethodsWrapper.deregisterAuthenticator(call, result) - Constants.METHOD_LOGOUT -> oneginiMethodsWrapper.logout(result) - Constants.METHOD_ACCEPT_PIN_AUTHENTICATION_REQUEST -> PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(call.argument("pin")?.toCharArray()) - Constants.METHOD_DENY_PIN_AUTHENTICATION_REQUEST -> PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) - // Fingerprint - Constants.METHOD_ACCEPT_FINGERPRINT_AUTHENTICATION_REQUEST -> FingerprintAuthenticationRequestHandler.fingerprintCallback?.acceptAuthenticationRequest() - Constants.METHOD_DENY_FINGERPRINT_AUTHENTICATION_REQUEST -> FingerprintAuthenticationRequestHandler.fingerprintCallback?.denyAuthenticationRequest() - Constants.METHOD_FINGERPRINT_FALL_BACK_TO_PIN -> FingerprintAuthenticationRequestHandler.fingerprintCallback?.fallbackToPin() - // OTP Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, client) - Constants.METHOD_ACCEPT_OTP_AUTHENTICATION_REQUEST -> MobileAuthOtpRequestHandler.CALLBACK?.acceptAuthenticationRequest() - Constants.METHOD_DENY_OTP_AUTHENTICATION_REQUEST -> MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() // Resources - Constants.METHOD_AUTHENTICATE_USER_IMPLICITLY -> oneginiMethodsWrapper.authenticateUserImplicitly(call, result) - Constants.METHOD_AUTHENTICATE_DEVICE -> oneginiMethodsWrapper.authenticateDevice(call, result) Constants.METHOD_GET_RESOURCE_ANONYMOUS -> oneginiMethodsWrapper.getResourceAnonymous(call, result) Constants.METHOD_GET_RESOURCE -> oneginiMethodsWrapper.getResource(call, result) Constants.METHOD_GET_IMPLICIT_RESOURCE -> oneginiMethodsWrapper.getImplicitResource(call, result) @@ -86,10 +53,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: // Other Constants.METHOD_CHANGE_PIN -> startChangePinFlow(result, client) Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> getAppToWebSingleSignOn(call.argument("url"), result, client) - Constants.METHOD_GET_USER_PROFILES -> oneginiMethodsWrapper.getUserProfiles(result) - Constants.METHOD_GET_ACCESS_TOKEN -> oneginiMethodsWrapper.getAccessToken(result) - Constants.METHOD_GET_AUTHENTICATED_USER_PROFILE -> oneginiMethodsWrapper.getAuthenticatedUserProfile(result) - Constants.METHOD_GET_REDIRECT_URL -> oneginiMethodsWrapper.getRedirectUrl(result) Constants.METHOD_VALIDATE_PIN_WITH_POLICY -> validatePinWithPolicy(call.argument("pin")?.toCharArray(), result, client) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 69734570..3f641c53 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -10,125 +10,25 @@ import javax.inject.Singleton @Singleton class OneginiMethodsWrapper @Inject constructor( - private val authenticateDeviceUseCase: AuthenticateDeviceUseCase, - private val authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase, - private val authenticateUserUseCase: AuthenticateUserUseCase, - private val cancelCustomRegistrationActionUseCase: CancelCustomRegistrationActionUseCase, - private val deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase, - private val deregisterUserUseCase: DeregisterUserUseCase, - private val getAccessTokenUseCase: GetAccessTokenUseCase, - private val getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase, - private val getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase, - private val getIdentityProvidersUseCase: GetIdentityProvidersUseCase, private val getImplicitResourceUseCase: GetImplicitResourceUseCase, - private val getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase, - private val getRedirectUrlUseCase: GetRedirectUrlUseCase, - private val getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase, private val getResourceAnonymousUseCase: GetResourceAnonymousUseCase, private val getResourceUseCase: GetResourceUseCase, private val getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase, - private val getUserProfilesUseCase: GetUserProfilesUseCase, - private val handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase, private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, - private val logoutUseCase: LogoutUseCase, - private val registerAuthenticatorUseCase: RegisterAuthenticatorUseCase, - private val registrationUseCase: RegistrationUseCase, private val resourceHelper: ResourceHelper, - private val setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase, private val startAppUseCase: StartAppUseCase, - private val submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase ) { - fun registerUser(call: MethodCall, result: MethodChannel.Result) { -// registrationUseCase(call, result) - } - - fun respondCustomRegistrationAction( - call: MethodCall, - result: MethodChannel.Result) { -// submitCustomRegistrationActionUseCase(result, call) - } - - fun cancelCustomRegistrationAction( - call: MethodCall, - result: MethodChannel.Result) { -// cancelCustomRegistrationActionUseCase(result, call) - } - - fun handleRegisteredUrl(call: MethodCall) { -// handleRegisteredUrlUseCase(call) - } - - fun getIdentityProviders(result: MethodChannel.Result) { -// getIdentityProvidersUseCase(result) - } - - fun getAccessToken(result: MethodChannel.Result) { -// getAccessTokenUseCase(result) - } - fun cancelBrowserRegistration() { BrowserRegistrationRequestHandler.onRegistrationCanceled() } - fun getAuthenticatedUserProfile(result: MethodChannel.Result) { -// getAuthenticatedUserProfileUseCase(result) - } - - fun getUserProfiles(result: MethodChannel.Result) { -// getUserProfilesUseCase(result) - } - fun startApp(call: MethodCall, result: MethodChannel.Result) { startAppUseCase(call, result) } - fun getRegisteredAuthenticators(call: MethodCall, result: MethodChannel.Result) { -// getRegisteredAuthenticatorsUseCase(call, result) - } - - fun getNotRegisteredAuthenticators(call: MethodCall, result: MethodChannel.Result) { -// getNotRegisteredAuthenticatorsUseCase(call, result) - } - - fun setPreferredAuthenticator(call: MethodCall, result: MethodChannel.Result) { -// setPreferredAuthenticatorUseCase(call, result) - } - - fun deregisterUser(call: MethodCall, result: MethodChannel.Result) { -// deregisterUserUseCase(call, result) - } - - fun deregisterAuthenticator(call: MethodCall, result: MethodChannel.Result) { -// deregisterAuthenticatorUseCase(call, result) - } - - fun registerAuthenticator(call: MethodCall, result: MethodChannel.Result) { -// registerAuthenticatorUseCase(call, result) - } - - fun getAllAuthenticators(call: MethodCall, result: MethodChannel.Result) { -// getAllAuthenticatorsUseCase(call, result) - } - - fun getRedirectUrl(result: MethodChannel.Result) { -// getRedirectUrlUseCase(result) - } - - fun authenticateUser(call: MethodCall, result: MethodChannel.Result) { -// authenticateUserUseCase(call, result) - } - - fun authenticateDevice(call: MethodCall, result: MethodChannel.Result){ -// authenticateDeviceUseCase(call, result) - } - - fun authenticateUserImplicitly(call: MethodCall, result: MethodChannel.Result){ -// authenticateUserImplicitlyUseCase(call, result) - } - fun getResourceAnonymous(call: MethodCall, result: MethodChannel.Result){ -// getResourceAnonymousUseCase(call, result, resourceHelper) + getResourceAnonymousUseCase(call, result, resourceHelper) } fun getResource(call: MethodCall, result: MethodChannel.Result){ @@ -146,8 +46,4 @@ class OneginiMethodsWrapper @Inject constructor( fun isAuthenticatorRegistered(call: MethodCall, result: MethodChannel.Result) { isAuthenticatorRegisteredUseCase(call, result) } - - fun logout(result: MethodChannel.Result) { -// logoutUseCase(result) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 73657ab7..33d4d674 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -30,8 +30,9 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { // Pigeon setup UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) -// nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) + // Reference Example code for when we implement the event callbacks using flutter +// nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) // fixme what is the new way to do this? // val oneginiSDK = OneginiSDK(nativeApi) From 9daf824b9e2c35c6da8045396e60e12bea27a3a7 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 9 Mar 2023 12:36:48 +0100 Subject: [PATCH 107/364] FP-20: iOS, Pigeon: Enforce FlutterError usage except in top level api --- .../NativeBridge/Handlers/AppToWebHandler.swift | 4 ++-- .../NativeBridge/Handlers/AuthenticatorsHandler.swift | 10 +++++----- ios/Classes/NativeBridge/Handlers/PinHandler.swift | 6 +++--- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 4 ++-- .../ModuleExtensions/OneginiModuleSwift+Pin.swift | 4 ++-- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 8 ++++++-- 7 files changed, 21 insertions(+), 17 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift index 6618f0ff..4f3a8966 100644 --- a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift @@ -3,12 +3,12 @@ import OneginiSDKiOS //MARK: - protocol AppToWebHandlerProtocol: AnyObject { - func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) + func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) } //MARK: - class AppToWebHandler: AppToWebHandlerProtocol { - func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) { + func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().appToWebSingleSignOn(withTargetUrl: targetURL) { (url, token, error) in if let url = url, let token = token { completion(.success(OWAppToWebSingleSignOn(token: token, redirectUrl: url.absoluteString))) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index a5522d52..28a9093c 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -3,9 +3,9 @@ import OneginiSDKiOS //MARK: - protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { - func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? { get } @@ -19,7 +19,7 @@ protocol AuthenticatorsNotificationReceiverProtocol: class { class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { var pinChallenge: ONGPinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? - var registrationCompletion: ((Result) -> Void)? + var registrationCompletion: ((Result) -> Void)? var deregistrationCompletion: ((Result) -> Void)? unowned var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? @@ -65,7 +65,7 @@ class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { //MARK: - BridgeToAuthenticatorsHandlerProtocol extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { - func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { + func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return @@ -95,7 +95,7 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { ONGUserClient.sharedInstance().deregister(authenticator, delegate: self) } - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { + func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index f079693a..81916507 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -3,7 +3,7 @@ import Flutter protocol PinConnectorToPinHandler: AnyObject { func onPinProvided(pin: String) - func onChangePinCalled(completion: @escaping (Result) -> Void) + func onChangePinCalled(completion: @escaping (Result) -> Void) func onCancel() func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) func closeFlow() @@ -30,7 +30,7 @@ class PinHandler: NSObject { var flow: PinFlow? var mode: PINEntryMode? var pinEntryToVerify = Array() - var changePinCompletion: ((Result) -> Void)? + var changePinCompletion: ((Result) -> Void)? unowned var pinReceiver: PinHandlerToReceiverProtocol? unowned var notificationReceiver: PinNotificationReceiverProtocol? @@ -127,7 +127,7 @@ extension PinHandler: PinConnectorToPinHandler{ processPin(pinEntry: pinArray) } - func onChangePinCalled(completion: @escaping (Result) -> Void) { + func onChangePinCalled(completion: @escaping (Result) -> Void) { changePinCompletion = completion ONGUserClient.sharedInstance().changePin(self) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 4efd0042..464c4142 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -23,7 +23,7 @@ extension OneginiModuleSwift { bridgeConnector.toResourceFetchHandler.authenticateUserImplicitly(profile, scopes: scopes, completion: completion) } - func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { + func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { guard let url = URL(string: path) else { completion(.failure(FlutterError(.providedUrlIncorrect))) @@ -47,7 +47,7 @@ extension OneginiModuleSwift { } - func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { + func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 53686abb..d8ff58da 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -8,11 +8,11 @@ extension OneginiModuleSwift { bridgeConnector.toPinHandlerConnector.pinHandler.onCancel() } - func submitPinAction(_ flow: String, action: String, pin: String, completion: @escaping (Result) -> Void) { + func submitPinAction(_ flow: String, action: String, pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin) } - func changePin(completion: @escaping (Result) -> Void) { + func changePin(completion: @escaping (Result) -> Void) { bridgeConnector.toPinHandlerConnector.pinHandler.onChangePinCalled(completion: completion) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 8ab2f1ba..808d29f3 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -56,7 +56,7 @@ extension OneginiModuleSwift { bridgeConnector.toRegistrationConnector.registrationHandler.cancelBrowserRegistration() } - func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { + func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { bridgeConnector.toAuthenticatorsHandler.registerAuthenticator(authenticatorId, completion) } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 309bbe87..483af179 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -115,7 +115,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: pin, completion: completion) + OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: pin) { result in + completion(result.mapError{$0}) + } // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } @@ -127,7 +129,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: pin, completion: completion) + OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: pin) { result in + completion(result.mapError{$0}) + } // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } From 495d1fd0d4125b8b9179404aacd8bbf2976e1324 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 13:09:48 +0100 Subject: [PATCH 108/364] fp-20 update merge conflict --- .../com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index ed90c01a..cf5b778a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -17,6 +17,7 @@ class OneginiMethodsWrapper @Inject constructor( private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, private val resourceHelper: ResourceHelper, private val startAppUseCase: StartAppUseCase, + private val changePinUseCase: ChangePinUseCase, private val validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase, ) { @@ -51,4 +52,8 @@ class OneginiMethodsWrapper @Inject constructor( fun validatePinWithPolicy(call: MethodCall, result: MethodChannel.Result) { validatePinWithPolicyUseCase(call, result) } + + fun changePin(result: MethodChannel.Result) { + changePinUseCase(result) + } } From 78e45b26c204f9548e9c7890fea45402c722bfca Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 13:35:44 +0100 Subject: [PATCH 109/364] fp-20 update changepin use case with tests for pigeon --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 1 - .../sdk/flutter/OneginiMethodsWrapper.kt | 4 --- .../sdk/flutter/useCases/ChangePinUseCase.kt | 31 ++++++++++--------- .../mobile/sdk/ChangePinUseCaseTests.kt | 31 +++++++++++++------ 4 files changed, 39 insertions(+), 28 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index d745bfc4..885b4f35 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -52,7 +52,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: Constants.METHOD_GET_UNAUTHENTICATED_RESOURCE -> oneginiMethodsWrapper.getUnauthenticatedResource(call, result) // Other - Constants.METHOD_CHANGE_PIN -> oneginiMethodsWrapper.changePin(result) Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> getAppToWebSingleSignOn(call.argument("url"), result, client) else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index cf5b778a..f01fddb9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -52,8 +52,4 @@ class OneginiMethodsWrapper @Inject constructor( fun validatePinWithPolicy(call: MethodCall, result: MethodChannel.Result) { validatePinWithPolicyUseCase(call, result) } - - fun changePin(result: MethodChannel.Result) { - changePinUseCase(result) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt index a617dd15..df71fcdc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ChangePinUseCase.kt @@ -4,24 +4,27 @@ import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class ChangePinUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(result: MethodChannel.Result) { - oneginiSDK.oneginiClient.userClient.changePin(object : OneginiChangePinHandler { - override fun onSuccess() { - result.success(null) - } + operator fun invoke(callback: (Result) -> Unit) { + oneginiSDK.oneginiClient.userClient.changePin(object : OneginiChangePinHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } - override fun onError(error: OneginiChangePinError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) - } - }) - } + override fun onError(error: OneginiChangePinError) { + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) + } + }) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index d1e56366..b95f25fc 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -5,9 +5,10 @@ import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -15,7 +16,8 @@ import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any -import org.mockito.kotlin.eq +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -32,7 +34,7 @@ class ChangePinUseCaseTests { lateinit var callMock: MethodCall @Mock - lateinit var resultMock: MethodChannel.Result + lateinit var callbackMock: (Result) -> Unit @Mock lateinit var oneginiChangePinError: OneginiChangePinError @@ -51,9 +53,12 @@ class ChangePinUseCaseTests { it.getArgument(0).onSuccess() } - changePinUseCase(resultMock) + changePinUseCase(callbackMock) - verify(resultMock).success(null) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) + } } @Test @@ -62,10 +67,18 @@ class ChangePinUseCaseTests { it.getArgument(0).onError(oneginiChangePinError) } - changePinUseCase(resultMock) - - val message = oneginiChangePinError.message - verify(resultMock).error(eq(oneginiChangePinError.errorType.toString()), eq(message), any()) + changePinUseCase(callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiChangePinError.errorType) + Assert.assertEquals(error.message, oneginiChangePinError.message) + } + else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) + } + } } private fun setupErrorMock() { From 2d420f59fb592481957176e3746886e99b192daf Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:07:45 +0100 Subject: [PATCH 110/364] fp-20 now all non async usecases return a flutter error instead of sdk error to make it consistent with async functions --- .../mobile/sdk/flutter/PigeonInterface.kt | 51 ++++++------------- .../flutter/useCases/GetAccessTokenUseCase.kt | 2 +- .../useCases/GetAllAuthenticatorsUseCase.kt | 2 +- .../GetAuthenticatedUserProfileUseCase.kt | 2 +- .../GetNotRegisteredAuthenticatorsUseCase.kt | 2 +- .../GetRegisteredAuthenticatorsUseCase.kt | 2 +- .../SetPreferredAuthenticatorUseCase.kt | 4 +- .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 5 +- .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 3 +- ...GetAuthenticatedUserProfileUseCaseTests.kt | 5 +- ...NotRegisteredAuthenticatorsUseCaseTests.kt | 5 +- ...GetRegisteredAuthenticatorsUseCaseTests.kt | 5 +- .../SetPreferredAuthenticatorUseCaseTests.kt | 9 ++-- 13 files changed, 41 insertions(+), 56 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 190d173a..7be656e2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -18,6 +18,7 @@ import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUseCase +import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase @@ -98,11 +99,13 @@ open class PigeonInterface : UserClientApi { lateinit var startAppUseCase: StartAppUseCase @Inject lateinit var submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase + @Inject + lateinit var changePinUseCase: ChangePinUseCase // FIXME REMOVE ME AT THE END; Example function on how it could be initiated on Flutter send to Native override fun fetchUserProfiles(callback: (Result>) -> Unit) { val a = Result.success(listOf(OWUserProfile("ghalo"))) - flutterCallback(callback, a) +// flutterCallback(callback, a) // val b = Result.failure>(SdkError(2000, "hallo")) // flutterCallback(callback, b) @@ -113,13 +116,11 @@ open class PigeonInterface : UserClientApi { } override fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) { - val result = handleRegisteredUrlUseCase(url, signInType) - flutterCallback(callback, result) + callback(handleRegisteredUrlUseCase(url, signInType)) } override fun getIdentityProviders(callback: (Result>) -> Unit) { - val result = getIdentityProvidersUseCase() - flutterCallback(callback, result) + callback(getIdentityProvidersUseCase()) } override fun deregisterUser(profileId: String, callback: (Result) -> Unit) { @@ -127,18 +128,15 @@ open class PigeonInterface : UserClientApi { } override fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - val result = getRegisteredAuthenticatorsUseCase(profileId) - flutterCallback(callback, result) + callback(getRegisteredAuthenticatorsUseCase(profileId)) } override fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) { - val result = getAllAuthenticatorsUseCase(profileId) - flutterCallback(callback, result) + callback(getAllAuthenticatorsUseCase(profileId)) } override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { - val result = getAuthenticatedUserProfileUseCase() - flutterCallback(callback, result) + callback(getAuthenticatedUserProfileUseCase()) } override fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) { @@ -146,17 +144,15 @@ open class PigeonInterface : UserClientApi { } override fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - val result = getNotRegisteredAuthenticatorsUseCase(profileId) - flutterCallback(callback, result) + callback(getNotRegisteredAuthenticatorsUseCase(profileId)) } override fun changePin(callback: (Result) -> Unit) { -// TODO("Not yet implemented") + changePinUseCase(callback) } override fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - val result = setPreferredAuthenticatorUseCase(authenticatorId) - flutterCallback(callback, result) + callback(setPreferredAuthenticatorUseCase(authenticatorId)) } override fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { @@ -180,18 +176,15 @@ open class PigeonInterface : UserClientApi { } override fun getAccessToken(callback: (Result) -> Unit) { - val result = getAccessTokenUseCase() - flutterCallback(callback, result) + callback(getAccessTokenUseCase()) } override fun getRedirectUrl(callback: (Result) -> Unit) { - val result = getRedirectUrlUseCase() - flutterCallback(callback, result) + callback(getRedirectUrlUseCase()) } override fun getUserProfiles(callback: (Result>) -> Unit) { - val result = getUserProfilesUseCase() - flutterCallback(callback, result) + callback(getUserProfilesUseCase()) } override fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) { @@ -274,18 +267,4 @@ open class PigeonInterface : UserClientApi { BrowserRegistrationRequestHandler.onRegistrationCanceled() callback(Result.success(Unit)) } - - private fun flutterCallback(callback: (Result) -> Unit, result: Result) { - result.fold( - onFailure = { error -> - when (error) { - is SdkError -> callback(Result.failure(error.pigeonError())) - else -> callback(Result.failure(error)) - } - }, - onSuccess = { value -> - callback(Result.success(value)) - } - ) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt index c81c39d4..ad42d616 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt @@ -13,6 +13,6 @@ class GetAccessTokenUseCase @Inject constructor(private val oneginiSDK: OneginiS return Result.success(token) } - return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) + return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt index 215bbae8..096ea735 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt @@ -15,7 +15,7 @@ class GetAllAuthenticatorsUseCase @Inject constructor( val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return Result.failure(error) + return Result.failure(error.pigeonError()) } val allAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt index c544ecbf..de1985fe 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt @@ -11,7 +11,7 @@ import javax.inject.Singleton class GetAuthenticatedUserProfileUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(): Result { return when (val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile) { - null -> Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) + null -> Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) else -> Result.success(OWUserProfile(authenticatedUserProfile.profileId)) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt index 332d5d88..432c0c84 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt @@ -19,7 +19,7 @@ class GetNotRegisteredAuthenticatorsUseCase @Inject constructor( val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return Result.failure(error) + return Result.failure(error.pigeonError()) } val notRegisteredAuthenticators = oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(userProfile) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt index 3016299e..08034d4e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt @@ -15,7 +15,7 @@ class GetRegisteredAuthenticatorsUseCase @Inject constructor( val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return Result.failure(error) + return Result.failure(error.pigeonError()) } val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 28300973..5da640bf 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -13,10 +13,10 @@ class SetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD operator fun invoke(authenticatorId: String): Result { val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED)) + ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) val authenticator = getAuthenticatorById(authenticatorId, userProfile) - ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND)) + ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError()) oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) return Result.success(Unit) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index 5682be5f..0a13b85b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -3,6 +3,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase import junit.framework.Assert.fail import org.junit.Assert @@ -32,8 +33,8 @@ class GetAccessTokenUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn(null) when (val error = getAccessTokenUseCase().exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index 69bf3da9..b0d40fa9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -5,6 +5,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -45,7 +46,7 @@ class GetAllAuthenticatorsUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("ABCDEF"))) when (val error = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull()) { - is SdkError -> { + is FlutterError -> { Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index f066b87e..43b619d3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -4,6 +4,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase import junit.framework.Assert.fail import org.junit.Assert @@ -35,8 +36,8 @@ class GetAuthenticatedUserProfileUseCaseTests { val result = getAuthenticatedUserProfileUseCase() when (val error = result.exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) } else -> fail("Test failed as no sdk error was passed") diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 1cd1be2c..90b5fe39 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -5,6 +5,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -54,8 +55,8 @@ class GetNotRegisteredAuthenticatorsUseCaseTests { val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") when (val error = result.exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index df1f18c3..f08316dc 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -6,6 +6,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -59,8 +60,8 @@ class GetRegisteredAuthenticatorsUseCaseTests { val result = getRegisteredAuthenticatorsUseCase("QWERTY") when (val error = result.exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index 1e03bb85..d22177af 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -6,6 +6,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import junit.framework.Assert.fail import org.junit.Assert @@ -42,8 +43,8 @@ class SetPreferredAuthenticatorUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, NO_USER_PROFILE_IS_AUTHENTICATED.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) @@ -58,8 +59,8 @@ class SetPreferredAuthenticatorUseCaseTests { setPreferredAuthenticatorUseCase("test") when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { - is SdkError -> { - Assert.assertEquals(error.code, AUTHENTICATOR_NOT_FOUND.code) + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) From 67c134f0988d990504a07068a3957b670016d3de Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:15:22 +0100 Subject: [PATCH 111/364] fp-20 process feedback and rename pigeonchannel to pigeoncallback for the vustomregistrationcallbacks --- .../flutter/providers/CustomRegistrationAction.kt | 4 ++-- .../providers/CustomRegistrationActionImpl.kt | 12 ++++++------ .../providers/CustomTwoStepRegistrationActionImpl.kt | 12 ++++++------ 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt index a978cb31..d318ba88 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt @@ -8,7 +8,7 @@ interface CustomRegistrationAction { fun getIdProvider(): String - fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) + fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) - fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) + fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 119b7eee..3491c6c0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -33,24 +33,24 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust return providerId } - override fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) { + override fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) { when (callback) { - null -> pigeonChannel(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + null -> pigeonCallback(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) else -> { this.callback?.returnSuccess(result) - pigeonChannel(Result.success(Unit)) + pigeonCallback(Result.success(Unit)) } } callback = null } - override fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) { + override fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) { when (callback) { - null -> pigeonChannel(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + null -> pigeonCallback(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) else -> { this.callback?.returnError(exception) - pigeonChannel(Result.success(Unit)) + pigeonCallback(Result.success(Unit)) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 31ca0dff..62d09f77 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -39,24 +39,24 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg return providerId } - override fun returnSuccess(result: String?, pigeonChannel: (Result) -> Unit) { + override fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) { when (callback) { - null -> pigeonChannel(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + null -> pigeonCallback(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) else -> { this.callback?.returnSuccess(result) - pigeonChannel(Result.success(Unit)) + pigeonCallback(Result.success(Unit)) } } callback = null } - override fun returnError(exception: Exception?, pigeonChannel: (Result) -> Unit) { + override fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) { when (callback) { - null -> pigeonChannel(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + null -> pigeonCallback(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) else -> { this.callback?.returnError(exception) - pigeonChannel(Result.success(Unit)) + pigeonCallback(Result.success(Unit)) } } From 2c69ae8d884ffc3e7a02dc1a72ab2eca0299bbe1 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:40:14 +0100 Subject: [PATCH 112/364] fp-20 fix for two broken functions --- .../mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt | 5 +---- .../onegini/mobile/sdk/RegistrationUseCaseTests.kt | 14 +++++++------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index b0d40fa9..b11b6944 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -42,12 +42,9 @@ class GetAllAuthenticatorsUseCaseTests { @Test fun `When an unknown or unregistered profileId is given, Then an error should be thrown`() { - whenever(callMock.argument("profileId")).thenReturn("QWERTY") - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("ABCDEF"))) - when (val error = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull()) { is FlutterError -> { - Assert.assertEquals(error.code, USER_PROFILE_DOES_NOT_EXIST.code) + Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) } else -> fail(UNEXPECTED_ERROR_TYPE.message) diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index a4293b8b..416fc912 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -64,7 +64,7 @@ class RegistrationUseCaseTests { } @Test - fun `should match the IDs with the identity provider id as a parameter when the given ID is found in the SDK identity providers`() { + fun `When the given ID is found in the SDK identity providers, Then it should match the IDs with the identity provider id as a parameter`() { val testProviderId = "testId" val testScopes = listOf("read") val setOfIdentityProviders = setOf(oneginiIdentityProviderMock) @@ -81,7 +81,7 @@ class RegistrationUseCaseTests { } @Test - fun `should return error when the given ID is not found in the SDK identity providers`() { + fun `When the given ID is not found in the SDK identity providers, Then it should return error`() { whenever(oneginiIdentityProviderMock.id).thenReturn("id") whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderMock)) @@ -101,7 +101,7 @@ class RegistrationUseCaseTests { } @Test - fun `should call result success with identity provider id as a param when given identity provider id is found in SDK identity providers`() { + fun `When given identity provider id is found in SDK identity providers, Then it should call result success with identity provider id as a param`() { whenever(oneginiIdentityProviderMock.id).thenReturn("testId") whenever(oneginiSdk.oneginiClient.userClient.identityProviders).thenReturn(setOf(oneginiIdentityProviderMock)) whenever(oneginiSdk.oneginiClient.userClient.registerUser(isNotNull(), eq(arrayOf("read")), any())).thenAnswer { @@ -119,14 +119,14 @@ class RegistrationUseCaseTests { } @Test - fun `should call 'registerUser' method once when given identity provider id is null`() { + fun `When given identity provider id is null, Then it should call 'registerUser' method once`() { registrationUseCase(null, listOf("read"), callbackMock) verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), eq(arrayOf("read")), any()) } @Test - fun `should scopes param be array of two scopes when given scopes contains two strings`() { + fun `When given scopes contains two strings, Then the scopes param should be array of two scopes`() { registrationUseCase(null, listOf("read", "write"), callbackMock) argumentCaptor> { @@ -137,12 +137,12 @@ class RegistrationUseCaseTests { } @Test - fun `should scopes param be array of zero lengths when given scopes is null`() { + fun `When given scopes is null, Then the scopes param should be be an array of null`() { registrationUseCase(null, null, callbackMock) argumentCaptor> { verify(oneginiSdk.oneginiClient.userClient).registerUser(isNull(), capture(), any()) - assertThat(firstValue).isEmpty() + assertThat(firstValue).isNull() } } } From 99334c3cf263e2bfa1c82dea5235cdfd0f7285c0 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:44:18 +0100 Subject: [PATCH 113/364] fp-20 move callback of custom registration actions outside of the customregistration providers into the pigeon interface --- .../mobile/sdk/flutter/PigeonInterface.kt | 4 +-- .../providers/CustomRegistrationAction.kt | 4 +-- .../providers/CustomRegistrationActionImpl.kt | 28 +++++++++++-------- .../CustomTwoStepRegistrationActionImpl.kt | 28 +++++++++++-------- .../CancelCustomRegistrationActionUseCase.kt | 8 +++--- .../SubmitCustomRegistrationActionUseCase.kt | 10 ++++--- 6 files changed, 46 insertions(+), 36 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 7be656e2..ca536235 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -201,11 +201,11 @@ open class PigeonInterface : UserClientApi { // Callback functions override fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { - submitCustomRegistrationActionUseCase(identityProviderId, data, callback) + callback(submitCustomRegistrationActionUseCase(identityProviderId, data)) } override fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { - cancelCustomRegistrationActionUseCase(identityProviderId, error, callback) + callback(cancelCustomRegistrationActionUseCase(identityProviderId, error)) } override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt index d318ba88..22a690ef 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt @@ -8,7 +8,7 @@ interface CustomRegistrationAction { fun getIdProvider(): String - fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) + fun returnSuccess(result: String?): Result - fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) + fun returnError(exception: Exception?): Result } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 3491c6c0..ee65086f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -33,27 +33,31 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust return providerId } - override fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) { - when (callback) { - null -> pigeonCallback(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + override fun returnSuccess(result: String?): Result { + return when (callback) { + null -> { + callback = null + Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } else -> { this.callback?.returnSuccess(result) - pigeonCallback(Result.success(Unit)) + callback = null + Result.success(Unit) } } - - callback = null } - override fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) { - when (callback) { - null -> pigeonCallback(Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + override fun returnError(exception: Exception?): Result { + return when (callback) { + null -> { + callback = null + Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } else -> { + callback = null this.callback?.returnError(exception) - pigeonCallback(Result.success(Unit)) + Result.success(Unit) } } - - callback = null } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 62d09f77..c1be28e3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -39,27 +39,31 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg return providerId } - override fun returnSuccess(result: String?, pigeonCallback: (Result) -> Unit) { - when (callback) { - null -> pigeonCallback(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + override fun returnSuccess(result: String?): Result { + return when (callback) { + null -> { + callback = null + Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } else -> { this.callback?.returnSuccess(result) - pigeonCallback(Result.success(Unit)) + callback = null + Result.success(Unit) } } - - callback = null } - override fun returnError(exception: Exception?, pigeonCallback: (Result) -> Unit) { - when (callback) { - null -> pigeonCallback(Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError())) + override fun returnError(exception: Exception?): Result { + return when (callback) { + null -> { + callback = null + Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } else -> { + callback = null this.callback?.returnError(exception) - pigeonCallback(Result.success(Unit)) + Result.success(Unit) } } - - callback = null } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt index a7f66b9f..9da96b46 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt @@ -8,10 +8,10 @@ import javax.inject.Singleton @Singleton class CancelCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(identityProviderId: String, error: String, callback: (Result) -> Unit) { - when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { - null -> callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) - else -> action.returnError(Exception(error), callback) + operator fun invoke(identityProviderId: String, error: String): Result { + return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { + null -> Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError()) + else -> action.returnError(Exception(error)) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt index 38bfc472..49e41924 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt @@ -8,10 +8,12 @@ import javax.inject.Singleton @Singleton class SubmitCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(identityProviderId: String, data: String?, callback: (Result) -> Unit) { - when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { - null -> callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) - else -> action.returnSuccess(data, callback) + operator fun invoke(identityProviderId: String, data: String?): Result { + return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { + null -> Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError()) + else -> { + action.returnSuccess(data) + } } } } From 6dad3e5da04dc54617eec5defe5d2c2a91be5959 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:53:32 +0100 Subject: [PATCH 114/364] fp-20 removed unused variable --- .../com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index f01fddb9..ed90c01a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -17,7 +17,6 @@ class OneginiMethodsWrapper @Inject constructor( private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, private val resourceHelper: ResourceHelper, private val startAppUseCase: StartAppUseCase, - private val changePinUseCase: ChangePinUseCase, private val validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase, ) { From 1a7f3f8e764e6a9becb7c2ea9c959f8e061bdac9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 14:58:27 +0100 Subject: [PATCH 115/364] fp-20 removed rendundant code --- example/lib/screens/login_screen.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index bd6c2756..1255f834 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -133,10 +133,6 @@ class _LoginScreenState extends State { Future> getUserProfiles() async { try { - var userApi = UserClientApi(); - var derp = await userApi.fetchUserProfiles(); - print(derp[0].profileId); - var profiles = await Onegini.instance.userClient.getUserProfiles(); return profiles; } catch (err) { @@ -148,6 +144,7 @@ class _LoginScreenState extends State { Future getImplicitUserDetails(String profileId) async { var returnString = ""; try { + print("boop"); var userProfileId = await Onegini.instance.userClient .authenticateUserImplicitly(profileId, ["read"]); From 20cae12f54f8b774b9af66a14e5c97e6a8309284 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 15:09:44 +0100 Subject: [PATCH 116/364] fp-20 use pigeons change pin as these are implemented now --- lib/user_client.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index 91d36032..a6c48e1b 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -92,11 +92,8 @@ class UserClient { Future changePin( BuildContext? context, ) async { + await api.changePin(); Onegini.instance.setEventContext(context); - - // todo use api once the branch is merged that puts this in an usecase on android - // await api.changePin(); - await Onegini.instance.channel.invokeMethod(Constants.changePin); } /// Registers authenticator from [getNotRegisteredAuthenticators] list. From 1ff621f36dc6b8d8e05f87b949c4eddbf2ad59bf Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 9 Mar 2023 15:25:24 +0100 Subject: [PATCH 117/364] fp-20 add validate pin to pigeon, updated usecase, test and userclient --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 1 - .../sdk/flutter/OneginiMethodsWrapper.kt | 4 - .../mobile/sdk/flutter/PigeonInterface.kt | 5 +- .../useCases/ValidatePinWithPolicyUseCase.kt | 44 ++++--- .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 112 +++++++++--------- lib/user_client.dart | 12 +- 6 files changed, 80 insertions(+), 98 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 885b4f35..5843be23 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -40,7 +40,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) - Constants.METHOD_VALIDATE_PIN_WITH_POLICY -> oneginiMethodsWrapper.validatePinWithPolicy(call, result) // OTP Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, client) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index ed90c01a..9f1d657e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -47,8 +47,4 @@ class OneginiMethodsWrapper @Inject constructor( fun isAuthenticatorRegistered(call: MethodCall, result: MethodChannel.Result) { isAuthenticatorRegisteredUseCase(call, result) } - - fun validatePinWithPolicy(call: MethodCall, result: MethodChannel.Result) { - validatePinWithPolicyUseCase(call, result) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index ca536235..fcebbdff 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -41,6 +41,7 @@ import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUseCase +import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase import javax.inject.Inject //private val getIdentityProvidersUseCase: GetIdentityProvidersUseCase @@ -101,6 +102,8 @@ open class PigeonInterface : UserClientApi { lateinit var submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase @Inject lateinit var changePinUseCase: ChangePinUseCase + @Inject + lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase // FIXME REMOVE ME AT THE END; Example function on how it could be initiated on Flutter send to Native override fun fetchUserProfiles(callback: (Result>) -> Unit) { @@ -188,7 +191,7 @@ open class PigeonInterface : UserClientApi { } override fun validatePinWithPolicy(pin: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + validatePinWithPolicyUseCase(pin, callback) } override fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt index 7a0ea709..720d95e8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ValidatePinWithPolicyUseCase.kt @@ -2,36 +2,32 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @Singleton class ValidatePinWithPolicyUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val nonNullPin = call.argument("pin")?.toCharArray() ?: return SdkError( - OneWelcomeWrapperErrors.ARGUMENT_NOT_CORRECT.code, - OneWelcomeWrapperErrors.ARGUMENT_NOT_CORRECT.message + " pin is null" - ).flutterError(result) + operator fun invoke(pin: String, callback: (Result) -> Unit) { + oneginiSDK.oneginiClient.userClient.validatePinWithPolicy( + pin.toCharArray(), + object : OneginiPinValidationHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } - oneginiSDK.oneginiClient.userClient.validatePinWithPolicy( - nonNullPin, - object : OneginiPinValidationHandler { - override fun onSuccess() { - result.success(null) - } - - override fun onError(oneginiPinValidationError: OneginiPinValidationError) { - SdkError( - code = oneginiPinValidationError.errorType, - message = oneginiPinValidationError.message - ).flutterError(result) - } - } - ) - } + override fun onError(oneginiPinValidationError: OneginiPinValidationError) { + callback( + Result.failure( + SdkError( + code = oneginiPinValidationError.errorType, + message = oneginiPinValidationError.message + ).pigeonError() + ) + ) + } + } + ) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt index 5c49684c..83c35e0e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -5,9 +5,10 @@ import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import junit.framework.Assert.fail +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -15,85 +16,82 @@ import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class ValidatePinWithPolicyUseCaseTests { - @Mock - lateinit var oneginiPinValidationErrorMock: OneginiPinValidationError + @Mock + lateinit var oneginiPinValidationErrorMock: OneginiPinValidationError + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall + @Mock + lateinit var callbackMock: (Result) -> Unit - @Mock - lateinit var resultMock: MethodChannel.Result + lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase - lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase + @Before + fun attach() { + validatePinWithPolicyUseCase = ValidatePinWithPolicyUseCase(oneginiSdk) + } - @Before - fun attach() { - validatePinWithPolicyUseCase = ValidatePinWithPolicyUseCase(oneginiSdk) - } - - - @Test - fun `When supplying null as pin, Then should reject with ARGUMENT_NOT_CORRECT error`() { - whenever(callMock.argument("pin")).thenReturn(null) - - validatePinWithPolicyUseCase(callMock, resultMock) - - val message = ARGUMENT_NOT_CORRECT.message + " pin is null" - verify(resultMock).error(eq(ARGUMENT_NOT_CORRECT.code.toString()), eq(message), any()) - } - @Test - fun `When pin is not null should call validatePinWithPolicy on the onegini sdk`() { - whenever(callMock.argument("pin")).thenReturn("14789") + @Test + fun `When pin is not null, Then it should call validatePinWithPolicy on the onegini sdk`() { + validatePinWithPolicyUseCase("14789", callbackMock) - validatePinWithPolicyUseCase(callMock, resultMock) + verify(oneginiSdk.oneginiClient.userClient).validatePinWithPolicy(eq("14789".toCharArray()), any()) + } - verify(oneginiSdk.oneginiClient.userClient).validatePinWithPolicy(eq("14789".toCharArray()), any()) + @Test + fun `When oginini validatePinWithPolicy calls onSuccess on the handler, Then the promise should resolve successfully`() { + whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { + it.getArgument(1).onSuccess() } - @Test - fun `When oginini validatePinWithPolicy calls onSuccess on the handler, promise should resolve with null`() { - whenever(callMock.argument("pin")).thenReturn("14789") - whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { - it.getArgument(1).onSuccess() - } - - validatePinWithPolicyUseCase(callMock, resultMock) + validatePinWithPolicyUseCase("14789", callbackMock) - verify(resultMock).success(null) + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull(), Unit) } + } - @Test - fun `When oginini validatePinWithPolicy calls onError on the handler, promise should reject with error from native sdk`() { - whenever(callMock.argument("pin")).thenReturn("14789") - whenPinValidationReturnedError() + @Test + fun `When oginini validatePinWithPolicy calls onError on the handler, Then the promise should reject with error from native sdk`() { + whenPinValidationReturnedError() - validatePinWithPolicyUseCase(callMock, resultMock) + validatePinWithPolicyUseCase("14789", callbackMock) - val message = oneginiPinValidationErrorMock.message - verify(resultMock).error(eq(oneginiPinValidationErrorMock.errorType.toString()), eq(message), any()) - } + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) - private fun whenPinValidationReturnedError() { - val errorCode = 111 - val errorMessage = "message" - whenever(oneginiPinValidationErrorMock.errorType).thenReturn(errorCode) - whenever(oneginiPinValidationErrorMock.message).thenReturn(errorMessage) - whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { - it.getArgument(1).onError(oneginiPinValidationErrorMock) + when (val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), oneginiPinValidationErrorMock.errorType) + Assert.assertEquals(error.message, oneginiPinValidationErrorMock.message) } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } + + private fun whenPinValidationReturnedError() { + val errorCode = 111 + val errorMessage = "message" + whenever(oneginiPinValidationErrorMock.errorType).thenReturn(errorCode) + whenever(oneginiPinValidationErrorMock.message).thenReturn(errorMessage) + whenever(oneginiSdk.oneginiClient.userClient.validatePinWithPolicy(any(), any())).thenAnswer { + it.getArgument(1).onError(oneginiPinValidationErrorMock) } + } } diff --git a/lib/user_client.dart b/lib/user_client.dart index a6c48e1b..88db0ee6 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -187,17 +187,7 @@ class UserClient { /// todo removed boolean return update docu Future validatePinWithPolicy(String pin) async { // todo use api once the branch is merged that puts this in an usecase on android - // await api.validatePinWithPolicy(pin); - try { - var success = await Onegini.instance.channel.invokeMethod( - Constants.validatePinWithPolicy, {'pin': pin}); - return success ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + await api.validatePinWithPolicy(pin); } /// todo removed boolean return update docu From 4afa36746504b2a1b1efc3fa61c19b659805d277 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 11:44:43 +0100 Subject: [PATCH 118/364] FP-49: Rework a large part of pin handling Previously there was a lot of incoherent handling of the pins, especially for changing pin flow. This commit updates the change pin behavior to use the already existing login/register behaviors. It also removes a lot of initalizers in the BridgeConnector and various pin handling classes. It also updates the dart api to actually use the pigeon api instead of the message channels for starting the changepin flow. --- .../Connectors/BridgeConnector.swift | 20 +- .../Connectors/PinConnector.swift | 39 +-- .../Connectors/RegistrationConnector.swift | 7 +- .../NativeBridge/Errors/ErrorMapper.swift | 1 + .../Handlers/AuthenticatorsHandler.swift | 12 +- .../Handlers/ChangePinHandler.swift | 53 ++++ .../NativeBridge/Handlers/LoginHandler.swift | 110 +++------ .../NativeBridge/Handlers/PinHandler.swift | 230 ------------------ .../Handlers/RegistrationHandler.swift | 83 ++++--- .../OneginiModuleSwift+OTP.swift | 2 + .../OneginiModuleSwift+Pin.swift | 34 ++- ios/Classes/SwiftOneginiPlugin.swift | 13 +- lib/user_client.dart | 5 +- 13 files changed, 191 insertions(+), 418 deletions(-) create mode 100644 ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift delete mode 100644 ios/Classes/NativeBridge/Handlers/PinHandler.swift diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index f5115bc3..9433f8d7 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -4,28 +4,28 @@ protocol BridgeConnectorProtocol: AnyObject { class BridgeConnector: BridgeConnectorProtocol { - let toRegistrationConnector: BridgeToRegistrationConnectorProtocol = RegistrationConnector() - let toPinHandlerConnector: BridgeToPinConnectorProtocol = PinConnector() - let toLoginHandler: BridgeToLoginHandlerProtocol = LoginHandler() + + let toPinConnector = PinConnector() + let toLoginHandler: LoginHandler = LoginHandler() let toAppToWebHandler: AppToWebHandlerProtocol = AppToWebHandler() let toResourceFetchHandler: FetchResourcesHandlerProtocol = ResourcesHandler() let toMobileAuthConnector: BridgeToMobileAuthConnectorProtocol = MobileAuthConnector() var toLogoutUserHandler = LogoutHandler() var toDeregisterUserHandler = DeregisterUserHandler() let toAuthenticatorsHandler: AuthenticatorsHandler = AuthenticatorsHandler() - + let toRegistrationConnector: BridgeToRegistrationConnectorProtocol + let toChangePinHandler: ChangePinHandler weak var bridge: ConnectorToFlutterBridgeProtocol? public static var shared:BridgeConnector? init() { + self.toRegistrationConnector = RegistrationConnector(handler: RegistrationHandler()) + self.toAuthenticatorsHandler.notificationReceiver = toMobileAuthConnector + self.toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationConnector.registrationHandler) + self.toRegistrationConnector.bridgeConnector = self - self.toPinHandlerConnector.bridgeConnector = self + self.toPinConnector.bridgeConnector = self BridgeConnector.shared = self - - let pinHandler = self.toPinHandlerConnector.pinHandler - self.toRegistrationConnector.registrationHandler.pinHandler = pinHandler - self.toLoginHandler.pinHandler = pinHandler - self.toAuthenticatorsHandler.notificationReceiver = toMobileAuthConnector } func sendBridgeEvent(eventName: OneginiBridgeEvents, data: Any!) { diff --git a/ios/Classes/NativeBridge/Connectors/PinConnector.swift b/ios/Classes/NativeBridge/Connectors/PinConnector.swift index 419bccf5..810822c2 100644 --- a/ios/Classes/NativeBridge/Connectors/PinConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/PinConnector.swift @@ -1,38 +1,11 @@ -//MARK: - BridgeToPinConnectorProtocol -protocol BridgeToPinConnectorProtocol: PinNotificationReceiverProtocol { +protocol BridgeToPinConnectorProtocol { var bridgeConnector: BridgeConnectorProtocol? { get set } - var pinHandler: PinConnectorToPinHandler { get } - - func handlePinAction(_ flow: String, _ action: String, _ pin: String) -> Void } -//MARK: - PinConnector -class PinConnector : BridgeToPinConnectorProtocol, PinNotificationReceiverProtocol { - var pinHandler: PinConnectorToPinHandler +class PinConnector : BridgeToPinConnectorProtocol { unowned var bridgeConnector: BridgeConnectorProtocol? - init() { - let handler = PinHandler() - pinHandler = handler - handler.notificationReceiver = self - } - - func handlePinAction(_ flow: String, _ action: String, _ pin: String) { - - switch action { - case PinAction.provide.rawValue: - pinHandler.onPinProvided(pin: pin) - break - case PinAction.cancel.rawValue: - pinHandler.onCancel() - break - default: - sendEvent(data: ["eventName": PinNotification.showError.rawValue, "eventValue": SdkError(.unsupportedPinAction).details as Any?]) - break - } - } - - func sendNotification(event: PinNotification, flow: PinFlow?, error: SdkError?) { + func sendNotification(event: PinNotification, error: SdkError?) { switch (event){ case .open: sendEvent(data: PinNotification.open.rawValue) @@ -81,7 +54,7 @@ enum PinAction : String { enum PinFlow : String { case create = "create", - change = "change", - authentication = "authentication", - nextAuthenticationAttempt = "nextAuthenticationAttempt" +// change = "change", + authentication = "authentication" +// nextAuthenticationAttempt = "nextAuthenticationAttempt" } diff --git a/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift b/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift index 6b582b9d..84cd7c67 100644 --- a/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift @@ -1,16 +1,15 @@ //MARK: - protocol BridgeToRegistrationConnectorProtocol: CustomRegistrationNotificationReceiverProtocol { var bridgeConnector: BridgeConnectorProtocol? { get set } - var registrationHandler: RegistrationConnectorToHandlerProtocol & BrowserHandlerToRegisterHandlerProtocol { get } + var registrationHandler: RegistrationHandler { get } } //MARK: - class RegistrationConnector : BridgeToRegistrationConnectorProtocol, CustomRegistrationNotificationReceiverProtocol { - var registrationHandler: RegistrationConnectorToHandlerProtocol & BrowserHandlerToRegisterHandlerProtocol + var registrationHandler: RegistrationHandler unowned var bridgeConnector: BridgeConnectorProtocol? - init() { - let handler = RegistrationHandler() + init(handler: RegistrationHandler) { registrationHandler = handler handler.customNotificationReceiver = self } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index d6fb2935..10e2b7db 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -101,6 +101,7 @@ class ErrorMapper { func mapErrorFromPinChallenge(_ challenge: ONGPinChallenge?) -> SdkError? { if let error = challenge?.error, error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue { + // FIXME: this probably shouldn't be here guard let maxAttempts = challenge?.maxFailureCount, let previousCount = challenge?.previousFailureCount, maxAttempts != previousCount else { diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 28a9093c..0405cfe4 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -16,7 +16,7 @@ protocol AuthenticatorsNotificationReceiverProtocol: class { } //MARK: - -class AuthenticatorsHandler: NSObject, PinHandlerToReceiverProtocol { +class AuthenticatorsHandler: NSObject { var pinChallenge: ONGPinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? var registrationCompletion: ((Result) -> Void)? @@ -130,11 +130,11 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue, challenge.previousFailureCount < challenge.maxFailureCount { // 9009 - BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) +// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) return } - BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) +// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishRegistrationChallenge) { @@ -143,12 +143,12 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { registrationCompletion?(.success(())) customAuthChallenge = challenge - BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) +// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) } func userClient(_: ONGUserClient, didFailToRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender:self) - BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() +// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) } else { @@ -160,7 +160,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) registrationCompletion?(.success(())) - BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() +// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() } } diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift new file mode 100644 index 00000000..9b46d6d2 --- /dev/null +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -0,0 +1,53 @@ +import OneginiSDKiOS +import Flutter + +class ChangePinHandler: NSObject { + var changePinCompletion: ((Result) -> Void)? + private let loginHandler: LoginHandler + private let registrationHandler: RegistrationHandler + + init(loginHandler: LoginHandler, registrationHandler: RegistrationHandler) { + self.loginHandler = loginHandler + self.registrationHandler = registrationHandler + } +} + +extension ChangePinHandler { + func changePin(completion: @escaping (Result) -> Void) { + changePinCompletion = completion + ONGUserClient.sharedInstance().changePin(self) + } + } + +extension ChangePinHandler: ONGChangePinDelegate { + func userClient(_ userClient: ONGUserClient, didReceive challenge: ONGPinChallenge) { + loginHandler.handleDidReceiveChallenge(challenge) + } + + func userClient(_: ONGUserClient, didReceive challenge: ONGCreatePinChallenge) { + loginHandler.handleDidAuthenticateUser() + registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) + } + + func userClient(_: ONGUserClient, didFailToChangePinForUser _: ONGUserProfile, error: Error) { + loginHandler.handleDidFailToAuthenticateUser() + registrationHandler.handleDidFailToRegister() + + // FIXME: Clearly we already have an error for canceling pin, so why do we need to create our own here? + // Fixing this could probably remove all those lines and just pass the Error directly. + let mappedError = ErrorMapper().mapError(error) + if error.code == ONGGenericError.actionCancelled.rawValue { + changePinCompletion?(.failure(FlutterError(.changingPinCancelled))) + } else { + changePinCompletion?(.failure(FlutterError(mappedError))) + } + changePinCompletion = nil + } + + func userClient(_: ONGUserClient, didChangePinForUser _: ONGUserProfile) { + registrationHandler.handleDidRegisterUser() + changePinCompletion?(.success(())) + changePinCompletion = nil + + } +} diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 9b29963b..03be1d28 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -1,114 +1,70 @@ import OneginiSDKiOS import Flutter -//MARK: - -protocol BridgeToLoginHandlerProtocol: LoginHandlerToPinHanlderProtocol { - func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (Result) -> Void) -} - -protocol LoginHandlerToPinHanlderProtocol: class { - var pinHandler: PinConnectorToPinHandler? { get set } -} - -//MARK: - -class LoginHandler: NSObject, PinHandlerToReceiverProtocol { +class LoginHandler: NSObject { var pinChallenge: ONGPinChallenge? - var customChallange: ONGCustomAuthFinishAuthenticationChallenge? var loginCompletion: ((Result) -> Void)? - - unowned var pinHandler: PinConnectorToPinHandler? - func handlePin(pin: String?) { - if let _pin = pin { - if let _cc = customChallange { - _cc.sender.respond(withData: _pin, challenge: _cc) - } - if let _pc = pinChallenge { - _pc.sender.respond(withPin: _pin, challenge: _pc) - } - } else { - if let _cc = customChallange { - _cc.sender.cancel(_cc, underlyingError: nil) - } - if let _pc = pinChallenge { - _pc.sender.cancel(_pc) - } + func handlePin(pin: String) { + //FIXME: add a completion handler and errors for in progress + if let pinChallenge = pinChallenge { + pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) } } - fileprivate func mapErrorFromCustomAuthChallenge(_ challenge: ONGCustomAuthFinishAuthenticationChallenge) -> SdkError? { - if let error = challenge.error, error.code != ONGAuthenticationError.customAuthenticatorFailure.rawValue { - return ErrorMapper().mapError(error) + func cancelPinAuthentication() { + //FIXME: add a completion handler and errors for in progress + if let pinChallenge = pinChallenge { + pinChallenge.sender.cancel(pinChallenge) + } + } + + func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { + pinChallenge = challenge + if let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) { + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.nextAuthenticationAttempt, error: pinError) } else { - return nil + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.openAuth, error: nil) } } + + func handleDidAuthenticateUser() { + pinChallenge = nil + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.closeAuth, error: nil) + } + + func handleDidFailToAuthenticateUser() { + guard pinChallenge != nil else { return } + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.closeAuth, error: nil) + pinChallenge = nil + } } -//MARK: - -extension LoginHandler : BridgeToLoginHandlerProtocol { +extension LoginHandler { func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (Result) -> Void) { loginCompletion = completion ONGUserClient.sharedInstance().authenticateUser(profile, authenticator: authenticator, delegate: self) } } -//MARK: - extension LoginHandler: ONGAuthenticationDelegate { func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge) { - pinChallenge = challenge - let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) - - if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue, challenge.previousFailureCount < challenge.maxFailureCount { // 9009 - pinHandler?.handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) - return - } - - pinHandler?.handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) - - guard let pinError = pinError else { return } - guard challenge.maxFailureCount == challenge.previousFailureCount else { - return - } - - pinHandler?.closeFlow() - pinHandler?.onCancel() - - loginCompletion?(.failure((FlutterError(pinError)))) + handleDidReceiveChallenge(challenge) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishAuthenticationChallenge) { - // TODO: Will need to check it in the future - - customChallange = challenge - - let customError = mapErrorFromCustomAuthChallenge(challenge) - pinHandler?.handleFlowUpdate(PinFlow.authentication, customError, receiver: self) - - guard let _ = customError else { return } - - pinHandler?.closeFlow() - pinHandler?.onCancel() + // We don't support custom authenticators in FlutterPlugin right now. } func userClient(_ userClient: ONGUserClient, didAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, info customAuthInfo: ONGCustomInfo?) { - Logger.log("didAuthenticateUser", sender: self) - - pinChallenge = nil - customChallange = nil - + handleDidAuthenticateUser() loginCompletion?(.success( OWRegistrationResponse(userProfile: OWUserProfile(userProfile), customInfo: toOWCustomInfo(customAuthInfo)))) - pinHandler?.closeFlow() } func userClient(_ userClient: ONGUserClient, didFailToAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, error: Error) { - Logger.log("didFailToAuthenticateUser", sender: self) - - pinChallenge = nil - customChallange = nil - pinHandler?.closeFlow() + handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { loginCompletion?(.failure(FlutterError(.loginCanceled))) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift deleted file mode 100644 index 81916507..00000000 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ /dev/null @@ -1,230 +0,0 @@ -import OneginiSDKiOS -import Flutter - -protocol PinConnectorToPinHandler: AnyObject { - func onPinProvided(pin: String) - func onChangePinCalled(completion: @escaping (Result) -> Void) - func onCancel() - func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) - func closeFlow() - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) -} - -protocol PinHandlerToReceiverProtocol: class { - func handlePin(pin: String?) -} - -protocol PinNotificationReceiverProtocol: class { - func sendNotification(event: PinNotification, flow: PinFlow?, error: SdkError?) -} - -enum PINEntryMode { - case login - case registration -} - -//MARK: - -class PinHandler: NSObject { - var pinChallenge: ONGPinChallenge? - var createPinChallenge: ONGCreatePinChallenge? - var flow: PinFlow? - var mode: PINEntryMode? - var pinEntryToVerify = Array() - var changePinCompletion: ((Result) -> Void)? - - unowned var pinReceiver: PinHandlerToReceiverProtocol? - unowned var notificationReceiver: PinNotificationReceiverProtocol? - - private func processPin(pinEntry: Array) { - let pincode = pinEntry.joined() - switch mode { - case .login, .registration: - pinReceiver?.handlePin(pin: pincode) - break - case .none: - pinReceiver?.handlePin(pin: pincode) - break - } - } - - private func processCancelAction() { - mode = nil - pinReceiver?.handlePin(pin: nil) - } - - private func notifyOnError(_ error: SdkError) { - sendConnectorNotification(PinNotification.showError, flow, error) - } - - private func notifyNextAuthenticationAttempt(_ error: SdkError) { - sendConnectorNotification(PinNotification.nextAuthenticationAttempt, flow, error) - } - - private func sendConnectorNotification(_ event: PinNotification, _ flow: PinFlow?, _ error: SdkError?) { - notificationReceiver?.sendNotification(event: event, flow: flow, error: error) - } -} - -//MARK: - -extension PinHandler: PinConnectorToPinHandler{ - func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) { - if(self.flow == nil){ - self.flow = flow - pinReceiver = receiver - } - - if let _error = error { - if flow == .nextAuthenticationAttempt { - notifyNextAuthenticationAttempt(_error) - } else { - notifyOnError(_error) - } - } else { - if(mode == nil) { - var notification = PinNotification.open; - - switch flow { - case PinFlow.authentication: - mode = .login - notification = PinNotification.openAuth; - break - case PinFlow.create: - mode = .registration - notification = PinNotification.open; - break - case PinFlow.nextAuthenticationAttempt: - mode = .login - notification = PinNotification.nextAuthenticationAttempt; - break - default: - mode = .registration - notification = PinNotification.open; - break - } - - sendConnectorNotification(notification, flow, nil) - } - } - } - - func closeFlow() { - if(flow != nil){ - var closeNotification = PinNotification.close - if (mode == PINEntryMode.login) { - closeNotification = PinNotification.closeAuth - } - - mode = nil - flow = nil - sendConnectorNotification(closeNotification, flow, nil) - } - } - - func onPinProvided(pin: String) { - let characters: String = pin as String - let pinArray: Array = Array(arrayLiteral: characters) - - processPin(pinEntry: pinArray) - } - - func onChangePinCalled(completion: @escaping (Result) -> Void) { - changePinCompletion = completion - ONGUserClient.sharedInstance().changePin(self) - } - - func onCancel() { - processCancelAction() - } - - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { - ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in - guard let error = error else { - completion(.success(())) - return - } - completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) - } - } - } - -//MARK: - -extension PinHandler : PinHandlerToReceiverProtocol { - func handlePin(pin: String?) { - guard let createPinChallenge = self.createPinChallenge else { - guard let pinChallenge = self.pinChallenge else { return } - - if let _pin = pin { - pinChallenge.sender.respond(withPin: _pin, challenge: pinChallenge) - - } else { - pinChallenge.sender.cancel(pinChallenge) - } - - return - } - - if let _pin = pin { - createPinChallenge.sender.respond(withCreatedPin: _pin, challenge: createPinChallenge) - - } else { - createPinChallenge.sender.cancel(createPinChallenge) - } - } - - fileprivate func mapErrorFromCreatePinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { - if let error = challenge.error { - return ErrorMapper().mapError(error) - } else { - return nil - } - } -} - -//MARK: - ONGChangePinDelegate -extension PinHandler: ONGChangePinDelegate { - func userClient(_ userClient: ONGUserClient, didReceive challenge: ONGPinChallenge) { - Logger.log("didReceive ONGPinChallenge", sender: self) - pinChallenge = challenge - let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) - - if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue, challenge.previousFailureCount < challenge.maxFailureCount { // 9009 - handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) - return - } - - handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) - } - - func userClient(_: ONGUserClient, didReceive challenge: ONGCreatePinChallenge) { - Logger.log("didReceive ONGCreatePinChallenge", sender: self) - pinChallenge = nil - closeFlow() - createPinChallenge = challenge - let pinError = mapErrorFromCreatePinChallenge(challenge) - handleFlowUpdate(PinFlow.create, pinError, receiver: self) - } - - func userClient(_: ONGUserClient, didFailToChangePinForUser _: ONGUserProfile, error: Error) { - Logger.log("didFailToChangePinForUser", sender: self) - pinChallenge = nil - createPinChallenge = nil - closeFlow() - - let mappedError = ErrorMapper().mapError(error) - - if error.code == ONGGenericError.actionCancelled.rawValue { - changePinCompletion?(.failure(FlutterError(.changingPinCancelled))) - } else if error.code == ONGGenericError.userDeregistered.rawValue { - changePinCompletion?(.failure(FlutterError(mappedError))) - } else { - changePinCompletion?(.failure(FlutterError(mappedError))) - } - } - - func userClient(_: ONGUserClient, didChangePinForUser _: ONGUserProfile) { - Logger.log("didChangePinForUser", sender: self) - createPinChallenge = nil - closeFlow() - changePinCompletion?(.success(())) - } -} diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 61b75461..a81c7f85 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -1,20 +1,14 @@ import OneginiSDKiOS -protocol RegistrationConnectorToHandlerProtocol: RegistrationHandlerToPinHanlderProtocol { +protocol RegistrationConnectorToHandlerProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func processRedirectURL(url: String, webSignInType: Int) -> Result func cancelBrowserRegistration() - func deregister(profileId: String, completion: @escaping (Result) -> Void) - func identityProviders() -> Array func submitCustomRegistrationSuccess(_ data: String?) func cancelCustomRegistration(_ error: String) func currentChallenge() -> ONGCustomRegistrationChallenge? } -protocol RegistrationHandlerToPinHanlderProtocol: class { - var pinHandler: PinConnectorToPinHandler? { get set } -} - protocol CustomRegistrationNotificationReceiverProtocol: class { func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) } @@ -24,24 +18,23 @@ enum WebSignInType: Int { case safari } -class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, PinHandlerToReceiverProtocol, RegistrationHandlerToPinHanlderProtocol { +class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { var createPinChallenge: ONGCreatePinChallenge? var browserRegistrationChallenge: ONGBrowserRegistrationChallenge? var customRegistrationChallenge: ONGCustomRegistrationChallenge? var browserConntroller: BrowserHandlerProtocol? - var deregisterUserHandler = DeregisterUserHandler() + var signUpCompletion: ((Result) -> Void)? - unowned var pinHandler: PinConnectorToPinHandler? - unowned var customNotificationReceiver: CustomRegistrationNotificationReceiverProtocol? - - //MARK:- + + // Should not be needed func currentChallenge() -> ONGCustomRegistrationChallenge? { return self.customRegistrationChallenge } + // FIXME: why do we need this? func identityProviders() -> Array { var list = Array(ONGUserClient.sharedInstance().identityProviders()) @@ -100,13 +93,40 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, Pi createPinChallenge.sender.cancel(createPinChallenge) } } - - fileprivate func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { - if let error = challenge.error { - return ErrorMapper().mapError(error) + + func cancelPinRegistration() { + // FIXME: add completion here and error if createPin not in progress + guard let createPinChallenge = self.createPinChallenge else { return } + createPinChallenge.sender.cancel(createPinChallenge) + } + + + func handleDidReceivePinRegistrationChallenge(_ challenge: ONGCreatePinChallenge) { + createPinChallenge = challenge + if let pinError = mapErrorFromPinChallenge(challenge) { + // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.showError, error: pinError) } else { - return nil + // FIXME: we should be sending the pin length here. + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.open, error: nil) + } + } + + func handleDidFailToRegister() { + if (createPinChallenge == nil && customRegistrationChallenge == nil && browserRegistrationChallenge == nil) { + return } + createPinChallenge = nil + customRegistrationChallenge = nil + browserRegistrationChallenge = nil + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.close, error: nil) + } + + func handleDidRegisterUser() { + createPinChallenge = nil + customRegistrationChallenge = nil + browserRegistrationChallenge = nil + BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.close, error: nil) } private func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) { @@ -127,10 +147,6 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) } - - func deregister(profileId: String, completion: @escaping (Result) -> Void) { - deregisterUserHandler.deregister(profileId: profileId, completion: completion) - } func processRedirectURL(url: String, webSignInType: Int) -> Result { let webSignInType = WebSignInType(rawValue: webSignInType) ?? .insideApp @@ -178,17 +194,11 @@ extension RegistrationHandler: ONGRegistrationDelegate { func userClient(_: ONGUserClient, didReceivePinRegistrationChallenge challenge: ONGCreatePinChallenge) { Logger.log("didReceivePinRegistrationChallenge ONGCreatePinChallenge", sender: self) - createPinChallenge = challenge - let pinError = mapErrorFromPinChallenge(challenge) - pinHandler?.handleFlowUpdate(.create, pinError, receiver: self) + handleDidReceivePinRegistrationChallenge(challenge) } func userClient(_ userClient: ONGUserClient, didRegisterUser userProfile: ONGUserProfile, identityProvider: ONGIdentityProvider, info: ONGCustomInfo?) { - Logger.log("didRegisterUser", sender: self) - createPinChallenge = nil - customRegistrationChallenge = nil - pinHandler?.closeFlow() - + handleDidRegisterUser() signUpCompletion?(.success( OWRegistrationResponse(userProfile: OWUserProfile(userProfile), customInfo: toOWCustomInfo(info)))) @@ -213,11 +223,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { } func userClient(_ userClient: ONGUserClient, didFailToRegisterWith identityProvider: ONGIdentityProvider, error: Error) { - Logger.log("didFailToRegisterWithError", sender: self) - createPinChallenge = nil - customRegistrationChallenge = nil - pinHandler?.closeFlow() - + handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { signUpCompletion?(.failure(FlutterError(.registrationCancelled))) } else { @@ -238,4 +244,11 @@ extension RegistrationHandler: ONGRegistrationDelegate { } } +fileprivate func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { + if let error = challenge.error { + return ErrorMapper().mapError(error) + } else { + return nil + } +} diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index 4c25554a..6f6edc5f 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -5,6 +5,7 @@ import Flutter extension OneginiModuleSwift { public func otpResourceCodeConfirmation(code: String?, callback: @escaping FlutterResult) { + // FIXME: Check what's going on here, why is custom registration challange put in mobile auth bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleOTPMobileAuth(code ?? "", customRegistrationChallenge: bridgeConnector.toRegistrationConnector.registrationHandler.currentChallenge()) { (_ , error) -> Void in @@ -31,6 +32,7 @@ extension OneginiModuleSwift { } private func handleQRCode(_ code: String?, callback: @escaping FlutterResult) { + // FIXME: Check what's going on here, why is custom registration challange put in mobile auth let challenge = bridgeConnector.toRegistrationConnector.registrationHandler.currentChallenge() var handleMobileAuthConfirmation = false diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index d8ff58da..643684e7 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -3,23 +3,37 @@ import OneginiSDKiOS import Flutter extension OneginiModuleSwift { + + func pinAcceptAuthenticationRequest(_ pin: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toLoginHandler.handlePin(pin: pin) + } + + func pinDenyAuthenticationRequest(_ completion: @escaping (Result) -> Void) { + bridgeConnector.toLoginHandler.cancelPinAuthentication() + } - func cancelPinAuth() { - bridgeConnector.toPinHandlerConnector.pinHandler.onCancel() + func pinAcceptRegistrationRequest(_ pin: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationConnector.registrationHandler.handlePin(pin: pin) } - - func submitPinAction(_ flow: String, action: String, pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toPinHandlerConnector.handlePinAction(flow, action, pin) - } + + func pinDenyRegistrationRequest(_ completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationConnector.registrationHandler.cancelPinRegistration() + } + func changePin(completion: @escaping (Result) -> Void) { - bridgeConnector.toPinHandlerConnector.pinHandler.onChangePinCalled(completion: completion) + bridgeConnector.toChangePinHandler.changePin(completion: completion) } func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in - completion(result) - }) + // FIXME: Move this out of this file + ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in + guard let error = error else { + completion(.success(())) + return + } + completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) + } } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 483af179..755a1883 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -65,7 +65,6 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { - func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? @@ -109,29 +108,25 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.cancelPinAuth() + OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest(completion) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.authentication.rawValue, action: PinAction.provide.rawValue, pin: pin) { result in - completion(result.mapError{$0}) - } + OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin, completion: completion) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.cancelPinAuth() + OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest(completion) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitPinAction(PinFlow.create.rawValue, action: PinAction.provide.rawValue, pin: pin) { result in - completion(result.mapError{$0}) - } + OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin, completion: completion) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 completion(.success(())) } diff --git a/lib/user_client.dart b/lib/user_client.dart index b3a5e533..6a8c6936 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -93,10 +93,7 @@ class UserClient { BuildContext? context, ) async { Onegini.instance.setEventContext(context); - - // todo use api once the branch is merged that puts this in an usecase on android - // await api.changePin(); - await Onegini.instance.channel.invokeMethod(Constants.changePin); + await api.changePin(); } /// Registers authenticator from [getNotRegisteredAuthenticators] list. From 8232a156b572cf01c469c80ef79f07b6914531a8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 11:49:54 +0100 Subject: [PATCH 119/364] FP-49: Use pigeon api for validatePin --- lib/user_client.dart | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index 6a8c6936..765849f3 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -168,18 +168,7 @@ class UserClient { /// todo removed boolean return update docu Future validatePinWithPolicy(String pin) async { - // todo use api once the branch is merged that puts this in an usecase on android - // await api.validatePinWithPolicy(pin); - try { - var success = await Onegini.instance.channel.invokeMethod( - Constants.validatePinWithPolicy, {'pin': pin}); - return success ?? false; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + await api.validatePinWithPolicy(pin); } /// todo removed boolean return update docu From e52869c3c66848a39dab9c2c14590114a35d0724 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 11:50:13 +0100 Subject: [PATCH 120/364] FP-49: Update some error handling for different pin flows --- example/lib/screens/pin_request_screen.dart | 34 ++++++++++----------- example/lib/screens/user_screen.dart | 15 ++++++--- 2 files changed, 27 insertions(+), 22 deletions(-) diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index e45f2ce6..d8f48258 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -83,24 +83,22 @@ class _PinRequestScreenState extends State { ); } } else { - await Onegini.instance.userClient - .validatePinWithPolicy(pin) - .catchError((error) { - if (error is PlatformException) { - clearAllDigits(); - showFlutterToast(error.message); - } - }); - Navigator.of(context) - ..pop() - ..push( - MaterialPageRoute( - builder: (context) => PinRequestScreen( - confirmation: true, - previousCode: pin, - customAuthenticator: this.widget.customAuthenticator, - )), - ); + try { + await Onegini.instance.userClient.validatePinWithPolicy(pin); + Navigator.of(context) + ..pop() + ..push( + MaterialPageRoute( + builder: (context) => PinRequestScreen( + confirmation: true, + previousCode: pin, + customAuthenticator: this.widget.customAuthenticator, + )), + ); + } on PlatformException catch (error) { + clearAllDigits(); + showFlutterToast(error.message); + } } } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6bf23872..bb9f3f79 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -173,11 +173,18 @@ class _UserScreenState extends State with RouteAware { Onegini.instance.userClient.changePin(context).catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); + // FIXME: this should be extracted into a seperate method and should also use constants (dont exist yet) + if (error.code == "8002" || + error.code == "9002" || + error.code == "9003" || + error.code == "9010" || + error.code == "10012") { + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => LoginScreen()), + ); + } } - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => LoginScreen()), - ); }); } From 44c10fab5ba1de45b9e9cab7760d828654f27726 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 12:12:56 +0100 Subject: [PATCH 121/364] FP-49: Add Errors for auth/registration not in progress in ios/android --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 4 +- .../NativeBridge/Errors/ErrorMapper.swift | 62 +++++++++---------- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index c4511060..9bcbae64 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -7,9 +7,12 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + + REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), USER_NOT_AUTHENTICATED_IMPLICITLY(8035, "The requested action requires you to be authenticated implicitly"), METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), ARGUMENT_NOT_CORRECT(8036, "The passed argument is not correct"), + AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), @@ -21,5 +24,4 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), - REGISTRATION_NOT_IN_PROGRESS(8034, "No registration in progress for the given Identity Provider"), } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 10e2b7db..37fc7936 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -8,8 +8,10 @@ enum OneWelcomeWrapperError: Int { case authenticatorNotFound = 8004 case httpRequestError = 8011 case errorCodeHttpRequest = 8013 + case registrationNotInProgress = 8034 case unauthenticatedImplicitly = 8035 case methodArgumentNotFound = 8036 + case authenticationNotInProgress = 8037 // iOS only case providedUrlIncorrect = 8014 @@ -31,64 +33,62 @@ enum OneWelcomeWrapperError: Int { case authenticatorRegistrationCancelled = 8031 func message() -> String { - var message = "" - switch self { case .genericError: - message = "Something went wrong." + return "Something went wrong." case .userProfileDoesNotExist: - message = "The requested User profile does not exist." + return "The requested User profile does not exist." case .noUserProfileIsAuthenticated: - message = "There is currently no User Profile authenticated." + return "There is currently no User Profile authenticated." case .authenticatorNotFound: - message = "The requested authenticator is not found." + return "The requested authenticator is not found." case .providedUrlIncorrect: - message = "Provided url is incorrect." + return "Provided url is incorrect." case .enrollmentFailed: - message = "Enrollment failed. Please try again or contact maintainer." + return "Enrollment failed. Please try again or contact maintainer." case .loginCanceled: - message = "Login cancelled." + return "Login cancelled." case .authenticationCancelled: - message = "Authentication cancelled." + return "Authentication cancelled." case .authenticatorDeregistrationCancelled: - message = "Authenticator deregistration cancelled." + return "Authenticator deregistration cancelled." case .changingPinCancelled: - message = "Changing pin cancelled." + return "Changing pin cancelled." case .registrationCancelled: - message = "Registration cancelled." + return "Registration cancelled." case .cantHandleOTP: - message = "Can't handle otp authentication request." + return "Can't handle otp authentication request." case .incorrectResourcesAccess: - message = "Incorrect access to resources." + return "Incorrect access to resources." case .authenticatorNotRegistered: - message = "This authenticator is not registered." + return "This authenticator is not registered." case .failedToParseData: - message = "Failed to parse data." + return "Failed to parse data." case .responseIsNull: - message = "Response doesn't contain data." + return "Response doesn't contain data." case .authenticatorIdIsNull: - message = "Authenticator ID is empty." + return "Authenticator ID is empty." case .emptyInputValue: - message = "Empty input value." + return "Empty input value." case .errorCodeHttpRequest: - message = "OneWelcome: HTTP Request failed. Check Response for more info." + return "OneWelcome: HTTP Request failed. Check Response for more info." case .httpRequestError: - message = "OneWelcome: HTTP Request failed. Check iosCode and iosMessage for more info." + return "OneWelcome: HTTP Request failed. Check iosCode and iosMessage for more info." case .unsupportedPinAction: - message = "Unsupported pin action. Contact SDK maintainer." + return "Unsupported pin action. Contact SDK maintainer." case .unsupportedCustomRegistrationAction: - message = "Unsupported custom registration action. Contact SDK maintainer." + return "Unsupported custom registration action. Contact SDK maintainer." case .authenticatorRegistrationCancelled: - message = "The authenticator-registration was cancelled." + return "The authenticator-registration was cancelled." case .unauthenticatedImplicitly: - message = "The requested action requires you to be authenticated implicitly" + return "The requested action requires you to be authenticated implicitly" case .methodArgumentNotFound: - message = "The passed argument from Flutter could not be found" - default: - message = "Something went wrong." + return "The passed argument from Flutter could not be found" + case .registrationNotInProgress: + return "Registration is currently not in progress" + case .authenticationNotInProgress: + return "Authentication is currently not in progress" } - - return message } } From d263470952341cba79804d19fcffb1ffbe02ae70 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 13:24:58 +0100 Subject: [PATCH 122/364] FP-49: Don't throw custom error for cancel changePin --- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 7 ++----- .../NativeBridge/Handlers/ChangePinHandler.swift | 10 ++-------- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 37fc7936..49de273d 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -18,7 +18,6 @@ enum OneWelcomeWrapperError: Int { case loginCanceled = 8015 case enrollmentFailed = 8016 case authenticationCancelled = 8017 - case changingPinCancelled = 8018 case registrationCancelled = 8020 case cantHandleOTP = 8021 case incorrectResourcesAccess = 8022 @@ -52,8 +51,6 @@ enum OneWelcomeWrapperError: Int { return "Authentication cancelled." case .authenticatorDeregistrationCancelled: return "Authenticator deregistration cancelled." - case .changingPinCancelled: - return "Changing pin cancelled." case .registrationCancelled: return "Registration cancelled." case .cantHandleOTP: @@ -93,7 +90,7 @@ enum OneWelcomeWrapperError: Int { } class ErrorMapper { - func mapError(_ error: Error, pinChallenge: ONGPinChallenge? = nil, customInfo: ONGCustomInfo? = nil) -> SdkError { + func mapError(_ error: Error) -> SdkError { Logger.log("Error domain: \(error.domain)") return SdkError(code: error.code, errorDescription: error.localizedDescription) @@ -105,7 +102,7 @@ class ErrorMapper { guard let maxAttempts = challenge?.maxFailureCount, let previousCount = challenge?.previousFailureCount, maxAttempts != previousCount else { - return ErrorMapper().mapError(error, pinChallenge: challenge) + return SdkError(code: error.code, errorDescription: error.localizedDescription) } return SdkError(code: error.code, errorDescription: "Failed attempts", info: ["failedAttempts": previousCount, "maxAttempts": maxAttempts]) } else { diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 9b46d6d2..9dcb4d99 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -28,19 +28,13 @@ extension ChangePinHandler: ONGChangePinDelegate { loginHandler.handleDidAuthenticateUser() registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } - + func userClient(_: ONGUserClient, didFailToChangePinForUser _: ONGUserProfile, error: Error) { loginHandler.handleDidFailToAuthenticateUser() registrationHandler.handleDidFailToRegister() - // FIXME: Clearly we already have an error for canceling pin, so why do we need to create our own here? - // Fixing this could probably remove all those lines and just pass the Error directly. let mappedError = ErrorMapper().mapError(error) - if error.code == ONGGenericError.actionCancelled.rawValue { - changePinCompletion?(.failure(FlutterError(.changingPinCancelled))) - } else { - changePinCompletion?(.failure(FlutterError(mappedError))) - } + changePinCompletion?(.failure(FlutterError(mappedError))) changePinCompletion = nil } From 6d41c613e5942000de83b9591a6c586b0afb348f Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 14:27:38 +0100 Subject: [PATCH 123/364] FP-49: Remove some logic for custom authenticators We don't support custom authenticators, so let's not have code for it, this commit removes that :^) --- .../Handlers/AuthenticatorsHandler.swift | 27 +++---------------- 1 file changed, 4 insertions(+), 23 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 0405cfe4..c865789c 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -125,30 +125,15 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge) { Logger.log("[AUTH] userClient didReceive ONGPinChallenge", sender: self) - - pinChallenge = challenge - let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) - - if let error = pinError, error.code == ONGAuthenticationError.invalidPin.rawValue, challenge.previousFailureCount < challenge.maxFailureCount { // 9009 -// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.nextAuthenticationAttempt, error, receiver: self) - return - } - -// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.authentication, pinError, receiver: self) + BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishRegistrationChallenge) { - Logger.log("[AUTH] userClient didReceive ONGCustomAuthFinishRegistrationChallenge", sender: self) - // TODO: Will need to check it in the future - - registrationCompletion?(.success(())) - customAuthChallenge = challenge -// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) + // We currently don't support custom authenticators } func userClient(_: ONGUserClient, didFailToRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender:self) -// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) } else { @@ -159,12 +144,11 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) + BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() registrationCompletion?(.success(())) -// BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() } } -//MARK: - ONGAuthenticatorDeregistrationDelegate extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { func userClient(_: ONGUserClient, didDeregister _: ONGAuthenticator, forUser _: ONGUserProfile) { Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) @@ -172,14 +156,11 @@ extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthDeregistrationChallenge) { - Logger.log("[AUTH] userClient didReceive ONGCustomAuthDeregistrationChallenge", sender: self) - - deregistrationCompletion?(.success(())) + // We currently don't support custom authenticators } func userClient(_: ONGUserClient, didFailToDeregister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) - //BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() if error.code == ONGGenericError.actionCancelled.rawValue { deregistrationCompletion?(.failure(FlutterError(.authenticatorDeregistrationCancelled))) } else { From 56e6ffb7ec25229a4dcaa28cc7e85e304b7fd927 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 10 Mar 2023 14:28:22 +0100 Subject: [PATCH 124/364] FP-49: iOS: Make pin submit/cancel reject if not in progress Previously the wrapper did not care if auth/registration was in progress when submitting/canceling pin. This commit adds that functionality for these methods. --- .../NativeBridge/Handlers/LoginHandler.swift | 20 +++++++++------- .../Handlers/RegistrationHandler.swift | 23 +++++++++--------- .../OneginiModuleSwift+Pin.swift | 16 ++++++------- ios/Classes/SwiftOneginiPlugin.swift | 24 +++++++++---------- 4 files changed, 44 insertions(+), 39 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 03be1d28..dd9556d0 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -5,18 +5,22 @@ class LoginHandler: NSObject { var pinChallenge: ONGPinChallenge? var loginCompletion: ((Result) -> Void)? - func handlePin(pin: String) { - //FIXME: add a completion handler and errors for in progress - if let pinChallenge = pinChallenge { - pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) + func handlePin(pin: String, completion: (Result) -> Void) { + guard let pinChallenge = pinChallenge else { + completion(.failure(FlutterError(.authenticationNotInProgress))) + return } + pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) + completion(.success(())) } - func cancelPinAuthentication() { - //FIXME: add a completion handler and errors for in progress - if let pinChallenge = pinChallenge { - pinChallenge.sender.cancel(pinChallenge) + func cancelPinAuthentication(completion: (Result) -> Void) { + guard let pinChallenge = pinChallenge else { + completion(.failure(FlutterError(.authenticationNotInProgress))) + return } + pinChallenge.sender.cancel(pinChallenge) + completion(.success(())) } func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index a81c7f85..73986aca 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -83,21 +83,22 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { browserRegistrationChallenge.sender.respond(with: url, challenge: browserRegistrationChallenge) } - func handlePin(pin: String?) { - guard let createPinChallenge = self.createPinChallenge else { return } - - if let _pin = pin { - createPinChallenge.sender.respond(withCreatedPin: _pin, challenge: createPinChallenge) - - } else { - createPinChallenge.sender.cancel(createPinChallenge) + func handlePin(pin: String, completion: (Result) -> Void) { + guard let createPinChallenge = createPinChallenge else { + completion(.failure(FlutterError(.registrationNotInProgress))) + return } + createPinChallenge.sender.respond(withCreatedPin: pin, challenge: createPinChallenge) + completion(.success(())) } - func cancelPinRegistration() { - // FIXME: add completion here and error if createPin not in progress - guard let createPinChallenge = self.createPinChallenge else { return } + func cancelPinRegistration(completion: (Result) -> Void) { + guard let createPinChallenge = self.createPinChallenge else { + completion(.failure(FlutterError(.registrationNotInProgress))) + return + } createPinChallenge.sender.cancel(createPinChallenge) + completion(.success(())) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 643684e7..e3acb86b 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -4,20 +4,20 @@ import Flutter extension OneginiModuleSwift { - func pinAcceptAuthenticationRequest(_ pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toLoginHandler.handlePin(pin: pin) + func pinAcceptAuthenticationRequest(_ pin: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toLoginHandler.handlePin(pin: pin, completion: completion) } - func pinDenyAuthenticationRequest(_ completion: @escaping (Result) -> Void) { - bridgeConnector.toLoginHandler.cancelPinAuthentication() + func pinDenyAuthenticationRequest(_ completion: @escaping (Result) -> Void) { + bridgeConnector.toLoginHandler.cancelPinAuthentication(completion: completion) } - func pinAcceptRegistrationRequest(_ pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toRegistrationConnector.registrationHandler.handlePin(pin: pin) + func pinAcceptRegistrationRequest(_ pin: String, completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationConnector.registrationHandler.handlePin(pin: pin, completion: completion) } - func pinDenyRegistrationRequest(_ completion: @escaping (Result) -> Void) { - bridgeConnector.toRegistrationConnector.registrationHandler.cancelPinRegistration() + func pinDenyRegistrationRequest(_ completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationConnector.registrationHandler.cancelPinRegistration(completion: completion) } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 755a1883..276aed7c 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -108,27 +108,27 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest(completion) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest() { result in + completion(result.mapError{$0}) + } } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin, completion: completion) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin) { result in + completion(result.mapError{$0}) + } } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest(completion) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest() { result in + completion(result.mapError{$0}) + } } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin, completion: completion) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin) { result in + completion(result.mapError{$0}) + } } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { From 7e9498a578667e7753986687ef417b98a94f217c Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 13 Mar 2023 14:04:23 +0100 Subject: [PATCH 125/364] fp-20 process feedback --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 39 +---------- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 - .../sdk/flutter/OneginiMethodsWrapper.kt | 1 - .../mobile/sdk/flutter/OneginiPlugin.kt | 11 ---- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 3 - .../mobile/sdk/flutter/PigeonInterface.kt | 65 ++++++++++++------- .../mobile/sdk/flutter/helpers/SdkError.kt | 4 +- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 20 ------ .../providers/CustomRegistrationActionImpl.kt | 7 +- .../CustomTwoStepRegistrationActionImpl.kt | 6 +- .../AuthenticateUserImplicitlyUseCase.kt | 1 - .../useCases/AuthenticateUserUseCase.kt | 14 +--- .../DeregisterAuthenticatorUseCase.kt | 14 +--- .../useCases/GetAllAuthenticatorsUseCase.kt | 19 +----- .../useCases/GetIdentityProvidersUseCase.kt | 11 +--- .../GetNotRegisteredAuthenticatorsUseCase.kt | 21 +----- .../GetRegisteredAuthenticatorsUseCase.kt | 19 +----- .../useCases/GetUserProfilesUseCase.kt | 20 +----- .../useCases/RegisterAuthenticatorUseCase.kt | 16 +---- .../flutter/useCases/RegistrationUseCase.kt | 16 +---- .../SetPreferredAuthenticatorUseCase.kt | 16 +---- .../mobile/sdk/ChangePinUseCaseTests.kt | 3 - .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 1 - ...NotRegisteredAuthenticatorsUseCaseTests.kt | 1 - ios/Classes/Pigeon.swift | 16 ----- ios/Classes/SwiftOneginiPlugin.swift | 8 --- lib/pigeon.dart | 27 -------- lib/user_client.dart | 19 +----- pigeons/onewelcome_pigeon_interface.dart | 4 -- 29 files changed, 73 insertions(+), 330 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 5843be23..c1b51366 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -5,17 +5,9 @@ import android.util.Patterns import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler -import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler -import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError -import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError -import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import com.onegini.mobile.sdk.flutter.helpers.MobileAuthenticationObject import com.onegini.mobile.sdk.flutter.helpers.SdkError import io.flutter.plugin.common.MethodCall @@ -39,6 +31,7 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { + // TODO: Move remaining methods to pigeon; https://onewelcome.atlassian.net/browse/FP-71 Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) // OTP @@ -50,37 +43,7 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: Constants.METHOD_GET_IMPLICIT_RESOURCE -> oneginiMethodsWrapper.getImplicitResource(call, result) Constants.METHOD_GET_UNAUTHENTICATED_RESOURCE -> oneginiMethodsWrapper.getUnauthenticatedResource(call, result) - // Other - Constants.METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON -> getAppToWebSingleSignOn(call.argument("url"), result, client) - else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } - - fun getAppToWebSingleSignOn(url: String?, result: MethodChannel.Result, oneginiClient: OneginiClient) { - if (url == null) { - SdkError(URL_CANT_BE_NULL).flutterError(result) - return - } - if (!Patterns.WEB_URL.matcher(url).matches()) { - SdkError(MALFORMED_URL).flutterError(result) - return - } - val targetUri: Uri = Uri.parse(url) - oneginiClient.userClient.getAppToWebSingleSignOn( - targetUri, - object : OneginiAppToWebSingleSignOnHandler { - override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { - result.success(Gson().toJson(mapOf("token" to oneginiAppToWebSingleSignOn.token, "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString()))) - } - - override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { - SdkError( - code = oneginiSingleSignOnError.errorType, - message = oneginiSingleSignOnError.message - ).flutterError(result) - } - } - ) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index c869e221..13c00a71 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -9,7 +9,6 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), USER_NOT_AUTHENTICATED_IMPLICITLY(8035, "The requested action requires you to be authenticated implicitly"), METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), - ARGUMENT_NOT_CORRECT(8036, "The passed argument is not correct"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 9f1d657e..3f641c53 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -17,7 +17,6 @@ class OneginiMethodsWrapper @Inject constructor( private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, private val resourceHelper: ResourceHelper, private val startAppUseCase: StartAppUseCase, - private val validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase, ) { fun cancelBrowserRegistration() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 33d4d674..2c4d4aa2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -19,23 +19,12 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { private lateinit var channel: MethodChannel private lateinit var eventChannel: EventChannel - @Inject - lateinit var oneginiSDK: OneginiSDK - -// @Inject -// lateinit var nativeApi: NativeCallFlutterApi - @Inject lateinit var onMethodCallMapper: OnMethodCallMapper override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { // Pigeon setup UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) - // Reference Example code for when we implement the event callbacks using flutter -// nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) - // fixme what is the new way to do this? -// val oneginiSDK = OneginiSDK(nativeApi) - val component = DaggerFlutterOneWelcomeSdkComponent.builder() .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext)) .build() diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index 96314911..dbd78329 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -3,7 +3,6 @@ package com.onegini.mobile.sdk.flutter import android.content.Context import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.client.OneginiClientBuilder -import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithPushFingerprintRequestHandler import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel import com.onegini.mobile.sdk.flutter.handlers.* import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -16,7 +15,6 @@ import com.onegini.mobile.sdk.flutter.providers.CustomTwoStepRegistrationActionI import io.flutter.plugin.common.MethodChannel import java.util.concurrent.TimeUnit import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import javax.inject.Inject import javax.inject.Singleton @@ -29,7 +27,6 @@ class OneginiSDK @Inject constructor( private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler, private val createPinRequestHandler: PinRequestHandler, private val mobileAuthWithOtpRequestHandler: MobileAuthOtpRequestHandler, -// private var nativeApi: NativeCallFlutterApi, ){ val oneginiClient: OneginiClient diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index fcebbdff..62e032dd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,6 +1,10 @@ package com.onegini.mobile.sdk.flutter -import com.onegini.mobile.sdk.flutter.constants.Constants +import android.net.Uri +import android.util.Patterns +import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError +import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler @@ -44,7 +48,6 @@ import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUse import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase import javax.inject.Inject -//private val getIdentityProvidersUseCase: GetIdentityProvidersUseCase open class PigeonInterface : UserClientApi { @Inject lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase @@ -104,15 +107,8 @@ open class PigeonInterface : UserClientApi { lateinit var changePinUseCase: ChangePinUseCase @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase - - // FIXME REMOVE ME AT THE END; Example function on how it could be initiated on Flutter send to Native - override fun fetchUserProfiles(callback: (Result>) -> Unit) { - val a = Result.success(listOf(OWUserProfile("ghalo"))) -// flutterCallback(callback, a) - -// val b = Result.failure>(SdkError(2000, "hallo")) -// flutterCallback(callback, b) - } + @Inject + lateinit var oneginiSDK: OneginiSDK override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { registrationUseCase(identityProviderId, scopes, callback) @@ -171,11 +167,34 @@ open class PigeonInterface : UserClientApi { } override fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO; dependent on: + // https://onewelcome.atlassian.net/browse/FP-20 + // https://onewelcome.atlassian.net/browse/FP-70 } override fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) { -// TODO("Not yet implemented") + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-62 + if (!Patterns.WEB_URL.matcher(url).matches()) { + callback(Result.failure(SdkError(OneWelcomeWrapperErrors.MALFORMED_URL).pigeonError())) + return + } + val targetUri: Uri = Uri.parse(url) + + oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( + targetUri, + object : OneginiAppToWebSingleSignOnHandler { + override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { + callback(Result.success(OWAppToWebSingleSignOn(oneginiAppToWebSingleSignOn.token, oneginiAppToWebSingleSignOn.redirectUrl.toString()))) + } + + override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { + callback(Result.failure(SdkError( + code = oneginiSingleSignOnError.errorType, + message = oneginiSingleSignOnError.message + ).pigeonError())) + } + } + ) } override fun getAccessToken(callback: (Result) -> Unit) { @@ -212,61 +231,61 @@ open class PigeonInterface : UserClientApi { } override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 FingerprintAuthenticationRequestHandler.fingerprintCallback?.fallbackToPin() callback(Result.success(Unit)) } override fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 FingerprintAuthenticationRequestHandler.fingerprintCallback?.denyAuthenticationRequest() callback(Result.success(Unit)) } override fun fingerprintAcceptAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 FingerprintAuthenticationRequestHandler.fingerprintCallback?.acceptAuthenticationRequest() callback(Result.success(Unit)) } override fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-70 MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() callback(Result.success(Unit)) } override fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-70 MobileAuthOtpRequestHandler.CALLBACK?.acceptAuthenticationRequest() callback(Result.success(Unit)) } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() callback(Result.success(Unit)) } override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) callback(Result.success(Unit)) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 PinRequestHandler.CALLBACK?.denyAuthenticationRequest() callback(Result.success(Unit)) } override fun pinAcceptRegistrationRequest(pin: String, callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) callback(Result.success(Unit)) } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE + // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-74 BrowserRegistrationRequestHandler.onRegistrationCanceled() callback(Result.success(Unit)) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index b9ab64c8..3c07acbe 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -11,9 +11,9 @@ import io.flutter.plugin.common.MethodChannel import okhttp3.Response class SdkError: Exception { - val code: Int + private val code: Int override val message: String - val details: MutableMap = mutableMapOf() + private val details: MutableMap = mutableMapOf() // Only error codes constructor( diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index a7a054dc..54fd84e6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -255,7 +255,6 @@ private object UserClientApiCodec : StandardMessageCodec() { * Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface UserClientApi { - fun fetchUserProfiles(callback: (Result>) -> Unit) fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) @@ -305,25 +304,6 @@ interface UserClientApi { /** Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. */ @Suppress("UNCHECKED_CAST") fun setUp(binaryMessenger: BinaryMessenger, api: UserClientApi?) { - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fetchUserProfiles", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.fetchUserProfiles() { result: Result> -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) if (api != null) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index ee65086f..3ea3d50c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -17,9 +17,6 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - // Example Tell flutter to start this method from native -// onewelcomeEventApi.testEventFunction("customOneStepOnFinish") { } - val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) @@ -36,7 +33,6 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust override fun returnSuccess(result: String?): Result { return when (callback) { null -> { - callback = null Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } else -> { @@ -50,12 +46,11 @@ class CustomRegistrationActionImpl(private val providerId: String) : OneginiCust override fun returnError(exception: Exception?): Result { return when (callback) { null -> { - callback = null Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } else -> { - callback = null this.callback?.returnError(exception) + callback = null Result.success(Unit) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index c1be28e3..49959a3d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -25,8 +25,6 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg override fun finishRegistration(callback: OneginiCustomRegistrationCallback, customInfo: CustomInfo?) { this.callback = callback -// onewelcomeEventApi.testEventFunction("custom2stepOnFinish") { } - val data = Gson().toJson(CustomRegistrationModel(customInfo?.data.orEmpty(), customInfo?.status, providerId)) OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) } @@ -42,7 +40,6 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg override fun returnSuccess(result: String?): Result { return when (callback) { null -> { - callback = null Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } else -> { @@ -56,12 +53,11 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg override fun returnError(exception: Exception?): Result { return when (callback) { null -> { - callback = null Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } else -> { - callback = null this.callback?.returnError(exception) + callback = null Result.success(Unit) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt index b33610d1..0261a4a3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserImplicitlyUseCase.kt @@ -14,7 +14,6 @@ class AuthenticateUserImplicitlyUseCase @Inject constructor( private val getUserProfileUseCase: GetUserProfileUseCase ) { operator fun invoke(profileId: String, scopes: List?, callback: (Result) -> Unit) { - // TODO replace this logic with result val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 9d71aa4a..ffcc703d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -26,7 +26,8 @@ class AuthenticateUserUseCase @Inject constructor( return callback(Result.failure(error.pigeonError())) } - val authenticator = getRegisteredAuthenticatorById(authenticatorId, userProfile) + val authenticator = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) + .find { it.id == authenticatorId } when { authenticatorId != null && authenticator == null -> callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) @@ -34,17 +35,6 @@ class AuthenticateUserUseCase @Inject constructor( } } - private fun getRegisteredAuthenticatorById(registeredAuthenticatorsId: String?, userProfile: UserProfile): OneginiAuthenticator? { - if (registeredAuthenticatorsId == null) return null - val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - for (registeredAuthenticator in registeredAuthenticators) { - if (registeredAuthenticator.id == registeredAuthenticatorsId) { - return registeredAuthenticator - } - } - return null - } - private fun authenticate( userProfile: UserProfile, authenticator: OneginiAuthenticator?, diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt index 9d31e6ec..f0bb261b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt @@ -16,7 +16,8 @@ class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - val authenticator = getAuthenticatorById(authenticatorId, userProfile) + val authenticator = oneginiSDK.oneginiClient.userClient + .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(authenticator, object : OneginiAuthenticatorDeregistrationHandler { @@ -37,15 +38,4 @@ class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: } ) } - - private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { - var authenticator: OneginiAuthenticator? = null - val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - for (registeredAuthenticator in registeredAuthenticators) { - if (registeredAuthenticator.id == authenticatorId) { - authenticator = registeredAuthenticator - } - } - return authenticator - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt index 096ea735..b4e3e574 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt @@ -18,21 +18,8 @@ class GetAllAuthenticatorsUseCase @Inject constructor( return Result.failure(error.pigeonError()) } - val allAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - val authenticators = mutableListOf() - - for (auth in allAuthenticators) { - val authenticator = OWAuthenticator( - auth.id, - auth.name, - auth.isRegistered, - auth.isPreferred, - auth.type.toLong() - ) - - authenticators.add(authenticator) - } - - return Result.success(authenticators) + return oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) + .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } + .let { Result.success(it) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt index 3b96ee91..8cc0ef24 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetIdentityProvidersUseCase.kt @@ -8,13 +8,8 @@ import javax.inject.Singleton @Singleton class GetIdentityProvidersUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(): Result> { - val identityProviders = oneginiSDK.oneginiClient.userClient.identityProviders - val providers: MutableList = mutableListOf() - - for (identityProvider in identityProviders) { - providers.add(OWIdentityProvider(identityProvider.id, identityProvider.name)) - } - - return Result.success(providers) + return oneginiSDK.oneginiClient.userClient.identityProviders + .map { OWIdentityProvider(it.id, it.name) } + .let { Result.success(it) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt index 432c0c84..38bfa64a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt @@ -1,12 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.GsonBuilder -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel import javax.inject.Inject import javax.inject.Singleton @@ -22,19 +18,8 @@ class GetNotRegisteredAuthenticatorsUseCase @Inject constructor( return Result.failure(error.pigeonError()) } - val notRegisteredAuthenticators = oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(userProfile) - val authenticators = mutableListOf() - for (auth in notRegisteredAuthenticators) { - val authenticator = OWAuthenticator( - auth.id, - auth.name, - auth.isRegistered, - auth.isPreferred, - auth.type.toLong() - ) - - authenticators.add(authenticator) - } - return Result.success(authenticators) + return oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(userProfile) + .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } + .let { Result.success(it) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt index 08034d4e..5364408f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt @@ -18,21 +18,8 @@ class GetRegisteredAuthenticatorsUseCase @Inject constructor( return Result.failure(error.pigeonError()) } - val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - val authenticators = mutableListOf() - - for (registeredAuthenticator in registeredAuthenticators) { - val authenticator = OWAuthenticator( - registeredAuthenticator.id, - registeredAuthenticator.name, - registeredAuthenticator.isRegistered, - registeredAuthenticator.isPreferred, - registeredAuthenticator.type.toLong() - ) - - authenticators.add(authenticator) - } - - return Result.success(authenticators) + return oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) + .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } + .let { Result.success(it) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt index 09bc13b9..70088b44 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfilesUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject @@ -9,21 +8,8 @@ import javax.inject.Singleton @Singleton class GetUserProfilesUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(): Result> { - val userProfiles = oneginiSDK.oneginiClient.userClient.userProfiles - val userProfileList = getUserProfileArray(userProfiles) - return Result.success(userProfileList) - } - - private fun getUserProfileArray(userProfiles: Set?): List { - val userProfileList = mutableListOf() - - if (userProfiles != null) { - for (userProfile in userProfiles) { - if (userProfile != null) { - userProfileList.add(OWUserProfile(userProfile.profileId)) - } - } - } - return userProfileList + return oneginiSDK.oneginiClient.userClient.userProfiles + .map { OWUserProfile(it.profileId) } + .let { Result.success(it) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt index 3a49abca..b9bd715a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt @@ -17,7 +17,8 @@ class RegisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: O val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - val authenticator = getAuthenticatorById(authenticatorId, authenticatedUserProfile) + val authenticator = oneginiSDK.oneginiClient.userClient + .getAllAuthenticators(authenticatedUserProfile).find { it.id == authenticatorId } ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) oneginiSDK.oneginiClient.userClient.registerAuthenticator(authenticator, object : OneginiAuthenticatorRegistrationHandler { @@ -38,17 +39,4 @@ class RegisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: O } ) } - - private fun getAuthenticatorById(authenticatorId: String?, authenticatedUserProfile: UserProfile): OneginiAuthenticator? { - var authenticator: OneginiAuthenticator? = null - - // We don't have to check if the authenticator is already registered as the sdk will do that for us. - val allAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(authenticatedUserProfile) - for (auth in allAuthenticators) { - if (auth.id == authenticatorId) { - authenticator = auth - } - } - return authenticator - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index 721f25d6..485fefe1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -18,7 +18,8 @@ import javax.inject.Singleton @Singleton class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { - val identityProvider = getIdentityProviderById(identityProviderId) + val identityProvider = oneginiSDK.oneginiClient.userClient.identityProviders.find { it.id == identityProviderId } + if (identityProviderId != null && identityProvider == null) { callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) } @@ -28,19 +29,6 @@ class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK register(identityProvider, registerScopes, callback) } - private fun getIdentityProviderById(identityProviderId: String?): OneginiIdentityProvider? { - if (identityProviderId == null) return null - var foundIdentityProvider: OneginiIdentityProvider? = null - val identityProviders = oneginiSDK.oneginiClient.userClient.identityProviders - for (identityProvider in identityProviders) { - if (identityProvider.id == identityProviderId) { - foundIdentityProvider = identityProvider - break - } - } - return foundIdentityProvider - } - private fun register(identityProvider: OneginiIdentityProvider?, scopes: Array?, callback: (Result) -> Unit) { oneginiSDK.oneginiClient.userClient.registerUser(identityProvider, scopes, object : OneginiRegistrationHandler { override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 5da640bf..62a1f92c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -1,7 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -15,21 +13,11 @@ class SetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) - val authenticator = getAuthenticatorById(authenticatorId, userProfile) + val authenticator = oneginiSDK.oneginiClient.userClient + .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError()) oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) return Result.success(Unit) } - - private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { - var authenticator: OneginiAuthenticator? = null - val registeredAuthenticators = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - for (registeredAuthenticator in registeredAuthenticators) { - if (registeredAuthenticator.id == authenticatorId) { - authenticator = registeredAuthenticator - } - } - return authenticator - } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index b95f25fc..ed02c4bf 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -30,9 +30,6 @@ class ChangePinUseCaseTests { @Mock lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall - @Mock lateinit var callbackMock: (Result) -> Unit diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index b11b6944..6744f2b9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -4,7 +4,6 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 90b5fe39..8b34270a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -4,7 +4,6 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 46adf461..4ba2e7c9 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -241,7 +241,6 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { - func fetchUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) @@ -290,21 +289,6 @@ class UserClientApiSetup { static var codec: FlutterStandardMessageCodec { UserClientApiCodec.shared } /// Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UserClientApi?) { - let fetchUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fetchUserProfiles", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - fetchUserProfilesChannel.setMessageHandler { _, reply in - api.fetchUserProfiles() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - fetchUserProfilesChannel.setMessageHandler(nil) - } let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerUserChannel.setMessageHandler { message, reply in diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3bf0d018..d8e343eb 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -107,12 +107,4 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } } } - - // Example function for Flutter -> Native functions and how to return a response or error - func fetchUserProfiles(completion: @escaping (Result<[PigeonUserProfile], Error>) -> Void) { -// let a = .success([PigeonUserProfile(profileId: "boopios", isDefault: true)]) - completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) - -// completion(.success([PigeonUserProfile(profileId: "boopios", isDefault: true)])) - } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 1a2b65ba..b13eb0c5 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -236,33 +236,6 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future> fetchUserProfiles() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fetchUserProfiles', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as List?)!.cast(); - } - } - Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, diff --git a/lib/user_client.dart b/lib/user_client.dart index 88db0ee6..e81c20f0 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -148,24 +148,7 @@ class UserClient { /// Single sign on the user web page. Future getAppToWebSingleSignOn(String url) async { // todo use api once the branch is merged that puts this in an usecase on android - // return await api.getAppToWebSingleSignOn(url); - try { - var oneginiAppToWebSingleSignOn = await Onegini.instance.channel - .invokeMethod(Constants.getAppToWebSingleSignOn, { - 'url': url, - }); - - var oldAppToWeb = oneginiAppToWebSingleSignOnFromJson(oneginiAppToWebSingleSignOn); - var token = oldAppToWeb.token != null ? oldAppToWeb.token.toString() : ""; - var redirectUrl = oldAppToWeb.redirectUrl != null ? oldAppToWeb.redirectUrl.toString() : ""; - - return OWAppToWebSingleSignOn(token: token, redirectUrl: redirectUrl); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + return await api.getAppToWebSingleSignOn(url); } // Get Access Token diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 8740dbd8..b8f96eab 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -67,10 +67,6 @@ class OWRegistrationResponse { /// Flutter calls native @HostApi() abstract class UserClientApi { - // example function - @async - List fetchUserProfiles(); - @async OWRegistrationResponse registerUser( String? identityProviderId, List? scopes); From d8e1bc3ad4244f69b7522ad4ea78e037d0babdf9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 14 Mar 2023 17:17:59 +0100 Subject: [PATCH 126/364] FP-47 Complete rework of the resource call structure integrated with pigeon, android version --- .../mobile/sdk/flutter/OneginiPlugin.kt | 2 + .../mobile/sdk/flutter/PigeonInterface.kt | 29 +++- .../sdk/flutter/helpers/ResourceHelper.kt | 18 ++- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 140 ++++++++++++++++- .../useCases/GetResourceAnonymousUseCase.kt | 1 - .../flutter/useCases/GetResourceUseCase.kt | 1 - .../GetUnauthenticatedResourceUseCase.kt | 1 - .../useCases/ResourceRequestUseCase.kt | 138 +++++++++++++++++ .../onegini/mobile/sdk/ResourceHelperTests.kt | 5 +- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 129 ++++++++++++++++ example/lib/screens/login_screen.dart | 13 +- example/lib/screens/user_screen.dart | 10 +- ios/Classes/Pigeon.swift | 144 +++++++++++++++++- lib/model/request_details.dart | 32 ++++ lib/model/request_response.dart | 9 ++ lib/pigeon.dart | 144 +++++++++++++++++- lib/resources_methods.dart | 20 +++ pigeons/README.md | 18 +++ pigeons/onewelcome_pigeon_interface.dart | 41 ++++- 19 files changed, 862 insertions(+), 33 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt create mode 100644 lib/model/request_details.dart create mode 100644 lib/model/request_response.dart diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 2c4d4aa2..ee1d11da 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -4,6 +4,7 @@ import androidx.annotation.NonNull import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceMethodApi import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodChannel @@ -24,6 +25,7 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { // Pigeon setup UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) + ResourceMethodApi.setUp(flutterPluginBinding.binaryMessenger, this) val component = DaggerFlutterOneWelcomeSdkComponent.builder() .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext)) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 62e032dd..199b7194 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -17,7 +17,11 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceMethodApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase @@ -42,13 +46,14 @@ import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase +import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUseCase import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase import javax.inject.Inject -open class PigeonInterface : UserClientApi { +open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase @Inject @@ -108,6 +113,8 @@ open class PigeonInterface : UserClientApi { @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase @Inject + lateinit var resourceRequestUseCase: ResourceRequestUseCase + @Inject lateinit var oneginiSDK: OneginiSDK override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { @@ -289,4 +296,24 @@ open class PigeonInterface : UserClientApi { BrowserRegistrationRequestHandler.onRegistrationCanceled() callback(Result.success(Unit)) } + + override fun requestResource(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { + resourceRequestUseCase(type, details, callback) + } + + override fun getResourceAnonymous(callback: (Result) -> Unit) { + // TODO("Not yet implemented") + } + + override fun getResource(callback: (Result) -> Unit) { + // TODO("Not yet implemented") + } + + override fun getResourceImplicit(callback: (Result) -> Unit) { + // TODO("Not yet implemented") + } + + override fun getUnauthenticatedResource(callback: (Result) -> Unit) { + // TODO("Not yet implemented") + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt index 8b2cb74e..53f0c820 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt @@ -1,31 +1,45 @@ package com.onegini.mobile.sdk.flutter.helpers import com.google.gson.Gson +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_BODY import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_HEADERS import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_STATUS_CODE import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_URL +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.POST +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PUT +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PATCH +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Headers import okhttp3.Headers.Companion.toHeaders import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import java.io.IOException import java.util.Locale import javax.inject.Inject import javax.inject.Singleton import kotlin.collections.HashMap @Singleton -class ResourceHelper @Inject constructor() { - +class ResourceHelper @Inject constructor(private val oneginiSDK: OneginiSDK) { fun callRequest(okHttpClient: OkHttpClient, request: Request, result: MethodChannel.Result) { Observable.fromCallable { okHttpClient.newCall(request).execute() } .subscribeOn(Schedulers.io()) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 54fd84e6..773b9819 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -37,6 +37,33 @@ class FlutterError ( val details: Any? = null ) : Throwable() +enum class HttpRequestMethod(val raw: Int) { + GET(0), + POST(1), + PUT(2), + DELETE(3), + PATCH(4); + + companion object { + fun ofRaw(raw: Int): HttpRequestMethod? { + return values().firstOrNull { it.raw == raw } + } + } +} + +enum class ResourceRequestType(val raw: Int) { + AUTHENTICATED(0), + IMPLICIT(1), + ANONYMOUS(2), + UNAUTHENTICATED(3); + + companion object { + fun ofRaw(raw: Int): ResourceRequestType? { + return values().firstOrNull { it.raw == raw } + } + } +} + /** * Result objects * @@ -181,6 +208,62 @@ data class OWRegistrationResponse ( } } +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWRequestDetails ( + val path: String, + val method: HttpRequestMethod, + val headers: Map? = null, + val body: String? = null + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWRequestDetails { + val path = list[0] as String + val method = HttpRequestMethod.ofRaw(list[1] as Int)!! + val headers = list[2] as? Map + val body = list[3] as? String + return OWRequestDetails(path, method, headers, body) + } + } + fun toList(): List { + return listOf( + path, + method?.raw, + headers, + body, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWRequestResponse ( + val headers: Map, + val body: String, + val ok: Boolean, + val status: Long + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWRequestResponse { + val headers = list[0] as Map + val body = list[1] as String + val ok = list[2] as Boolean + val status = list[3].let { if (it is Int) it.toLong() else it as Long } + return OWRequestResponse(headers, body, ok, status) + } + } + fun toList(): List { + return listOf( + headers, + body, + ok, + status, + ) + } +} + @Suppress("UNCHECKED_CAST") private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { @@ -975,8 +1058,41 @@ interface UserClientApi { } } } +@Suppress("UNCHECKED_CAST") +private object ResourceMethodApiCodec : StandardMessageCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 128.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWRequestDetails.fromList(it) + } + } + 129.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWRequestResponse.fromList(it) + } + } + else -> super.readValueOfType(type, buffer) + } + } + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + when (value) { + is OWRequestDetails -> { + stream.write(128) + writeValue(stream, value.toList()) + } + is OWRequestResponse -> { + stream.write(129) + writeValue(stream, value.toList()) + } + else -> super.writeValue(stream, value) + } + } +} + /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface ResourceMethodApi { + fun requestResource(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) fun getResourceAnonymous(callback: (Result) -> Unit) fun getResource(callback: (Result) -> Unit) fun getResourceImplicit(callback: (Result) -> Unit) @@ -985,11 +1101,33 @@ interface ResourceMethodApi { companion object { /** The codec used by ResourceMethodApi. */ val codec: MessageCodec by lazy { - StandardMessageCodec() + ResourceMethodApiCodec } /** Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. */ @Suppress("UNCHECKED_CAST") fun setUp(binaryMessenger: BinaryMessenger, api: ResourceMethodApi?) { + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.requestResource", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + var wrapped = listOf() + val args = message as List + val typeArg = ResourceRequestType.ofRaw(args[0] as Int)!! + val detailsArg = args[1] as OWRequestDetails + api.requestResource(typeArg, detailsArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", codec) if (api != null) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt index e740a5f7..344e2f5c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import io.flutter.plugin.common.MethodCall diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt index 9da05f32..d6664c20 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import io.flutter.plugin.common.MethodCall diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt index 49df412e..28238470 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import io.flutter.plugin.common.MethodCall diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt new file mode 100644 index 00000000..221f85b3 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -0,0 +1,138 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.POST +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PUT +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PATCH +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Headers +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import java.io.IOException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { + val resourceClient = getOkHttpClient(type) + val request = buildRequest(details) + + performCall(resourceClient, request, callback) + } + + private fun getOkHttpClient(type: ResourceRequestType): OkHttpClient { + return when (type) { + ResourceRequestType.AUTHENTICATED -> oneginiSDK.oneginiClient.userClient.resourceOkHttpClient + ResourceRequestType.IMPLICIT -> oneginiSDK.oneginiClient.userClient.implicitResourceOkHttpClient + ResourceRequestType.ANONYMOUS -> oneginiSDK.oneginiClient.deviceClient.anonymousResourceOkHttpClient + ResourceRequestType.UNAUTHENTICATED -> oneginiSDK.oneginiClient.deviceClient.unauthenticatedResourceOkHttpClient + } + } + + private fun buildRequest(details: OWRequestDetails): Request { + return Request.Builder() + .url(getCompleteResourceUrl(details.path)) + .headers(getHeaders(details.headers)) + .setMethod(details) + .build() + } + + private fun getCompleteResourceUrl(path: String): String { + // TODO Add support for multiple base resource urls + val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl + + return when (path.startsWith(resourceBaseUrl)) { + true -> path + else -> resourceBaseUrl + path + } + } + + private fun getHeaders(headers: Map?): Headers { + val headerBuilder = Headers.Builder() + + headers?.entries?.forEach { + val headerKey = it.key + val headerValue = it.value + + // Pigeon 9.0.5 limits enforcing non null values in maps + if (headerKey is String && headerValue is String) { + headerBuilder.add(headerKey, headerValue) + } + } + + return headerBuilder.build() + } + + private fun Request.Builder.setMethod(details: OWRequestDetails): Request.Builder { + return when (details.method) { + GET -> { + this.get() + } + POST -> { + val body = details.body ?: "" + this.post(body.toRequestBody(null)) + } + PUT -> { + val body = details.body ?: "" + this.put(body.toRequestBody(null)) + } + PATCH -> { + val body = details.body ?: "" + this.patch(body.toRequestBody(null)) + } + DELETE -> { + this.delete(details.body?.toRequestBody()) + } + } + } + + private fun performCall(okHttpClient: OkHttpClient, request: Request, callback: (Result) -> Unit) { + okHttpClient.newCall(request).enqueue(object : Callback { + override fun onFailure(call: Call, e: IOException) { + callback( + Result.failure( + SdkError( + code = HTTP_REQUEST_ERROR.code, + message = e.message.toString() + ).pigeonError() + ) + ) + } + + override fun onResponse(call: Call, response: Response) { + // Fail on non-successful http-codes to align behaviour with iOS + if (response.code >= 400) { + callback( + Result.failure( + SdkError( + wrapperError = ERROR_CODE_HTTP_REQUEST, + httpResponse = response + ).pigeonError() + ) + ) + } else { + val owResponse = OWRequestResponse( + headers = response.headers.toMap(), + body = response.body?.string() ?: "", + ok = response.isSuccessful, + status = response.code.toLong() + ) + + callback(Result.success(owResponse)) + } + } + }) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt index 240895ed..46ab8e2d 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt @@ -34,14 +34,11 @@ class ResourceHelperTests { @Mock lateinit var callMock: MethodCall - @Spy - lateinit var resultSpy: MethodChannel.Result - lateinit var resourceHelper: ResourceHelper @Before fun setup() { - resourceHelper = ResourceHelper() +// resourceHelper = ResourceHelper() } @Test fun `should build correct url when 'path' parameter is given`() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt new file mode 100644 index 00000000..211be6f9 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -0,0 +1,129 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.client.UserClient +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType +import okhttp3.Callback +import okhttp3.Headers +import okhttp3.Response +import org.mockito.kotlin.any +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST + +import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase +import junit.framework.Assert.fail +import okhttp3.OkHttpClient +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class ResourceRequestUseCaseTests { + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var userClient: UserClient + + @Mock + lateinit var resourceOkHttpClientMock: OkHttpClient + + @Mock + lateinit var okhttp3CallMock: okhttp3.Call + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var responseMock: Response + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var resourceRequestUseCase: ResourceRequestUseCase + + @Before + fun attach() { + resourceRequestUseCase = ResourceRequestUseCase(oneginiSdk) + + whenever(oneginiSdk.oneginiClient.userClient.resourceOkHttpClient).thenReturn(resourceOkHttpClientMock) + whenever(oneginiSdk.oneginiClient.userClient.implicitResourceOkHttpClient).thenReturn(resourceOkHttpClientMock) + whenever(oneginiSdk.oneginiClient.deviceClient.anonymousResourceOkHttpClient).thenReturn(resourceOkHttpClientMock) + whenever(oneginiSdk.oneginiClient.deviceClient.unauthenticatedResourceOkHttpClient).thenReturn(resourceOkHttpClientMock) + + whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") + } + + @Test + fun `When a successful http response is send, Then the call should resolve with an OWRequestResponse containing correct information`() { + setupSuccessFullResponseMock() + whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) + argumentCaptor { + whenever( + okhttp3CallMock.enqueue(capture())).thenAnswer { + firstValue.onResponse(okhttp3CallMock, responseMock) + } + } + + resourceRequestUseCase(ResourceRequestType.IMPLICIT, OWRequestDetails("TEST", GET), callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + + val expectedResponse = OWRequestResponse(mapOf("headerKey" to "headerValue"), "responseBody", true, 200) + Assert.assertEquals(firstValue.getOrNull(), expectedResponse) + } + } + + @Test + fun `When a successful http response is send but with an error http code, Then the call should resolve with an flutter error`() { + setupErrorFullResponseMock() + whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) + argumentCaptor { + whenever( + okhttp3CallMock.enqueue(capture())).thenAnswer { + firstValue.onResponse(okhttp3CallMock, responseMock) + } + } + + resourceRequestUseCase(ResourceRequestType.IMPLICIT, OWRequestDetails("TEST", GET), callbackMock) + + argumentCaptor>().apply { + verify(callbackMock, times(1)).invoke(capture()) + + when(val error = firstValue.exceptionOrNull()) { + is FlutterError -> { + Assert.assertEquals(error.code.toInt(), ERROR_CODE_HTTP_REQUEST.code) + Assert.assertEquals(error.message, ERROR_CODE_HTTP_REQUEST.message) + Assert.assertEquals(((error.details as Map<*, *>).toMap()["response"] as Map<*, *>)["statusCode"], "400") + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) + } + } + } + + private fun setupSuccessFullResponseMock() { + whenever(responseMock.code).thenReturn(200) + whenever(responseMock.isSuccessful).thenReturn(true) + whenever(responseMock.body?.string()).thenReturn("responseBody") + val headers = Headers.Builder().add("headerKey", "headerValue").build() + whenever(responseMock.headers).thenReturn(headers) + } + + private fun setupErrorFullResponseMock() { + whenever(responseMock.code).thenReturn(400) + whenever(responseMock.isSuccessful).thenReturn(false) + val headers = Headers.Builder().add("headerKey", "headerValue").build() + whenever(responseMock.headers).thenReturn(headers) + } +} \ No newline at end of file diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 1255f834..02c294cf 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -4,8 +4,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_registration_callback.dart'; -import 'package:onegini/model/onegini_list_response.dart'; -import 'package:onegini/model/registration_response.dart'; +import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'package:onegini_example/screens/user_screen.dart'; @@ -148,11 +147,13 @@ class _LoginScreenState extends State { var userProfileId = await Onegini.instance.userClient .authenticateUserImplicitly(profileId, ["read"]); - var response = await Onegini.instance.resourcesMethods - .getResourceImplicit("user-id-decorated"); - var res = json.decode(response); + var response = await Onegini.instance.resourcesMethods.resourceRequest( + ResourceRequestType.implicit, + RequestDetails(path: "user-id-decorated", method: HttpRequestMethod.get)); - returnString = json.decode(res["body"])["decorated_user_id"]; + var res = json.decode(response.body); + + returnString =res["decorated_user_id"]; return returnString; } catch (err) { diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6bf23872..e0dd6281 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -4,7 +4,7 @@ import 'dart:convert'; import "package:collection/collection.dart"; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/model/onegini_list_response.dart'; +import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/models/application_details.dart'; @@ -413,13 +413,11 @@ class Info extends StatefulWidget { class _InfoState extends State { Future getApplicationDetails() async { - var response = ""; await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - response = await Onegini.instance.resourcesMethods - .getResourceAnonymous("application-details"); - var res = json.decode(response); - return applicationDetailsFromJson(res["body"]); + var response = await Onegini.instance.resourcesMethods.resourceRequest(ResourceRequestType.anonymous, RequestDetails(path: "application-details", method: HttpRequestMethod.get)); + var res = json.decode(response.body); + return applicationDetailsFromJson(res); } Future getClientResource() async { diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 4ba2e7c9..2d1f4a3d 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -31,6 +31,21 @@ private func wrapError(_ error: Any) -> [Any?] { ] } +enum HttpRequestMethod: Int { + case get = 0 + case post = 1 + case put = 2 + case delete = 3 + case patch = 4 +} + +enum ResourceRequestType: Int { + case authenticated = 0 + case implicit = 1 + case anonymous = 2 + case unauthenticated = 3 +} + /// Result objects /// /// Generated class from Pigeon that represents data sent in messages. @@ -176,6 +191,66 @@ struct OWRegistrationResponse { } } +/// Generated class from Pigeon that represents data sent in messages. +struct OWRequestDetails { + var path: String + var method: HttpRequestMethod + var headers: [String?: String?]? = nil + var body: String? = nil + + static func fromList(_ list: [Any?]) -> OWRequestDetails? { + let path = list[0] as! String + let method = HttpRequestMethod(rawValue: list[1] as! Int)! + let headers = list[2] as? [String?: String?] + let body = list[3] as? String + + return OWRequestDetails( + path: path, + method: method, + headers: headers, + body: body + ) + } + func toList() -> [Any?] { + return [ + path, + method.rawValue, + headers, + body, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWRequestResponse { + var headers: [String?: String?] + var body: String + var ok: Bool + var status: Int32 + + static func fromList(_ list: [Any?]) -> OWRequestResponse? { + let headers = list[0] as! [String?: String?] + let body = list[1] as! String + let ok = list[2] as! Bool + let status = list[3] as! Int32 + + return OWRequestResponse( + headers: headers, + body: body, + ok: ok, + status: status + ) + } + func toList() -> [Any?] { + return [ + headers, + body, + ok, + status, + ] + } +} + private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -851,8 +926,50 @@ class UserClientApiSetup { } } } +private class ResourceMethodApiCodecReader: FlutterStandardReader { + override func readValue(ofType type: UInt8) -> Any? { + switch type { + case 128: + return OWRequestDetails.fromList(self.readValue() as! [Any]) + case 129: + return OWRequestResponse.fromList(self.readValue() as! [Any]) + default: + return super.readValue(ofType: type) + } + } +} + +private class ResourceMethodApiCodecWriter: FlutterStandardWriter { + override func writeValue(_ value: Any) { + if let value = value as? OWRequestDetails { + super.writeByte(128) + super.writeValue(value.toList()) + } else if let value = value as? OWRequestResponse { + super.writeByte(129) + super.writeValue(value.toList()) + } else { + super.writeValue(value) + } + } +} + +private class ResourceMethodApiCodecReaderWriter: FlutterStandardReaderWriter { + override func reader(with data: Data) -> FlutterStandardReader { + return ResourceMethodApiCodecReader(data: data) + } + + override func writer(with data: NSMutableData) -> FlutterStandardWriter { + return ResourceMethodApiCodecWriter(data: data) + } +} + +class ResourceMethodApiCodec: FlutterStandardMessageCodec { + static let shared = ResourceMethodApiCodec(readerWriter: ResourceMethodApiCodecReaderWriter()) +} + /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol ResourceMethodApi { + func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) func getResourceAnonymous(completion: @escaping (Result) -> Void) func getResource(completion: @escaping (Result) -> Void) func getResourceImplicit(completion: @escaping (Result) -> Void) @@ -862,9 +979,28 @@ protocol ResourceMethodApi { /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class ResourceMethodApiSetup { /// The codec used by ResourceMethodApi. + static var codec: FlutterStandardMessageCodec { ResourceMethodApiCodec.shared } /// Sets up an instance of `ResourceMethodApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: ResourceMethodApi?) { - let getResourceAnonymousChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", binaryMessenger: binaryMessenger) + let requestResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.requestResource", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + requestResourceChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let typeArg = ResourceRequestType(rawValue: args[0] as! Int)! + let detailsArg = args[1] as! OWRequestDetails + api.requestResource(type: typeArg, details: detailsArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + requestResourceChannel.setMessageHandler(nil) + } + let getResourceAnonymousChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getResourceAnonymousChannel.setMessageHandler { _, reply in api.getResourceAnonymous() { result in @@ -879,7 +1015,7 @@ class ResourceMethodApiSetup { } else { getResourceAnonymousChannel.setMessageHandler(nil) } - let getResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResource", binaryMessenger: binaryMessenger) + let getResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResource", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getResourceChannel.setMessageHandler { _, reply in api.getResource() { result in @@ -894,7 +1030,7 @@ class ResourceMethodApiSetup { } else { getResourceChannel.setMessageHandler(nil) } - let getResourceImplicitChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", binaryMessenger: binaryMessenger) + let getResourceImplicitChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getResourceImplicitChannel.setMessageHandler { _, reply in api.getResourceImplicit() { result in @@ -909,7 +1045,7 @@ class ResourceMethodApiSetup { } else { getResourceImplicitChannel.setMessageHandler(nil) } - let getUnauthenticatedResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", binaryMessenger: binaryMessenger) + let getUnauthenticatedResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getUnauthenticatedResourceChannel.setMessageHandler { _, reply in api.getUnauthenticatedResource() { result in diff --git a/lib/model/request_details.dart b/lib/model/request_details.dart new file mode 100644 index 00000000..c87ef278 --- /dev/null +++ b/lib/model/request_details.dart @@ -0,0 +1,32 @@ +import 'package:onegini/pigeon.dart'; + +abstract class GenericRequest implements RequestPost, RequestGet { +} + +class RequestPost { + String path; + Map? headers; + HttpRequestMethod method = HttpRequestMethod.post; + String body; + + RequestPost({required this.path, required this.body, this.headers}); +} + +class RequestGet { + String path; + Map? headers; + HttpRequestMethod method = HttpRequestMethod.get; + String? body; + + RequestGet({required this.path, this.headers}); +} + +// Wrapper class for pigeon class to enforce non null map values. +class RequestDetails { + String path; + HttpRequestMethod method; + Map? headers; + String? body; + + RequestDetails({required this.path, required this.method, this.headers, this.body}); +} diff --git a/lib/model/request_response.dart b/lib/model/request_response.dart new file mode 100644 index 00000000..f3bbf4fe --- /dev/null +++ b/lib/model/request_response.dart @@ -0,0 +1,9 @@ +// Wrapper class for pigeon class to enforce non null map values. +class RequestResponse { + Map headers; + String body; + bool ok; + int status; + + RequestResponse({required this.headers, required this.body, required this.ok, required this.status}); +} diff --git a/lib/pigeon.dart b/lib/pigeon.dart index b13eb0c5..be5d846c 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -8,6 +8,21 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +enum HttpRequestMethod { + get, + post, + put, + delete, + patch, +} + +enum ResourceRequestType { + authenticated, + implicit, + anonymous, + unauthenticated, +} + /// Result objects class OWUserProfile { OWUserProfile({ @@ -177,6 +192,78 @@ class OWRegistrationResponse { } } +class OWRequestDetails { + OWRequestDetails({ + required this.path, + required this.method, + this.headers, + this.body, + }); + + String path; + + HttpRequestMethod method; + + Map? headers; + + String? body; + + Object encode() { + return [ + path, + method.index, + headers, + body, + ]; + } + + static OWRequestDetails decode(Object result) { + result as List; + return OWRequestDetails( + path: result[0]! as String, + method: HttpRequestMethod.values[result[1]! as int], + headers: (result[2] as Map?)?.cast(), + body: result[3] as String?, + ); + } +} + +class OWRequestResponse { + OWRequestResponse({ + required this.headers, + required this.body, + required this.ok, + required this.status, + }); + + Map headers; + + String body; + + bool ok; + + int status; + + Object encode() { + return [ + headers, + body, + ok, + status, + ]; + } + + static OWRequestResponse decode(Object result) { + result as List; + return OWRequestResponse( + headers: (result[0] as Map?)!.cast(), + body: result[1]! as String, + ok: result[2]! as bool, + status: result[3]! as int, + ); + } +} + class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override @@ -1046,6 +1133,34 @@ class UserClientApi { } } +class _ResourceMethodApiCodec extends StandardMessageCodec { + const _ResourceMethodApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is OWRequestDetails) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else if (value is OWRequestResponse) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return OWRequestDetails.decode(readValue(buffer)!); + case 129: + return OWRequestResponse.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + class ResourceMethodApi { /// Constructor for [ResourceMethodApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default @@ -1054,7 +1169,34 @@ class ResourceMethodApi { : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); + static const MessageCodec codec = _ResourceMethodApiCodec(); + + Future requestResource(ResourceRequestType arg_type, OWRequestDetails arg_details) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.ResourceMethodApi.requestResource', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_type.index, arg_details]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as OWRequestResponse?)!; + } + } Future getResourceAnonymous() async { final BasicMessageChannel channel = BasicMessageChannel( diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index f1b07dbb..15887fc3 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -1,10 +1,30 @@ +import 'dart:ui'; + +import 'model/request_details.dart'; +import 'model/request_response.dart'; + import 'package:flutter/services.dart'; +import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'onegini.dart'; /// The class with resources methods class ResourcesMethods { + final api = ResourceMethodApi(); + + /// Gets any type of resource + Future resourceRequest(ResourceRequestType type, RequestDetails details) async { + var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + var owResponse = await api.requestResource(type, owDetails); + + owResponse.headers.removeWhere((key, value) => key == null || value == null); + var headers = Map.from(owResponse.headers); + + return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + } + + /// Gets resources anonymously. /// /// Method requires [path] parameter. diff --git a/pigeons/README.md b/pigeons/README.md index 1413567b..b886dc63 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -29,3 +29,21 @@ We can use @FlutterApi to call functions on the dart side from the Native parts. https://github.com/flutter/flutter/issues/108531 where https://github.com/zero-li/flutter_pigeon_plugin gives a simple example project (with chines documentation) but gives a good idea on how it works as a reference. + +#### Android +This can be setup through setting the native api during the onattachengine step +``` +@Inject +lateinit var nativeApi: NativeCallFlutterApi + +onattachengine (..) { + .. + nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) + .. +} +``` + +then to call flutter from the native side you perform a: + +```// Example Tell flutter to start this method from native +onewelcomeEventApi.testEventFunction("customOneStepOnFinish") { }``` \ No newline at end of file diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index b8f96eab..040b41cc 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -64,6 +64,39 @@ class OWRegistrationResponse { OWRegistrationResponse({required this.userProfile, this.customInfo}); } +enum HttpRequestMethod { + get, + post, + put, + delete, + patch // unsure if we want to support this +} + +enum ResourceRequestType { + authenticated, + implicit, + anonymous, + unauthenticated +} + +class OWRequestDetails { + String path; + HttpRequestMethod method; + Map? headers; + String? body; + + OWRequestDetails({required this.path, required this.method, headers, body}); +} + +class OWRequestResponse { + Map headers; + String body; + bool ok; + int status; + + OWRequestResponse({required this.headers, required this.body, required this.ok, required this.status}); +} + /// Flutter calls native @HostApi() abstract class UserClientApi { @@ -77,7 +110,6 @@ abstract class UserClientApi { @async List getIdentityProviders(); - // removed boolean return @async void deregisterUser(String profileId); @@ -100,18 +132,15 @@ abstract class UserClientApi { @async void changePin(); - // changed it into void instead of boolean @async void setPreferredAuthenticator(String authenticatorId); - // changed it into void instead of boolean @async void deregisterAuthenticator(String authenticatorId); @async void registerAuthenticator(String authenticatorId); - // changed it into void instead of boolean @async void logout(); @@ -137,7 +166,6 @@ abstract class UserClientApi { @async void authenticateDevice(List? scopes); - // todo update return value to object @async void authenticateUserImplicitly(String profileId, List? scopes); @@ -186,6 +214,9 @@ abstract class UserClientApi { @HostApi() abstract class ResourceMethodApi { + @async + OWRequestResponse requestResource(ResourceRequestType type, OWRequestDetails details); + @async String? getResourceAnonymous(); From 21cb757f130791d79e8546139c9f0b40b1540343 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 15 Mar 2023 11:11:26 +0100 Subject: [PATCH 127/364] FP-47 Rework secure resource requests on android and on dart side, with integration of pigeon --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 12 -- .../sdk/flutter/OneginiMethodsWrapper.kt | 22 --- .../mobile/sdk/flutter/PigeonInterface.kt | 26 ---- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 80 ---------- .../sdk/GetImplicitResourceUseCaseTests.kt | 99 ------------ .../sdk/GetResourceAnonymousUseCaseTests.kt | 76 ---------- .../mobile/sdk/GetResourceUseCaseTests.kt | 85 ----------- .../GetUnauthenticatedResourceUseCaseTests.kt | 91 ----------- .../onegini/mobile/sdk/ResourceHelperTests.kt | 89 ----------- example/lib/screens/user_screen.dart | 14 +- ios/Classes/Pigeon.swift | 64 -------- lib/model/request_details.dart | 21 --- lib/pigeon.dart | 88 ----------- lib/resources_methods.dart | 143 ++++-------------- pigeons/onewelcome_pigeon_interface.dart | 12 -- 15 files changed, 40 insertions(+), 882 deletions(-) delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetImplicitResourceUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetResourceAnonymousUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetResourceUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetUnauthenticatedResourceUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index c1b51366..bf336c35 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -1,12 +1,6 @@ package com.onegini.mobile.sdk.flutter -import android.net.Uri -import android.util.Patterns -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler -import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError -import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.constants.Constants import com.onegini.mobile.sdk.flutter.helpers.MobileAuthenticationObject import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -37,12 +31,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: // OTP Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, client) - // Resources - Constants.METHOD_GET_RESOURCE_ANONYMOUS -> oneginiMethodsWrapper.getResourceAnonymous(call, result) - Constants.METHOD_GET_RESOURCE -> oneginiMethodsWrapper.getResource(call, result) - Constants.METHOD_GET_IMPLICIT_RESOURCE -> oneginiMethodsWrapper.getImplicitResource(call, result) - Constants.METHOD_GET_UNAUTHENTICATED_RESOURCE -> oneginiMethodsWrapper.getUnauthenticatedResource(call, result) - else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 3f641c53..77658c6d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -1,7 +1,6 @@ package com.onegini.mobile.sdk.flutter import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import com.onegini.mobile.sdk.flutter.useCases.* import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel @@ -10,12 +9,7 @@ import javax.inject.Singleton @Singleton class OneginiMethodsWrapper @Inject constructor( - private val getImplicitResourceUseCase: GetImplicitResourceUseCase, - private val getResourceAnonymousUseCase: GetResourceAnonymousUseCase, - private val getResourceUseCase: GetResourceUseCase, - private val getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase, private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, - private val resourceHelper: ResourceHelper, private val startAppUseCase: StartAppUseCase, ) { @@ -27,22 +21,6 @@ class OneginiMethodsWrapper @Inject constructor( startAppUseCase(call, result) } - fun getResourceAnonymous(call: MethodCall, result: MethodChannel.Result){ - getResourceAnonymousUseCase(call, result, resourceHelper) - } - - fun getResource(call: MethodCall, result: MethodChannel.Result){ - getResourceUseCase(call, result, resourceHelper) - } - - fun getImplicitResource(call: MethodCall, result: MethodChannel.Result){ - getImplicitResourceUseCase(call, result, resourceHelper) - } - - fun getUnauthenticatedResource(call: MethodCall, result: MethodChannel.Result){ - getUnauthenticatedResourceUseCase(call, result, resourceHelper) - } - fun isAuthenticatorRegistered(call: MethodCall, result: MethodChannel.Result) { isAuthenticatorRegisteredUseCase(call, result) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 199b7194..18df0af5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -75,20 +75,12 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase @Inject - lateinit var getImplicitResourceUseCase: GetImplicitResourceUseCase - @Inject lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase @Inject lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase @Inject lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase @Inject - lateinit var getResourceAnonymousUseCase: GetResourceAnonymousUseCase - @Inject - lateinit var getResourceUseCase: GetResourceUseCase - @Inject - lateinit var getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase - @Inject lateinit var getUserProfilesUseCase: GetUserProfilesUseCase @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase @@ -101,8 +93,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var registrationUseCase: RegistrationUseCase @Inject - lateinit var resourceHelper: ResourceHelper - @Inject lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase @Inject lateinit var startAppUseCase: StartAppUseCase @@ -300,20 +290,4 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { override fun requestResource(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { resourceRequestUseCase(type, details, callback) } - - override fun getResourceAnonymous(callback: (Result) -> Unit) { - // TODO("Not yet implemented") - } - - override fun getResource(callback: (Result) -> Unit) { - // TODO("Not yet implemented") - } - - override fun getResourceImplicit(callback: (Result) -> Unit) { - // TODO("Not yet implemented") - } - - override fun getUnauthenticatedResource(callback: (Result) -> Unit) { - // TODO("Not yet implemented") - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 773b9819..53963cf5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1093,10 +1093,6 @@ private object ResourceMethodApiCodec : StandardMessageCodec() { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface ResourceMethodApi { fun requestResource(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) - fun getResourceAnonymous(callback: (Result) -> Unit) - fun getResource(callback: (Result) -> Unit) - fun getResourceImplicit(callback: (Result) -> Unit) - fun getUnauthenticatedResource(callback: (Result) -> Unit) companion object { /** The codec used by ResourceMethodApi. */ @@ -1128,82 +1124,6 @@ interface ResourceMethodApi { channel.setMessageHandler(null) } } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.getResourceAnonymous() { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResource", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.getResource() { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.getResourceImplicit() { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - var wrapped = listOf() - api.getUnauthenticatedResource() { result: Result -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetImplicitResourceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetImplicitResourceUseCaseTests.kt deleted file mode 100644 index ff43075a..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetImplicitResourceUseCaseTests.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.onegini.mobile.sdk - -import com.google.common.truth.Truth -import com.onegini.mobile.sdk.android.client.UserClient -import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_NOT_AUTHENTICATED_IMPLICITLY -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.flutter.useCases.GetImplicitResourceUseCase -import com.onegini.mobile.sdk.utils.RxSchedulerRule -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import okhttp3.Request -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetImplicitResourceUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @get:Rule - val schedulerRule = RxSchedulerRule() - - @Mock - lateinit var userClient: UserClient - - @Mock - lateinit var implicitResourceOkHttpClient: OkHttpClient - - @Mock - lateinit var callMock: MethodCall - - @Mock - lateinit var configModelMock: OneginiClientConfigModel - - @Mock - lateinit var requestMock: Request - - @Spy - lateinit var resultSpy: MethodChannel.Result - - @Mock - lateinit var resourceHelper: ResourceHelper - - lateinit var getImplicitResourceUseCase: GetImplicitResourceUseCase - @Before - fun attach() { - getImplicitResourceUseCase = GetImplicitResourceUseCase(oneginiSdk) - whenever(oneginiSdk.oneginiClient.userClient).thenReturn(userClient) - whenever(userClient.implicitResourceOkHttpClient).thenReturn(implicitResourceOkHttpClient) - whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should return error when the user is not implicitly authenticated`() { - getImplicitResourceUseCase(callMock, resultSpy, resourceHelper) - - verify(resultSpy).error( - USER_NOT_AUTHENTICATED_IMPLICITLY.code.toString(), USER_NOT_AUTHENTICATED_IMPLICITLY.message, - mutableMapOf("code" to USER_NOT_AUTHENTICATED_IMPLICITLY.code.toString(), "message" to USER_NOT_AUTHENTICATED_IMPLICITLY.message) - ) - } - - @Test - fun `should call getRequest with correct params`() { - whenever(oneginiSdk.oneginiClient.userClient.implicitlyAuthenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - - getImplicitResourceUseCase(callMock, resultSpy, resourceHelper) - - verify(resourceHelper).getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call request with correct HTTP client`() { - whenever(resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/")).thenReturn(requestMock) - whenever(oneginiSdk.oneginiClient.userClient.implicitlyAuthenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - - getImplicitResourceUseCase(callMock, resultSpy, resourceHelper) - - argumentCaptor { - verify(resourceHelper).callRequest(capture(), eq(requestMock), eq(resultSpy)) - Truth.assertThat(firstValue).isEqualTo(oneginiSdk.oneginiClient.userClient.implicitResourceOkHttpClient) - } - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetResourceAnonymousUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetResourceAnonymousUseCaseTests.kt deleted file mode 100644 index 5d577de3..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetResourceAnonymousUseCaseTests.kt +++ /dev/null @@ -1,76 +0,0 @@ -package com.onegini.mobile.sdk - -import com.google.common.truth.Truth -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.flutter.useCases.GetResourceAnonymousUseCase -import com.onegini.mobile.sdk.utils.RxSchedulerRule -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import okhttp3.Request -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetResourceAnonymousUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @get:Rule - val schedulerRule = RxSchedulerRule() - - @Mock - lateinit var clientMock: OneginiClient - - @Mock - lateinit var callMock: MethodCall - - @Spy - lateinit var resultSpy: MethodChannel.Result - - @Mock - lateinit var requestMock: Request - - @Mock - lateinit var resourceHelper: ResourceHelper - - lateinit var getResourceAnonymousUseCase: GetResourceAnonymousUseCase - @Before - fun attach() { - getResourceAnonymousUseCase = GetResourceAnonymousUseCase(oneginiSdk) - whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call getRequest with correct params`() { - getResourceAnonymousUseCase(callMock, resultSpy, resourceHelper) - - verify(resourceHelper).getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call request with correct HTTP client`() { - whenever(resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/")).thenReturn(requestMock) - - getResourceAnonymousUseCase(callMock, resultSpy, resourceHelper) - - argumentCaptor { - verify(resourceHelper).callRequest(capture(), eq(requestMock), eq(resultSpy)) - Truth.assertThat(firstValue).isEqualTo(oneginiSdk.oneginiClient.deviceClient.anonymousResourceOkHttpClient) - } - } - -} \ No newline at end of file diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetResourceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetResourceUseCaseTests.kt deleted file mode 100644 index 1e77604e..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetResourceUseCaseTests.kt +++ /dev/null @@ -1,85 +0,0 @@ -package com.onegini.mobile.sdk - -import com.google.common.truth.Truth -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.flutter.useCases.GetResourceUseCase -import com.onegini.mobile.sdk.utils.RxSchedulerRule -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import okhttp3.Request -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetResourceUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @get:Rule - val schedulerRule = RxSchedulerRule() - - @Mock - lateinit var clientMock: OneginiClient - - @Mock - lateinit var callMock: MethodCall - - @Mock - lateinit var configModelMock: OneginiClientConfigModel - - @Mock - lateinit var resourceOkHttpClient: OkHttpClient - - @Mock - lateinit var requestMock: Request - - @Mock - lateinit var resourceHelper: ResourceHelper - - @Spy - lateinit var resultSpy: MethodChannel.Result - - lateinit var getResourceUseCase: GetResourceUseCase - @Before - fun attach() { - getResourceUseCase = GetResourceUseCase(oneginiSdk) - whenever(oneginiSdk.oneginiClient.userClient.resourceOkHttpClient).thenReturn(resourceOkHttpClient) - whenever(oneginiSdk.oneginiClient.configModel).thenReturn(configModelMock) - whenever(configModelMock.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call getRequest with correct params`() { - getResourceUseCase(callMock, resultSpy, resourceHelper) - - verify(resourceHelper).getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call request with correct HTTP client`() { - whenever(resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/")).thenReturn(requestMock) - - getResourceUseCase(callMock, resultSpy, resourceHelper) - - argumentCaptor { - verify(resourceHelper).callRequest(capture(), eq(requestMock), eq(resultSpy)) - Truth.assertThat(firstValue).isEqualTo(resourceOkHttpClient) - } - } - -} \ No newline at end of file diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetUnauthenticatedResourceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetUnauthenticatedResourceUseCaseTests.kt deleted file mode 100644 index c128fff7..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetUnauthenticatedResourceUseCaseTests.kt +++ /dev/null @@ -1,91 +0,0 @@ -package com.onegini.mobile.sdk - -import com.google.common.truth.Truth -import com.onegini.mobile.sdk.android.client.DeviceClient -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.flutter.useCases.GetUnauthenticatedResourceUseCase -import com.onegini.mobile.sdk.utils.RxSchedulerRule -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import okhttp3.Request -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetUnauthenticatedResourceUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @get:Rule - val schedulerRule = RxSchedulerRule() - - @Mock - lateinit var clientMock: OneginiClient - - @Mock - lateinit var deviceClient: DeviceClient - - @Mock - lateinit var callMock: MethodCall - - @Mock - lateinit var configModelMock: OneginiClientConfigModel - - @Mock - lateinit var unauthenticatedResourceOkHttpClient: OkHttpClient - - @Mock - lateinit var requestMock: Request - - @Spy - lateinit var resultSpy: MethodChannel.Result - - @Mock - lateinit var resourceHelper: ResourceHelper - - lateinit var getUnauthenticatedResourceUseCase: GetUnauthenticatedResourceUseCase - - @Before - fun attach() { - getUnauthenticatedResourceUseCase = GetUnauthenticatedResourceUseCase(oneginiSdk) - whenever(oneginiSdk.oneginiClient.deviceClient).thenReturn(deviceClient) - whenever(deviceClient.unauthenticatedResourceOkHttpClient).thenReturn(unauthenticatedResourceOkHttpClient) - whenever(oneginiSdk.oneginiClient.configModel).thenReturn(configModelMock) - whenever(configModelMock.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call getRequest with correct params`() { - getUnauthenticatedResourceUseCase(callMock, resultSpy, resourceHelper) - - verify(resourceHelper).getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - } - - @Test - fun `should call request with correct HTTP client`() { - whenever(resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/")).thenReturn(requestMock) - - getUnauthenticatedResourceUseCase(callMock, resultSpy, resourceHelper) - - argumentCaptor { - verify(resourceHelper).callRequest(capture(), eq(requestMock), eq(resultSpy)) - Truth.assertThat(firstValue).isEqualTo(unauthenticatedResourceOkHttpClient) - } - } - -} \ No newline at end of file diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt deleted file mode 100644 index 46ab8e2d..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceHelperTests.kt +++ /dev/null @@ -1,89 +0,0 @@ -package com.onegini.mobile.sdk - -import com.google.common.truth.Truth -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.utils.RxSchedulerRule -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.Headers.Companion.toHeaders -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import okhttp3.RequestBody.Companion.toRequestBody -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class ResourceHelperTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @get:Rule - val schedulerRule = RxSchedulerRule() - - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall - - lateinit var resourceHelper: ResourceHelper - - @Before - fun setup() { -// resourceHelper = ResourceHelper() - } - @Test - fun `should build correct url when 'path' parameter is given`() { - whenever(callMock.argument("path")).thenReturn("test") - - val request = resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - - Truth.assertThat(request.url.host).isEqualTo("token-mobile.test.onegini.com") - Truth.assertThat(request.url.toString()).isEqualTo("https://token-mobile.test.onegini.com/resources/test") - } - - @Test - fun `should build correct url with headers when 'headers' parameter is given`() { - whenever(callMock.argument("path")).thenReturn("test") - whenever(callMock.argument>("headers")).thenReturn(hashMapOf(Pair("key1", "value1"), Pair("key2", "value2"))) - - val request = resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - - Truth.assertThat(request.headers).isEqualTo(mapOf(Pair("key1", "value1"), Pair("key2", "value2")).toHeaders()) - } - - @Test - fun `should build correct method and body when 'method' and 'body' parameter is given`() { - whenever(callMock.argument("path")).thenReturn("test") - whenever(callMock.argument("body")).thenReturn("test body") - whenever(callMock.argument("method")).thenReturn("POST") - - val request = resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - - Truth.assertThat(request.method).isEqualTo("POST") - Truth.assertThat(request.body?.contentType()?.type).isEqualTo("application") - Truth.assertThat(request.body?.contentType()?.subtype).isEqualTo("json") - Truth.assertThat(request.body?.contentLength()).isEqualTo("test body".toRequestBody("application/json".toMediaTypeOrNull()).contentLength()) - } - - @Test - fun `should build correct parameters when 'parameters' parameter is given`() { - whenever(callMock.argument("path")).thenReturn("test") - whenever(callMock.argument>("parameters")).thenReturn(hashMapOf(Pair("key1", "value1"), Pair("key2", "value2"))) - - val request = resourceHelper.getRequest(callMock, "https://token-mobile.test.onegini.com/resources/") - - Truth.assertThat(request.url.toString()).isEqualTo("https://token-mobile.test.onegini.com/resources/test?key1=value1&key2=value2") - Truth.assertThat(request.url.queryParameterNames).isEqualTo(setOf("key1", "key2")) - Truth.assertThat(request.url.queryParameterValues("key1")).isEqualTo(listOf("value1")) - Truth.assertThat(request.url.queryParameterValues("key2")).isEqualTo(listOf("value2")) - } -} \ No newline at end of file diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index e0dd6281..87a91ea7 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -12,6 +12,7 @@ import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:onegini/pigeon.dart'; +import 'package:onegini/model/request_details.dart'; import '../main.dart'; import 'login_screen.dart'; @@ -422,26 +423,26 @@ class _InfoState extends State { Future getClientResource() async { var response = await Onegini.instance.resourcesMethods - .getResource("devices") + .getResource(RequestDetails(path: "devices", method: HttpRequestMethod.get)) .catchError((error) { print('Caught error: $error'); showFlutterToast(error.message); }); - var res = json.decode(response); - return clientResourceFromJson(res["body"]); + return clientResourceFromJson(response.body); } Future makeUnaunthenticatedRequest() async { var headers = {'Declareren-Appversion': 'CZ.app'}; var response = await Onegini.instance.resourcesMethods - .getUnauthenticatedResource("devices", headers: headers, method: 'GET') + .getUnauthenticatedResource(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) .catchError((onError) { debugPrint(onError); }); - var res = json.decode(response); - return res["body"]; + + var res = json.decode(response.body); + return res; } @override @@ -515,7 +516,6 @@ class _InfoState extends State { height: 20, ), FutureBuilder( - //implicit future: makeUnaunthenticatedRequest(), builder: (context, snapshot) { return snapshot.hasData diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 2d1f4a3d..c5211d1f 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -970,10 +970,6 @@ class ResourceMethodApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol ResourceMethodApi { func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) - func getResourceAnonymous(completion: @escaping (Result) -> Void) - func getResource(completion: @escaping (Result) -> Void) - func getResourceImplicit(completion: @escaping (Result) -> Void) - func getUnauthenticatedResource(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -1000,66 +996,6 @@ class ResourceMethodApiSetup { } else { requestResourceChannel.setMessageHandler(nil) } - let getResourceAnonymousChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - getResourceAnonymousChannel.setMessageHandler { _, reply in - api.getResourceAnonymous() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - getResourceAnonymousChannel.setMessageHandler(nil) - } - let getResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResource", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - getResourceChannel.setMessageHandler { _, reply in - api.getResource() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - getResourceChannel.setMessageHandler(nil) - } - let getResourceImplicitChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - getResourceImplicitChannel.setMessageHandler { _, reply in - api.getResourceImplicit() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - getResourceImplicitChannel.setMessageHandler(nil) - } - let getUnauthenticatedResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - getUnauthenticatedResourceChannel.setMessageHandler { _, reply in - api.getUnauthenticatedResource() { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - getUnauthenticatedResourceChannel.setMessageHandler(nil) - } } } /// Native calls to Flutter diff --git a/lib/model/request_details.dart b/lib/model/request_details.dart index c87ef278..aca2d40a 100644 --- a/lib/model/request_details.dart +++ b/lib/model/request_details.dart @@ -1,26 +1,5 @@ import 'package:onegini/pigeon.dart'; -abstract class GenericRequest implements RequestPost, RequestGet { -} - -class RequestPost { - String path; - Map? headers; - HttpRequestMethod method = HttpRequestMethod.post; - String body; - - RequestPost({required this.path, required this.body, this.headers}); -} - -class RequestGet { - String path; - Map? headers; - HttpRequestMethod method = HttpRequestMethod.get; - String? body; - - RequestGet({required this.path, this.headers}); -} - // Wrapper class for pigeon class to enforce non null map values. class RequestDetails { String path; diff --git a/lib/pigeon.dart b/lib/pigeon.dart index be5d846c..bcfcc2b2 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1197,94 +1197,6 @@ class ResourceMethodApi { return (replyList[0] as OWRequestResponse?)!; } } - - Future getResourceAnonymous() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResourceMethodApi.getResourceAnonymous', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return (replyList[0] as String?); - } - } - - Future getResource() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResourceMethodApi.getResource', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return (replyList[0] as String?); - } - } - - Future getResourceImplicit() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResourceMethodApi.getResourceImplicit', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return (replyList[0] as String?); - } - } - - Future getUnauthenticatedResource() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResourceMethodApi.getUnauthenticatedResource', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return (replyList[0] as String?); - } - } } /// Native calls to Flutter diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index 15887fc3..26881f07 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -1,14 +1,8 @@ -import 'dart:ui'; - import 'model/request_details.dart'; import 'model/request_response.dart'; -import 'package:flutter/services.dart'; import 'package:onegini/pigeon.dart'; -import 'constants/constants.dart'; -import 'onegini.dart'; - /// The class with resources methods class ResourcesMethods { final api = ResourceMethodApi(); @@ -26,117 +20,46 @@ class ResourcesMethods { /// Gets resources anonymously. - /// - /// Method requires [path] parameter. - Future getResourceAnonymous( - String path, { - Map? headers, - String? method, - String? encoding, - Map? params, - String? body, - }) async { - var response; - response = await Onegini.instance.channel - .invokeMethod(Constants.getResourceAnonymous, { - 'path': path, - 'headers': headers, - 'method': method, - 'encoding': encoding, - 'parameters': params, - 'body': body - }); - - return response; + Future getResourceAnonymous(RequestDetails details) async { + var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + var owResponse = await api.requestResource(ResourceRequestType.anonymous, owDetails); + + owResponse.headers.removeWhere((key, value) => key == null || value == null); + var headers = Map.from(owResponse.headers); + + return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); } /// Gets resources. - /// - /// Method requires [path] parameter. - Future getResource( - String path, { - Map? headers, - String? method, - String? encoding, - Map? params, - String? body, - }) async { - try { - var response = await Onegini.instance.channel - .invokeMethod(Constants.getResource, { - 'path': path, - 'headers': headers, - 'method': method, - 'encoding': encoding, - 'parameters': params, - 'body': body - }); - return response; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + Future getResource(RequestDetails details) async { + var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + var owResponse = await api.requestResource(ResourceRequestType.authenticated, owDetails); + + owResponse.headers.removeWhere((key, value) => key == null || value == null); + var headers = Map.from(owResponse.headers); + + return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); } /// Gets implicit resource. - /// - /// Method requires [path] parameter. - Future getResourceImplicit( - String path, { - Map? headers, - String? method, - String? encoding, - Map? params, - String? body, - }) async { - try { - var response; - - response = await Onegini.instance.channel - .invokeMethod(Constants.getImplicitResource, { - 'path': path, - 'headers': headers, - 'method': method, - 'encoding': encoding, - 'parameters': params, - 'body': body - }); - - return response; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + Future getResourceImplicit(RequestDetails details) async { + var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + var owResponse = await api.requestResource(ResourceRequestType.implicit, owDetails); + + owResponse.headers.removeWhere((key, value) => key == null || value == null); + var headers = Map.from(owResponse.headers); + + return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); } - Future getUnauthenticatedResource( - String path, { - Map? headers, - String? method, - String? encoding, - Map? params, - String? body, - }) async { - try { - var response = await Onegini.instance.channel - .invokeMethod(Constants.getUnauthenticatedResource, { - 'path': path, - 'headers': headers, - 'method': method, - 'encoding': encoding, - 'parameters': params, - 'body': body - }); - return response; - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + /// Gets unauthenticated resource. + Future getUnauthenticatedResource(RequestDetails details) async { + var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + var owResponse = await api.requestResource(ResourceRequestType.unauthenticated, owDetails); + + owResponse.headers.removeWhere((key, value) => key == null || value == null); + var headers = Map.from(owResponse.headers); + + return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 040b41cc..31afe0af 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -216,18 +216,6 @@ abstract class UserClientApi { abstract class ResourceMethodApi { @async OWRequestResponse requestResource(ResourceRequestType type, OWRequestDetails details); - - @async - String? getResourceAnonymous(); - - @async - String? getResource(); - - @async - String? getResourceImplicit(); - - @async - String? getUnauthenticatedResource(); } /// Native calls to Flutter From fc206d8ff922897575ad4084558f085f5e2fe4f2 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 15 Mar 2023 11:35:24 +0100 Subject: [PATCH 128/364] FP-47 Rename getresourceunauthenticated to be more consistent --- example/lib/screens/user_screen.dart | 2 +- lib/resources_methods.dart | 2 +- test/resource_methods_test.dart | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 87a91ea7..fb735a64 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -436,7 +436,7 @@ class _InfoState extends State { Future makeUnaunthenticatedRequest() async { var headers = {'Declareren-Appversion': 'CZ.app'}; var response = await Onegini.instance.resourcesMethods - .getUnauthenticatedResource(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) + .getResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) .catchError((onError) { debugPrint(onError); }); diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index 26881f07..508ceb17 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -53,7 +53,7 @@ class ResourcesMethods { } /// Gets unauthenticated resource. - Future getUnauthenticatedResource(RequestDetails details) async { + Future getResourceUnauthenticated(RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(ResourceRequestType.unauthenticated, owDetails); diff --git a/test/resource_methods_test.dart b/test/resource_methods_test.dart index 648f5f91..9bf7d69e 100644 --- a/test/resource_methods_test.dart +++ b/test/resource_methods_test.dart @@ -110,7 +110,7 @@ void main() { ); }); - group('ResourcesMethods getUnauthenticatedResource', () { + group('ResourcesMethods getResourceUnauthenticated', () { test( 'return String', () async { @@ -119,7 +119,7 @@ void main() { Constants.getUnauthenticatedResource, Future.value('success')); //act - var result = await resourcesMethods.getUnauthenticatedResource(''); + var result = await resourcesMethods.getResourceUnauthenticated(''); //assert expect(result, 'success'); @@ -134,7 +134,7 @@ void main() { Constants.getUnauthenticatedResource, Future.value(null)); //act - var result = await resourcesMethods.getUnauthenticatedResource(''); + var result = await resourcesMethods.getResourceUnauthenticated(''); //assert expect(result, null); @@ -150,7 +150,7 @@ void main() { //assert expect( - () async => await resourcesMethods.getUnauthenticatedResource(''), + () async => await resourcesMethods.getResourceUnauthenticated(''), throwsA(isA())); }, ); From dc5d6df3e960303abd511cdcd3e90c3e497caa0f Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 10:48:55 +0100 Subject: [PATCH 129/364] FP-20: Add an extension for .success(()) -> .success --- .../Handlers/AuthenticatorsHandler.swift | 10 +++---- .../Handlers/DeregisterUserHandler.swift | 2 +- .../NativeBridge/Handlers/LogoutHandler.swift | 2 +- .../NativeBridge/Handlers/PinHandler.swift | 4 +-- .../Handlers/RegistrationHandler.swift | 2 +- .../Handlers/ResourcesHandler.swift | 4 +-- ios/Classes/SwiftOneginiPlugin.swift | 28 +++++++++++-------- 7 files changed, 28 insertions(+), 24 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 28a9093c..1f55bc72 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -108,7 +108,7 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } ONGUserClient.sharedInstance().preferredAuthenticator = authenticator - completion(.success(())) + completion(.success) } func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array { @@ -141,7 +141,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { Logger.log("[AUTH] userClient didReceive ONGCustomAuthFinishRegistrationChallenge", sender: self) // TODO: Will need to check it in the future - registrationCompletion?(.success(())) + registrationCompletion?(.success) customAuthChallenge = challenge BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) } @@ -159,7 +159,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) - registrationCompletion?(.success(())) + registrationCompletion?(.success) BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() } } @@ -168,13 +168,13 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { func userClient(_: ONGUserClient, didDeregister _: ONGAuthenticator, forUser _: ONGUserProfile) { Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) - deregistrationCompletion?(.success(())) + deregistrationCompletion?(.success) } func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthDeregistrationChallenge) { Logger.log("[AUTH] userClient didReceive ONGCustomAuthDeregistrationChallenge", sender: self) - deregistrationCompletion?(.success(())) + deregistrationCompletion?(.success) } func userClient(_: ONGUserClient, didFailToDeregister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { diff --git a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift index fc0ceea5..0c42d1e8 100644 --- a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift @@ -17,7 +17,7 @@ class DeregisterUserHandler: DeregisterUserHandlerProtocol { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) } else { - completion(.success(())) + completion(.success) } } } diff --git a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift index 3ceec44e..fce7790b 100644 --- a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift @@ -14,7 +14,7 @@ class LogoutHandler: LogoutHandlerProtocol { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) } else { - completion(.success(())) + completion(.success) } } } diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 81916507..737332cb 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -139,7 +139,7 @@ extension PinHandler: PinConnectorToPinHandler{ func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in guard let error = error else { - completion(.success(())) + completion(.success) return } completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) @@ -225,6 +225,6 @@ extension PinHandler: ONGChangePinDelegate { Logger.log("didChangePinForUser", sender: self) createPinChallenge = nil closeFlow() - changePinCompletion?(.success(())) + changePinCompletion?(.success) } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 61b75461..7132b371 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -146,7 +146,7 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { } presentBrowserUserRegistrationView(registrationUserURL: url, webSignInType: webSignInType) - return .success(()) + return .success } func submitCustomRegistrationSuccess(_ data: String?) { diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 665eb3bc..72485108 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -23,7 +23,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { let mappedError = FlutterError(ErrorMapper().mapError(error)) completion(.failure(mappedError)) } else { - completion(.success(())) + completion(.success) } } } @@ -32,7 +32,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { Logger.log("authenticateImplicitly", sender: self) ONGUserClient.sharedInstance().implicitlyAuthenticateUser(profile, scopes: scopes) { success, error in if success { - completion(.success(())) + completion(.success) } else { // This error construction is obviously not good, but it will work for now till we refactor this later let mappedError = FlutterError(error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError)) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 483af179..8424f2f6 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -52,6 +52,10 @@ extension OWIdentityProvider { } } +extension Result where Success == Void { + public static var success: Result { .success(()) } +} + func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } return OWCustomInfo(status: Int32(info.status), data: info.data) @@ -69,49 +73,49 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success(())) + completion(.success) } func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success(())) + completion(.success) } func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) { Logger.log("fingerprintFallbackToPin is Android only and should not be called on iOS") // FIXME: We should actually reject here with a specific error - completion(.success(())) + completion(.success) } func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { Logger.log("fingerprintDenyAuthenticationRequest is Android only and should not be called on iOS") // FIXME: We should actually reject here with a specific error - completion(.success(())) + completion(.success) } func fingerprintAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { Logger.log("fingerprintAcceptAuthenticationRequest is Android only and should not be called on iOS") // FIXME: We should actually reject here with a specific error - completion(.success(())) + completion(.success) } func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.denyMobileAuthConfirmation() // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success(())) + completion(.success) } func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.acceptMobileAuthConfirmation() // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success(())) + completion(.success) } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.cancelPinAuth() // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + completion(.success) } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { @@ -119,13 +123,13 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { completion(result.mapError{$0}) } // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + completion(.success) } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.cancelPinAuth() // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + completion(.success) } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { @@ -133,13 +137,13 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { completion(result.mapError{$0}) } // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-49 - completion(.success(())) + completion(.success) } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success(())) + completion(.success) } func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { From 573551a0fe7e0e274d07a495414b5d10ab94be31 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:12:09 +0100 Subject: [PATCH 130/364] FP-20: Use guard instead of if/else --- .../NativeBridge/Handlers/LogoutHandler.swift | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift index fce7790b..3e85de50 100644 --- a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift @@ -8,19 +8,17 @@ protocol LogoutHandlerProtocol: AnyObject { class LogoutHandler: LogoutHandlerProtocol { func logout(completion: @escaping (Result) -> Void) { let userClient = ONGUserClient.sharedInstance() - if userClient.authenticatedUserProfile() != nil { - userClient.logoutUser { _, error in - if let error = error { - let mappedError = ErrorMapper().mapError(error) - completion(.failure(FlutterError(mappedError))) - } else { - completion(.success) - } - } - } - else - { + guard userClient.authenticatedUserProfile() != nil else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + return + } + userClient.logoutUser { _, error in + if let error = error { + let mappedError = ErrorMapper().mapError(error) + completion(.failure(FlutterError(mappedError))) + } else { + completion(.success) + } } } } From 8d907e8c93ac5943d852738214b06c1051c4dc4b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:16:44 +0100 Subject: [PATCH 131/364] FP-20: Use init of WebSignInType to set insideApp as default --- .../NativeBridge/Handlers/RegistrationHandler.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 7132b371..a86174c8 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -20,8 +20,15 @@ protocol CustomRegistrationNotificationReceiverProtocol: class { } enum WebSignInType: Int { - case insideApp = 0 - case safari + case insideApp + case safari + + init(rawValue: Int) { + switch rawValue { + case 1: self = .safari + default: self = .insideApp + } + } } class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol, PinHandlerToReceiverProtocol, RegistrationHandlerToPinHanlderProtocol { @@ -133,7 +140,7 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { } func processRedirectURL(url: String, webSignInType: Int) -> Result { - let webSignInType = WebSignInType(rawValue: webSignInType) ?? .insideApp + let webSignInType = WebSignInType(rawValue: webSignInType) guard let url = URL.init(string: url) else { //FIXME: This doesn't seem right, we're canceling the whole registration here??? signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) From 6625bc28c703f818f77237a82221ab3a8c8a5cd4 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:19:26 +0100 Subject: [PATCH 132/364] FP-20: Throw generic error when we get nothing from sdk --- ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift index 4f3a8966..53d07500 100644 --- a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift @@ -14,6 +14,8 @@ class AppToWebHandler: AppToWebHandlerProtocol { completion(.success(OWAppToWebSingleSignOn(token: token, redirectUrl: url.absoluteString))) } else if let error = error { completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) + } else { + completion(.failure(SdkError(.genericError).flutterError())) } } } From a86f66230cfd557d3763ecf8516749b06afa83b1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:19:52 +0100 Subject: [PATCH 133/364] FP-20: Call completion() when we have actually done all the work --- .../NativeBridge/Handlers/AuthenticatorsHandler.swift | 4 ++-- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 1f55bc72..736438e1 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -141,9 +141,9 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { Logger.log("[AUTH] userClient didReceive ONGCustomAuthFinishRegistrationChallenge", sender: self) // TODO: Will need to check it in the future - registrationCompletion?(.success) customAuthChallenge = challenge BridgeConnector.shared?.toPinHandlerConnector.pinHandler.handleFlowUpdate(PinFlow.create, nil, receiver: self) + registrationCompletion?(.success) } func userClient(_: ONGUserClient, didFailToRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { @@ -159,8 +159,8 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) - registrationCompletion?(.success) BridgeConnector.shared?.toPinHandlerConnector.pinHandler.closeFlow() + registrationCompletion?(.success) } } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 9b29963b..95187655 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -96,11 +96,9 @@ extension LoginHandler: ONGAuthenticationDelegate { pinChallenge = nil customChallange = nil - - loginCompletion?(.success( - OWRegistrationResponse(userProfile: OWUserProfile(userProfile), - customInfo: toOWCustomInfo(customAuthInfo)))) pinHandler?.closeFlow() + loginCompletion?(.success(OWRegistrationResponse(userProfile: OWUserProfile(userProfile), + customInfo: toOWCustomInfo(customAuthInfo)))) } func userClient(_ userClient: ONGUserClient, didFailToAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, error: Error) { From 4e8d7468f78e1e34a0c8e3bb2e3a5ae22914c3bc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:25:15 +0100 Subject: [PATCH 134/364] FP-20: Remove redundant catch block --- ios/Classes/NativeBridge/Handlers/PinHandler.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/PinHandler.swift b/ios/Classes/NativeBridge/Handlers/PinHandler.swift index 737332cb..3258249a 100644 --- a/ios/Classes/NativeBridge/Handlers/PinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/PinHandler.swift @@ -66,7 +66,7 @@ class PinHandler: NSObject { } //MARK: - -extension PinHandler: PinConnectorToPinHandler{ +extension PinHandler: PinConnectorToPinHandler { func handleFlowUpdate(_ flow: PinFlow, _ error: SdkError?, receiver: PinHandlerToReceiverProtocol) { if(self.flow == nil){ self.flow = flow @@ -214,8 +214,6 @@ extension PinHandler: ONGChangePinDelegate { if error.code == ONGGenericError.actionCancelled.rawValue { changePinCompletion?(.failure(FlutterError(.changingPinCancelled))) - } else if error.code == ONGGenericError.userDeregistered.rawValue { - changePinCompletion?(.failure(FlutterError(mappedError))) } else { changePinCompletion?(.failure(FlutterError(mappedError))) } From cc754fc9032c7320912d83fd9a438070dbbc3a76 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:25:39 +0100 Subject: [PATCH 135/364] FP-20: Formatting changes --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 1 - .../ModuleExtensions/OneginiModuleSwift+Pin.swift | 4 +--- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 2 +- ios/Classes/NativeBridge/OneginiModuleSwift.swift | 2 +- 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 464c4142..1fcc8cba 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -44,7 +44,6 @@ extension OneginiModuleSwift { bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in completion(result) } - } func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index d8ff58da..6d4590e1 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -17,9 +17,7 @@ extension OneginiModuleSwift { } func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: { result in - completion(result) - }) + bridgeConnector.toPinHandlerConnector.pinHandler.validatePinWithPolicy(pin: pin, completion: completion) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 808d29f3..a5bf681a 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -81,7 +81,7 @@ extension OneginiModuleSwift { return .failure(FlutterError(.userProfileDoesNotExist)) } let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) - return .success(allAuthenticators.compactMap({OWAuthenticator($0)})) + return .success(allAuthenticators.compactMap { OWAuthenticator($0) } ) } func getRedirectUrl() -> Result { diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index e86ef028..cf62e8ba 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -63,7 +63,7 @@ public class OneginiModuleSwift: NSObject, ConnectorToFlutterBridgeProtocol, Flu func getUserProfiles() -> Result<[OWUserProfile], FlutterError> { let profiles = ONGUserClient.sharedInstance().userProfiles() - return .success(profiles.compactMap({OWUserProfile($0)})) + return .success(profiles.compactMap { OWUserProfile($0) } ) } public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { From 12ceb9993144d9258cdab834e44433ef39510bb9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 16 Mar 2023 11:46:08 +0100 Subject: [PATCH 136/364] FP-47 Reworked iOS request structure and removed patch as this is not supported on iOS --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 3 +- .../useCases/ResourceRequestUseCase.kt | 5 - .../NativeBridge/Errors/SdkError.swift | 10 + .../Handlers/ResourcesHandler.swift | 242 +++++------------- .../OneginiModuleSwift+Resources.swift | 36 +-- ios/Classes/Pigeon.swift | 1 - .../SwiftOneginiPlugin+Resources.swift | 23 -- ios/Classes/SwiftOneginiPlugin.swift | 41 ++- lib/pigeon.dart | 1 - pigeons/onewelcome_pigeon_interface.dart | 1 - 10 files changed, 107 insertions(+), 256 deletions(-) delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Resources.swift diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 53963cf5..ebd173c7 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -41,8 +41,7 @@ enum class HttpRequestMethod(val raw: Int) { GET(0), POST(1), PUT(2), - DELETE(3), - PATCH(4); + DELETE(3); companion object { fun ofRaw(raw: Int): HttpRequestMethod? { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 221f85b3..b09c3e8d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -10,7 +10,6 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.POST import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PUT -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PATCH import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE import okhttp3.Call import okhttp3.Callback @@ -88,10 +87,6 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini val body = details.body ?: "" this.put(body.toRequestBody(null)) } - PATCH -> { - val body = details.body ?: "" - this.patch(body.toRequestBody(null)) - } DELETE -> { this.delete(details.body?.toRequestBody()) } diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index 46cee0c7..34e21f17 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -97,3 +97,13 @@ class SdkError: Error { return _error.flutterError() } } + +extension ONGResourceResponse { + func toJSON() -> Dictionary { + return ["statusCode": statusCode, + "headers": allHeaderFields, + "url": rawResponse.url?.absoluteString, + "body": data != nil ? String(data: data!, encoding: .utf8) : nil + ] + } +} diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 665eb3bc..c819d29d 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -6,11 +6,7 @@ typealias FlutterDataCallback = (Any?, SdkError?) -> Void protocol FetchResourcesHandlerProtocol: AnyObject { func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) - func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool, parameters: [String: Any], completion: @escaping FlutterDataCallback) - func fetchSimpleResources(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) - func fetchAnonymousResource(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) - func fetchResourceWithImplicitResource(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) - func unauthenticatedRequest(_ path: String, parameters: [String: Any?], callback: @escaping FlutterResult) + func requestResource(_ type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) } //MARK: - @@ -34,28 +30,13 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { if success { completion(.success(())) } else { - // This error construction is obviously not good, but it will work for now till we refactor this later + // This error construction is obviously not good, but it will work for now till we refactor this later let mappedError = FlutterError(error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError)) completion(.failure(mappedError)) } } } - func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool, parameters: [String: Any], completion: @escaping FlutterDataCallback) { - Logger.log("resourceRequest", sender: self) - if(isImplicit == true){ - implicitResourcesRequest(parameters, completion) - } else{ - simpleResourcesRequest(isAnonymousCall: isAnonymousCall, parameters: parameters, completion) - } - } - - private func isProfileImplicitlyAuthenticated(_ profile: ONGUserProfile) -> Bool { - Logger.log("isProfileImplicitlyAuthenticated", sender: self) - let implicitlyAuthenticatedProfile = ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() - return implicitlyAuthenticatedProfile != nil && implicitlyAuthenticatedProfile == profile - } - private func authenticateProfileImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Bool, SdkError?) -> Void) { Logger.log("authenticateProfileImplicitly", sender: self) ONGUserClient.sharedInstance().implicitlyAuthenticateUser(profile, scopes: scopes) { success, error in @@ -68,192 +49,91 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } } - private func simpleResourcesRequest(isAnonymousCall: Bool, parameters: [String: Any], _ completion: @escaping (Any?, SdkError?) -> Void) { - Logger.log("simpleResourcesRequest", sender: self) - let request = generateONGResourceRequest(from: parameters) + func requestResource(_ my_type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { + Logger.log("requestResource", sender: self) - let completionRequest: ((ONGResourceResponse?, Error?) -> Void)? = { response, error in - if let error = error { - if response != nil { - completion(nil, SdkError(.errorCodeHttpRequest, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) - } else { - completion(nil, SdkError(.httpRequestError, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) - } - } else { - if let response = response, let _ = response.data { - completion(response.toString(), nil) - } else { - completion(nil, SdkError(.responseIsNull)) - } - } - } - - if isAnonymousCall { - ONGDeviceClient.sharedInstance().fetchResource(request, completion: completionRequest) - } else { - ONGUserClient.sharedInstance().fetchResource(request, completion: completionRequest) - } - } - - private func implicitResourcesRequest(_ parameters: [String: Any], _ completion: @escaping FlutterDataCallback) { - Logger.log("implicitResourcesRequest", sender: self) + let request = generateONGResourceRequest(details) + let requestCompletion = getCompletionRequest(completion) - let request = generateONGResourceRequest(from: parameters) - - ONGUserClient.sharedInstance().fetchImplicitResource(request) { response, error in - if let error = error { - if response != nil { - completion(nil, SdkError(.errorCodeHttpRequest, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) - } else { - completion(nil, SdkError(.httpRequestError, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) - } - } else { - if let response = response, let _ = response.data { - completion(response.toString(), nil) - } else { - completion(nil, SdkError(.responseIsNull)) - } + switch my_type { + case ResourceRequestType.implicit: + // For consistency with Android we perform this step + guard let _ = ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() else { + completion(.failure(FlutterError(SdkError(.unauthenticatedImplicitly)))) + return } - } - } - private func getEncodingByValue(_ value: String) -> ONGParametersEncoding { - Logger.log("getEncodingByValue", sender: self) - switch value { - case "application/json": - return ONGParametersEncoding.JSON - case "application/x-www-form-urlencoded": - return ONGParametersEncoding.formURL - default: - return ONGParametersEncoding.JSON + ONGUserClient.sharedInstance().fetchImplicitResource(request, completion: requestCompletion) + case ResourceRequestType.anonymous: + ONGDeviceClient.sharedInstance().fetchResource(request, completion: requestCompletion) + case ResourceRequestType.authenticated: + ONGUserClient.sharedInstance().fetchResource(request, completion: requestCompletion) + case ResourceRequestType.unauthenticated: + ONGDeviceClient.sharedInstance().fetchUnauthenticatedResource(request, completion: requestCompletion) } } //MARK: - Bridge - func fetchAnonymousResource(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) { - Logger.log("fetchAnonymousResource", sender: self) - - let newParameters = generateParameters(from: parameters, path: path) + private func generateONGResourceRequest(_ details: OWRequestDetails) -> ONGResourceRequest { + Logger.log("generateONGResourceRequest", sender: self) + return ONGResourceRequest.init(path: details.path, + method: getRequestMethod(details.method), + body: details.body?.data(using: .utf8), + headers: getRequestHeaders(details.headers) + ) + } - OneginiModuleSwift.sharedInstance.resourceRequest(isImplicit: false, parameters: newParameters) { (data, error) in - if let _errorResource = error { - completion(_errorResource) - return - } else { - completion(data) - } + private func getRequestHeaders(_ headers: Dictionary?) -> Dictionary? { + Logger.log("getRequestHeaders", sender: self) + if (headers == nil) { + return nil } - } - func fetchSimpleResources(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) { - Logger.log("fetchSimpleResources", sender: self) - let newParameters = generateParameters(from: parameters, path: path) - OneginiModuleSwift.sharedInstance.resourceRequest(isImplicit: false, isAnonymousCall: false, parameters: newParameters) { (_data, error) in - if let _errorResource = error { - completion(_errorResource) - return - } else { - completion(_data) + var requestHeaders = Dictionary() + + headers?.forEach { + if ($0.key != nil && $0.value != nil) { + requestHeaders[$0.key ?? ""] = $0.value } } - } - func fetchResourceWithImplicitResource(_ path: String, parameters: [String: Any?], completion: @escaping FlutterResult) { - Logger.log("fetchResourceWithImplicitResource", sender: self) - guard let _ = ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() else { - completion(SdkError(.unauthenticatedImplicitly).flutterError()) - return - } + return requestHeaders + } - let newParameters = generateParameters(from: parameters, path: path) - let scopes = newParameters["scope"] as? [String] - - OneginiModuleSwift.sharedInstance.resourceRequest(isImplicit: true, parameters: newParameters) { (data, error) in - completion(data ?? error) + private func getRequestMethod(_ method: HttpRequestMethod) -> String { + Logger.log("getRequestMethod", sender: self) + switch method { + case HttpRequestMethod.get: + return "GET" + case HttpRequestMethod.post: + return "POST" + case HttpRequestMethod.delete: + return "DELETE" + case HttpRequestMethod.put: + return "PUT" } } - func unauthenticatedRequest(_ path: String, parameters: [String: Any?], callback: @escaping FlutterResult) { - Logger.log("unauthenticatedRequest", sender: self) - - let newParameters = generateParameters(from: parameters, path: path) - - let request = generateONGResourceRequest(from: newParameters) - - ONGDeviceClient.sharedInstance().fetchUnauthenticatedResource(request) { (response, error) in - if let _errorResource = error { + private func getCompletionRequest(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { + Logger.log("getCompletionRequest", sender: self) + let completionRequest: ((ONGResourceResponse?, Error?) -> Void)? = { response, error in + if let error = error { if response != nil { - callback(SdkError.convertToFlutter(SdkError(.errorCodeHttpRequest, response: response, iosCode: _errorResource.code, iosMessage: _errorResource.localizedDescription))) + let flutterError = FlutterError(SdkError(.errorCodeHttpRequest, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) + completion(.failure(flutterError)) } else { - callback(SdkError.convertToFlutter(SdkError(.httpRequestError, response: response, iosCode: _errorResource.code, iosMessage: _errorResource.localizedDescription))) + let flutterError = FlutterError(SdkError(.httpRequestError, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) + completion(.failure(flutterError)) } - return } else { - if let response = response, let data = response.data { - if let _ = String(data: data, encoding: .utf8) { - callback(response.toString()) - } else { - callback(data) - } + if let response = response { + completion(.success(OWRequestResponse(response))) } else { - callback(SdkError(.responseIsNull)) + completion(.failure(FlutterError(SdkError(.responseIsNull)))) } } } - } - - func generateParameters(from parameters: [String: Any?], path: String) -> [String: Any] { - let buffer = parameters.filter { !($0.1 is NSNull) } - - var newParameters = [String: Any]() - newParameters["path"] = path - newParameters["encoding"] = buffer["encoding"] ?? "application/json" - newParameters["method"] = buffer["method"] ?? "GET" - - if let headers = buffer["headers"] { - newParameters["headers"] = headers - } - - if let body = buffer["body"] { - newParameters["body"] = body - } - - if let parameters = buffer["parameters"] { - newParameters["parameters"] = parameters - } - - return newParameters - } - - func generateONGResourceRequest(from parameters: [String: Any]) -> ONGResourceRequest { - let encoding = getEncodingByValue(parameters["encoding"] as! String) - let path = parameters["path"] as! String - let method = parameters["method"] as! String - let headers = parameters["headers"] as? [String : String] - - var request: ONGResourceRequest! - - if let body = parameters["body"] as? String { - let data = body.data(using: .utf8) - request = ONGResourceRequest.init(path: path, method: method, body: data, headers: headers) - } else { - request = ONGResourceRequest.init(path:path, method: method, parameters: parameters["parameters"] as? [String : Any], encoding: encoding, headers: headers) - } - - return request - } -} - -extension ONGResourceResponse { - func toJSON() -> Dictionary { - return ["statusCode": statusCode, - "headers": allHeaderFields, - "url": rawResponse.url?.absoluteString, - "body": data != nil ? String(data: data!, encoding: .utf8) : nil - ] - } - func toString() -> String { - return String.stringify(json: self.toJSON()) + return completionRequest } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift index a0fa7601..8dfae5df 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Resources.swift @@ -3,41 +3,11 @@ import OneginiSDKiOS import Flutter extension OneginiModuleSwift { - - public func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { + func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { bridgeConnector.toResourceFetchHandler.authenticateDevice(scopes, completion: completion) } - public func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool = true, parameters: [String: Any], - callback: @escaping (Any?, FlutterError?) -> Void) { - - bridgeConnector.toResourceFetchHandler.resourceRequest(isImplicit: isImplicit, isAnonymousCall: isAnonymousCall, parameters: parameters, completion: { - (data, error) -> Void in - callback(data, error?.flutterError()) - }) - } - - public func fetchResources(_ path: String, type: String, parameters: [String: Any?], callback: @escaping FlutterResult) { - switch type { - case Constants.Routes.getImplicitResource: - Logger.log("super path1 \(path)") - Logger.log("super params1 \(parameters)") - bridgeConnector.toResourceFetchHandler.fetchResourceWithImplicitResource(path, parameters: parameters, completion: callback) - case Constants.Routes.getResourceAnonymous: - Logger.log("super path2 \(path)") - Logger.log("super params2 \(parameters)") - bridgeConnector.toResourceFetchHandler.fetchAnonymousResource(path, parameters: parameters, completion: callback) - case Constants.Routes.getResource: - Logger.log("super path3 \(path)") - Logger.log("super params3 \(parameters)") - bridgeConnector.toResourceFetchHandler.fetchSimpleResources(path, parameters: parameters, completion: callback) - case Constants.Routes.unauthenticatedRequest: - Logger.log("super path4 \(path)") - Logger.log("super params4 \(parameters)") - bridgeConnector.toResourceFetchHandler.unauthenticatedRequest(path, parameters: parameters, callback: callback) - default: - callback(SdkError.convertToFlutter(SdkError(.incorrectResourcesAccess))) - } + func requestResource(_ type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { + bridgeConnector.toResourceFetchHandler.requestResource(type, details, completion: completion) } } - diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index c5211d1f..700f7258 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -36,7 +36,6 @@ enum HttpRequestMethod: Int { case post = 1 case put = 2 case delete = 3 - case patch = 4 } enum ResourceRequestType: Int { diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Resources.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Resources.swift deleted file mode 100644 index 6534a093..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Resources.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - -protocol OneginiPluginResouceProtocol { - func getResource(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void -} - -extension SwiftOneginiPlugin: OneginiPluginResouceProtocol { - func getResource(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - handleGetResource(call, result) - } - - private func handleGetResource(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, let _path = _arg["path"] as! String? else { - result(SdkError(.incorrectResourcesAccess).flutterError()) - return - } - - OneginiModuleSwift.sharedInstance.fetchResources(_path, type: call.method, parameters: _arg, callback: result) - } -} - diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 594fce26..96424f1d 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -52,6 +52,27 @@ extension OWIdentityProvider { } } +extension OWRequestResponse { + init(_ response: ONGResourceResponse) { + headers = toOWRequestHeaders(response.allHeaderFields) + body = String(data: response.data ?? Data(), encoding: .utf8) ?? "" + status = Int32(response.statusCode) + ok = response.statusCode <= 299 && response.statusCode >= 200 + } +} + +func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> Dictionary { + var owHeaders = Dictionary() + + headers.forEach { + if ($0.key is String && $0.value is String) { + owHeaders[$0.key as! String] = ($0.value as? String) + } + } + + return owHeaders +} + func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } return OWCustomInfo(status: Int32(info.status), data: info.data) @@ -62,9 +83,12 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { return OWCustomInfo(status: Int32(info.status), data: info.data) } - -public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { - +public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { + func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.requestResource(type, details) { result in + completion(result.mapError{$0}) + } + } func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) @@ -266,8 +290,11 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // Init Pigeon communication let messenger : FlutterBinaryMessenger = registrar.messenger() - let api : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() - UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) + let userClientApi : UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() + UserClientApiSetup.setUp(binaryMessenger: messenger, api: userClientApi) + + let resourceMethodApi : ResourceMethodApi & NSObjectProtocol = SwiftOneginiPlugin.init() + ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: resourceMethodApi) flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) @@ -294,10 +321,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { // otp case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) - // resources - case Constants.Routes.getResourceAnonymous, Constants.Routes.getResource, Constants.Routes.getImplicitResource, Constants.Routes.unauthenticatedRequest: - getResource(call, result) - default: do { Logger.log("Method wasn't handled: " + call.method) result(FlutterMethodNotImplemented) diff --git a/lib/pigeon.dart b/lib/pigeon.dart index bcfcc2b2..ccf76534 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -13,7 +13,6 @@ enum HttpRequestMethod { post, put, delete, - patch, } enum ResourceRequestType { diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 31afe0af..56b7f438 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -69,7 +69,6 @@ enum HttpRequestMethod { post, put, delete, - patch // unsure if we want to support this } enum ResourceRequestType { From 5bea5c8e297cd136cb4b7ad44ada736d3131a333 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 16 Mar 2023 11:47:29 +0100 Subject: [PATCH 137/364] removed unused method for authenticateprofileimplicitly --- .../NativeBridge/Handlers/ResourcesHandler.swift | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index c819d29d..d2551575 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -37,18 +37,6 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } } - private func authenticateProfileImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Bool, SdkError?) -> Void) { - Logger.log("authenticateProfileImplicitly", sender: self) - ONGUserClient.sharedInstance().implicitlyAuthenticateUser(profile, scopes: scopes) { success, error in - if !success { - let mappedError = error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError) - completion(success, mappedError) - return - } - completion(success, nil) - } - } - func requestResource(_ my_type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { Logger.log("requestResource", sender: self) From 3b042501517be3019a55fcadc4c870fa3f3d9a19 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 16 Mar 2023 11:48:55 +0100 Subject: [PATCH 138/364] FP-20: Formatting changes --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 2 +- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 1fcc8cba..2001d71b 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -6,7 +6,7 @@ extension OneginiModuleSwift { func getIdentityProviders() -> Result<[OWIdentityProvider], FlutterError> { let providers = ONGClient.sharedInstance().userClient.identityProviders() - return .success(providers.compactMap({OWIdentityProvider($0)})) + return .success(providers.compactMap { OWIdentityProvider($0) } ) } func logOut(callback: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index a5bf681a..02647431 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -65,7 +65,7 @@ extension OneginiModuleSwift { return .failure(FlutterError(.userProfileDoesNotExist)) } let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) - return .success(registeredAuthenticators.compactMap({OWAuthenticator($0)})) + return .success(registeredAuthenticators.compactMap { OWAuthenticator($0) } ) } func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { @@ -73,7 +73,7 @@ extension OneginiModuleSwift { return .failure(FlutterError(.userProfileDoesNotExist)) } let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) - return .success(notRegisteredAuthenticators.compactMap({OWAuthenticator($0)})) + return .success(notRegisteredAuthenticators.compactMap { OWAuthenticator($0) } ) } func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { From 59d290a2471ce74cdc84ac5131bfbc9d32177644 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 16 Mar 2023 12:03:09 +0100 Subject: [PATCH 139/364] fp-47 rename function because logic --- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index d2551575..05c789b6 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -41,7 +41,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { Logger.log("requestResource", sender: self) let request = generateONGResourceRequest(details) - let requestCompletion = getCompletionRequest(completion) + let requestCompletion = getRequestCompletion(completion) switch my_type { case ResourceRequestType.implicit: @@ -102,7 +102,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } } - private func getCompletionRequest(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { + private func getRequestCompletion(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { Logger.log("getCompletionRequest", sender: self) let completionRequest: ((ONGResourceResponse?, Error?) -> Void)? = { response, error in if let error = error { From 13c960e8dab35ff5d319fbdd1f8b09d9fbe1172d Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 16 Mar 2023 16:27:21 +0100 Subject: [PATCH 140/364] FP-20 Process feedback, added class for custom assert equality --- .../mobile/sdk/flutter/SdkErrorAssert.kt | 30 ++++++++ .../providers/CustomRegistrationActionImpl.kt | 76 ++++++++----------- .../CustomTwoStepRegistrationActionImpl.kt | 30 +++----- .../sdk/AuthenticateDeviceUseCaseTests.kt | 19 ++--- .../AuthenticateUserImplicitlyUseCaseTests.kt | 31 +++----- .../sdk/AuthenticateUserUseCaseTests.kt | 43 ++++------- .../mobile/sdk/ChangePinUseCaseTests.kt | 17 ++--- .../DeregisterAuthenticatorUseCaseTests.kt | 46 +++-------- .../mobile/sdk/DeregisterUserUseCaseTests.kt | 26 ++----- .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 13 +--- .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 15 +--- ...GetAuthenticatedUserProfileUseCaseTests.kt | 16 +--- ...NotRegisteredAuthenticatorsUseCaseTests.kt | 12 +-- ...GetRegisteredAuthenticatorsUseCaseTests.kt | 14 +--- .../mobile/sdk/GetUserProfilesUseCaseTests.kt | 1 - .../onegini/mobile/sdk/LogoutUseCaseTests.kt | 17 ++--- .../sdk/RegisterAuthenticatorUseCaseTests.kt | 47 +++--------- .../mobile/sdk/RegistrationUseCaseTests.kt | 18 ++--- .../SetPreferredAuthenticatorUseCaseTests.kt | 25 ++---- .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 18 ++--- 20 files changed, 173 insertions(+), 341 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt new file mode 100644 index 00000000..75082638 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt @@ -0,0 +1,30 @@ +package com.onegini.mobile.sdk.flutter + +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import org.junit.Assert +import javax.inject.Singleton + +@Singleton +class SdkErrorAssert : Assert() { + companion object { + fun assertEquals(expected: OneWelcomeWrapperErrors, actual: Any?) { + when (actual) { + is FlutterError -> { + assertEquals(actual.code.toInt(), expected.code) + assertEquals(actual.message, expected.message) + } + else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + } + } + + fun assertEquals(expected: FlutterError, actual: Any?) { + when (actual) { + is FlutterError -> { + assertEquals(actual.code, expected.code) + assertEquals(actual.message, expected.message) + } + else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 3ea3d50c..b0ed031f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -12,47 +12,37 @@ import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel import com.onegini.mobile.sdk.flutter.models.OneginiEvent class CustomRegistrationActionImpl(private val providerId: String) : OneginiCustomRegistrationAction, CustomRegistrationAction { - var callback: OneginiCustomRegistrationCallback? = null - - override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { - this.callback = callback - - val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) - - } - - override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { - return this - } - - override fun getIdProvider(): String { - return providerId - } - - override fun returnSuccess(result: String?): Result { - return when (callback) { - null -> { - Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - } - else -> { - this.callback?.returnSuccess(result) - callback = null - Result.success(Unit) - } - } - } - - override fun returnError(exception: Exception?): Result { - return when (callback) { - null -> { - Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - } - else -> { - this.callback?.returnError(exception) - callback = null - Result.success(Unit) - } - } - } + var callback: OneginiCustomRegistrationCallback? = null + + override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { + this.callback = callback + + val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) + OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) + + } + + override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { + return this + } + + override fun getIdProvider(): String { + return providerId + } + + override fun returnSuccess(result: String?): Result { + return callback?.let { customRegistrationCallback -> + customRegistrationCallback.returnSuccess(result) + callback = null + Result.success(Unit) + } ?: Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } + + override fun returnError(exception: Exception?): Result { + return callback?.let { customRegistrationCallback -> + customRegistrationCallback.returnError(exception) + callback = null + Result.success(Unit) + } ?: Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 49959a3d..9ffac996 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -38,28 +38,18 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String) : Oneg } override fun returnSuccess(result: String?): Result { - return when (callback) { - null -> { - Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - } - else -> { - this.callback?.returnSuccess(result) - callback = null - Result.success(Unit) - } - } + return callback?.let { customRegistrationCallback -> + customRegistrationCallback.returnSuccess(result) + callback = null + Result.success(Unit) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } override fun returnError(exception: Exception?): Result { - return when (callback) { - null -> { - Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - } - else -> { - this.callback?.returnError(exception) - callback = null - Result.success(Unit) - } - } + return callback?.let { customRegistrationCallback -> + customRegistrationCallback.returnError(exception) + callback = null + Result.success(Unit) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt index e69290df..128243f2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt @@ -3,11 +3,10 @@ package com.onegini.mobile.sdk import com.google.common.truth.Truth import com.onegini.mobile.sdk.android.handlers.OneginiDeviceAuthenticationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiDeviceAuthenticationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -20,7 +19,6 @@ import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.isNull -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -44,7 +42,7 @@ class AuthenticateDeviceUseCaseTests { } @Test - fun `When the sdk returns an Authentication error, Then it should return an`() { + fun `When the sdk returns an Authentication error, Then it should resolve with an error`() { whenever(oneginiDeviceAuthenticationErrorMock.errorType).thenReturn(OneginiDeviceAuthenticationError.GENERAL_ERROR) whenever(oneginiDeviceAuthenticationErrorMock.message).thenReturn("General error") whenever(oneginiSdk.oneginiClient.deviceClient.authenticateDevice(isNull(), any())).thenAnswer { @@ -53,15 +51,10 @@ class AuthenticateDeviceUseCaseTests { authenticateDeviceUseCase(null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), OneginiDeviceAuthenticationError.GENERAL_ERROR) - Assert.assertEquals(error.message, "General error") - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val expected = FlutterError(OneginiDeviceAuthenticationError.GENERAL_ERROR.toString(), "General error") + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } @@ -74,7 +67,7 @@ class AuthenticateDeviceUseCaseTests { authenticateDeviceUseCase(listOf("test"), callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt index e5234788..7a4f3be7 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt @@ -6,10 +6,10 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiImplicitTokenRequest import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -22,7 +22,6 @@ import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.isNull -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -59,15 +58,11 @@ class AuthenticateUserImplicitlyUseCaseTests { authenticateUserImplicitlyUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), GENERIC_ERROR.code) - Assert.assertEquals(error.message, GENERIC_ERROR.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(GENERIC_ERROR.code.toString(), GENERIC_ERROR.message) + + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } @@ -78,15 +73,9 @@ class AuthenticateUserImplicitlyUseCaseTests { authenticateUserImplicitlyUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) } } @@ -106,7 +95,7 @@ class AuthenticateUserImplicitlyUseCaseTests { authenticateUserImplicitlyUseCase("QWERTY", listOf("test"), callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index fa8106ad..bbab88fb 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -7,13 +7,13 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -24,7 +24,6 @@ import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -60,7 +59,7 @@ class AuthenticateUserUseCaseTests { authenticateUserUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) @@ -74,15 +73,9 @@ class AuthenticateUserUseCaseTests { authenticateUserUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) } } @@ -94,15 +87,9 @@ class AuthenticateUserUseCaseTests { authenticateUserUseCase("QWERTY", "TEST", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -128,7 +115,7 @@ class AuthenticateUserUseCaseTests { authenticateUserUseCase("QWERTY", "TEST", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) @@ -147,14 +134,10 @@ class AuthenticateUserUseCaseTests { authenticateUserUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiAuthenticationErrorMock.errorType) - Assert.assertEquals(error.message, oneginiAuthenticationErrorMock.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(oneginiAuthenticationErrorMock.errorType.toString(), oneginiAuthenticationErrorMock.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index ed02c4bf..8b54d8ae 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -3,11 +3,10 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase -import io.flutter.plugin.common.MethodCall import org.junit.Assert import org.junit.Before import org.junit.Test @@ -17,7 +16,6 @@ import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -53,7 +51,7 @@ class ChangePinUseCaseTests { changePinUseCase(callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -67,14 +65,9 @@ class ChangePinUseCaseTests { changePinUseCase(callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiChangePinError.errorType) - Assert.assertEquals(error.message, oneginiChangePinError.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiChangePinError.errorType.toString(), oneginiChangePinError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt index 355af5a9..4fd72428 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt @@ -6,9 +6,9 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -19,7 +19,6 @@ import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -52,14 +51,8 @@ class DeregisterAuthenticatorUseCaseTests { deregisterAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, firstValue.exceptionOrNull()) } } @@ -76,14 +69,8 @@ class DeregisterAuthenticatorUseCaseTests { deregisterAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -95,14 +82,8 @@ class DeregisterAuthenticatorUseCaseTests { deregisterAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -122,7 +103,7 @@ class DeregisterAuthenticatorUseCaseTests { deregisterAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -145,14 +126,9 @@ class DeregisterAuthenticatorUseCaseTests { deregisterAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiAuthenticatorDeregistrationErrorMock.errorType) - Assert.assertEquals(error.message, oneginiAuthenticatorDeregistrationErrorMock.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiAuthenticatorDeregistrationErrorMock.errorType.toString(), oneginiAuthenticatorDeregistrationErrorMock.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt index 047ca7ef..e26cfeb8 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt @@ -5,6 +5,7 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiDeregistrationError import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -18,7 +19,6 @@ import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -49,14 +49,8 @@ class DeregisterUserUseCaseTests { deregisterUserUseCase("ABCDEF", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) } } @@ -71,7 +65,7 @@ class DeregisterUserUseCaseTests { deregisterUserUseCase("QWERTY", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -88,14 +82,10 @@ class DeregisterUserUseCaseTests { deregisterUserUseCase("QWERTY", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiDeregistrationErrorMock.errorType) - Assert.assertEquals(error.message, oneginiDeregistrationErrorMock.message) - } - else -> junit.framework.Assert.fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(oneginiDeregistrationErrorMock.errorType.toString(), oneginiDeregistrationErrorMock.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index 0a13b85b..fb687681 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -2,10 +2,8 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -32,13 +30,8 @@ class GetAccessTokenUseCaseTests { fun `When the accessToken is null, Then should error with NO_USER_PROFILE_IS_AUTHENTICATED`() { whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn(null) - when (val error = getAccessTokenUseCase().exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val result = getAccessTokenUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index 6744f2b9..1ae20ff2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -4,11 +4,10 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import io.flutter.plugin.common.MethodCall import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before @@ -24,9 +23,6 @@ class GetAllAuthenticatorsUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var callMock: MethodCall - @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator @@ -41,13 +37,8 @@ class GetAllAuthenticatorsUseCaseTests { @Test fun `When an unknown or unregistered profileId is given, Then an error should be thrown`() { - when (val error = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val result = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull() + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index 43b619d3..1bad4627 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -3,10 +3,8 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -33,15 +31,8 @@ class GetAuthenticatedUserProfileUseCaseTests { fun `When no user is authenticated, Then should reject with NO_USER_PROFILE_IS_AUTHENTICATED`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - val result = getAuthenticatedUserProfileUseCase() - - when (val error = result.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> fail("Test failed as no sdk error was passed") - } + val result = getAuthenticatedUserProfileUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) } @Test @@ -49,7 +40,6 @@ class GetAuthenticatedUserProfileUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) val result = getAuthenticatedUserProfileUseCase().getOrNull() - Assert.assertEquals(result?.profileId, "QWERTY") } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 8b34270a..105c3131 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -4,7 +4,7 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -51,15 +51,9 @@ class GetNotRegisteredAuthenticatorsUseCaseTests { @Test fun `When the UserProfile is not found, Then an error should be returned`() { - val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") + val result = getNotRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - when (val error = result.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index f08316dc..86f3d73e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -5,8 +5,7 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase @@ -57,15 +56,8 @@ class GetRegisteredAuthenticatorsUseCaseTests { fun `When UserProfile is null, Then it should return an error`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - val result = getRegisteredAuthenticatorsUseCase("QWERTY") - - when (val error = result.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), USER_PROFILE_DOES_NOT_EXIST.code) - Assert.assertEquals(error.message, USER_PROFILE_DOES_NOT_EXIST.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val result = getRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt index 223f9b1b..7d7548cd 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt @@ -35,7 +35,6 @@ class GetUserProfilesUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) val result = getUserProfilesUseCase() - Assert.assertEquals(result.getOrNull(), mutableListOf>()) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt index e29d4f0c..8b85b210 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt @@ -3,11 +3,10 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiLogoutHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiLogoutError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -17,7 +16,6 @@ import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -52,7 +50,7 @@ class LogoutUseCaseTests { logoutUseCase(callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -68,15 +66,10 @@ class LogoutUseCaseTests { logoutUseCase(callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiLogoutError.errorType) - Assert.assertEquals(error.message, oneginiLogoutError.message) - } - else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) - } + val expected = FlutterError(oneginiLogoutError.errorType.toString(), oneginiLogoutError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index a1b903be..127db9fc 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -8,9 +8,9 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -21,7 +21,6 @@ import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -57,14 +56,8 @@ class RegisterAuthenticatorUseCaseTests { registerAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, firstValue.exceptionOrNull()) } } @@ -77,14 +70,8 @@ class RegisterAuthenticatorUseCaseTests { registerAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -96,14 +83,8 @@ class RegisterAuthenticatorUseCaseTests { registerAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -119,7 +100,7 @@ class RegisterAuthenticatorUseCaseTests { registerAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -138,14 +119,10 @@ class RegisterAuthenticatorUseCaseTests { registerAuthenticatorUseCase("test", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), OneginiAuthenticatorRegistrationError.GENERAL_ERROR) - Assert.assertEquals(error.message, "General error") - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(OneginiAuthenticatorRegistrationError.GENERAL_ERROR.toString(), "General error") + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 416fc912..3307fe02 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -8,12 +8,11 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -56,7 +55,7 @@ class RegistrationUseCaseTests { registrationUseCase(null, listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) @@ -88,15 +87,8 @@ class RegistrationUseCaseTests { registrationUseCase("differentId", listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.message, IDENTITY_PROVIDER_NOT_FOUND.message) - Assert.assertEquals(error.code, IDENTITY_PROVIDER_NOT_FOUND.code.toString()) - } - else -> fail("Test failed as no sdk error was passed") - } + verify(callbackMock).invoke(capture()) + SdkErrorAssert.assertEquals(IDENTITY_PROVIDER_NOT_FOUND, firstValue.exceptionOrNull()) } } @@ -111,7 +103,7 @@ class RegistrationUseCaseTests { registrationUseCase("testId", listOf("read"), callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) val testUser = OWUserProfile("QWERTY") val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index d22177af..71df687d 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -5,10 +5,8 @@ import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -41,14 +39,8 @@ class SetPreferredAuthenticatorUseCaseTests { @Test fun `When no user is authenticated, Then return an error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), NO_USER_PROFILE_IS_AUTHENTICATED.code) - Assert.assertEquals(error.message, NO_USER_PROFILE_IS_AUTHENTICATED.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) } @Test @@ -56,15 +48,8 @@ class SetPreferredAuthenticatorUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - setPreferredAuthenticatorUseCase("test") - - when (val error = setPreferredAuthenticatorUseCase("test").exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), AUTHENTICATOR_NOT_FOUND.code) - Assert.assertEquals(error.message, AUTHENTICATOR_NOT_FOUND.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt index 83c35e0e..8f8254ca 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -3,11 +3,10 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -18,7 +17,6 @@ import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -61,7 +59,7 @@ class ValidatePinWithPolicyUseCaseTests { validatePinWithPolicyUseCase("14789", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) + verify(callbackMock).invoke(capture()) Assert.assertEquals(firstValue.getOrNull(), Unit) } } @@ -73,15 +71,9 @@ class ValidatePinWithPolicyUseCaseTests { validatePinWithPolicyUseCase("14789", callbackMock) argumentCaptor>().apply { - verify(callbackMock, times(1)).invoke(capture()) - - when (val error = firstValue.exceptionOrNull()) { - is FlutterError -> { - Assert.assertEquals(error.code.toInt(), oneginiPinValidationErrorMock.errorType) - Assert.assertEquals(error.message, oneginiPinValidationErrorMock.message) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiPinValidationErrorMock.errorType.toString(), oneginiPinValidationErrorMock.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } From b16ad31aa6f8d9731a989d426de2e07850b9d3cd Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 17 Mar 2023 11:32:56 +0100 Subject: [PATCH 141/364] FP-49: CodeStyle changes --- .../Connectors/BridgeConnector.swift | 2 +- .../Connectors/PinConnector.swift | 12 ----- .../Handlers/ChangePinHandler.swift | 2 +- .../NativeBridge/Handlers/LoginHandler.swift | 4 +- .../Handlers/RegistrationHandler.swift | 4 +- .../OneginiModuleSwift+Pin.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 48 +++++++++---------- 7 files changed, 31 insertions(+), 43 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index 9433f8d7..92d33f73 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -6,7 +6,7 @@ class BridgeConnector: BridgeConnectorProtocol { let toPinConnector = PinConnector() - let toLoginHandler: LoginHandler = LoginHandler() + let toLoginHandler = LoginHandler() let toAppToWebHandler: AppToWebHandlerProtocol = AppToWebHandler() let toResourceFetchHandler: FetchResourcesHandlerProtocol = ResourcesHandler() let toMobileAuthConnector: BridgeToMobileAuthConnectorProtocol = MobileAuthConnector() diff --git a/ios/Classes/NativeBridge/Connectors/PinConnector.swift b/ios/Classes/NativeBridge/Connectors/PinConnector.swift index 810822c2..2ca71c09 100644 --- a/ios/Classes/NativeBridge/Connectors/PinConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/PinConnector.swift @@ -46,15 +46,3 @@ enum PinNotification : String { showError = "eventError", nextAuthenticationAttempt = "eventNextAuthenticationAttempt" } - -enum PinAction : String { - case provide = "provide", - cancel = "cancel" -} - -enum PinFlow : String { - case create = "create", -// change = "change", - authentication = "authentication" -// nextAuthenticationAttempt = "nextAuthenticationAttempt" -} diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 9dcb4d99..43575520 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -40,7 +40,7 @@ extension ChangePinHandler: ONGChangePinDelegate { func userClient(_: ONGUserClient, didChangePinForUser _: ONGUserProfile) { registrationHandler.handleDidRegisterUser() - changePinCompletion?(.success(())) + changePinCompletion?(.success) changePinCompletion = nil } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index e66355c2..007e64b8 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -11,7 +11,7 @@ class LoginHandler: NSObject { return } pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) - completion(.success(())) + completion(.success) } func cancelPinAuthentication(completion: (Result) -> Void) { @@ -20,7 +20,7 @@ class LoginHandler: NSObject { return } pinChallenge.sender.cancel(pinChallenge) - completion(.success(())) + completion(.success) } func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index a39ab306..4f4f68fa 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -96,7 +96,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { return } createPinChallenge.sender.respond(withCreatedPin: pin, challenge: createPinChallenge) - completion(.success(())) + completion(.success) } func cancelPinRegistration(completion: (Result) -> Void) { @@ -105,7 +105,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { return } createPinChallenge.sender.cancel(createPinChallenge) - completion(.success(())) + completion(.success) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index e3acb86b..a58b59ad 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -29,7 +29,7 @@ extension OneginiModuleSwift { // FIXME: Move this out of this file ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in guard let error = error else { - completion(.success(())) + completion(.success) return } completion(.failure(SdkError(code: error.code, errorDescription: error.localizedDescription).flutterError())) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 0387e96c..5049d393 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -113,25 +113,25 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest() { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest() { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } @@ -143,7 +143,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.registerUser(identityProviderId, scopes: scopes) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } @@ -152,64 +152,64 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { } func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getIdentityProviders().mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getIdentityProviders().mapError { $0 }) } func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.deregisterUser(profileId: profileId) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError { $0 }) } func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError { $0 }) } func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError { $0 }) } func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorId: registeredAuthenticatorId) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError { $0 }) } func changePin(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.changePin() { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.registerAuthenticator(authenticatorId) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func logout(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.logOut(){ result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } @@ -219,37 +219,37 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi { func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.runSingleSignOn(url) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func getAccessToken(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAccessToken().mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getAccessToken().mapError { $0 }) } func getRedirectUrl(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRedirectUrl().mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getRedirectUrl().mapError { $0 }) } func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getUserProfiles().mapError{$0}) + completion(OneginiModuleSwift.sharedInstance.getUserProfiles().mapError { $0 }) } func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.validatePinWithPolicy(pin) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.authenticateDevice(scopes) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.authenticateUserImplicitly(profileId, scopes) { result in - completion(result.mapError{$0}) + completion(result.mapError { $0 }) } } From 2061ba5d6c2a28d42da7a2c83d743b0700a25b79 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 08:54:43 +0100 Subject: [PATCH 142/364] fp-47 process feedback --- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index a7a92b14..bf65059e 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -37,13 +37,13 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } } - func requestResource(_ my_type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { + func requestResource(_ requestType: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { Logger.log("requestResource", sender: self) let request = generateONGResourceRequest(details) let requestCompletion = getRequestCompletion(completion) - switch my_type { + switch requestType { case ResourceRequestType.implicit: // For consistency with Android we perform this step guard let _ = ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() else { From 485813ce207e3a1bcbf51d32312cd865535c4277 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 09:27:48 +0100 Subject: [PATCH 143/364] fp-47 process missed feedback --- .../Handlers/ResourcesHandler.swift | 47 +++++++------------ ios/Classes/SwiftOneginiPlugin.swift | 2 +- 2 files changed, 18 insertions(+), 31 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 8b8e181b..c6ef5c32 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -66,41 +66,17 @@ private extension ResourcesHandler { func generateONGResourceRequest(_ details: OWRequestDetails) -> ONGResourceRequest { Logger.log("generateONGResourceRequest", sender: self) return ONGResourceRequest(path: details.path, - method: getRequestMethod(details.method), - body: details.body?.data(using: .utf8), - headers: getRequestHeaders(details.headers) - ) + method: details.method.stringValue, + body: details.body?.data(using: .utf8), + headers: getRequestHeaders(details.headers) + ) } func getRequestHeaders(_ headers: [String?: String?]?) -> [String: String]? { Logger.log("getRequestHeaders", sender: self) - if (headers == nil) { - return nil - } - - var requestHeaders = Dictionary() - - headers?.forEach { - if ($0.key != nil && $0.value != nil) { - requestHeaders[$0.key ?? ""] = $0.value - } - } - - return requestHeaders - } + guard let headers = headers else { return nil } - func getRequestMethod(_ method: HttpRequestMethod) -> String { - Logger.log("getRequestMethod", sender: self) - switch method { - case HttpRequestMethod.get: - return "GET" - case HttpRequestMethod.post: - return "POST" - case HttpRequestMethod.delete: - return "DELETE" - case HttpRequestMethod.put: - return "PUT" - } + return headers.filter { $0.key != nil && $0.value != nil } as? [String: String] ?? [:] } func getRequestCompletion(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { @@ -126,3 +102,14 @@ private extension ResourcesHandler { return completionRequest } } + +private extension HttpRequestMethod { + var stringValue: String { + switch self { + case .get: return "GET" + case .post: return "POST" + case .delete: return "DELETE" + case .put: return "PUT" + } + } +} diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 5bdc809b..457c2347 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -65,7 +65,7 @@ extension Result where Success == Void { public static var success: Result { .success(()) } } -func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> Dictionary { +func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> [String: String] { return headers.filter { $0.key is String && $0.value is String } as? [String: String] ?? [:] } From 252710b600ef283362f41d03cc7e057dc4f57892 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 12:02:21 +0100 Subject: [PATCH 144/364] fp-47 process feedback and removed old unused reworked files --- .../mobile/sdk/flutter/PigeonInterface.kt | 5 - .../sdk/flutter/helpers/ResourceHelper.kt | 122 ------------------ .../useCases/GetImplicitResourceUseCase.kt | 27 ---- .../useCases/GetResourceAnonymousUseCase.kt | 19 --- .../flutter/useCases/GetResourceUseCase.kt | 19 --- .../GetUnauthenticatedResourceUseCase.kt | 19 --- .../useCases/ResourceRequestUseCase.kt | 13 +- example/lib/screens/login_screen.dart | 7 +- example/lib/screens/user_screen.dart | 6 +- .../NativeBridge/Errors/SdkError.swift | 30 +++-- .../Handlers/ResourcesHandler.swift | 3 +- lib/resources_methods.dart | 12 +- test/resource_methods_test.dart | 24 ++-- 13 files changed, 45 insertions(+), 261 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetImplicitResourceUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 18df0af5..18d678aa 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -10,7 +10,6 @@ import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestH import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn @@ -33,13 +32,9 @@ import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetImplicitResourceUseCase import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetResourceAnonymousUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetResourceUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetUnauthenticatedResourceUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt deleted file mode 100644 index 53f0c820..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/ResourceHelper.kt +++ /dev/null @@ -1,122 +0,0 @@ -package com.onegini.mobile.sdk.flutter.helpers - -import com.google.gson.Gson -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_BODY -import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_HEADERS -import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_STATUS_CODE -import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_URL -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.POST -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PUT -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PATCH -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse -import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType - -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers -import io.reactivex.rxjava3.core.Observable -import io.reactivex.rxjava3.schedulers.Schedulers -import okhttp3.Call -import okhttp3.Callback -import okhttp3.Headers -import okhttp3.Headers.Companion.toHeaders -import okhttp3.HttpUrl.Companion.toHttpUrlOrNull -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.Response -import java.io.IOException -import java.util.Locale -import javax.inject.Inject -import javax.inject.Singleton -import kotlin.collections.HashMap - -@Singleton -class ResourceHelper @Inject constructor(private val oneginiSDK: OneginiSDK) { - fun callRequest(okHttpClient: OkHttpClient, request: Request, result: MethodChannel.Result) { - Observable.fromCallable { okHttpClient.newCall(request).execute() } - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe( - { data -> - if (data.code >= 400) { - SdkError( - wrapperError = ERROR_CODE_HTTP_REQUEST, - httpResponse = data - ).flutterError(result) - } else { - val response = Gson().toJson(mapOf( - RESPONSE_STATUS_CODE to data.code, - RESPONSE_BODY to data.body?.string(), - RESPONSE_HEADERS to data.headers, - RESPONSE_URL to data.request.url.toString())) - result.success(response) - } - }, - { - if (it.message != null) { - SdkError( - code = HTTP_REQUEST_ERROR.code, - message = it.message.toString() - ).flutterError(result) - } else { - SdkError(HTTP_REQUEST_ERROR).flutterError(result) - } - } - ) - } - - fun getRequest(call: MethodCall, url: String): Request { - val path = call.argument("path") - val headers = call.argument>("headers") - val method = call.argument("method") ?: "GET" - val encoding = call.argument("encoding") ?: "application/json" - val params = call.argument>("parameters") - val body = call.argument("body") - return prepareRequest(headers, method, "$url$path", encoding, body, params) - } - - private fun prepareRequest(headers: HashMap?, method: String, url: String, encoding: String, body: String?, params: HashMap?): Request { - val builder = Request.Builder() - prepareBodyForRequest(builder, body, method, encoding) - prepareUrlForRequest(builder, url, params) - prepareHeadersForRequest(builder, headers) - return builder.build() - } - - private fun prepareBodyForRequest(builder: Request.Builder, body: String?, method: String, encoding: String) { - if (body != null && body.isNotEmpty() && method.toUpperCase(Locale.ROOT) != "GET") { - val createdBody = body.toRequestBody(encoding.toMediaTypeOrNull()) - builder.method(method, createdBody) - } - } - - private fun prepareHeadersForRequest(builder: Request.Builder, headers: HashMap?) { - if (headers != null && headers.isNotEmpty()) { - builder.headers(headers.toHeaders()) - } - } - - private fun prepareUrlForRequest(builder: Request.Builder, url: String, params: HashMap?) { - val urlBuilder = url.toHttpUrlOrNull()?.newBuilder() - - params?.forEach { - urlBuilder?.addQueryParameter(it.key, it.value) - } - - val httpUrl = urlBuilder?.build() - - if (httpUrl != null) { - builder.url(httpUrl) - } else { - builder.url(url) - } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetImplicitResourceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetImplicitResourceUseCase.kt deleted file mode 100644 index 88487dd1..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetImplicitResourceUseCase.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_NOT_AUTHENTICATED_IMPLICITLY -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetImplicitResourceUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result, resourceHelper: ResourceHelper) { - when (oneginiSDK.oneginiClient.userClient.implicitlyAuthenticatedUserProfile) { - null -> SdkError(USER_NOT_AUTHENTICATED_IMPLICITLY).flutterError(result) - else -> { - val okHttpClient: OkHttpClient = oneginiSDK.oneginiClient.userClient.implicitResourceOkHttpClient - val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - val request = resourceHelper.getRequest(call, resourceBaseUrl) - resourceHelper.callRequest(okHttpClient, request, result) - } - } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt deleted file mode 100644 index 344e2f5c..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceAnonymousUseCase.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetResourceAnonymousUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result, resourceHelper: ResourceHelper) { - val okHttpClient: OkHttpClient = oneginiSDK.oneginiClient.deviceClient.anonymousResourceOkHttpClient - val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - val request = resourceHelper.getRequest(call, resourceBaseUrl) - resourceHelper.callRequest(okHttpClient, request, result) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt deleted file mode 100644 index d6664c20..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetResourceUseCase.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetResourceUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result, resourceHelper: ResourceHelper) { - val okHttpClient: OkHttpClient = oneginiSDK.oneginiClient.userClient.resourceOkHttpClient - val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - val request = resourceHelper.getRequest(call, resourceBaseUrl) - resourceHelper.callRequest(okHttpClient, request, result) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt deleted file mode 100644 index 28238470..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUnauthenticatedResourceUseCase.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.ResourceHelper -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import okhttp3.OkHttpClient -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetUnauthenticatedResourceUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result, resourceHelper: ResourceHelper) { - val okHttpClient: OkHttpClient = oneginiSDK.oneginiClient.deviceClient.unauthenticatedResourceOkHttpClient - val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - val request = resourceHelper.getRequest(call, resourceBaseUrl) - resourceHelper.callRequest(okHttpClient, request, result) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index b09c3e8d..3e63c218 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -61,15 +61,10 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini private fun getHeaders(headers: Map?): Headers { val headerBuilder = Headers.Builder() - headers?.entries?.forEach { - val headerKey = it.key - val headerValue = it.value - - // Pigeon 9.0.5 limits enforcing non null values in maps - if (headerKey is String && headerValue is String) { - headerBuilder.add(headerKey, headerValue) - } - } + // Pigeon 9.0.5 limits enforcing non null values in maps + headers?.entries + ?.filter { it.key is String && it.value is String} + ?.forEach { headerBuilder.add(it.key as String, it.value as String) } return headerBuilder.build() } diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 02c294cf..854b6203 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -143,11 +143,8 @@ class _LoginScreenState extends State { Future getImplicitUserDetails(String profileId) async { var returnString = ""; try { - print("boop"); - var userProfileId = await Onegini.instance.userClient - .authenticateUserImplicitly(profileId, ["read"]); - - var response = await Onegini.instance.resourcesMethods.resourceRequest( + await Onegini.instance.userClient.authenticateUserImplicitly(profileId, ["read"]); + var response = await Onegini.instance.resourcesMethods.requestResource( ResourceRequestType.implicit, RequestDetails(path: "user-id-decorated", method: HttpRequestMethod.get)); diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index f3ba32b0..89712418 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -423,14 +423,14 @@ class _InfoState extends State { Future getApplicationDetails() async { await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - var response = await Onegini.instance.resourcesMethods.resourceRequest(ResourceRequestType.anonymous, RequestDetails(path: "application-details", method: HttpRequestMethod.get)); + var response = await Onegini.instance.resourcesMethods.requestResource(ResourceRequestType.anonymous, RequestDetails(path: "application-details", method: HttpRequestMethod.get)); var res = json.decode(response.body); return applicationDetailsFromJson(res); } Future getClientResource() async { var response = await Onegini.instance.resourcesMethods - .getResource(RequestDetails(path: "devices", method: HttpRequestMethod.get)) + .requestResourceAuthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get)) .catchError((error) { print('Caught error: $error'); @@ -443,7 +443,7 @@ class _InfoState extends State { Future makeUnaunthenticatedRequest() async { var headers = {'Declareren-Appversion': 'CZ.app'}; var response = await Onegini.instance.resourcesMethods - .getResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) + .requestResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) .catchError((onError) { debugPrint(onError); }); diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index e578e505..fa5ba9be 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -56,12 +56,25 @@ class SdkError: Error { setResponseDetails(response, iosCode, iosMessage) } - private func setGenericDetails() { + func flutterError() -> FlutterError { + let _error = FlutterError(code: "\(self.code)", message: self.errorDescription, details: details) + + return _error + } + + static func convertToFlutter(_ error: SdkError?) -> FlutterError { + let _error = error ?? SdkError(.genericError) + return _error.flutterError() + } +} + +private extension SdkError { + func setGenericDetails() { details["code"] = String(code) details["message"] = errorDescription } - private func setInfoDetails(_ info: [String: Any?]?) { + func setInfoDetails(_ info: [String: Any?]?) { if (info == nil) { details["userInfo"] = [:] } else { @@ -69,7 +82,7 @@ class SdkError: Error { } } - private func setResponseDetails(_ response: ONGResourceResponse?, _ iosCode: Int?, _ iosMessage: String?) { + func setResponseDetails(_ response: ONGResourceResponse?, _ iosCode: Int?, _ iosMessage: String?) { if (response == nil) { details["response"] = Dictionary() } else { @@ -85,17 +98,6 @@ class SdkError: Error { details["iosMessage"] = iosMessage } } - - func flutterError() -> FlutterError { - let _error = FlutterError(code: "\(self.code)", message: self.errorDescription, details: details) - - return _error - } - - static func convertToFlutter(_ error: SdkError?) -> FlutterError { - let _error = error ?? SdkError(.genericError) - return _error.flutterError() - } } private extension ONGResourceResponse { diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index c6ef5c32..bd2b6992 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -73,10 +73,11 @@ private extension ResourcesHandler { } func getRequestHeaders(_ headers: [String?: String?]?) -> [String: String]? { + // Pigeon 9.0.5 limits enforcing non null values in maps; from Flutter we only pass [String: String] Logger.log("getRequestHeaders", sender: self) guard let headers = headers else { return nil } - return headers.filter { $0.key != nil && $0.value != nil } as? [String: String] ?? [:] + return headers.filter { $0.key != nil && $0.value != nil } as? [String: String] } func getRequestCompletion(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index 508ceb17..38514b2d 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -8,7 +8,7 @@ class ResourcesMethods { final api = ResourceMethodApi(); /// Gets any type of resource - Future resourceRequest(ResourceRequestType type, RequestDetails details) async { + Future requestResource(ResourceRequestType type, RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(type, owDetails); @@ -20,7 +20,7 @@ class ResourcesMethods { /// Gets resources anonymously. - Future getResourceAnonymous(RequestDetails details) async { + Future requestResourceAnonymous(RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(ResourceRequestType.anonymous, owDetails); @@ -30,8 +30,8 @@ class ResourcesMethods { return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); } - /// Gets resources. - Future getResource(RequestDetails details) async { + /// Gets authenticated resources. + Future requestResourceAuthenticated(RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(ResourceRequestType.authenticated, owDetails); @@ -42,7 +42,7 @@ class ResourcesMethods { } /// Gets implicit resource. - Future getResourceImplicit(RequestDetails details) async { + Future requestResourceImplicit(RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(ResourceRequestType.implicit, owDetails); @@ -53,7 +53,7 @@ class ResourcesMethods { } /// Gets unauthenticated resource. - Future getResourceUnauthenticated(RequestDetails details) async { + Future requestResourceUnauthenticated(RequestDetails details) async { var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); var owResponse = await api.requestResource(ResourceRequestType.unauthenticated, owDetails); diff --git a/test/resource_methods_test.dart b/test/resource_methods_test.dart index 9bf7d69e..63110d9c 100644 --- a/test/resource_methods_test.dart +++ b/test/resource_methods_test.dart @@ -23,7 +23,7 @@ void main() { }); } - group('ResourcesMethods getResourceAnonymous', () { + group('ResourcesMethods requestResourceAnonymous', () { test( 'return String', () async { @@ -32,7 +32,7 @@ void main() { Constants.getResourceAnonymous, Future.value('success')); //act - var result = await resourcesMethods.getResourceAnonymous(''); + var result = await resourcesMethods.requestResourceAnonymous(''); //assert expect(result, 'success'); @@ -46,7 +46,7 @@ void main() { setupMethodChannel(Constants.getResourceAnonymous, Future.value(null)); //act - var result = await resourcesMethods.getResourceAnonymous(''); + var result = await resourcesMethods.requestResourceAnonymous(''); //assert expect(result, null); @@ -61,13 +61,13 @@ void main() { Future.error(PlatformException(code: '1'))); //assert - expect(() async => await resourcesMethods.getResourceAnonymous(''), + expect(() async => await resourcesMethods.requestResourceAnonymous(''), throwsA(isA())); }, ); }); - group('ResourcesMethods getResource', () { + group('ResourcesMethods requestResource', () { test( 'return String', () async { @@ -75,7 +75,7 @@ void main() { setupMethodChannel(Constants.getResource, Future.value('success')); //act - var result = await resourcesMethods.getResource(''); + var result = await resourcesMethods.requestResource(''); //assert expect(result, 'success'); @@ -89,7 +89,7 @@ void main() { setupMethodChannel(Constants.getResource, Future.value(null)); //act - var result = await resourcesMethods.getResource(''); + var result = await resourcesMethods.requestResource(''); //assert expect(result, null); @@ -104,13 +104,13 @@ void main() { Constants.getResource, Future.error(PlatformException(code: '1'))); //assert - expect(() async => await resourcesMethods.getResource(''), + expect(() async => await resourcesMethods.requestResource(''), throwsA(isA())); }, ); }); - group('ResourcesMethods getResourceUnauthenticated', () { + group('ResourcesMethods requestResourceUnauthenticated', () { test( 'return String', () async { @@ -119,7 +119,7 @@ void main() { Constants.getUnauthenticatedResource, Future.value('success')); //act - var result = await resourcesMethods.getResourceUnauthenticated(''); + var result = await resourcesMethods.requestResourceUnauthenticated(''); //assert expect(result, 'success'); @@ -134,7 +134,7 @@ void main() { Constants.getUnauthenticatedResource, Future.value(null)); //act - var result = await resourcesMethods.getResourceUnauthenticated(''); + var result = await resourcesMethods.requestResourceUnauthenticated(''); //assert expect(result, null); @@ -150,7 +150,7 @@ void main() { //assert expect( - () async => await resourcesMethods.getResourceUnauthenticated(''), + () async => await resourcesMethods.requestResourceUnauthenticated(''), throwsA(isA())); }, ); From 8a8d6e45f6b84643085b70323fafb41c23462b41 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 12:04:24 +0100 Subject: [PATCH 145/364] fp-47 link issue ticket to todo --- .../mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 3e63c218..b0d46755 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -49,7 +49,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini } private fun getCompleteResourceUrl(path: String): String { - // TODO Add support for multiple base resource urls + // TODO Add support for multiple base resource urls; https://onewelcome.atlassian.net/browse/FP-38 val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl return when (path.startsWith(resourceBaseUrl)) { From 8ecb7b359c8eb18ae3149497dbc98a068f071fa2 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 14:26:47 +0100 Subject: [PATCH 146/364] fp-43 remove cz specific headers from request --- example/lib/screens/user_screen.dart | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 89712418..0c2d53fd 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -441,11 +441,10 @@ class _InfoState extends State { } Future makeUnaunthenticatedRequest() async { - var headers = {'Declareren-Appversion': 'CZ.app'}; var response = await Onegini.instance.resourcesMethods - .requestResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get, headers: headers)) - .catchError((onError) { - debugPrint(onError); + .requestResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get)) + .catchError((error) { + print(error); }); var res = json.decode(response.body); From 29d7582f9e6a37a1e5ad3a22fda20fd766d2e2ea Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 20 Mar 2023 14:56:05 +0100 Subject: [PATCH 147/364] FP-75: Remove now redundant tests --- test/onegini_test.dart | 4 - test/resource_methods_test.dart | 158 ------- test/user_client_test.dart | 769 -------------------------------- 3 files changed, 931 deletions(-) delete mode 100644 test/onegini_test.dart delete mode 100644 test/resource_methods_test.dart delete mode 100644 test/user_client_test.dart diff --git a/test/onegini_test.dart b/test/onegini_test.dart deleted file mode 100644 index b2ad044f..00000000 --- a/test/onegini_test.dart +++ /dev/null @@ -1,4 +0,0 @@ -// TODO implement tests or remove file -void main() { - -} diff --git a/test/resource_methods_test.dart b/test/resource_methods_test.dart deleted file mode 100644 index 63110d9c..00000000 --- a/test/resource_methods_test.dart +++ /dev/null @@ -1,158 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:onegini/constants/constants.dart'; -import 'package:onegini/resources_methods.dart'; - -void main() { - late ResourcesMethods resourcesMethods; - late MethodChannel methodChannel; - - setUp(() { - TestWidgetsFlutterBinding.ensureInitialized(); - resourcesMethods = ResourcesMethods(); - methodChannel = const MethodChannel('onegini'); - }); - - void setupMethodChannel(String method, Future returnValue) { - TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannel, (methodCall) async { - if (methodCall.method == method) { - return returnValue; - } - return 0; - }); - } - - group('ResourcesMethods requestResourceAnonymous', () { - test( - 'return String', - () async { - //arrange - setupMethodChannel( - Constants.getResourceAnonymous, Future.value('success')); - - //act - var result = await resourcesMethods.requestResourceAnonymous(''); - - //assert - expect(result, 'success'); - }, - ); - - test( - 'return null', - () async { - //arrange - setupMethodChannel(Constants.getResourceAnonymous, Future.value(null)); - - //act - var result = await resourcesMethods.requestResourceAnonymous(''); - - //assert - expect(result, null); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getResourceAnonymous, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await resourcesMethods.requestResourceAnonymous(''), - throwsA(isA())); - }, - ); - }); - - group('ResourcesMethods requestResource', () { - test( - 'return String', - () async { - //arrange - setupMethodChannel(Constants.getResource, Future.value('success')); - - //act - var result = await resourcesMethods.requestResource(''); - - //assert - expect(result, 'success'); - }, - ); - - test( - 'return null', - () async { - //arrange - setupMethodChannel(Constants.getResource, Future.value(null)); - - //act - var result = await resourcesMethods.requestResource(''); - - //assert - expect(result, null); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.getResource, Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await resourcesMethods.requestResource(''), - throwsA(isA())); - }, - ); - }); - - group('ResourcesMethods requestResourceUnauthenticated', () { - test( - 'return String', - () async { - //arrange - setupMethodChannel( - Constants.getUnauthenticatedResource, Future.value('success')); - - //act - var result = await resourcesMethods.requestResourceUnauthenticated(''); - - //assert - expect(result, 'success'); - }, - ); - - test( - 'return null', - () async { - //arrange - setupMethodChannel( - Constants.getUnauthenticatedResource, Future.value(null)); - - //act - var result = await resourcesMethods.requestResourceUnauthenticated(''); - - //assert - expect(result, null); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getUnauthenticatedResource, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => await resourcesMethods.requestResourceUnauthenticated(''), - throwsA(isA())); - }, - ); - }); -} diff --git a/test/user_client_test.dart b/test/user_client_test.dart deleted file mode 100644 index 5b4eb553..00000000 --- a/test/user_client_test.dart +++ /dev/null @@ -1,769 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:onegini/constants/constants.dart'; -import 'package:onegini/user_client.dart'; - -void main() { - late UserClient userClient; - late MethodChannel methodChannel; - - setUp(() { - TestWidgetsFlutterBinding.ensureInitialized(); - userClient = UserClient(); - methodChannel = const MethodChannel('onegini'); - }); - - void setupMethodChannel(String method, Future returnValue) { - TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannel, (methodCall) async { - if (methodCall.method == method) { - return returnValue; - } - return 0; - }); - } - - group('UserClient registerUser', () { - test( - 'return RegistrationResponse', - () async { - //arrange - setupMethodChannel(Constants.registerUser, - Future.value('{"userProfile":{"profileId":"1234"}}')); - - var result = await userClient.registerUser(null, '', []); - - //assert - expect(result.userProfile?.profileId, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel(Constants.registerUser, Future.value(null)); - - //assert - expect(() async => await userClient.registerUser(null, '', []), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.registerUser, Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.registerUser(null, '', []), - throwsA(isA())); - }, - ); - }); - - group('UserClient getIdentityProviders', () { - test( - 'return List', - () async { - //arrange - setupMethodChannel(Constants.getIdentityProvidersMethod, - Future.value('[{"id" : "1234", "name" : "name"}]')); - - //act - var result = await userClient.getIdentityProviders(null); - - //assert - expect(result.first.id, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.getIdentityProvidersMethod, Future.value(null)); - - //assert - expect(() async => await userClient.getIdentityProviders(null), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getIdentityProvidersMethod, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.getIdentityProviders(null), - throwsA(isA())); - }, - ); - }); - - group('UserClient deregisterUser', () { - test( - 'return true', - () async { - //arrange - setupMethodChannel(Constants.deregisterUserMethod, Future.value(true)); - - //act - var result = await userClient.deregisterUser('1234'); - - //assert - expect(result, true); - }, - ); - - test( - 'return false', - () async { - //arrange - setupMethodChannel(Constants.deregisterUserMethod, Future.value(false)); - - //act - var result = await userClient.deregisterUser('1234'); - - //assert - expect(result, false); - }, - ); - - test( - 'return null defaults to false', - () async { - //arrange - setupMethodChannel(Constants.deregisterUserMethod, Future.value(null)); - - //act - var result = await userClient.deregisterUser('1234'); - - //assert - expect(result, false); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.deregisterUserMethod, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.deregisterUser('1234'), - throwsA(isA())); - }, - ); - }); - - group('UserClient getRegisteredAuthenticators', () { - test( - 'return List', - () async { - //arrange - setupMethodChannel(Constants.getRegisteredAuthenticators, - Future.value('[{"id" : "1234", "name" : "name"}]')); - - //act - var result = await userClient.getRegisteredAuthenticators(null, "1234"); - - //assert - expect(result.first.id, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.getRegisteredAuthenticators, Future.value(null)); - - //assert - expect(() async => await userClient.getIdentityProviders(null), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getRegisteredAuthenticators, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => await userClient.getRegisteredAuthenticators(null, ""), - throwsA(isA())); - }, - ); - }); - - group('UserClient getAllAuthenticators', () { - test( - 'return List', - () async { - //arrange - setupMethodChannel(Constants.getAllAuthenticators, - Future.value('[{"id" : "1234", "name" : "name"}]')); - - //act - var result = await userClient.getAllAuthenticators(null, "1234"); - - //assert - expect(result.first.id, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getAllAuthenticators, Future.value(null)); - - //assert - expect(() async => await userClient.getAllAuthenticators(null, ""), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getAllAuthenticators, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.getAllAuthenticators(null, ""), - throwsA(isA())); - }, - ); - }); - - group('UserClient authenticateUser', () { - test( - 'return RegistrationResponse', - () async { - //arrange - setupMethodChannel(Constants.authenticateUser, - Future.value('{"userProfile":{"profileId":"1234"}}')); - - //act - var result = await userClient.authenticateUser(null, "1234", ''); - - //assert - expect(result.userProfile?.profileId, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel(Constants.authenticateUser, Future.value(null)); - - //assert - expect(() async => await userClient.authenticateUser(null, "1234", ''), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.authenticateUser, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.authenticateUser(null, "1234", ''), - throwsA(isA())); - }, - ); - }); - - group('UserClient getNotRegisteredAuthenticators', () { - test( - 'return List', - () async { - //arrange - setupMethodChannel(Constants.getAllNotRegisteredAuthenticators, - Future.value('[{"id" : "1234", "name" : "name"}]')); - - //act - var result = - await userClient.getNotRegisteredAuthenticators(null, "1234"); - - //assert - expect(result.first.id, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.getAllNotRegisteredAuthenticators, Future.value(null)); - - //assert - expect( - () async => - await userClient.getNotRegisteredAuthenticators(null, ""), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getAllNotRegisteredAuthenticators, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => - await userClient.getNotRegisteredAuthenticators(null, ""), - throwsA(isA())); - }, - ); - }); - - group('UserClient registerAuthenticator', () { - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.registerAuthenticator, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => - await userClient.registerAuthenticator(null, 'fingerprint'), - throwsA(isA())); - }, - ); - }); - - group('UserClient deregisterAuthenticator', () { - test( - 'return true', - () async { - //arrange - setupMethodChannel( - Constants.deregisterAuthenticator, Future.value(true)); - - //act - var result = - await userClient.deregisterAuthenticator(null, 'fingerprint'); - - //assert - expect(result, true); - }, - ); - - test( - 'return false', - () async { - //arrange - setupMethodChannel( - Constants.deregisterAuthenticator, Future.value(false)); - - //act - var result = - await userClient.deregisterAuthenticator(null, 'fingerprint'); - - //assert - expect(result, false); - }, - ); - - test( - 'return null defaults to false', - () async { - //arrange - setupMethodChannel( - Constants.deregisterAuthenticator, Future.value(null)); - - //act - var result = - await userClient.deregisterAuthenticator(null, 'fingerprint'); - - //assert - expect(result, false); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.deregisterAuthenticator, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => - await userClient.deregisterAuthenticator(null, 'fingerprint'), - throwsA(isA())); - }, - ); - }); - - group('UserClient logout', () { - test( - 'return true', - () async { - //arrange - setupMethodChannel(Constants.logout, Future.value(true)); - - //act - var result = await userClient.logout(); - - //assert - expect(result, true); - }, - ); - - test( - 'return false', - () async { - //arrange - setupMethodChannel(Constants.logout, Future.value(false)); - - //act - var result = await userClient.logout(); - - //assert - expect(result, false); - }, - ); - - test( - 'return null defaults to false', - () async { - //arrange - setupMethodChannel(Constants.logout, Future.value(null)); - - //act - var result = await userClient.logout(); - - //assert - expect(result, false); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.logout, Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.logout(), - throwsA(isA())); - }, - ); - }); - - group('UserClient mobileAuthWithOtp', () { - test( - 'return String', - () async { - //arrange - setupMethodChannel( - Constants.handleMobileAuthWithOtp, Future.value('success')); - - //act - var result = await userClient.mobileAuthWithOtp(''); - - //assert - expect(result, 'success'); - }, - ); - - test( - 'return null', - () async { - //arrange - setupMethodChannel( - Constants.handleMobileAuthWithOtp, Future.value(null)); - - //act - var result = await userClient.mobileAuthWithOtp(''); - - //assert - expect(result, null); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.handleMobileAuthWithOtp, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.mobileAuthWithOtp(''), - throwsA(isA())); - }, - ); - }); - - group('UserClient getAppToWebSingleSignOn', () { - test( - 'return OneginiAppToWebSingleSignOn', - () async { - //arrange - setupMethodChannel(Constants.getAppToWebSingleSignOn, - Future.value('{"token": "1234", "redirectUrl" : ""}')); - - var result = await userClient.getAppToWebSingleSignOn(''); - - //assert - expect(result.token, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.getAppToWebSingleSignOn, Future.value(null)); - - //assert - expect(() async => await userClient.getAppToWebSingleSignOn(''), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getAppToWebSingleSignOn, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.getAppToWebSingleSignOn(''), - throwsA(isA())); - }, - ); - }); - - group('UserClient getUserProfiles', () { - test( - 'return List', - () async { - //arrange - setupMethodChannel(Constants.getUserProfiles, - Future.value('[{"profileId":"1234","isDefault":true}]')); - - //act - var result = await userClient.getUserProfiles(); - - //assert - expect(result.first.profileId, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getUserProfiles, Future.value(null)); - - //assert - expect(() async => await userClient.getUserProfiles(), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.getUserProfiles, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.getUserProfiles(), - throwsA(isA())); - }, - ); - }); - - group('UserClient validatePinWithPolicy', () { - test( - 'return true', - () async { - //arrange - setupMethodChannel(Constants.validatePinWithPolicy, Future.value(true)); - - //act - var result = await userClient.validatePinWithPolicy(''); - - //assert - expect(result, true); - }, - ); - - test( - 'return false', - () async { - //arrange - setupMethodChannel( - Constants.validatePinWithPolicy, Future.value(false)); - - //act - var result = await userClient.validatePinWithPolicy(''); - - //assert - expect(result, false); - }, - ); - - test( - 'return null defaults to false', - () async { - //arrange - setupMethodChannel(Constants.validatePinWithPolicy, Future.value(null)); - - //act - var result = await userClient.validatePinWithPolicy(''); - - //assert - expect(result, false); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.validatePinWithPolicy, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.validatePinWithPolicy(''), - throwsA(isA())); - }, - ); - }); - - group('UserClient authenticateDevice', () { - test( - 'return true', - () async { - //arrange - setupMethodChannel(Constants.authenticateDevice, Future.value(true)); - - //act - var result = await userClient.authenticateDevice(null); - - //assert - expect(result, true); - }, - ); - - test( - 'return false', - () async { - //arrange - setupMethodChannel(Constants.authenticateDevice, Future.value(false)); - - //act - var result = await userClient.authenticateDevice(null); - - //assert - expect(result, false); - }, - ); - - test( - 'return null defaults to false', - () async { - //arrange - setupMethodChannel(Constants.authenticateDevice, Future.value(null)); - - //act - var result = await userClient.authenticateDevice(null); - - //assert - expect(result, false); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.authenticateDevice, - Future.error(PlatformException(code: '1'))); - - //assert - expect(() async => await userClient.authenticateDevice(null), - throwsA(isA())); - }, - ); - }); - - group('UserClient authenticateUserImplicitly', () { - test( - 'return UserProfile', - () async { - //arrange - setupMethodChannel(Constants.authenticateUserImplicitly, - Future.value('1234')); - - var result = await userClient.authenticateUserImplicitly("1234", null); - - //assert - expect(result, '1234'); - }, - ); - - test( - 'return null, handle TypeError and throw PlatformException', - () async { - //arrange - setupMethodChannel( - Constants.authenticateUserImplicitly, Future.value(null)); - - //assert - expect( - () async => await userClient.authenticateUserImplicitly("", null), - throwsA(isA())); - }, - ); - - test( - 'handle PlatformException', - () async { - //arrange - setupMethodChannel(Constants.authenticateUserImplicitly, - Future.error(PlatformException(code: '1'))); - - //assert - expect( - () async => await userClient.authenticateUserImplicitly("", null), - throwsA(isA())); - }, - ); - }); -} From fc245bece23ca03eefcad9b4eb1730448a604020 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 20 Mar 2023 14:56:28 +0100 Subject: [PATCH 148/364] FP-75: setup NativeApi and setup a provider for the nativeApi --- .../kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt | 5 ++++- .../sdk/flutter/module/FlutterOneWelcomeSdkModule.kt | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index ee1d11da..6ee9d517 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -4,6 +4,7 @@ import androidx.annotation.NonNull import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceMethodApi import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel @@ -19,6 +20,7 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { /// when the Flutter Engine is detached from the Activity private lateinit var channel: MethodChannel private lateinit var eventChannel: EventChannel + lateinit var nativeApi : NativeCallFlutterApi @Inject lateinit var onMethodCallMapper: OnMethodCallMapper @@ -26,9 +28,10 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { // Pigeon setup UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) ResourceMethodApi.setUp(flutterPluginBinding.binaryMessenger, this) + nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) val component = DaggerFlutterOneWelcomeSdkComponent.builder() - .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext)) + .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext, nativeApi)) .build() component.inject(this) channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onegini") diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt index 37f880bd..2a2b340c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt @@ -1,14 +1,19 @@ package com.onegini.mobile.sdk.flutter.module import android.content.Context +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import dagger.Module import dagger.Provides import javax.inject.Singleton @Module -class FlutterOneWelcomeSdkModule(private val applicationContext: Context) { +class FlutterOneWelcomeSdkModule(private val applicationContext: Context, private val nativeApi: NativeCallFlutterApi) { @Provides @Singleton fun provideContext() = applicationContext + + @Provides + @Singleton + fun provideNativeApi() = nativeApi } From d991a936ea2e9b6af59bdd9bd5da496e6f381d0d Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 15:17:11 +0100 Subject: [PATCH 149/364] fp-73 added usecases for pin --- .../mobile/sdk/flutter/PigeonInterface.kt | 22 +++++++-------- .../SubmitPinAuthenticationRequestUseCase.kt | 27 +++++++++++++++++++ .../SubmitPinRegistrationRequestUseCase.kt | 24 +++++++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 18d678aa..028aba56 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -45,6 +45,8 @@ import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUseCase +import com.onegini.mobile.sdk.flutter.useCases.SubmitPinAuthenticationRequestUseCase +import com.onegini.mobile.sdk.flutter.useCases.SubmitPinRegistrationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase import javax.inject.Inject @@ -98,6 +100,10 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase @Inject + lateinit var submitPinAuthenticationRequestUseCase: SubmitPinAuthenticationRequestUseCase + @Inject + lateinit var submitPinRegistrationRequestUseCase: SubmitPinRegistrationRequestUseCase + @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase @Inject lateinit var oneginiSDK: OneginiSDK @@ -253,27 +259,19 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 - PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() - callback(Result.success(Unit)) + callback(submitPinAuthenticationRequestUseCase(null)) } override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 - PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) - callback(Result.success(Unit)) + callback(submitPinAuthenticationRequestUseCase(pin)) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 - PinRequestHandler.CALLBACK?.denyAuthenticationRequest() - callback(Result.success(Unit)) + callback(submitPinRegistrationRequestUseCase(null)) } override fun pinAcceptRegistrationRequest(pin: String, callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-73 - PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) - callback(Result.success(Unit)) + callback(submitPinRegistrationRequestUseCase(pin)) } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt new file mode 100644 index 00000000..6b8870d5 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt @@ -0,0 +1,27 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SubmitPinAuthenticationRequestUseCase @Inject constructor() { + operator fun invoke(pin: String?): Result { + if (PinAuthenticationRequestHandler.CALLBACK == null) { + return Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + when (pin) { + null -> { + PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() + } + else -> { + PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) + } + } + + return Result.success(Unit) + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt new file mode 100644 index 00000000..de6e0b80 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt @@ -0,0 +1,24 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS + +class SubmitPinRegistrationRequestUseCase { + operator fun invoke(pin: String?): Result { + if (PinRequestHandler.CALLBACK == null) { + return Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } + + when (pin) { + null -> { + PinRequestHandler.CALLBACK?.denyAuthenticationRequest() + } + else -> { + PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) + } + } + + return Result.success(Unit) + } +} From d930559b8e1f7e3ad4cfc69e924fbfa7ad0fab37 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 16:27:28 +0100 Subject: [PATCH 150/364] FP-73 Updated usecases such that each callback has its own usecase in addition to adding new test cases --- .../mobile/sdk/flutter/PigeonInterface.kt | 24 ++++++---- .../PinAuthenticationRequestAcceptUseCase.kt | 20 ++++++++ .../PinAuthenticationRequestDenyUseCase.kt | 20 ++++++++ .../PinRegistrationRequestAcceptUseCase.kt | 20 ++++++++ .../PinRegistrationRequestDenyUseCase.kt | 20 ++++++++ .../SubmitPinAuthenticationRequestUseCase.kt | 27 ----------- .../SubmitPinRegistrationRequestUseCase.kt | 24 ---------- ...nAuthenticationRequestAcceptUseCaseTest.kt | 46 +++++++++++++++++++ ...PinAuthenticationRequestDenyUseCaseTest.kt | 46 +++++++++++++++++++ ...PinRegistrationRequestAcceptUseCaseTest.kt | 44 ++++++++++++++++++ .../PinRegistrationRequestDenyUseCaseTest.kt | 46 +++++++++++++++++++ 11 files changed, 276 insertions(+), 61 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 028aba56..e2c01e29 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -8,8 +8,6 @@ import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn @@ -45,8 +43,10 @@ import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase import com.onegini.mobile.sdk.flutter.useCases.SubmitCustomRegistrationActionUseCase -import com.onegini.mobile.sdk.flutter.useCases.SubmitPinAuthenticationRequestUseCase -import com.onegini.mobile.sdk.flutter.useCases.SubmitPinRegistrationRequestUseCase +import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUseCase +import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCase +import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestAcceptUseCase +import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestDenyUseCase import com.onegini.mobile.sdk.flutter.useCases.ValidatePinWithPolicyUseCase import javax.inject.Inject @@ -100,9 +100,13 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase @Inject - lateinit var submitPinAuthenticationRequestUseCase: SubmitPinAuthenticationRequestUseCase + lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase @Inject - lateinit var submitPinRegistrationRequestUseCase: SubmitPinRegistrationRequestUseCase + lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase + @Inject + lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase + @Inject + lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase @Inject @@ -259,19 +263,19 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { - callback(submitPinAuthenticationRequestUseCase(null)) + callback(pinAuthenticationRequestDenyUseCase()) } override fun pinAcceptAuthenticationRequest(pin: String, callback: (Result) -> Unit) { - callback(submitPinAuthenticationRequestUseCase(pin)) + callback(pinAuthenticationRequestAcceptUseCase(pin)) } override fun pinDenyRegistrationRequest(callback: (Result) -> Unit) { - callback(submitPinRegistrationRequestUseCase(null)) + callback(pinRegistrationRequestDenyUseCase()) } override fun pinAcceptRegistrationRequest(pin: String, callback: (Result) -> Unit) { - callback(submitPinRegistrationRequestUseCase(pin)) + callback(pinRegistrationRequestAcceptUseCase(pin)) } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt new file mode 100644 index 00000000..4b9e33bf --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class PinAuthenticationRequestAcceptUseCase @Inject constructor() { + operator fun invoke(pin: String): Result { + return when (val pinCallback = PinAuthenticationRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + pinCallback.acceptAuthenticationRequest(pin.toCharArray()) + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt new file mode 100644 index 00000000..25977947 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class PinAuthenticationRequestDenyUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val pinCallback = PinAuthenticationRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + pinCallback.denyAuthenticationRequest() + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt new file mode 100644 index 00000000..93a85544 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class PinRegistrationRequestAcceptUseCase @Inject constructor() { + operator fun invoke(pin: String): Result { + return when (val pinCallback = PinRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + pinCallback.acceptAuthenticationRequest(pin.toCharArray()) + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt new file mode 100644 index 00000000..ccde27fc --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class PinRegistrationRequestDenyUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val pinCallback = PinRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + pinCallback.denyAuthenticationRequest() + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt deleted file mode 100644 index 6b8870d5..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinAuthenticationRequestUseCase.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS -import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class SubmitPinAuthenticationRequestUseCase @Inject constructor() { - operator fun invoke(pin: String?): Result { - if (PinAuthenticationRequestHandler.CALLBACK == null) { - return Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } - - when (pin) { - null -> { - PinAuthenticationRequestHandler.CALLBACK?.denyAuthenticationRequest() - } - else -> { - PinAuthenticationRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) - } - } - - return Result.success(Unit) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt deleted file mode 100644 index de6e0b80..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitPinRegistrationRequestUseCase.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS - -class SubmitPinRegistrationRequestUseCase { - operator fun invoke(pin: String?): Result { - if (PinRequestHandler.CALLBACK == null) { - return Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - } - - when (pin) { - null -> { - PinRequestHandler.CALLBACK?.denyAuthenticationRequest() - } - else -> { - PinRequestHandler.CALLBACK?.acceptAuthenticationRequest(pin.toCharArray()) - } - } - - return Result.success(Unit) - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt new file mode 100644 index 00000000..22a633e2 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class PinAuthenticationRequestAcceptUseCaseTest { + + @Mock + lateinit var oneginiPinCallbackMock: OneginiPinCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase + + @Before + fun attach() { + pinAuthenticationRequestAcceptUseCase = PinAuthenticationRequestAcceptUseCase() + } + + @Test + fun `When no pin registration callback is set, Then it should resolve with an error`() { + PinAuthenticationRequestHandler.CALLBACK = null + + val result = pinAuthenticationRequestAcceptUseCase("12345").exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin registration callback is set, Then it should resolve successfully`() { + PinAuthenticationRequestHandler.CALLBACK = oneginiPinCallbackMock + + val result = pinAuthenticationRequestAcceptUseCase("12345").getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt new file mode 100644 index 00000000..249a80a8 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class PinAuthenticationRequestDenyUseCaseTest { + + @Mock + lateinit var oneginiPinCallbackMock: OneginiPinCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase + + @Before + fun attach() { + pinAuthenticationRequestDenyUseCase = PinAuthenticationRequestDenyUseCase() + } + + @Test + fun `When no pin registration callback is set, Then it should resolve with an error`() { + PinAuthenticationRequestHandler.CALLBACK = null + + val result = pinAuthenticationRequestDenyUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin registration callback is set, Then it should resolve successfully`() { + PinAuthenticationRequestHandler.CALLBACK = oneginiPinCallbackMock + + val result = pinAuthenticationRequestDenyUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt new file mode 100644 index 00000000..20455726 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -0,0 +1,44 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestAcceptUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class PinRegistrationRequestAcceptUseCaseTest { + + @Mock + lateinit var oneginiPinCallbackMock: OneginiPinCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase + + @Before + fun attach() { + pinRegistrationRequestAcceptUseCase = PinRegistrationRequestAcceptUseCase() + } + + @Test + fun `When no pin registration callback is set, Then it should resolve with an error`() { + val result = pinRegistrationRequestAcceptUseCase("12345").exceptionOrNull() + SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin registration callback is set, Then it should resolve successfully`() { + PinRequestHandler.CALLBACK = oneginiPinCallbackMock + + val result = pinRegistrationRequestAcceptUseCase("12345").getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt new file mode 100644 index 00000000..a4c8e70d --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestDenyUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class PinRegistrationRequestDenyUseCaseTest { + + @Mock + lateinit var oneginiPinCallbackMock: OneginiPinCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase + + @Before + fun attach() { + pinRegistrationRequestDenyUseCase = PinRegistrationRequestDenyUseCase() + } + + @Test + fun `When no pin registration callback is set, Then it should resolve with an error`() { + PinRequestHandler.CALLBACK = null + + val result = pinRegistrationRequestDenyUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin registration callback is set, Then it should resolve successfully`() { + PinRequestHandler.CALLBACK = oneginiPinCallbackMock + + val result = pinRegistrationRequestDenyUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} From a18b5360fc8ce18ef655d08bf00891bc155f4187 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 20 Mar 2023 16:58:53 +0100 Subject: [PATCH 151/364] FP-72 Created usecases and tests for the several fingerprint related callbacks --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../mobile/sdk/flutter/PigeonInterface.kt | 21 +++++---- ...printAuthenticationRequestAcceptUseCase.kt | 20 ++++++++ ...erprintAuthenticationRequestDenyUseCase.kt | 20 ++++++++ .../FingerprintFallbackToPinUseCase.kt | 20 ++++++++ ...tAuthenticationRequestAcceptUseCaseTest.kt | 46 +++++++++++++++++++ ...intAuthenticationRequestDenyUseCaseTest.kt | 46 +++++++++++++++++++ .../FingerprintFallbackToPinUseCaseTest.kt | 46 +++++++++++++++++++ 8 files changed, 211 insertions(+), 9 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 2f19366b..a34fc1db 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -12,6 +12,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { USER_NOT_AUTHENTICATED_IMPLICITLY(8035, "The requested action requires you to be authenticated implicitly"), METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), + FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 18d678aa..cd02cb15 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -28,6 +28,9 @@ import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUse import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase +import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestAcceptUseCase +import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestDenyUseCase +import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase @@ -98,6 +101,12 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase @Inject + lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase + @Inject + lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + @Inject + lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase @Inject lateinit var oneginiSDK: OneginiSDK @@ -223,21 +232,15 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 - FingerprintAuthenticationRequestHandler.fingerprintCallback?.fallbackToPin() - callback(Result.success(Unit)) + callback(fingerprintFallbackToPinUseCase()) } override fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 - FingerprintAuthenticationRequestHandler.fingerprintCallback?.denyAuthenticationRequest() - callback(Result.success(Unit)) + callback(fingerprintAuthenticationRequestDenyUseCase()) } override fun fingerprintAcceptAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-72 - FingerprintAuthenticationRequestHandler.fingerprintCallback?.acceptAuthenticationRequest() - callback(Result.success(Unit)) + callback(fingerprintAuthenticationRequestAcceptUseCase()) } override fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt new file mode 100644 index 00000000..a4761031 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class FingerprintAuthenticationRequestAcceptUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { + null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + fingerprintCallback.acceptAuthenticationRequest() + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt new file mode 100644 index 00000000..0c32dc14 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class FingerprintAuthenticationRequestDenyUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { + null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + fingerprintCallback.denyAuthenticationRequest() + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt new file mode 100644 index 00000000..233d36de --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class FingerprintFallbackToPinUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { + null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + fingerprintCallback.fallbackToPin() + Result.success(Unit) + } + } + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt new file mode 100644 index 00000000..81e477cd --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestAcceptUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class FingerprintAuthenticationRequestAcceptUseCaseTest { + + @Mock + lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + + @Before + fun attach() { + fingerprintAuthenticationRequestAcceptUseCase = FingerprintAuthenticationRequestAcceptUseCase() + } + + @Test + fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = null + + val result = fingerprintAuthenticationRequestAcceptUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin authentication callback is set, Then it should resolve successfully`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + + val result = fingerprintAuthenticationRequestAcceptUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt new file mode 100644 index 00000000..ad3e55ad --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestDenyUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class FingerprintAuthenticationRequestDenyUseCaseTest { + + @Mock + lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase + + @Before + fun attach() { + fingerprintAuthenticationRequestDenyUseCase = FingerprintAuthenticationRequestDenyUseCase() + } + + @Test + fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = null + + val result = fingerprintAuthenticationRequestDenyUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin authentication callback is set, Then it should resolve successfully`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + + val result = fingerprintAuthenticationRequestDenyUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt new file mode 100644 index 00000000..54e66a2f --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -0,0 +1,46 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class FingerprintFallbackToPinUseCaseTest { + + @Mock + lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + + @Before + fun attach() { + fingerprintFallbackToPinUseCase = FingerprintFallbackToPinUseCase() + } + + @Test + fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = null + + val result = fingerprintFallbackToPinUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin authentication callback is set, Then it should resolve successfully`() { + FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + + val result = fingerprintFallbackToPinUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} From e3833e4b1cfbe59de3eb67dc7fef620c13691f6e Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 09:27:17 +0100 Subject: [PATCH 152/364] FP-74 Created usecase for cancel browser registration --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../mobile/sdk/flutter/PigeonInterface.kt | 8 ++++---- .../BrowserRegistrationRequestHandler.kt | 12 +----------- .../CancelBrowserRegistrationUseCase.kt | 19 +++++++++++++++++++ 4 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 2f19366b..9e0a58bf 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -12,6 +12,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { USER_NOT_AUTHENTICATED_IMPLICITLY(8035, "The requested action requires you to be authenticated implicitly"), METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), + BROWSER_AUTHENTICATION_NOT_IN_PROGRESS(8039, "Browser Authentication is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 18d678aa..f5c4f3c6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -5,7 +5,6 @@ import android.util.Patterns import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn -import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler @@ -24,6 +23,7 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import com.onegini.mobile.sdk.flutter.useCases.AuthenticateDeviceUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserImplicitlyUseCase import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase +import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUseCase import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase @@ -64,6 +64,8 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var getAccessTokenUseCase: GetAccessTokenUseCase @Inject + lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase + @Inject lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase @Inject lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase @@ -277,9 +279,7 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun cancelBrowserRegistration(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-74 - BrowserRegistrationRequestHandler.onRegistrationCanceled() - callback(Result.success(Unit)) + callback(cancelBrowserRegistrationUseCase()) } override fun requestResource(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt index 2fbbef2b..8bdc0086 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt @@ -15,7 +15,7 @@ import javax.inject.Singleton class BrowserRegistrationRequestHandler @Inject constructor(): OneginiBrowserRegistrationRequestHandler { companion object { - private var CALLBACK: OneginiBrowserRegistrationCallback? = null + var CALLBACK: OneginiBrowserRegistrationCallback? = null /** * Finish registration action with result from web browser @@ -26,16 +26,6 @@ class BrowserRegistrationRequestHandler @Inject constructor(): OneginiBrowserReg CALLBACK = null } } - - /** - * Cancel registration action in case of web browser error - */ - fun onRegistrationCanceled() { - if (CALLBACK != null) { - CALLBACK?.denyRegistration() - CALLBACK = null - } - } } override fun startRegistration(uri: Uri, oneginiBrowserRegistrationCallback: OneginiBrowserRegistrationCallback) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt new file mode 100644 index 00000000..779277b4 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt @@ -0,0 +1,19 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_AUTHENTICATION_NOT_IN_PROGRESS +import javax.inject.Inject + +class CancelBrowserRegistrationUseCase @Inject constructor() { + operator fun invoke(): Result { + return when (val browserCallback = BrowserRegistrationRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + browserCallback.denyRegistration() + BrowserRegistrationRequestHandler.CALLBACK = null + Result.success(Unit) + } + } + } +} From 43a1a77663582cd36f218aad4aafc038ecf223c5 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 09:28:31 +0100 Subject: [PATCH 153/364] fp-72 removed unused mock --- .../sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt | 3 --- .../sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt | 3 --- .../onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt | 3 --- 3 files changed, 9 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index 81e477cd..b172c725 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -18,9 +18,6 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback - @Mock - lateinit var callbackMock: (Result) -> Unit - lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase @Before diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index ad3e55ad..98194dd6 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -18,9 +18,6 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback - @Mock - lateinit var callbackMock: (Result) -> Unit - lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase @Before diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 54e66a2f..618facf7 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -18,9 +18,6 @@ class FingerprintFallbackToPinUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback - @Mock - lateinit var callbackMock: (Result) -> Unit - lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase @Before From b1bc2bc079fd271b0d69666b1deb21a5cf0df090 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 10:08:56 +0100 Subject: [PATCH 154/364] FP-75: Update Pigeon interface and native2flutter callbacks in flutter --- .../flutter/helpers/OneginiEventsSender.kt | 14 - .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 212 ++++++++- ios/Classes/Pigeon.swift | 219 +++++++++- lib/onegini.dart | 9 +- lib/onegini_event_listener.dart | 185 ++++---- lib/pigeon.dart | 413 +++++++++++++++++- pigeons/onewelcome_pigeon_interface.dart | 87 +++- 7 files changed, 1011 insertions(+), 128 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/OneginiEventsSender.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/OneginiEventsSender.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/OneginiEventsSender.kt deleted file mode 100644 index a8eaf002..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/OneginiEventsSender.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.onegini.mobile.sdk.flutter.helpers - -import io.flutter.plugin.common.EventChannel - -class OneginiEventsSender { - companion object { - var events: EventChannel.EventSink? = null - - fun setEventSink(eventSink: EventChannel.EventSink?) { - if (eventSink != null) - events = eventSink - } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index ebd173c7..01beb07d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -263,6 +263,53 @@ data class OWRequestResponse ( } } +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWAuthenticationAttempt ( + val failedAttempts: Long, + val maxAttempts: Long, + val remainingAttempts: Long + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWAuthenticationAttempt { + val failedAttempts = list[0].let { if (it is Int) it.toLong() else it as Long } + val maxAttempts = list[1].let { if (it is Int) it.toLong() else it as Long } + val remainingAttempts = list[2].let { if (it is Int) it.toLong() else it as Long } + return OWAuthenticationAttempt(failedAttempts, maxAttempts, remainingAttempts) + } + } + fun toList(): List { + return listOf( + failedAttempts, + maxAttempts, + remainingAttempts, + ) + } +} + +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWOneginiError ( + val code: String, + val message: String + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWOneginiError { + val code = list[0] as String + val message = list[1] as String + return OWOneginiError(code, message) + } + } + fun toList(): List { + return listOf( + code, + message, + ) + } +} + @Suppress("UNCHECKED_CAST") private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { @@ -1126,6 +1173,47 @@ interface ResourceMethodApi { } } } +@Suppress("UNCHECKED_CAST") +private object NativeCallFlutterApiCodec : StandardMessageCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 128.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWAuthenticationAttempt.fromList(it) + } + } + 129.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWCustomInfo.fromList(it) + } + } + 130.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWOneginiError.fromList(it) + } + } + else -> super.readValueOfType(type, buffer) + } + } + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + when (value) { + is OWAuthenticationAttempt -> { + stream.write(128) + writeValue(stream, value.toList()) + } + is OWCustomInfo -> { + stream.write(129) + writeValue(stream, value.toList()) + } + is OWOneginiError -> { + stream.write(130) + writeValue(stream, value.toList()) + } + else -> super.writeValue(stream, value) + } + } +} + /** * Native calls to Flutter * @@ -1136,14 +1224,126 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { companion object { /** The codec used by NativeCallFlutterApi. */ val codec: MessageCodec by lazy { - StandardMessageCodec() + NativeCallFlutterApiCodec + } + } + /**Called to handle registration URL */ + fun n2fHandleRegisteredUrl(urlArg: String, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl", codec) + channel.send(listOf(urlArg)) { + callback() + } + } + /** Called to open OTP authentication. */ + fun n2fOpenAuthOtp(messageArg: String, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", codec) + channel.send(listOf(messageArg)) { + callback() + } + } + /** Called to close OTP authentication. */ + fun n2fCloseAuthOtp(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", codec) + channel.send(null) { + callback() + } + } + /** Called to open pin registration screen. */ + fun n2fOpenPinRequestScreen(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen", codec) + channel.send(null) { + callback() + } + } + /** Called to open pin authentication screen. */ + fun n2fOpenPinScreenAuth(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth", codec) + channel.send(null) { + callback() + } + } + /** Called to open pin authentication screen. */ + fun n2fOpenPinAuthenticator(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator", codec) + channel.send(null) { + callback() + } + } + /** Called to attempt next authentication. */ + fun n2fNextAuthenticationAttempt(authenticationAttemptArg: OWAuthenticationAttempt, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", codec) + channel.send(listOf(authenticationAttemptArg)) { + callback() + } + } + /** Called to close pin registration screen. */ + fun n2fClosePin(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin", codec) + channel.send(null) { + callback() + } + } + /** Called to close pin authentication screen. */ + fun n2fClosePinAuth(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth", codec) + channel.send(null) { + callback() + } + } + /** Called to open fingerprint screen. */ + fun n2fOpenFingerprintScreen(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen", codec) + channel.send(null) { + callback() + } + } + /** Called to scan fingerprint. */ + fun n2fShowScanningFingerprint(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint", codec) + channel.send(null) { + callback() + } + } + /** Called when fingerprint was received. */ + fun n2fReceivedFingerprint(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint", codec) + channel.send(null) { + callback() + } + } + /** Called to close fingerprint screen. */ + fun n2fCloseFingerprintScreen(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", codec) + channel.send(null) { + callback() + } + } + /** Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) */ + fun n2fEventInitCustomRegistration(customInfoArg: OWCustomInfo?, providerIdArg: String, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration", codec) + channel.send(listOf(customInfoArg, providerIdArg)) { + callback() + } + } + /** Called when the FinishCustomRegistration event occurs and a response should be given */ + fun n2fEventFinishCustomRegistration(customInfoArg: OWCustomInfo?, providerIdArg: String, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration", codec) + channel.send(listOf(customInfoArg, providerIdArg)) { + callback() + } + } + /** Called when error event was received. */ + fun n2fEventError(errorArg: OWOneginiError, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError", codec) + channel.send(listOf(errorArg)) { + callback() } } - fun testEventFunction(argumentArg: String, callback: (String) -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction", codec) - channel.send(listOf(argumentArg)) { - val result = it as String - callback(result) + /** Called whenever error occured. */ + fun n2fShowError(errorArg: OWOneginiError, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError", codec) + channel.send(listOf(errorArg)) { + callback() } } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 700f7258..36936e93 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -250,6 +250,54 @@ struct OWRequestResponse { } } +/// Generated class from Pigeon that represents data sent in messages. +struct OWAuthenticationAttempt { + var failedAttempts: Int32 + var maxAttempts: Int32 + var remainingAttempts: Int32 + + static func fromList(_ list: [Any?]) -> OWAuthenticationAttempt? { + let failedAttempts = list[0] as! Int32 + let maxAttempts = list[1] as! Int32 + let remainingAttempts = list[2] as! Int32 + + return OWAuthenticationAttempt( + failedAttempts: failedAttempts, + maxAttempts: maxAttempts, + remainingAttempts: remainingAttempts + ) + } + func toList() -> [Any?] { + return [ + failedAttempts, + maxAttempts, + remainingAttempts, + ] + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct OWOneginiError { + var code: String + var message: String + + static func fromList(_ list: [Any?]) -> OWOneginiError? { + let code = list[0] as! String + let message = list[1] as! String + + return OWOneginiError( + code: code, + message: message + ) + } + func toList() -> [Any?] { + return [ + code, + message, + ] + } +} + private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -997,6 +1045,52 @@ class ResourceMethodApiSetup { } } } +private class NativeCallFlutterApiCodecReader: FlutterStandardReader { + override func readValue(ofType type: UInt8) -> Any? { + switch type { + case 128: + return OWAuthenticationAttempt.fromList(self.readValue() as! [Any]) + case 129: + return OWCustomInfo.fromList(self.readValue() as! [Any]) + case 130: + return OWOneginiError.fromList(self.readValue() as! [Any]) + default: + return super.readValue(ofType: type) + } + } +} + +private class NativeCallFlutterApiCodecWriter: FlutterStandardWriter { + override func writeValue(_ value: Any) { + if let value = value as? OWAuthenticationAttempt { + super.writeByte(128) + super.writeValue(value.toList()) + } else if let value = value as? OWCustomInfo { + super.writeByte(129) + super.writeValue(value.toList()) + } else if let value = value as? OWOneginiError { + super.writeByte(130) + super.writeValue(value.toList()) + } else { + super.writeValue(value) + } + } +} + +private class NativeCallFlutterApiCodecReaderWriter: FlutterStandardReaderWriter { + override func reader(with data: Data) -> FlutterStandardReader { + return NativeCallFlutterApiCodecReader(data: data) + } + + override func writer(with data: NSMutableData) -> FlutterStandardWriter { + return NativeCallFlutterApiCodecWriter(data: data) + } +} + +class NativeCallFlutterApiCodec: FlutterStandardMessageCodec { + static let shared = NativeCallFlutterApiCodec(readerWriter: NativeCallFlutterApiCodecReaderWriter()) +} + /// Native calls to Flutter /// /// Generated class from Pigeon that represents Flutter messages that can be called from Swift. @@ -1005,11 +1099,126 @@ class NativeCallFlutterApi { init(binaryMessenger: FlutterBinaryMessenger){ self.binaryMessenger = binaryMessenger } - func testEventFunction(argument argumentArg: String, completion: @escaping (String) -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction", binaryMessenger: binaryMessenger) - channel.sendMessage([argumentArg] as [Any?]) { response in - let result = response as! String - completion(result) + var codec: FlutterStandardMessageCodec { + return NativeCallFlutterApiCodec.shared + } + ///Called to handle registration URL + func n2fHandleRegisteredUrl(url urlArg: String, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([urlArg] as [Any?]) { _ in + completion() + } + } + /// Called to open OTP authentication. + func n2fOpenAuthOtp(message messageArg: String, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([messageArg] as [Any?]) { _ in + completion() + } + } + /// Called to close OTP authentication. + func n2fCloseAuthOtp(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to open pin registration screen. + func n2fOpenPinRequestScreen(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to open pin authentication screen. + func n2fOpenPinScreenAuth(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to open pin authentication screen. + func n2fOpenPinAuthenticator(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to attempt next authentication. + func n2fNextAuthenticationAttempt(authenticationAttempt authenticationAttemptArg: OWAuthenticationAttempt, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([authenticationAttemptArg] as [Any?]) { _ in + completion() + } + } + /// Called to close pin registration screen. + func n2fClosePin(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to close pin authentication screen. + func n2fClosePinAuth(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to open fingerprint screen. + func n2fOpenFingerprintScreen(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to scan fingerprint. + func n2fShowScanningFingerprint(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called when fingerprint was received. + func n2fReceivedFingerprint(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to close fingerprint screen. + func n2fCloseFingerprintScreen(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) + func n2fEventInitCustomRegistration(customInfo customInfoArg: OWCustomInfo?, providerId providerIdArg: String, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([customInfoArg, providerIdArg] as [Any?]) { _ in + completion() + } + } + /// Called when the FinishCustomRegistration event occurs and a response should be given + func n2fEventFinishCustomRegistration(customInfo customInfoArg: OWCustomInfo?, providerId providerIdArg: String, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([customInfoArg, providerIdArg] as [Any?]) { _ in + completion() + } + } + /// Called when error event was received. + func n2fEventError(error errorArg: OWOneginiError, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([errorArg] as [Any?]) { _ in + completion() + } + } + /// Called whenever error occured. + func n2fShowError(error errorArg: OWOneginiError, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([errorArg] as [Any?]) { _ in + completion() } } } diff --git a/lib/onegini.dart b/lib/onegini.dart index 3b1b88bd..d9c36f35 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -7,6 +7,7 @@ import 'package:onegini/constants/constants.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/resources_methods.dart'; import 'package:onegini/user_client.dart'; +import 'package:onegini/pigeon.dart'; import 'model/onegini_removed_user_profile.dart'; @@ -50,8 +51,13 @@ class Onegini { try { var customIdentityProviderConfigsJson; if (customIdentityProviderConfigs != null) { - customIdentityProviderConfigsJson = [for (var customIdentityProviderConfig in customIdentityProviderConfigs) json.encode(customIdentityProviderConfig)]; + customIdentityProviderConfigsJson = [ + for (var customIdentityProviderConfig + in customIdentityProviderConfigs) + json.encode(customIdentityProviderConfig) + ]; } + NativeCallFlutterApi.setup(_eventListener); String removedUserProfiles = await channel .invokeMethod(Constants.startAppMethod, { @@ -61,7 +67,6 @@ class Onegini { 'connectionTimeout': connectionTimeout, 'readTimeout': readTimeout }); - eventListener.listen(); return removedUserProfileListFromJson(removedUserProfiles); } on TypeError catch (error) { throw PlatformException( diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 05bb959d..91784e45 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,17 +1,14 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/model/onegini_error.dart'; - +import 'package:onegini/model/onegini_error.dart' as fpError; +import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/authentication_attempt.dart'; +import 'model/onegini_error.dart'; import 'model/onegini_event.dart'; /// Extend from this class to describe the events that will take place inside OneginiSDK -abstract class OneginiEventListener { - /// A communication channel name - static const channel_name = 'onegini_events'; - static const EventChannel _eventChannel = const EventChannel(channel_name); - +abstract class OneginiEventListener implements NativeCallFlutterApi { BuildContext? _context; /// Saves the build context @@ -19,78 +16,6 @@ abstract class OneginiEventListener { _context = context; } - /// Sets up listener. - /// - /// Call methods based on received event name. - void listen() { - _eventChannel.receiveBroadcastStream(channel_name).listen((event) { - switch (event) { - case Constants.eventOpenPin: //2 - openPinRequestScreen(_context); - break; - case Constants.eventOpenPinAuth: //1 - openPinScreenAuth(_context); - break; - case Constants.eventOpenPinAuthenticator: - openPinAuthenticator(_context); - break; - case Constants.eventClosePin: - closePin(_context); - break; - case Constants.eventClosePinAuth: - closePinAuth(_context); - break; - case Constants.eventOpenFingerprintAuth: - openFingerprintScreen(_context); - break; - case Constants.eventShowScanningFingerprintAuth: - showScanningFingerprint(_context); - break; - case Constants.eventReceivedFingerprintAuth: - receivedFingerprint(_context); - break; - case Constants.eventCloseFingerprintAuth: - closeFingerprintScreen(_context); - break; - case Constants.eventCloseAuthOTP: - closeAuthOtp(_context); - break; - case Constants.getUserProfiles: - default: - if (event != null) { - Event _event = eventFromJson(event); - - switch(_event.eventName) { - case Constants.eventNextAuthenticationAttempt: - nextAuthenticationAttempt( - _context, authenticationAttemptFromJson(_event.eventValue!)); - break; - case Constants.eventOpenAuthOTP: - openAuthOtp(_context, _event.eventValue!); - break; - case Constants.eventHandleRegisteredUrl: - handleRegisteredUrl(_context, _event.eventValue!); - break; - case Constants.eventInitCustomRegistration: - eventInitCustomRegistration(_context, _event.eventValue!); - break; - case Constants.eventFinishCustomRegistration: - eventFinishCustomRegistration(_context, _event.eventValue!); - break; - case Constants.eventError: - showError(_context, oneginiErrorFromJson(_event.eventValue!)); - break; - default: - eventOther(_context, _event); - break; - } - } - } - }).onError((error) { - eventError(_context, error); - }); - } - ///Called to handle registration URL void handleRegisteredUrl(BuildContext? buildContext, String url); @@ -133,18 +58,114 @@ abstract class OneginiEventListener { /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) void eventInitCustomRegistration( - BuildContext? buildContext, String data); + BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given void eventFinishCustomRegistration( - BuildContext? buildContext, String data); + BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); /// Called when error event was received. void eventError(BuildContext? buildContext, PlatformException error); /// Called whenever error occured. - void showError(BuildContext? buildContext, OneginiError? error); + void showError(BuildContext? buildContext, fpError.OneginiError? error); /// Called when custom event was received. void eventOther(BuildContext? buildContext, Event event); + + @override + void n2fCloseAuthOtp() { + closeAuthOtp(_context); + } + + @override + void n2fCloseFingerprintScreen() { + closeFingerprintScreen(_context); + } + + @override + void n2fClosePin() { + closePin(_context); + } + + @override + void n2fClosePinAuth() { + closePinAuth(_context); + } + + @override + void n2fEventFinishCustomRegistration( + OWCustomInfo? customInfo, String providerId) { + eventFinishCustomRegistration(_context, customInfo, providerId); + } + + @override + void n2fEventInitCustomRegistration( + OWCustomInfo? customInfo, String providerId) { + eventInitCustomRegistration(_context, customInfo, providerId); + } + + @override + void n2fHandleRegisteredUrl(String url) { + print("hello from handleRegisteredUrl"); + handleRegisteredUrl(_context, url); + } + + @override + void n2fNextAuthenticationAttempt( + OWAuthenticationAttempt authenticationAttempt) { + nextAuthenticationAttempt( + _context, + AuthenticationAttempt( + failedAttempts: authenticationAttempt.failedAttempts, + maxAttempts: authenticationAttempt.maxAttempts, + remainingAttempts: authenticationAttempt.remainingAttempts)); + } + + @override + void n2fOpenAuthOtp(String message) { + openAuthOtp(_context, message); + } + + @override + void n2fOpenFingerprintScreen() { + openFingerprintScreen(_context); + } + + @override + void n2fOpenPinAuthenticator() { + openPinAuthenticator(_context); + } + + @override + void n2fOpenPinRequestScreen() { + openPinRequestScreen(_context); + } + + @override + void n2fOpenPinScreenAuth() { + openPinScreenAuth(_context); + } + + @override + void n2fReceivedFingerprint() { + receivedFingerprint(_context); + } + + @override + void n2fShowScanningFingerprint() { + showScanningFingerprint(_context); + } + + @override + void n2fEventError(OWOneginiError error) { + eventError( + _context, PlatformException(code: error.code, message: error.message)); + } + + @override + void n2fShowError(OWOneginiError error) { + // FIXME: use correct error code here. + showError(_context, OneginiError(code: 9999, message: error.message)); + } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ccf76534..e3d7a7f4 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -263,6 +263,63 @@ class OWRequestResponse { } } +class OWAuthenticationAttempt { + OWAuthenticationAttempt({ + required this.failedAttempts, + required this.maxAttempts, + required this.remainingAttempts, + }); + + int failedAttempts; + + int maxAttempts; + + int remainingAttempts; + + Object encode() { + return [ + failedAttempts, + maxAttempts, + remainingAttempts, + ]; + } + + static OWAuthenticationAttempt decode(Object result) { + result as List; + return OWAuthenticationAttempt( + failedAttempts: result[0]! as int, + maxAttempts: result[1]! as int, + remainingAttempts: result[2]! as int, + ); + } +} + +class OWOneginiError { + OWOneginiError({ + required this.code, + required this.message, + }); + + String code; + + String message; + + Object encode() { + return [ + code, + message, + ]; + } + + static OWOneginiError decode(Object result) { + result as List; + return OWOneginiError( + code: result[0]! as String, + message: result[1]! as String, + ); + } +} + class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override @@ -1198,29 +1255,367 @@ class ResourceMethodApi { } } +class _NativeCallFlutterApiCodec extends StandardMessageCodec { + const _NativeCallFlutterApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is OWAuthenticationAttempt) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else if (value is OWCustomInfo) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else if (value is OWOneginiError) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return OWAuthenticationAttempt.decode(readValue(buffer)!); + case 129: + return OWCustomInfo.decode(readValue(buffer)!); + case 130: + return OWOneginiError.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + /// Native calls to Flutter abstract class NativeCallFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + static const MessageCodec codec = _NativeCallFlutterApiCodec(); + + ///Called to handle registration URL + void n2fHandleRegisteredUrl(String url); + + /// Called to open OTP authentication. + void n2fOpenAuthOtp(String message); + + /// Called to close OTP authentication. + void n2fCloseAuthOtp(); + + /// Called to open pin registration screen. + void n2fOpenPinRequestScreen(); + + /// Called to open pin authentication screen. + void n2fOpenPinScreenAuth(); - Future testEventFunction(String argument); + /// Called to open pin authentication screen. + void n2fOpenPinAuthenticator(); + + /// Called to attempt next authentication. + void n2fNextAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); + + /// Called to close pin registration screen. + void n2fClosePin(); + + /// Called to close pin authentication screen. + void n2fClosePinAuth(); + + /// Called to open fingerprint screen. + void n2fOpenFingerprintScreen(); + + /// Called to scan fingerprint. + void n2fShowScanningFingerprint(); + + /// Called when fingerprint was received. + void n2fReceivedFingerprint(); + + /// Called to close fingerprint screen. + void n2fCloseFingerprintScreen(); + + /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) + void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); + + /// Called when the FinishCustomRegistration event occurs and a response should be given + void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); + + /// Called when error event was received. + void n2fEventError(OWOneginiError error); + + /// Called whenever error occured. + void n2fShowError(OWOneginiError error); static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); + final List args = (message as List?)!; + final String? arg_url = (args[0] as String?); + assert(arg_url != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null, expected non-null String.'); + api.n2fHandleRegisteredUrl(arg_url!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + final List args = (message as List?)!; + final String? arg_message = (args[0] as String?); + assert(arg_message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null, expected non-null String.'); + api.n2fOpenAuthOtp(arg_message!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fCloseAuthOtp(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fOpenPinRequestScreen(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fOpenPinScreenAuth(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fOpenPinAuthenticator(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt was null.'); + final List args = (message as List?)!; + final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); + assert(arg_authenticationAttempt != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); + api.n2fNextAuthenticationAttempt(arg_authenticationAttempt!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fClosePin(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fClosePinAuth(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fOpenFingerprintScreen(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fShowScanningFingerprint(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fReceivedFingerprint(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + // ignore message + api.n2fCloseFingerprintScreen(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); + final List args = (message as List?)!; + final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); + final String? arg_providerId = (args[1] as String?); + assert(arg_providerId != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null, expected non-null String.'); + api.n2fEventInitCustomRegistration(arg_customInfo, arg_providerId!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); + final List args = (message as List?)!; + final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); + final String? arg_providerId = (args[1] as String?); + assert(arg_providerId != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null, expected non-null String.'); + api.n2fEventFinishCustomRegistration(arg_customInfo, arg_providerId!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError was null.'); + final List args = (message as List?)!; + final OWOneginiError? arg_error = (args[0] as OWOneginiError?); + assert(arg_error != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError was null, expected non-null OWOneginiError.'); + api.n2fEventError(arg_error!); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError was null.'); final List args = (message as List?)!; - final String? arg_argument = (args[0] as String?); - assert(arg_argument != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.testEventFunction was null, expected non-null String.'); - final String output = await api.testEventFunction(arg_argument!); - return output; + final OWOneginiError? arg_error = (args[0] as OWOneginiError?); + assert(arg_error != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError was null, expected non-null OWOneginiError.'); + api.n2fShowError(arg_error!); + return; }); } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 56b7f438..59a85f2b 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -71,12 +71,7 @@ enum HttpRequestMethod { delete, } -enum ResourceRequestType { - authenticated, - implicit, - anonymous, - unauthenticated -} +enum ResourceRequestType { authenticated, implicit, anonymous, unauthenticated } class OWRequestDetails { String path; @@ -93,7 +88,27 @@ class OWRequestResponse { bool ok; int status; - OWRequestResponse({required this.headers, required this.body, required this.ok, required this.status}); + OWRequestResponse( + {required this.headers, + required this.body, + required this.ok, + required this.status}); +} + +class OWAuthenticationAttempt { + int failedAttempts; + int maxAttempts; + int remainingAttempts; + OWAuthenticationAttempt( + {required this.failedAttempts, + required this.maxAttempts, + required this.remainingAttempts}); +} + +class OWOneginiError { + String code; + String message; + OWOneginiError({required this.code, required this.message}); } /// Flutter calls native @@ -214,12 +229,64 @@ abstract class UserClientApi { @HostApi() abstract class ResourceMethodApi { @async - OWRequestResponse requestResource(ResourceRequestType type, OWRequestDetails details); + OWRequestResponse requestResource( + ResourceRequestType type, OWRequestDetails details); } /// Native calls to Flutter @FlutterApi() abstract class NativeCallFlutterApi { - @async - String testEventFunction(String argument); + ///Called to handle registration URL + void n2fHandleRegisteredUrl(String url); + + /// Called to open OTP authentication. + void n2fOpenAuthOtp(String message); + + /// Called to close OTP authentication. + void n2fCloseAuthOtp(); + + /// Called to open pin registration screen. + void n2fOpenPinRequestScreen(); + + /// Called to open pin authentication screen. + void n2fOpenPinScreenAuth(); + + /// Called to open pin authentication screen. + void n2fOpenPinAuthenticator(); + + /// Called to attempt next authentication. + void n2fNextAuthenticationAttempt( + OWAuthenticationAttempt authenticationAttempt); + + /// Called to close pin registration screen. + void n2fClosePin(); + + /// Called to close pin authentication screen. + void n2fClosePinAuth(); + + /// Called to open fingerprint screen. + void n2fOpenFingerprintScreen(); + + /// Called to scan fingerprint. + void n2fShowScanningFingerprint(); + + /// Called when fingerprint was received. + void n2fReceivedFingerprint(); + + /// Called to close fingerprint screen. + void n2fCloseFingerprintScreen(); + + /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) + void n2fEventInitCustomRegistration( + OWCustomInfo? customInfo, String providerId); + + /// Called when the FinishCustomRegistration event occurs and a response should be given + void n2fEventFinishCustomRegistration( + OWCustomInfo? customInfo, String providerId); + + /// Called when error event was received. + void n2fEventError(OWOneginiError error); + + /// Called whenever error occured. + void n2fShowError(OWOneginiError error); } From 5ad0399330cc6b23d098e0545d127fccdc635047 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 10:10:47 +0100 Subject: [PATCH 155/364] FP-75: Move android to new native2flutter api --- .../mobile/sdk/flutter/OneginiPlugin.kt | 11 -------- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 6 +++-- .../BrowserRegistrationRequestHandler.kt | 9 +++---- ...FingerprintAuthenticationRequestHandler.kt | 13 +++++----- .../handlers/MobileAuthOtpRequestHandler.kt | 9 +++---- .../PinAuthenticationRequestHandler.kt | 16 ++++++------ .../sdk/flutter/handlers/PinRequestHandler.kt | 16 +++++------- .../providers/CustomRegistrationActionImpl.kt | 17 ++++++------- .../CustomTwoStepRegistrationActionImpl.kt | 25 ++++++++++--------- 9 files changed, 50 insertions(+), 72 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 6ee9d517..23aea0b6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -1,7 +1,6 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -36,16 +35,6 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { component.inject(this) channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onegini") channel.setMethodCallHandler(onMethodCallMapper) - eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "onegini_events") - eventChannel.setStreamHandler(object : EventChannel.StreamHandler { - override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { - OneginiEventsSender.setEventSink(events) - } - - override fun onCancel(arguments: Any?) { - OneginiEventsSender.setEventSink(null) - } - }) } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index dbd78329..cdf13681 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -16,6 +16,7 @@ import io.flutter.plugin.common.MethodChannel import java.util.concurrent.TimeUnit import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @@ -27,6 +28,7 @@ class OneginiSDK @Inject constructor( private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler, private val createPinRequestHandler: PinRequestHandler, private val mobileAuthWithOtpRequestHandler: MobileAuthOtpRequestHandler, + private val nativeApi: NativeCallFlutterApi, ){ val oneginiClient: OneginiClient @@ -69,8 +71,8 @@ class OneginiSDK @Inject constructor( private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List) { customIdentityProviderConfigs.forEach { val action = when (it.isTwoStep) { - true -> CustomTwoStepRegistrationActionImpl(it.providerId) - false -> CustomRegistrationActionImpl(it.providerId) + true -> CustomTwoStepRegistrationActionImpl(it.providerId, nativeApi) + false -> CustomRegistrationActionImpl(it.providerId, nativeApi) } customRegistrationActions.add(action) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt index 2fbbef2b..f078a4f8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt @@ -1,18 +1,15 @@ package com.onegini.mobile.sdk.flutter.handlers import android.net.Uri -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.request.OneginiBrowserRegistrationRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiBrowserRegistrationCallback -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender -import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton // TODO Put functions into use cases; https://onewelcome.atlassian.net/browse/FP-35 @Singleton -class BrowserRegistrationRequestHandler @Inject constructor(): OneginiBrowserRegistrationRequestHandler { +class BrowserRegistrationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiBrowserRegistrationRequestHandler { companion object { private var CALLBACK: OneginiBrowserRegistrationCallback? = null @@ -40,6 +37,6 @@ class BrowserRegistrationRequestHandler @Inject constructor(): OneginiBrowserReg override fun startRegistration(uri: Uri, oneginiBrowserRegistrationCallback: OneginiBrowserRegistrationCallback) { CALLBACK = oneginiBrowserRegistrationCallback - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_HANDLE_REGISTERED_URL, uri.toString()))) + nativeApi.n2fHandleRegisteredUrl(uri.toString()) {} } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt index 232c83ea..74f4bbf0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt @@ -3,29 +3,28 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiFingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @Singleton -class FingerprintAuthenticationRequestHandler @Inject constructor(): OneginiFingerprintAuthenticationRequestHandler { +class FingerprintAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiFingerprintAuthenticationRequestHandler { override fun startAuthentication(userProfile: UserProfile, oneginiFingerprintCallback: OneginiFingerprintCallback) { fingerprintCallback = oneginiFingerprintCallback - OneginiEventsSender.events?.success(Constants.EVENT_OPEN_FINGERPRINT_AUTH) + nativeApi.n2fOpenFingerprintScreen { } } override fun onNextAuthenticationAttempt() { - OneginiEventsSender.events?.success(Constants.EVENT_RECEIVED_FINGERPRINT_AUTH) + nativeApi.n2fReceivedFingerprint { } } override fun onFingerprintCaptured() { - OneginiEventsSender.events?.success(Constants.EVENT_SHOW_SCANNING_FINGERPRINT_AUTH) + nativeApi.n2fShowScanningFingerprint { } } override fun finishAuthentication() { - OneginiEventsSender.events?.success(Constants.EVENT_CLOSE_FINGERPRINT_AUTH) + nativeApi.n2fCloseFingerprintScreen { } } companion object { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index 12474156..aa5ae7cb 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -5,13 +5,13 @@ import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithOtpR import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @Singleton -class MobileAuthOtpRequestHandler @Inject constructor(): OneginiMobileAuthWithOtpRequestHandler { +class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiMobileAuthWithOtpRequestHandler { private var userProfileId: String? = null private var message: String? = null override fun startAuthentication( @@ -22,12 +22,11 @@ class MobileAuthOtpRequestHandler @Inject constructor(): OneginiMobileAuthWithOt CALLBACK = oneginiAcceptDenyCallback userProfileId = oneginiMobileAuthenticationRequest.userProfile.profileId message = oneginiMobileAuthenticationRequest.message - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_OPEN_AUTH_OTP, message - ?: ""))) + nativeApi.n2fOpenAuthOtp(message ?: "") {} } override fun finishAuthentication() { - OneginiEventsSender.events?.success(Constants.EVENT_CLOSE_AUTH_OTP) + nativeApi.n2fCloseAuthOtp {} } companion object { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index 282f7f13..87289d92 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -1,33 +1,31 @@ package com.onegini.mobile.sdk.flutter.handlers -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.request.OneginiPinAuthenticationRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender -import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticationAttempt import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinAuthenticationRequestHandler @Inject constructor(): OneginiPinAuthenticationRequestHandler { +class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiPinAuthenticationRequestHandler { companion object { var CALLBACK: OneginiPinCallback? = null } override fun startAuthentication(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, attemptCounter: AuthenticationAttemptCounter) { CALLBACK = oneginiPinCallback - OneginiEventsSender.events?.success(Constants.EVENT_OPEN_PIN_AUTH) + nativeApi.n2fOpenPinScreenAuth { } } override fun onNextAuthenticationAttempt(attemptCounter: AuthenticationAttemptCounter) { - val attemptCounterJson = Gson().toJson(mapOf("maxAttempts" to attemptCounter.maxAttempts, "failedAttempts" to attemptCounter.failedAttempts, "remainingAttempts" to attemptCounter.remainingAttempts)) - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_NEXT_AUTHENTICATION_ATTEMPT, attemptCounterJson))) + val authenticationAttempt = OWAuthenticationAttempt(attemptCounter.failedAttempts.toLong(), attemptCounter.maxAttempts.toLong(), attemptCounter.remainingAttempts.toLong()); + nativeApi.n2fNextAuthenticationAttempt(authenticationAttempt) {} } override fun finishAuthentication() { - OneginiEventsSender.events?.success(Constants.EVENT_CLOSE_PIN_AUTH) + nativeApi.n2fClosePinAuth { } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index a01124b5..f5c86746 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -1,19 +1,16 @@ package com.onegini.mobile.sdk.flutter.handlers -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.android.handlers.request.OneginiCreatePinRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender -import com.onegini.mobile.sdk.flutter.models.Error -import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWOneginiError import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinRequestHandler @Inject constructor(): OneginiCreatePinRequestHandler { +class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiCreatePinRequestHandler { companion object { var CALLBACK: OneginiPinCallback? = null @@ -21,15 +18,14 @@ class PinRequestHandler @Inject constructor(): OneginiCreatePinRequestHandler { override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { CALLBACK = oneginiPinCallback - OneginiEventsSender.events?.success(Constants.EVENT_OPEN_PIN) + nativeApi.n2fOpenPinRequestScreen { } } override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_ERROR, Gson().toJson(Error(oneginiPinValidationError.errorType.toString(), oneginiPinValidationError.message - ?: "")).toString()))) + nativeApi.n2fEventError(OWOneginiError(oneginiPinValidationError.errorType.toString(), oneginiPinValidationError.message ?: "")) {} } override fun finishPinCreation() { - OneginiEventsSender.events?.success(Constants.EVENT_CLOSE_PIN) + nativeApi.n2fClosePin { } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index b0ed031f..51d22374 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -1,25 +1,22 @@ package com.onegini.mobile.sdk.flutter.providers -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomRegistrationCallback import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel -import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo -class CustomRegistrationActionImpl(private val providerId: String) : OneginiCustomRegistrationAction, CustomRegistrationAction { +class CustomRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - - val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) - + val customInfoResponse = info?.let { + OWCustomInfo(info.status.toLong(), info.data) + } + nativeApi.n2fEventFinishCustomRegistration(customInfoResponse, providerId) {} } override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 9ffac996..13197901 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -1,32 +1,33 @@ package com.onegini.mobile.sdk.flutter.providers -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomTwoStepRegistrationAction import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomRegistrationCallback import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.OneginiEventsSender import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.models.CustomRegistrationModel -import com.onegini.mobile.sdk.flutter.models.OneginiEvent +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo +import javax.inject.Inject -class CustomTwoStepRegistrationActionImpl(private val providerId: String) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { +class CustomTwoStepRegistrationActionImpl constructor(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null override fun initRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - - val data = Gson().toJson(CustomRegistrationModel(info?.data.orEmpty(), info?.status, providerId)) - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_INIT_CUSTOM_REGISTRATION, data))) + val customInfoResponse = info?.let { + OWCustomInfo(info.status.toLong(), info.data) + } + nativeApi.n2fEventInitCustomRegistration(customInfoResponse, providerId) {} } - override fun finishRegistration(callback: OneginiCustomRegistrationCallback, customInfo: CustomInfo?) { + override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - val data = Gson().toJson(CustomRegistrationModel(customInfo?.data.orEmpty(), customInfo?.status, providerId)) - OneginiEventsSender.events?.success(Gson().toJson(OneginiEvent(Constants.EVENT_FINISH_CUSTOM_REGISTRATION, data))) + val customInfoResponse = info?.let { + OWCustomInfo(info.status.toLong(), info.data) + } + nativeApi.n2fEventFinishCustomRegistration(customInfoResponse, providerId) {} } override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { From 09ddb14a35bf94dcbdccd322aaf9d31eeb892b57 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 10:12:37 +0100 Subject: [PATCH 156/364] FP-75: Remove some old boilerplate and update custom reg api in example --- example/lib/main.dart | 6 ------ example/lib/onegini_listener.dart | 15 ++++++--------- example/lib/onegini_pigeon_listener.dart | 9 --------- 3 files changed, 6 insertions(+), 24 deletions(-) delete mode 100644 example/lib/onegini_pigeon_listener.dart diff --git a/example/lib/main.dart b/example/lib/main.dart index a527c166..4c043f6d 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,10 +1,7 @@ // @dart = 2.10 -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/pigeon.dart'; -import 'package:onegini_example/onegini_pigeon_listener.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/screens/login_screen.dart'; @@ -55,9 +52,6 @@ class _BodyWidgetState extends State { void initState() { _startApplication(); super.initState(); - - // init listener class todo move this to start application - NativeCallFlutterApi.setup(OneginiPigeonListenerImpl()); } void _startApplication() async { diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart index 6e2490c4..08c9cdc3 100644 --- a/example/lib/onegini_listener.dart +++ b/example/lib/onegini_listener.dart @@ -8,6 +8,7 @@ import 'package:onegini/model/onegini_error.dart'; import 'package:onegini/model/onegini_event.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/onegini_event_listener.dart'; +import 'package:onegini/pigeon.dart'; import 'package:onegini/user_client.dart'; import 'package:onegini_example/screens/auth_otp_screen.dart'; import 'package:onegini_example/screens/fingerprint_screen.dart'; @@ -141,11 +142,9 @@ class OneginiListener extends OneginiEventListener { } @override - void eventInitCustomRegistration(BuildContext buildContext, String data) { + void eventInitCustomRegistration( + BuildContext buildContext, OWCustomInfo customInfo, String providerId) { try { - var response = jsonDecode(data); - var providerId = response["providerId"]; - if (providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request OneginiCustomRegistrationCallback() @@ -162,17 +161,15 @@ class OneginiListener extends OneginiEventListener { } @override - void eventFinishCustomRegistration(BuildContext buildContext, String data) { + void eventFinishCustomRegistration( + BuildContext buildContext, OWCustomInfo customInfo, String providerId) { try { - var response = jsonDecode(data); - var providerId = response["providerId"]; - if (providerId == "2-way-otp-api") Navigator.push( buildContext, MaterialPageRoute( builder: (context) => OtpScreen( - password: response["data"], providerId: providerId)), + password: customInfo?.data, providerId: providerId)), ); } on FormatException catch (error) { showFlutterToast(error.message); diff --git a/example/lib/onegini_pigeon_listener.dart b/example/lib/onegini_pigeon_listener.dart deleted file mode 100644 index 0cfa8532..00000000 --- a/example/lib/onegini_pigeon_listener.dart +++ /dev/null @@ -1,9 +0,0 @@ -import 'package:onegini/pigeon.dart'; - -class OneginiPigeonListenerImpl extends NativeCallFlutterApi { - @override - Future testEventFunction(String argument) async { - print("testEventFunction was triggered from native: $argument"); - return "boop"; - } -} From c1531d2a2db5f6a9d1d3bc5d73303f2b1c294c44 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 10:13:08 +0100 Subject: [PATCH 157/364] fp-74 updated method wrapper, activity view to use use-case and wrote tests --- .../sdk/flutter/OneginiMethodsWrapper.kt | 5 --- .../sdk/flutter/activity/ActivityWebView.kt | 6 +-- .../CancelBrowserRegistrationUseCaseTest.kt | 42 +++++++++++++++++++ 3 files changed, 45 insertions(+), 8 deletions(-) create mode 100644 android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 77658c6d..4160ee50 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter -import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.useCases.* import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel @@ -13,10 +12,6 @@ class OneginiMethodsWrapper @Inject constructor( private val startAppUseCase: StartAppUseCase, ) { - fun cancelBrowserRegistration() { - BrowserRegistrationRequestHandler.onRegistrationCanceled() - } - fun startApp(call: MethodCall, result: MethodChannel.Result) { startAppUseCase(call, result) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt index 5f8a0269..0b4e8679 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt @@ -7,15 +7,15 @@ import android.os.Bundle import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient -import com.onegini.mobile.sdk.flutter.OneginiMethodsWrapper import com.onegini.mobile.sdk.flutter.R import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase import javax.inject.Inject class ActivityWebView: Activity() { @Inject - lateinit var oneginiMethodsWrapper: OneginiMethodsWrapper + lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { @@ -38,7 +38,7 @@ class ActivityWebView: Activity() { } val url = intent.getStringExtra("url") if (url == null || url.isEmpty()) { - oneginiMethodsWrapper.cancelBrowserRegistration() + cancelBrowserRegistrationUseCase() finish() } else { myWebView.loadUrl(url) diff --git a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt new file mode 100644 index 00000000..7b79620b --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt @@ -0,0 +1,42 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiBrowserRegistrationCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class CancelBrowserRegistrationUseCaseTest { + @Mock + lateinit var oneginiBrowserCallbackMock: OneginiBrowserRegistrationCallback + + lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase + + @Before + fun attach() { + cancelBrowserRegistrationUseCase = CancelBrowserRegistrationUseCase() + } + + @Test + fun `When no browser registration callback is set, Then it should resolve with an error`() { + BrowserRegistrationRequestHandler.CALLBACK = null + + val result = cancelBrowserRegistrationUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a pin browser registration callback is set, Then it should resolve successfully`() { + BrowserRegistrationRequestHandler.CALLBACK = oneginiBrowserCallbackMock + + val result = cancelBrowserRegistrationUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} From 5f319ed1e73a095e0c45b7fa5c32e615efcf2545 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 11:20:26 +0100 Subject: [PATCH 158/364] fp-74 left rework comments explaining why we skipped a usecase for now --- .../sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt | 2 ++ .../kotlin/com/onegini/mobile/onegini_example/MainActivity.kt | 2 ++ 2 files changed, 4 insertions(+) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt index 8bdc0086..91466e19 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt @@ -19,6 +19,8 @@ class BrowserRegistrationRequestHandler @Inject constructor(): OneginiBrowserReg /** * Finish registration action with result from web browser + * TODO: Move this to use-case after browser logic rework + * https://onewelcome.atlassian.net/browse/FP-35 */ fun handleRegistrationCallback(uri: Uri) { if (CALLBACK != null) { diff --git a/example/android/app/src/main/kotlin/com/onegini/mobile/onegini_example/MainActivity.kt b/example/android/app/src/main/kotlin/com/onegini/mobile/onegini_example/MainActivity.kt index cf856a75..ab0bdaae 100644 --- a/example/android/app/src/main/kotlin/com/onegini/mobile/onegini_example/MainActivity.kt +++ b/example/android/app/src/main/kotlin/com/onegini/mobile/onegini_example/MainActivity.kt @@ -9,6 +9,8 @@ class MainActivity : FlutterActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (intent.data != null) { + // TODO: Move this logic to outside of the SDK + // https://onewelcome.atlassian.net/browse/FP-35 BrowserRegistrationRequestHandler.handleRegistrationCallback(intent.data!!) } } From e671fde838e57c92a06d226d7077799681b561ea Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 11:36:20 +0100 Subject: [PATCH 159/364] FP-43 Added unauthenticated resource request button for test purposes and removed cz reference --- example/lib/screens/user_screen.dart | 48 ++++++++++------------------ 1 file changed, 17 insertions(+), 31 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 0c2d53fd..054bd769 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -350,6 +350,17 @@ class Home extends StatelessWidget { showFlutterToast(accessToken); } + performUnauthenticatedRequest() async { + var response = await Onegini.instance.resourcesMethods + .requestResourceUnauthenticated(RequestDetails(path: "unauthenticated", method: HttpRequestMethod.get)) + .catchError((error) { + print("An error occured $error"); + showFlutterToast("An error occured $error"); + }); + + showFlutterToast("Response: ${response.body}"); + } + @override Widget build(BuildContext context) { return Container( @@ -400,6 +411,12 @@ class Home extends StatelessWidget { }, child: Text('Access Token'), ), + ElevatedButton( + onPressed: () { + performUnauthenticatedRequest(); + }, + child: Text('Perform Unauthenticated Request'), + ), SizedBox( height: 20, ), @@ -440,17 +457,6 @@ class _InfoState extends State { return clientResourceFromJson(response.body); } - Future makeUnaunthenticatedRequest() async { - var response = await Onegini.instance.resourcesMethods - .requestResourceUnauthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get)) - .catchError((error) { - print(error); - }); - - var res = json.decode(response.body); - return res; - } - @override Widget build(BuildContext context) { return Stack( @@ -518,26 +524,6 @@ class _InfoState extends State { : Text(""); }, ), - SizedBox( - height: 20, - ), - FutureBuilder( - future: makeUnaunthenticatedRequest(), - builder: (context, snapshot) { - return snapshot.hasData - ? Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "UnaunthenticatedRequest - Users:", - style: TextStyle(fontSize: 20), - ), - Text(snapshot.data, style: TextStyle(fontSize: 20)), - ], - ) - : SizedBox.shrink(); - }, - ), Expanded( child: FutureBuilder( future: getClientResource(), From eeb25210c4947996fea23b7e991d2928f74ace5a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 12:22:48 +0100 Subject: [PATCH 160/364] FP-75: iOS: Move most event's to pigeon events, a few were skipped --- example/ios/Podfile.lock | 2 +- example/ios/Runner/AppDelegate.swift | 3 -- .../Connectors/BridgeConnector.swift | 25 ++-------- .../Connectors/MobileAuthConnector.swift | 41 --------------- .../Connectors/PinConnector.swift | 48 ------------------ .../Connectors/RegistrationConnector.swift | 49 ------------------ .../Handlers/AuthenticatorsHandler.swift | 14 ------ .../NativeBridge/Handlers/LoginHandler.swift | 8 +-- .../Handlers/MobileAuthHandler.swift | 25 +++------- .../Handlers/RegistrationHandler.swift | 44 +++------------- .../OneginiModuleSwift+OTP.swift | 14 +++--- .../OneginiModuleSwift+Pin.swift | 4 +- .../OneginiModuleSwift+Register.swift | 27 ++++------ .../NativeBridge/OneginiModuleSwift.swift | 50 +------------------ ios/Classes/SwiftOneginiPlugin.swift | 18 ++----- 15 files changed, 48 insertions(+), 324 deletions(-) delete mode 100644 ios/Classes/NativeBridge/Connectors/MobileAuthConnector.swift delete mode 100644 ios/Classes/NativeBridge/Connectors/PinConnector.swift delete mode 100644 ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index d0defe9b..531de25e 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de + url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift index d26a6779..7bb3fd55 100644 --- a/example/ios/Runner/AppDelegate.swift +++ b/example/ios/Runner/AppDelegate.swift @@ -19,9 +19,6 @@ import OneginiSDKiOS let eventChannel = FlutterEventChannel(name: exampleCustomEventIdentifier, binaryMessenger: controller.binaryMessenger) - eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) - - OneginiModuleSwift.sharedInstance.eventSinkCustomIdentifier = exampleCustomEventIdentifier GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index 92d33f73..9178043d 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -1,34 +1,17 @@ -protocol BridgeConnectorProtocol: AnyObject { - func sendBridgeEvent(eventName: OneginiBridgeEvents, data: Any!) -> Void -} - -class BridgeConnector: BridgeConnectorProtocol { - - - let toPinConnector = PinConnector() +class BridgeConnector { let toLoginHandler = LoginHandler() let toAppToWebHandler: AppToWebHandlerProtocol = AppToWebHandler() let toResourceFetchHandler: FetchResourcesHandlerProtocol = ResourcesHandler() - let toMobileAuthConnector: BridgeToMobileAuthConnectorProtocol = MobileAuthConnector() var toLogoutUserHandler = LogoutHandler() var toDeregisterUserHandler = DeregisterUserHandler() let toAuthenticatorsHandler: AuthenticatorsHandler = AuthenticatorsHandler() - let toRegistrationConnector: BridgeToRegistrationConnectorProtocol + let toRegistrationHandler = RegistrationHandler() let toChangePinHandler: ChangePinHandler - weak var bridge: ConnectorToFlutterBridgeProtocol? + let toMobileAuthHandler = MobileAuthHandler() public static var shared:BridgeConnector? init() { - self.toRegistrationConnector = RegistrationConnector(handler: RegistrationHandler()) - self.toAuthenticatorsHandler.notificationReceiver = toMobileAuthConnector - self.toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationConnector.registrationHandler) - - self.toRegistrationConnector.bridgeConnector = self - self.toPinConnector.bridgeConnector = self + self.toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationHandler) BridgeConnector.shared = self } - - func sendBridgeEvent(eventName: OneginiBridgeEvents, data: Any!) { - bridge?.sendBridgeEvent(eventName: eventName, data: data) - } } diff --git a/ios/Classes/NativeBridge/Connectors/MobileAuthConnector.swift b/ios/Classes/NativeBridge/Connectors/MobileAuthConnector.swift deleted file mode 100644 index 09313d79..00000000 --- a/ios/Classes/NativeBridge/Connectors/MobileAuthConnector.swift +++ /dev/null @@ -1,41 +0,0 @@ -//MARK: - -protocol BridgeToMobileAuthConnectorProtocol: AuthenticatorsNotificationReceiverProtocol { - var bridgeConnector: BridgeConnectorProtocol? { get set } - var mobileAuthHandler: MobileAuthConnectorToHandlerProtocol { get } -} - -//MARK: - -class MobileAuthConnector : BridgeToMobileAuthConnectorProtocol, MobileAuthNotificationReceiverProtocol { - var mobileAuthHandler: MobileAuthConnectorToHandlerProtocol - unowned var bridgeConnector: BridgeConnectorProtocol? - - init() { - let handler = MobileAuthHandler() - mobileAuthHandler = handler - handler.notificationReceiver = self - } - - func sendNotification(event: MobileAuthNotification, requestMessage: String?, error: SdkError?) { - switch (event){ - case .startAuthentication: - sendEvent(data:MobileAuthNotification.startAuthentication.rawValue) - break - case .finishAuthentication: - sendEvent(data: MobileAuthNotification.finishAuthentication.rawValue) - break; - default: - Logger.log("MobileAuthNotification: \(event.rawValue)", sender: self) - } - } - - private func sendEvent(data: Any!) { - bridgeConnector?.sendBridgeEvent(eventName: OneginiBridgeEvents.authWithOtpNotification, data: data) - } -} - -//MARK: - -enum MobileAuthNotification : String { - case eventOpenAuthOtp = "eventOpenAuthOtp", - startAuthentication = "eventOpenPin", - finishAuthentication = "eventClosePin" -} diff --git a/ios/Classes/NativeBridge/Connectors/PinConnector.swift b/ios/Classes/NativeBridge/Connectors/PinConnector.swift deleted file mode 100644 index 2ca71c09..00000000 --- a/ios/Classes/NativeBridge/Connectors/PinConnector.swift +++ /dev/null @@ -1,48 +0,0 @@ -protocol BridgeToPinConnectorProtocol { - var bridgeConnector: BridgeConnectorProtocol? { get set } -} - -class PinConnector : BridgeToPinConnectorProtocol { - unowned var bridgeConnector: BridgeConnectorProtocol? - - func sendNotification(event: PinNotification, error: SdkError?) { - switch (event){ - case .open: - sendEvent(data: PinNotification.open.rawValue) - break - case .close: - sendEvent(data: PinNotification.close.rawValue) - break; - case .openAuth: - sendEvent(data: PinNotification.openAuth.rawValue) - break; - case .closeAuth: - sendEvent(data: PinNotification.closeAuth.rawValue) - break; - case .showError: - sendEvent(data: String.stringify(json: ["eventName": PinNotification.showError.rawValue, "eventValue": error?.details as Any?])) - break - case .nextAuthenticationAttempt: - if (error != nil && error?.details["userInfo"] != nil) { - sendEvent(data: String.stringify(json: ["eventName": PinNotification.nextAuthenticationAttempt.rawValue, "eventValue": String.stringify(json: error?.details["userInfo"] as Any)])) - } else { - sendEvent(data: String.stringify(json: ["eventName": PinNotification.nextAuthenticationAttempt.rawValue, "eventValue": String.stringify(json: [:]) as Any?])) - } - break - } - } - - private func sendEvent(data: Any!) { - bridgeConnector?.sendBridgeEvent(eventName: OneginiBridgeEvents.pinNotification, data: data) - } -} - -//MARK: - -enum PinNotification : String { - case open = "eventOpenPin", - close = "eventClosePin", - openAuth = "eventOpenPinAuth", - closeAuth = "eventClosePinAuth", - showError = "eventError", - nextAuthenticationAttempt = "eventNextAuthenticationAttempt" -} diff --git a/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift b/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift deleted file mode 100644 index 84cd7c67..00000000 --- a/ios/Classes/NativeBridge/Connectors/RegistrationConnector.swift +++ /dev/null @@ -1,49 +0,0 @@ -//MARK: - -protocol BridgeToRegistrationConnectorProtocol: CustomRegistrationNotificationReceiverProtocol { - var bridgeConnector: BridgeConnectorProtocol? { get set } - var registrationHandler: RegistrationHandler { get } -} - -//MARK: - -class RegistrationConnector : BridgeToRegistrationConnectorProtocol, CustomRegistrationNotificationReceiverProtocol { - var registrationHandler: RegistrationHandler - unowned var bridgeConnector: BridgeConnectorProtocol? - - init(handler: RegistrationHandler) { - registrationHandler = handler - handler.customNotificationReceiver = self - } - - func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) { - - var _data = data - switch (event){ - case .initRegistration, .finishRegistration, .eventError, .eventHandleRegisteredUrl: - _data?["eventName"] = event.rawValue - break - } - - sendEvent(data: _data) - } - - private func sendEvent(data: Any?) { - let _data = String.stringify(json: data ?? "") - bridgeConnector?.sendBridgeEvent(eventName: OneginiBridgeEvents.customRegistrationNotification, data: _data) - } -} - -//MARK: - -// Custom registration notification actions -enum CustomRegistrationNotification : String { - case initRegistration = "eventInitCustomRegistration", - finishRegistration = "eventFinishCustomRegistration", - eventError = "eventError", - eventHandleRegisteredUrl = "eventHandleRegisteredUrl" -} - - -// Custom registration actions -enum CustomRegistrationAction : String { - case provide = "provide", - cancel = "cancel" -} diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index bbaade76..9c60ce4d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -8,21 +8,13 @@ protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool - var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? { get } } -protocol AuthenticatorsNotificationReceiverProtocol: class { - func sendNotification(event: MobileAuthNotification, requestMessage: String?, error: SdkError?) -} - -//MARK: - class AuthenticatorsHandler: NSObject { var pinChallenge: ONGPinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? var registrationCompletion: ((Result) -> Void)? var deregistrationCompletion: ((Result) -> Void)? - - unowned var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? func handlePin(pin: String?) { guard let customAuthChallenge = self.customAuthChallenge else { @@ -55,12 +47,6 @@ class AuthenticatorsHandler: NSObject { } } } - - private func sendConnectorNotification(_ event: MobileAuthNotification, _ requestMessage: String?, _ error: SdkError?) { - - notificationReceiver?.sendNotification(event: event, requestMessage: requestMessage, error: error) -// BridgeConnector.shared?.toMobileAuthConnector.sendNotification(event: event, requestMessage: requestMessage, error: error) - } } //MARK: - BridgeToAuthenticatorsHandlerProtocol diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 007e64b8..c4b6b6e6 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -26,20 +26,20 @@ class LoginHandler: NSObject { func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { pinChallenge = challenge if let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) { - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.nextAuthenticationAttempt, error: pinError) + // FIXME: send correct event here } else { - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.openAuth, error: nil) + SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} } } func handleDidAuthenticateUser() { pinChallenge = nil - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.closeAuth, error: nil) + SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} } func handleDidFailToAuthenticateUser() { guard pinChallenge != nil else { return } - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.closeAuth, error: nil) + SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} pinChallenge = nil } } diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index e95c003e..3a8bd9c5 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -1,7 +1,6 @@ import Foundation import OneginiSDKiOS -//MARK: - protocol MobileAuthConnectorToHandlerProtocol: AnyObject { func enrollForMobileAuth(_ completion: @escaping (Bool?, SdkError?) -> Void) func isUserEnrolledForMobileAuth() -> Bool @@ -10,35 +9,22 @@ protocol MobileAuthConnectorToHandlerProtocol: AnyObject { func handleQrOTPMobileAuth(_ otp: String , customRegistrationChallenge: ONGCustomRegistrationChallenge?, _ completion: @escaping (Any?, SdkError?) -> Void) } -protocol MobileAuthNotificationReceiverProtocol: class { - func sendNotification(event: MobileAuthNotification, requestMessage: String?, error: SdkError?) -} - enum MobileAuthAuthenticatorType: String { case fingerprint = "biometric" case pin = "PIN" case confirmation = "" } -//MARK: - class MobileAuthHandler: NSObject { - var userProfile: ONGUserProfile? - var message: String? var authenticatorType: MobileAuthAuthenticatorType? var confirmation: ((Bool) -> Void)? var mobileAuthCompletion: ((Any?, SdkError?) -> Void)? - - unowned var notificationReceiver: MobileAuthNotificationReceiverProtocol? - + fileprivate func handleConfirmationMobileAuth(_ cancelled: Bool) { guard let confirmation = confirmation else { fatalError() } confirmation(cancelled) } - - private func sendConnectorNotification(_ event: MobileAuthNotification, _ requestMessage: String?, _ error: SdkError?) { - notificationReceiver?.sendNotification(event: event, requestMessage: requestMessage, error: error) - } } //MARK: - MobileAuthConnectorToHandlerProtocol @@ -111,12 +97,11 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { //MARK: - ONGMobileAuthRequestDelegate extension MobileAuthHandler: ONGMobileAuthRequestDelegate { func userClient(_: ONGUserClient, didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void, for request: ONGMobileAuthRequest) { - message = request.message - userProfile = request.userProfile authenticatorType = .confirmation self.confirmation = confirmation mobileAuthCompletion?(request.message, nil) - sendConnectorNotification(MobileAuthNotification.startAuthentication, request.message, nil) + //FIXME: This message can clearly be nullable, we should support this. + SwiftOneginiPlugin.flutterApi?.n2fOpenAuthOtp(message: request.message ?? "") {} } func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge, for request: ONGMobileAuthRequest) { @@ -132,6 +117,7 @@ extension MobileAuthHandler: ONGMobileAuthRequestDelegate { } func userClient(_ userClient: ONGUserClient, didFailToHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, error: Error) { + SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} if error.code == ONGGenericError.actionCancelled.rawValue { mobileAuthCompletion?(false, SdkError(.authenticationCancelled)) } else { @@ -141,6 +127,7 @@ extension MobileAuthHandler: ONGMobileAuthRequestDelegate { } func userClient(_ userClient: ONGUserClient, didHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, info customAuthenticatorInfo: ONGCustomInfo?) { - mobileAuthCompletion?(message, nil) + SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} + mobileAuthCompletion?(request.message, nil) } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 4f4f68fa..c3e2fd5d 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -9,10 +9,6 @@ protocol RegistrationConnectorToHandlerProtocol { func currentChallenge() -> ONGCustomRegistrationChallenge? } -protocol CustomRegistrationNotificationReceiverProtocol: class { - func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) -} - enum WebSignInType: Int { case insideApp case safari @@ -34,8 +30,6 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { var signUpCompletion: ((Result) -> Void)? - unowned var customNotificationReceiver: CustomRegistrationNotificationReceiverProtocol? - // Should not be needed func currentChallenge() -> ONGCustomRegistrationChallenge? { return self.customRegistrationChallenge @@ -113,10 +107,10 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.showError, error: pinError) + SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: String(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.open, error: nil) + SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} } } @@ -127,18 +121,14 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge = nil customRegistrationChallenge = nil browserRegistrationChallenge = nil - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.close, error: nil) + SwiftOneginiPlugin.flutterApi?.n2fClosePin {} } func handleDidRegisterUser() { createPinChallenge = nil customRegistrationChallenge = nil browserRegistrationChallenge = nil - BridgeConnector.shared?.toPinConnector.sendNotification(event: PinNotification.close, error: nil) - } - - private func sendCustomRegistrationNotification(_ event: CustomRegistrationNotification,_ data: Dictionary?) { - customNotificationReceiver?.sendCustomRegistrationNotification(event, data) + SwiftOneginiPlugin.flutterApi?.n2fClosePin {} } } @@ -194,10 +184,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { browserRegistrationChallenge = challenge debugPrint(challenge.url) - var result = Dictionary() - result["eventValue"] = challenge.url.absoluteString - - sendCustomRegistrationNotification(CustomRegistrationNotification.eventHandleRegisteredUrl, result) + SwiftOneginiPlugin.flutterApi?.n2fHandleRegisteredUrl(url: challenge.url.absoluteString) {} } func userClient(_: ONGUserClient, didReceivePinRegistrationChallenge challenge: ONGCreatePinChallenge) { @@ -215,19 +202,13 @@ extension RegistrationHandler: ONGRegistrationDelegate { func userClient(_: ONGUserClient, didReceiveCustomRegistrationInitChallenge challenge: ONGCustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationInitChallenge ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge - - let result = makeCustomInfoResponse(challenge) - - sendCustomRegistrationNotification(CustomRegistrationNotification.initRegistration, result) + SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } func userClient(_: ONGUserClient, didReceiveCustomRegistrationFinish challenge: ONGCustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationFinish ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge - - let result = makeCustomInfoResponse(challenge) - - sendCustomRegistrationNotification(CustomRegistrationNotification.finishRegistration, result) + SwiftOneginiPlugin.flutterApi?.n2fEventFinishCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } func userClient(_ userClient: ONGUserClient, didFailToRegisterWith identityProvider: ONGIdentityProvider, error: Error) { @@ -239,17 +220,6 @@ extension RegistrationHandler: ONGRegistrationDelegate { signUpCompletion?(.failure(FlutterError(mappedError))) } } - - private func makeCustomInfoResponse(_ challenge: ONGCustomRegistrationChallenge) -> Dictionary { - var result = Dictionary() - var customInfo = Dictionary() - customInfo["status"] = challenge.info?.status - customInfo["data"] = challenge.info?.data - customInfo["providerId"] = challenge.identityProvider.identifier - result["eventValue"] = String.stringify(json: customInfo) - - return result - } } fileprivate func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index 6f6edc5f..cbb52ec4 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -6,7 +6,7 @@ extension OneginiModuleSwift { public func otpResourceCodeConfirmation(code: String?, callback: @escaping FlutterResult) { // FIXME: Check what's going on here, why is custom registration challange put in mobile auth - bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleOTPMobileAuth(code ?? "", customRegistrationChallenge: bridgeConnector.toRegistrationConnector.registrationHandler.currentChallenge()) { + bridgeConnector.toMobileAuthHandler.handleOTPMobileAuth(code ?? "", customRegistrationChallenge: bridgeConnector.toRegistrationHandler.currentChallenge()) { (_ , error) -> Void in error != nil ? callback(error?.flutterError()) : callback(nil) @@ -15,7 +15,7 @@ extension OneginiModuleSwift { public func otpQRResourceCodeConfirmation(code: String?, callback: @escaping FlutterResult) { - guard bridgeConnector.toMobileAuthConnector.mobileAuthHandler.isUserEnrolledForMobileAuth() else { + guard bridgeConnector.toMobileAuthHandler.isUserEnrolledForMobileAuth() else { ONGUserClient.sharedInstance().enroll { [weak self] (value, error) in if let _error = error { @@ -33,15 +33,15 @@ extension OneginiModuleSwift { private func handleQRCode(_ code: String?, callback: @escaping FlutterResult) { // FIXME: Check what's going on here, why is custom registration challange put in mobile auth - let challenge = bridgeConnector.toRegistrationConnector.registrationHandler.currentChallenge() + let challenge = bridgeConnector.toRegistrationHandler.currentChallenge() var handleMobileAuthConfirmation = false - bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleQrOTPMobileAuth(code ?? "", customRegistrationChallenge: challenge) { [weak self] + bridgeConnector.toMobileAuthHandler.handleQrOTPMobileAuth(code ?? "", customRegistrationChallenge: challenge) { [weak self] (value, error) -> Void in if(error == nil && !handleMobileAuthConfirmation) { handleMobileAuthConfirmation = true - self?.bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleMobileAuthConfirmation(cancelled: true) + self?.bridgeConnector.toMobileAuthHandler.handleMobileAuthConfirmation(cancelled: true) } else { error != nil ? callback(error?.flutterError()) : callback(value) } @@ -49,11 +49,11 @@ extension OneginiModuleSwift { } func acceptMobileAuthConfirmation() -> Void { - bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleMobileAuthConfirmation(cancelled: false) + bridgeConnector.toMobileAuthHandler.handleMobileAuthConfirmation(cancelled: false) } @objc func denyMobileAuthConfirmation() -> Void { - bridgeConnector.toMobileAuthConnector.mobileAuthHandler.handleMobileAuthConfirmation(cancelled: true) + bridgeConnector.toMobileAuthHandler.handleMobileAuthConfirmation(cancelled: true) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index a58b59ad..4c1abc74 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -13,11 +13,11 @@ extension OneginiModuleSwift { } func pinAcceptRegistrationRequest(_ pin: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toRegistrationConnector.registrationHandler.handlePin(pin: pin, completion: completion) + bridgeConnector.toRegistrationHandler.handlePin(pin: pin, completion: completion) } func pinDenyRegistrationRequest(_ completion: @escaping (Result) -> Void) { - bridgeConnector.toRegistrationConnector.registrationHandler.cancelPinRegistration(completion: completion) + bridgeConnector.toRegistrationHandler.cancelPinRegistration(completion: completion) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 02647431..05104ff5 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -11,49 +11,42 @@ extension OneginiModuleSwift { } func registerUser(_ identityProviderId: String? = nil, scopes: [String]? = nil, completion: @escaping (Result) -> Void) { - bridgeConnector.toRegistrationConnector.registrationHandler.registerUser(identityProviderId, scopes: scopes, completion: completion) + bridgeConnector.toRegistrationHandler.registerUser(identityProviderId, scopes: scopes, completion: completion) } func handleRegisteredProcessUrl(_ url: String, webSignInType: Int) -> Result { - return bridgeConnector.toRegistrationConnector.registrationHandler.processRedirectURL(url: url, webSignInType: webSignInType) + return bridgeConnector.toRegistrationHandler.processRedirectURL(url: url, webSignInType: webSignInType) } public func handleDeepLinkCallbackUrl(_ url: URL) -> Bool { guard let schemeLibrary = URL.init(string: ONGClient.sharedInstance().configModel.redirectURL)?.scheme else { - generateEventError(value: "RedirectURL's scheme of configModel is empty: \(String(describing: ONGClient.sharedInstance().configModel.redirectURL))") + //FIXME: find out what to do here. +// generateEventError(value: "RedirectURL's scheme of configModel is empty: \(String(describing: ONGClient.sharedInstance().configModel.redirectURL))") return false } guard let scheme = url.scheme, scheme.compare(schemeLibrary, options: .caseInsensitive) == .orderedSame else { let value = ["url_scheme": url.scheme, "library_scheme": schemeLibrary, "url": url.absoluteString] - generateEventError(value: value) + //FIXME: find out what to do here. +// generateEventError(value: value) return false } - bridgeConnector.toRegistrationConnector.registrationHandler.handleRedirectURL(url: url) + bridgeConnector.toRegistrationHandler.handleRedirectURL(url: url) return true } - private func generateEventError(value: Any?) { - var errorParameters = [String: Any]() - errorParameters["eventName"] = "eventError" - errorParameters["eventValue"] = value - - let data = String.stringify(json: errorParameters) - OneginiModuleSwift.sharedInstance.sendBridgeEvent(eventName: OneginiBridgeEvents.pinNotification, data: data) - } - func submitCustomRegistrationSuccess(_ data: String?) { - bridgeConnector.toRegistrationConnector.registrationHandler.submitCustomRegistrationSuccess(data) + bridgeConnector.toRegistrationHandler.submitCustomRegistrationSuccess(data) } func submitCustomRegistrationError(_ error: String) { - bridgeConnector.toRegistrationConnector.registrationHandler.cancelCustomRegistration(error) + bridgeConnector.toRegistrationHandler.cancelCustomRegistration(error) } public func cancelBrowserRegistration() -> Void { - bridgeConnector.toRegistrationConnector.registrationHandler.cancelBrowserRegistration() + bridgeConnector.toRegistrationHandler.cancelBrowserRegistration() } func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index cf62e8ba..d6da89d4 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -2,34 +2,15 @@ import Foundation import OneginiSDKiOS import Flutter -protocol ConnectorToFlutterBridgeProtocol: NSObject { - func sendBridgeEvent(eventName: OneginiBridgeEvents, data: Any!) -> Void -} - -enum OneginiBridgeEvents : String { - case pinNotification = "ONEGINI_PIN_NOTIFICATION" - case customRegistrationNotification = "ONEGINI_CUSTOM_REGISTRATION_NOTIFICATION" - case authWithOtpNotification = "ONEGINI_MOBILE_AUTH_OTP_NOTIFICATION" - case otpOpen = "OPEN_OTP" - case errorNotification = "ONEGINI_ERROR_NOTIFICATION" -} - -//MARK: - -public class OneginiModuleSwift: NSObject, ConnectorToFlutterBridgeProtocol, FlutterStreamHandler { +public class OneginiModuleSwift: NSObject { var bridgeConnector: BridgeConnector - private var eventSink: FlutterEventSink? - public var eventSinkNativePart: FlutterEventSink? - public var eventSinkCustomIdentifier: String? - public var customRegIdentifiers = [String]() - //public var schemeDeepLink: String! - + public var customRegIdentifiers = [String]() static public let sharedInstance = OneginiModuleSwift() override init() { self.bridgeConnector = BridgeConnector() super.init() - self.bridgeConnector.bridge = self } func configureCustomRegIdentifiers(_ list: [String]) { @@ -65,32 +46,5 @@ public class OneginiModuleSwift: NSObject, ConnectorToFlutterBridgeProtocol, Flu let profiles = ONGUserClient.sharedInstance().userProfiles() return .success(profiles.compactMap { OWUserProfile($0) } ) } - - public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { - if let _value = eventSinkCustomIdentifier, let _arg = arguments as! String?, _value == _arg { - self.eventSinkNativePart = events - } else if let _arg = arguments as! String?, _arg == "onegini_events" { - eventSink = events - } - return nil - } - - public func onCancel(withArguments arguments: Any?) -> FlutterError? { - return nil - } - - func sendBridgeEvent(eventName: OneginiBridgeEvents, data: Any!) -> Void { - Logger.log("event.name: \(eventName)") - if eventName == OneginiBridgeEvents.otpOpen { - eventSinkNativePart?(data) - return; - } - - guard let _eventSink = eventSink else { - return - } - - _eventSink(data) - } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 457c2347..3b40b9ac 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -273,25 +273,17 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc static var flutterApi: NativeCallFlutterApi? public static func register(with registrar: FlutterPluginRegistrar) { + // FIXME: We can remove this once we have moved all functions to Pigeon + // Init old communication let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) - let eventChannel = FlutterEventChannel(name: "onegini_events", - binaryMessenger: registrar.messenger()) let instance = SwiftOneginiPlugin() registrar.addMethodCallDelegate(instance, channel: channel) - eventChannel.setStreamHandler(OneginiModuleSwift.sharedInstance) - // Init Pigeon communication let messenger: FlutterBinaryMessenger = registrar.messenger() - let userClientApi: UserClientApi & NSObjectProtocol = SwiftOneginiPlugin.init() - UserClientApiSetup.setUp(binaryMessenger: messenger, api: userClientApi) - - let resourceMethodApi: ResourceMethodApi & NSObjectProtocol = SwiftOneginiPlugin.init() - ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: resourceMethodApi) - + let api = SwiftOneginiPlugin.init() + UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) + ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: api) flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) - - // Example on call flutter function from native during start - flutterApi?.testEventFunction(argument: "we initilized the function", completion: {_ in }) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { From 7b2779680656598ccaa2d39775208fef357a88a7 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 12:44:05 +0100 Subject: [PATCH 161/364] FP-75: Support nextAuthAttempt event --- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 14 -------------- .../NativeBridge/Handlers/LoginHandler.swift | 10 +++++++--- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 49de273d..85820201 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -95,19 +95,5 @@ class ErrorMapper { return SdkError(code: error.code, errorDescription: error.localizedDescription) } - - func mapErrorFromPinChallenge(_ challenge: ONGPinChallenge?) -> SdkError? { - if let error = challenge?.error, error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue { - // FIXME: this probably shouldn't be here - guard let maxAttempts = challenge?.maxFailureCount, - let previousCount = challenge?.previousFailureCount, - maxAttempts != previousCount else { - return SdkError(code: error.code, errorDescription: error.localizedDescription) - } - return SdkError(code: error.code, errorDescription: "Failed attempts", info: ["failedAttempts": previousCount, "maxAttempts": maxAttempts]) - } else { - return nil - } - } } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index c4b6b6e6..48315021 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -25,11 +25,15 @@ class LoginHandler: NSObject { func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { pinChallenge = challenge - if let pinError = ErrorMapper().mapErrorFromPinChallenge(challenge) { - // FIXME: send correct event here - } else { + guard let error = challenge.error , error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue else { SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} + return } + let authAttempt = OWAuthenticationAttempt( + failedAttempts: Int32(challenge.previousFailureCount), + maxAttempts: Int32(challenge.maxFailureCount), + remainingAttempts: Int32(challenge.remainingFailureCount)) + SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} } func handleDidAuthenticateUser() { From 5bb376b4035b6b33c8cc9dee44105a7fe50f1367 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 21 Mar 2023 13:20:41 +0100 Subject: [PATCH 162/364] FP-75: Update a few FIXME's --- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 05104ff5..0d03bbac 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -20,16 +20,14 @@ extension OneginiModuleSwift { public func handleDeepLinkCallbackUrl(_ url: URL) -> Bool { guard let schemeLibrary = URL.init(string: ONGClient.sharedInstance().configModel.redirectURL)?.scheme else { - //FIXME: find out what to do here. -// generateEventError(value: "RedirectURL's scheme of configModel is empty: \(String(describing: ONGClient.sharedInstance().configModel.redirectURL))") + //FIXME: We should propagate an error here to the caller, not through events. return false } guard let scheme = url.scheme, scheme.compare(schemeLibrary, options: .caseInsensitive) == .orderedSame else { let value = ["url_scheme": url.scheme, "library_scheme": schemeLibrary, "url": url.absoluteString] - //FIXME: find out what to do here. -// generateEventError(value: value) + //FIXME: We should propagate an error here to the caller, not through events. return false } From d324d904f9ef568919da3ee6c8a4fde4c05d82c6 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 21 Mar 2023 16:41:39 +0100 Subject: [PATCH 163/364] FP-70 Moved OTP related functions into their own use cases and added tests, additionally modified otp behaviour to not auto enroll anymore and added specific enroll mobile auth function on android --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../mobile/sdk/flutter/PigeonInterface.kt | 33 ++++--- .../helpers/MobileAuthenticationObject.kt | 3 + .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 28 +++++- .../EnrollMobileAuthenticationUseCase.kt | 32 +++++++ .../HandleMobileAuthWithOtpUseCase.kt | 33 +++++++ .../OtpAcceptAuthenticationRequestUseCase.kt | 23 +++++ .../OtpDenyAuthenticationRequestUseCase.kt | 23 +++++ .../EnrollMobileAuthenticationUseCaseTest.kt | 90 ++++++++++++++++++ .../sdk/HandleMobileAuthWithOtpUseCaseTest.kt | 91 +++++++++++++++++++ ...pAcceptAuthenticationRequestUseCaseTest.kt | 42 +++++++++ ...OtpDenyAuthenticationRequestUseCaseTest.kt | 42 +++++++++ ios/Classes/Pigeon.swift | 30 ++++-- ios/Classes/SwiftOneginiPlugin.swift | 16 +++- lib/pigeon.dart | 28 +++++- lib/user_client.dart | 14 ++- pigeons/onewelcome_pigeon_interface.dart | 6 +- 17 files changed, 502 insertions(+), 33 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index a34fc1db..ec68290e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -13,6 +13,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), + OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index be9bd374..13e0783e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -6,8 +6,6 @@ import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandle import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn @@ -26,6 +24,7 @@ import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUse import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase +import com.onegini.mobile.sdk.flutter.useCases.EnrollMobileAuthenticationUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestDenyUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase @@ -37,9 +36,12 @@ import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUse import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase +import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase +import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase +import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase @@ -119,6 +121,14 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase @Inject + lateinit var enrollMobileAuthenticationUseCase: EnrollMobileAuthenticationUseCase + @Inject + lateinit var handleMobileAuthWithOtpUseCase: HandleMobileAuthWithOtpUseCase + @Inject + lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase + @Inject + lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + @Inject lateinit var oneginiSDK: OneginiSDK override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { @@ -177,12 +187,15 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { logoutUseCase(callback) } - override fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) { - // TODO; dependent on: - // https://onewelcome.atlassian.net/browse/FP-20 - // https://onewelcome.atlassian.net/browse/FP-70 + override fun enrollMobileAuthentication(callback: (Result) -> Unit) { + enrollMobileAuthenticationUseCase(callback) } + override fun handleMobileAuthWithOtp(data: String, callback: (Result) -> Unit) { + handleMobileAuthWithOtpUseCase(data, callback) + } + + override fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) { // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-62 if (!Patterns.WEB_URL.matcher(url).matches()) { @@ -254,15 +267,11 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun otpDenyAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-70 - MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() - callback(Result.success(Unit)) + callback(otpDenyAuthenticationRequestUseCase()) } override fun otpAcceptAuthenticationRequest(callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-70 - MobileAuthOtpRequestHandler.CALLBACK?.acceptAuthenticationRequest() - callback(Result.success(Unit)) + callback(otpAcceptAuthenticationRequestUseCase()) } override fun pinDenyAuthenticationRequest(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/MobileAuthenticationObject.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/MobileAuthenticationObject.kt index 3a474bc3..589b17a7 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/MobileAuthenticationObject.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/MobileAuthenticationObject.kt @@ -8,6 +8,9 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthWithOtpErr import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import io.flutter.plugin.common.MethodChannel +// TODO delete this class once the iOS rework is finished and we transferred to pigeon api +// to insure consistent behaviour (new usecases dont auto enroll) +// https://onewelcome.atlassian.net/jira/software/c/projects/MS/boards/116?modal=detail&selectedIssue=FP-69 object MobileAuthenticationObject { fun mobileAuthWithOtp(data: String?, result: MethodChannel.Result, oneginiClient: OneginiClient) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index ebd173c7..69a8b34a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -351,7 +351,8 @@ interface UserClientApi { fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) fun logout(callback: (Result) -> Unit) - fun mobileAuthWithOtp(data: String, callback: (Result) -> Unit) + fun enrollMobileAuthentication(callback: (Result) -> Unit) + fun handleMobileAuthWithOtp(data: String, callback: (Result) -> Unit) fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) fun getAccessToken(callback: (Result) -> Unit) fun getRedirectUrl(callback: (Result) -> Unit) @@ -669,19 +670,36 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + var wrapped = listOf() + api.enrollMobileAuthentication() { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", codec) if (api != null) { channel.setMessageHandler { message, reply -> var wrapped = listOf() val args = message as List val dataArg = args[0] as String - api.mobileAuthWithOtp(dataArg) { result: Result -> + api.handleMobileAuthWithOtp(dataArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(wrapResult(null)) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt new file mode 100644 index 00000000..4d7d70c3 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt @@ -0,0 +1,32 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthEnrollmentHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class EnrollMobileAuthenticationUseCase @Inject constructor( + private val oneginiSDK: OneginiSDK, +) { + operator fun invoke(callback: (Result) -> Unit) { + oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + + oneginiSDK.oneginiClient.userClient.enrollUserForMobileAuth(object : OneginiMobileAuthEnrollmentHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } + + override fun onError(enrollError: OneginiMobileAuthEnrollmentError) { + callback(Result.failure(SdkError( + code = enrollError.errorType, + message = enrollError.message + ).pigeonError())) + } + }) + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt new file mode 100644 index 00000000..c7b34c17 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt @@ -0,0 +1,33 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthWithOtpHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthWithOtpError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject + +class HandleMobileAuthWithOtpUseCase @Inject constructor( + private val oneginiSDK: OneginiSDK, +) { + operator fun invoke(data: String, callback: (Result) -> Unit) { + oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + + oneginiSDK.oneginiClient.userClient.handleMobileAuthWithOtp( + data, + object : OneginiMobileAuthWithOtpHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } + + override fun onError(otpError: OneginiMobileAuthWithOtpError) { + callback(Result.failure(SdkError( + code = otpError.errorType, + message = otpError.message + ).pigeonError())) + } + } + ) + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt new file mode 100644 index 00000000..60cb671b --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt @@ -0,0 +1,23 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class OtpAcceptAuthenticationRequestUseCase @Inject constructor() { + operator fun invoke(): Result { + MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() + + return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + otpCallback.acceptAuthenticationRequest() + MobileAuthOtpRequestHandler.CALLBACK = null + Result.success(Unit) + } + } + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt new file mode 100644 index 00000000..029c1ac9 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt @@ -0,0 +1,23 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class OtpDenyAuthenticationRequestUseCase @Inject constructor() { + operator fun invoke(): Result { + MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() + + return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { + null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + otpCallback.denyAuthenticationRequest() + MobileAuthOtpRequestHandler.CALLBACK = null + Result.success(Unit) + } + } + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt new file mode 100644 index 00000000..cde70fb3 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt @@ -0,0 +1,90 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthEnrollmentHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError +import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.useCases.EnrollMobileAuthenticationUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class EnrollMobileAuthenticationUseCaseTest { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var enrollErrorMock: OneginiMobileAuthEnrollmentError + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var enrollMobileAuthenticationUseCase: EnrollMobileAuthenticationUseCase + + @Before + fun attach() { + enrollMobileAuthenticationUseCase = EnrollMobileAuthenticationUseCase(oneginiSdk) + whenever(enrollErrorMock.errorType).thenReturn(OneginiMobileAuthEnrollmentError.GENERAL_ERROR) + whenever(enrollErrorMock.message).thenReturn("General error") + } + + @Test + fun `When there is no authenticated user during the enrollment, Then it should resolve with an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) + + enrollMobileAuthenticationUseCase(callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + val expected = SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError() + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } + + @Test + fun `When the sdk returns an enrollment error, Then it should resolve with an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.enrollUserForMobileAuth(any())).thenAnswer { + it.getArgument(0).onError(enrollErrorMock) + } + + enrollMobileAuthenticationUseCase(callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(OneginiMobileAuthEnrollmentError.GENERAL_ERROR.toString(), "General error") + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } + + @Test + fun `When the sdk succeeds with the enrollment, Then it should resolve successfully`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.enrollUserForMobileAuth(any())).thenAnswer { + it.getArgument(0).onSuccess() + } + + enrollMobileAuthenticationUseCase(callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + Assert.assertEquals(firstValue.getOrNull(), Unit) + } + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt new file mode 100644 index 00000000..c2cb33ef --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt @@ -0,0 +1,91 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthWithOtpHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError +import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthWithOtpError +import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class HandleMobileAuthWithOtpUseCaseTest { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var otpErrorMock: OneginiMobileAuthWithOtpError + + @Mock + lateinit var callbackMock: (Result) -> Unit + + lateinit var handleMobileAuthWithOtpUseCase: HandleMobileAuthWithOtpUseCase + + @Before + fun attach() { + handleMobileAuthWithOtpUseCase = HandleMobileAuthWithOtpUseCase(oneginiSdk) + whenever(otpErrorMock.errorType).thenReturn(OneginiMobileAuthWithOtpError.GENERAL_ERROR) + whenever(otpErrorMock.message).thenReturn("General error") + } + + @Test + fun `When there is no authenticated user during the otp authentication, Then it should resolve with an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) + + handleMobileAuthWithOtpUseCase("otp_password", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + val expected = SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError() + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } + + @Test + fun `When the sdk returns an otp authentication error, Then it should resolve with an error`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.handleMobileAuthWithOtp(any(), any())).thenAnswer { + it.getArgument(1).onError(otpErrorMock) + } + + handleMobileAuthWithOtpUseCase("otp_password", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(OneginiMobileAuthEnrollmentError.GENERAL_ERROR.toString(), "General error") + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } + + @Test + fun `When the sdk succeeds with the otp authentication, Then it should resolve successfully`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.handleMobileAuthWithOtp(any(), any())).thenAnswer { + it.getArgument(1).onSuccess() + } + + handleMobileAuthWithOtpUseCase("otp_password", callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + Assert.assertEquals(firstValue.getOrNull(), Unit) + } + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt new file mode 100644 index 00000000..ef3b1d32 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt @@ -0,0 +1,42 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class OtpAcceptAuthenticationRequestUseCaseTest { + @Mock + lateinit var oneginiOtpCallbackMock: OneginiAcceptDenyCallback + + lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + + @Before + fun attach() { + otpAcceptAuthenticationRequestUseCase = OtpAcceptAuthenticationRequestUseCase() + } + + @Test + fun `When no otp authentication callback is set, Then it should resolve with an error`() { + MobileAuthOtpRequestHandler.CALLBACK = null + + val result = otpAcceptAuthenticationRequestUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a otp authentication callback is set, Then it should resolve successfully`() { + MobileAuthOtpRequestHandler.CALLBACK = oneginiOtpCallbackMock + + val result = otpAcceptAuthenticationRequestUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt new file mode 100644 index 00000000..b4d76738 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -0,0 +1,42 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class OtpDenyAuthenticationRequestUseCaseTest { + @Mock + lateinit var oneginiOtpCallbackMock: OneginiAcceptDenyCallback + + lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase + + @Before + fun attach() { + otpDenyAuthenticationRequestUseCase = OtpDenyAuthenticationRequestUseCase() + } + + @Test + fun `When no otp authentication callback is set, Then it should resolve with an error`() { + MobileAuthOtpRequestHandler.CALLBACK = null + + val result = otpDenyAuthenticationRequestUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) + } + + @Test + fun `When a otp authentication callback is set, Then it should resolve successfully`() { + MobileAuthOtpRequestHandler.CALLBACK = oneginiOtpCallbackMock + + val result = otpDenyAuthenticationRequestUseCase().getOrNull() + Assert.assertEquals(Unit, result) + } +} diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 700f7258..91894385 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -329,7 +329,8 @@ protocol UserClientApi { func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) func logout(completion: @escaping (Result) -> Void) - func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) + func enrollMobileAuthentication(completion: @escaping (Result) -> Void) + func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) func getAccessToken(completion: @escaping (Result) -> Void) func getRedirectUrl(completion: @escaping (Result) -> Void) @@ -596,22 +597,37 @@ class UserClientApiSetup { } else { logoutChannel.setMessageHandler(nil) } - let mobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) + let enrollMobileAuthenticationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - mobileAuthWithOtpChannel.setMessageHandler { message, reply in + enrollMobileAuthenticationChannel.setMessageHandler { _, reply in + api.enrollMobileAuthentication() { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + enrollMobileAuthenticationChannel.setMessageHandler(nil) + } + let handleMobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + handleMobileAuthWithOtpChannel.setMessageHandler { message, reply in let args = message as! [Any?] let dataArg = args[0] as! String - api.mobileAuthWithOtp(data: dataArg) { result in + api.handleMobileAuthWithOtp(data: dataArg) { result in switch result { - case .success(let res): - reply(wrapResult(res)) + case .success: + reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { - mobileAuthWithOtpChannel.setMessageHandler(nil) + handleMobileAuthWithOtpChannel.setMessageHandler(nil) } let getAppToWebSingleSignOnChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", binaryMessenger: binaryMessenger, codec: codec) if let api = api { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 457c2347..1d39b914 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -80,6 +80,18 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { + func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { + // Will be implemented during the OTP rework in + // https://onewelcome.atlassian.net/browse/FP-69 + completion(.success) + } + + func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { + // Will be implemented during the OTP rework in + // https://onewelcome.atlassian.net/browse/FP-69 + completion(.success) + } + func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.requestResource(type, details) { result in completion(result.mapError { $0 }) @@ -118,13 +130,13 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.denyMobileAuthConfirmation() - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in https://onewelcome.atlassian.net/browse/FP-69 completion(.success) } func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.acceptMobileAuthConfirmation() - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? + // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in https://onewelcome.atlassian.net/browse/FP-69 completion(.success) } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ccf76534..159062bd 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -665,9 +665,31 @@ class UserClientApi { } } - Future mobileAuthWithOtp(String arg_data) async { + Future enrollMobileAuthentication() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp', codec, + 'dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future handleMobileAuthWithOtp(String arg_data) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_data]) as List?; @@ -683,7 +705,7 @@ class UserClientApi { details: replyList[2], ); } else { - return (replyList[0] as String?); + return; } } diff --git a/lib/user_client.dart b/lib/user_client.dart index 33ca0e7d..a786b3e9 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -126,10 +126,20 @@ class UserClient { await api.logout(); } + // TODO Implement these functions within example app after. + // https://onewelcome.atlassian.net/browse/FP-69 + Future enrollMobileAuthentication() async { + await api.enrollMobileAuthentication(); + } + + Future handleMobileAuthWithOtp(String data) async { + await api.handleMobileAuthWithOtp(data); + } + /// Starts mobile authentication on web by OTP. Future mobileAuthWithOtp(String data) async { - // todo use api once the branch is merged that puts this in an usecase on android - // return await api.mobileAuthWithOtp(data); + // TODO once iOS rework is finished remove this functions + // https://onewelcome.atlassian.net/browse/FP-69 try { var isSuccess = await Onegini.instance.channel .invokeMethod(Constants.handleMobileAuthWithOtp, { diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 56b7f438..34bec779 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -143,9 +143,11 @@ abstract class UserClientApi { @async void logout(); - // todo investigate if string can be non null @async - String? mobileAuthWithOtp(String data); + void enrollMobileAuthentication(); + + @async + void handleMobileAuthWithOtp(String data); @async OWAppToWebSingleSignOn getAppToWebSingleSignOn(String url); From 61f02dcc044667ed1af540fff3d7a88943b427ba Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 22 Mar 2023 10:50:26 +0100 Subject: [PATCH 164/364] FP-75: Change code in OneginiError to Int so we can more safely use it This patch fixes an issue where we could not type safe obtain the code of an error so we just passed in a hardcoded integer as a workaround. --- .../mobile/sdk/flutter/handlers/PinRequestHandler.kt | 2 +- .../com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 4 ++-- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 4 ++-- ios/Classes/Pigeon.swift | 4 ++-- lib/onegini_event_listener.dart | 6 +++--- lib/pigeon.dart | 4 ++-- pigeons/onewelcome_pigeon_interface.dart | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index f5c86746..b4fe113f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -22,7 +22,7 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu } override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { - nativeApi.n2fEventError(OWOneginiError(oneginiPinValidationError.errorType.toString(), oneginiPinValidationError.message ?: "")) {} + nativeApi.n2fEventError(OWOneginiError(oneginiPinValidationError.errorType.toLong(), oneginiPinValidationError.message ?: "")) {} } override fun finishPinCreation() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 01beb07d..978ef1cc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -290,14 +290,14 @@ data class OWAuthenticationAttempt ( /** Generated class from Pigeon that represents data sent in messages. */ data class OWOneginiError ( - val code: String, + val code: Long, val message: String ) { companion object { @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWOneginiError { - val code = list[0] as String + val code = list[0].let { if (it is Int) it.toLong() else it as Long } val message = list[1] as String return OWOneginiError(code, message) } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index c3e2fd5d..4fdcb830 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -106,8 +106,8 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func handleDidReceivePinRegistrationChallenge(_ challenge: ONGCreatePinChallenge) { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { - // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. - SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: String(pinError.code), message: pinError.errorDescription)) {} + // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. FP-34 + SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int32(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 36936e93..102137ae 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -278,11 +278,11 @@ struct OWAuthenticationAttempt { /// Generated class from Pigeon that represents data sent in messages. struct OWOneginiError { - var code: String + var code: Int32 var message: String static func fromList(_ list: [Any?]) -> OWOneginiError? { - let code = list[0] as! String + let code = list[0] as! Int32 let message = list[1] as! String return OWOneginiError( diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 91784e45..d8d15301 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -159,13 +159,13 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { @override void n2fEventError(OWOneginiError error) { - eventError( - _context, PlatformException(code: error.code, message: error.message)); + eventError(_context, + PlatformException(code: error.code.toString(), message: error.message)); } @override void n2fShowError(OWOneginiError error) { // FIXME: use correct error code here. - showError(_context, OneginiError(code: 9999, message: error.message)); + showError(_context, OneginiError(code: error.code, message: error.message)); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index e3d7a7f4..6335d786 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -300,7 +300,7 @@ class OWOneginiError { required this.message, }); - String code; + int code; String message; @@ -314,7 +314,7 @@ class OWOneginiError { static OWOneginiError decode(Object result) { result as List; return OWOneginiError( - code: result[0]! as String, + code: result[0]! as int, message: result[1]! as String, ); } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 59a85f2b..d09c6b66 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -106,7 +106,7 @@ class OWAuthenticationAttempt { } class OWOneginiError { - String code; + int code; String message; OWOneginiError({required this.code, required this.message}); } From 3d713f7143039aef4fb34d50e0672fce26d8762f Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 22 Mar 2023 11:06:02 +0100 Subject: [PATCH 165/364] Chore: Update and lock the pigeon version --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 67 ++++--------- example/ios/Podfile.lock | 2 +- ios/Classes/Pigeon.swift | 98 +++++++++---------- ios/Classes/SwiftOneginiPlugin.swift | 14 +-- lib/pigeon.dart | 2 +- pubspec.yaml | 6 +- 6 files changed, 78 insertions(+), 111 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index ebd173c7..cebb7e08 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin @@ -31,6 +31,12 @@ private fun wrapError(exception: Throwable): List { } } +/** + * Error class for passing custom error details to Flutter via a thrown PlatformException. + * @property code The error code. + * @property message The error message. + * @property details The error details. Must be a datatype supported by the api codec. + */ class FlutterError ( val code: String, override val message: String? = null, @@ -96,7 +102,7 @@ data class OWCustomInfo ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWCustomInfo { val status = list[0].let { if (it is Int) it.toLong() else it as Long } - val data = list[1] as? String + val data = list[1] as String? return OWCustomInfo(status, data) } } @@ -193,7 +199,7 @@ data class OWRegistrationResponse ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWRegistrationResponse { val userProfile = OWUserProfile.fromList(list[0] as List) - val customInfo: OWCustomInfo? = (list[1] as? List)?.let { + val customInfo: OWCustomInfo? = (list[1] as List?)?.let { OWCustomInfo.fromList(it) } return OWRegistrationResponse(userProfile, customInfo) @@ -201,7 +207,7 @@ data class OWRegistrationResponse ( } fun toList(): List { return listOf( - userProfile?.toList(), + userProfile.toList(), customInfo?.toList(), ) } @@ -220,15 +226,15 @@ data class OWRequestDetails ( fun fromList(list: List): OWRequestDetails { val path = list[0] as String val method = HttpRequestMethod.ofRaw(list[1] as Int)!! - val headers = list[2] as? Map - val body = list[3] as? String + val headers = list[2] as Map? + val body = list[3] as String? return OWRequestDetails(path, method, headers, body) } } fun toList(): List { return listOf( path, - method?.raw, + method.raw, headers, body, ) @@ -390,10 +396,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val identityProviderIdArg = args[0] as? String - val scopesArg = args[1] as? List + val identityProviderIdArg = args[0] as String? + val scopesArg = args[1] as List? api.registerUser(identityProviderIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -412,7 +417,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } @@ -433,7 +437,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getIdentityProviders", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getIdentityProviders() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -452,7 +455,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.deregisterUser(profileIdArg) { result: Result -> @@ -472,7 +474,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -493,7 +494,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getAllAuthenticators(profileIdArg) { result: Result> -> @@ -514,7 +514,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAuthenticatedUserProfile() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -533,10 +532,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val registeredAuthenticatorIdArg = args[1] as? String + val registeredAuthenticatorIdArg = args[1] as String? api.authenticateUser(profileIdArg, registeredAuthenticatorIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -555,7 +553,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getNotRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -576,7 +573,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.changePin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -594,7 +590,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.setPreferredAuthenticator(authenticatorIdArg) { result: Result -> @@ -614,7 +609,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.deregisterAuthenticator(authenticatorIdArg) { result: Result -> @@ -634,7 +628,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.registerAuthenticator(authenticatorIdArg) { result: Result -> @@ -654,7 +647,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.logout", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.logout() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -672,7 +664,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val dataArg = args[0] as String api.mobileAuthWithOtp(dataArg) { result: Result -> @@ -693,7 +684,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String api.getAppToWebSingleSignOn(urlArg) { result: Result -> @@ -714,7 +704,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAccessToken", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAccessToken() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -733,7 +722,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRedirectUrl", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getRedirectUrl() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -752,7 +740,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getUserProfiles", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getUserProfiles() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -771,7 +758,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.validatePinWithPolicy(pinArg) { result: Result -> @@ -791,9 +777,8 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateDevice", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val scopesArg = args[0] as? List + val scopesArg = args[0] as List? api.authenticateDevice(scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -811,10 +796,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val scopesArg = args[1] as? List + val scopesArg = args[1] as List? api.authenticateUserImplicitly(profileIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -832,10 +816,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String - val dataArg = args[1] as? String + val dataArg = args[1] as String? api.submitCustomRegistrationAction(identityProviderIdArg, dataArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -853,7 +836,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String val errorArg = args[1] as String @@ -874,7 +856,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintFallbackToPin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -892,7 +873,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -910,7 +890,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -928,7 +907,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -946,7 +924,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -964,7 +941,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -982,7 +958,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptAuthenticationRequest(pinArg) { result: Result -> @@ -1002,7 +977,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyRegistrationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1020,7 +994,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptRegistrationRequest(pinArg) { result: Result -> @@ -1040,7 +1013,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.cancelBrowserRegistration() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1105,7 +1077,6 @@ interface ResourceMethodApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.requestResource", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val typeArg = ResourceRequestType.ofRaw(args[0] as Int)!! val detailsArg = args[1] as OWRequestDetails diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index d0defe9b..531de25e 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de + url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 700f7258..7bd5c6bd 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -51,7 +51,7 @@ enum ResourceRequestType: Int { struct OWUserProfile { var profileId: String - static func fromList(_ list: [Any?]) -> OWUserProfile? { + static func fromList(_ list: [Any]) -> OWUserProfile? { let profileId = list[0] as! String return OWUserProfile( @@ -67,12 +67,12 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { - var status: Int32 + var status: Int64 var data: String? = nil - static func fromList(_ list: [Any?]) -> OWCustomInfo? { - let status = list[0] as! Int32 - let data = list[1] as? String + static func fromList(_ list: [Any]) -> OWCustomInfo? { + let status = list[0] as! Int64 + let data = list[1] as! String? return OWCustomInfo( status: status, @@ -92,7 +92,7 @@ struct OWIdentityProvider { var id: String var name: String - static func fromList(_ list: [Any?]) -> OWIdentityProvider? { + static func fromList(_ list: [Any]) -> OWIdentityProvider? { let id = list[0] as! String let name = list[1] as! String @@ -115,14 +115,14 @@ struct OWAuthenticator { var name: String var isRegistered: Bool var isPreferred: Bool - var authenticatorType: Int32 + var authenticatorType: Int64 - static func fromList(_ list: [Any?]) -> OWAuthenticator? { + static func fromList(_ list: [Any]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String let isRegistered = list[2] as! Bool let isPreferred = list[3] as! Bool - let authenticatorType = list[4] as! Int32 + let authenticatorType = list[4] as! Int64 return OWAuthenticator( id: id, @@ -148,7 +148,7 @@ struct OWAppToWebSingleSignOn { var token: String var redirectUrl: String - static func fromList(_ list: [Any?]) -> OWAppToWebSingleSignOn? { + static func fromList(_ list: [Any]) -> OWAppToWebSingleSignOn? { let token = list[0] as! String let redirectUrl = list[1] as! String @@ -170,11 +170,11 @@ struct OWRegistrationResponse { var userProfile: OWUserProfile var customInfo: OWCustomInfo? = nil - static func fromList(_ list: [Any?]) -> OWRegistrationResponse? { - let userProfile = OWUserProfile.fromList(list[0] as! [Any?])! + static func fromList(_ list: [Any]) -> OWRegistrationResponse? { + let userProfile = OWUserProfile.fromList(list[0] as! [Any])! var customInfo: OWCustomInfo? = nil - if let customInfoList = list[1] as? [Any?] { - customInfo = OWCustomInfo.fromList(customInfoList) + if let customInfoList = list[1] as! [Any]? { + customInfo = OWCustomInfo.fromList(customInfoList as [Any]) } return OWRegistrationResponse( @@ -197,11 +197,11 @@ struct OWRequestDetails { var headers: [String?: String?]? = nil var body: String? = nil - static func fromList(_ list: [Any?]) -> OWRequestDetails? { + static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String let method = HttpRequestMethod(rawValue: list[1] as! Int)! - let headers = list[2] as? [String?: String?] - let body = list[3] as? String + let headers = list[2] as! [String?: String?]? + let body = list[3] as! String? return OWRequestDetails( path: path, @@ -225,13 +225,13 @@ struct OWRequestResponse { var headers: [String?: String?] var body: String var ok: Bool - var status: Int32 + var status: Int64 - static func fromList(_ list: [Any?]) -> OWRequestResponse? { + static func fromList(_ list: [Any]) -> OWRequestResponse? { let headers = list[0] as! [String?: String?] let body = list[1] as! String let ok = list[2] as! Bool - let status = list[3] as! Int32 + let status = list[3] as! Int64 return OWRequestResponse( headers: headers, @@ -316,7 +316,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) @@ -366,9 +366,9 @@ class UserClientApiSetup { let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let identityProviderIdArg = args[0] as? String - let scopesArg = args[1] as? [String] + let args = message as! [Any] + let identityProviderIdArg = args[0] as! String? + let scopesArg = args[1] as! [String]? api.registerUser(identityProviderId: identityProviderIdArg, scopes: scopesArg) { result in switch result { case .success(let res): @@ -384,9 +384,9 @@ class UserClientApiSetup { let handleRegisteredUserUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String - let signInTypeArg = args[1] as! Int32 + let signInTypeArg = (args[1] is Int) ? Int64(args[1] as! Int) : args[1] as! Int64 api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { case .success: @@ -417,7 +417,7 @@ class UserClientApiSetup { let deregisterUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.deregisterUser(profileId: profileIdArg) { result in switch result { @@ -434,7 +434,7 @@ class UserClientApiSetup { let getRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -451,7 +451,7 @@ class UserClientApiSetup { let getAllAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAllAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getAllAuthenticators(profileId: profileIdArg) { result in switch result { @@ -483,9 +483,9 @@ class UserClientApiSetup { let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let registeredAuthenticatorIdArg = args[1] as? String + let registeredAuthenticatorIdArg = args[1] as! String? api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in switch result { case .success(let res): @@ -501,7 +501,7 @@ class UserClientApiSetup { let getNotRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getNotRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getNotRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -533,7 +533,7 @@ class UserClientApiSetup { let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { setPreferredAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.setPreferredAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -550,7 +550,7 @@ class UserClientApiSetup { let deregisterAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.deregisterAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -567,7 +567,7 @@ class UserClientApiSetup { let registerAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.registerAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -599,7 +599,7 @@ class UserClientApiSetup { let mobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.mobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) if let api = api { mobileAuthWithOtpChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let dataArg = args[0] as! String api.mobileAuthWithOtp(data: dataArg) { result in switch result { @@ -616,7 +616,7 @@ class UserClientApiSetup { let getAppToWebSingleSignOnChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAppToWebSingleSignOnChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String api.getAppToWebSingleSignOn(url: urlArg) { result in switch result { @@ -678,7 +678,7 @@ class UserClientApiSetup { let validatePinWithPolicyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", binaryMessenger: binaryMessenger, codec: codec) if let api = api { validatePinWithPolicyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.validatePinWithPolicy(pin: pinArg) { result in switch result { @@ -695,8 +695,8 @@ class UserClientApiSetup { let authenticateDeviceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateDevice", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateDeviceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let scopesArg = args[0] as? [String] + let args = message as! [Any] + let scopesArg = args[0] as! [String]? api.authenticateDevice(scopes: scopesArg) { result in switch result { case .success: @@ -712,9 +712,9 @@ class UserClientApiSetup { let authenticateUserImplicitlyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserImplicitlyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let scopesArg = args[1] as? [String] + let scopesArg = args[1] as! [String]? api.authenticateUserImplicitly(profileId: profileIdArg, scopes: scopesArg) { result in switch result { case .success: @@ -731,9 +731,9 @@ class UserClientApiSetup { let submitCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String - let dataArg = args[1] as? String + let dataArg = args[1] as! String? api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in switch result { case .success: @@ -749,7 +749,7 @@ class UserClientApiSetup { let cancelCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { cancelCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String let errorArg = args[1] as! String api.cancelCustomRegistrationAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in @@ -860,7 +860,7 @@ class UserClientApiSetup { let pinAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptAuthenticationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptAuthenticationRequest(pin: pinArg) { result in switch result { @@ -893,7 +893,7 @@ class UserClientApiSetup { let pinAcceptRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptRegistrationRequest(pin: pinArg) { result in switch result { @@ -980,7 +980,7 @@ class ResourceMethodApiSetup { let requestResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.requestResource", binaryMessenger: binaryMessenger, codec: codec) if let api = api { requestResourceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let typeArg = ResourceRequestType(rawValue: args[0] as! Int)! let detailsArg = args[1] as! OWRequestDetails api.requestResource(type: typeArg, details: detailsArg) { result in diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 457c2347..de097301 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -26,11 +26,11 @@ extension OWUserProfile { extension OWCustomInfo { init(_ info: CustomInfo) { - status = Int32(info.status) + status = Int64(info.status) data = info.data } init(_ info: ONGCustomInfo) { - status = Int32(info.status) + status = Int64(info.status) data = info.data } } @@ -41,7 +41,7 @@ extension OWAuthenticator { name = authenticator.name isPreferred = authenticator.isPreferred isRegistered = authenticator.isRegistered - authenticatorType = Int32(authenticator.type.rawValue) + authenticatorType = Int64(authenticator.type.rawValue) } } @@ -56,7 +56,7 @@ extension OWRequestResponse { init(_ response: ONGResourceResponse) { headers = toOWRequestHeaders(response.allHeaderFields) body = String(data: response.data ?? Data(), encoding: .utf8) ?? "" - status = Int32(response.statusCode) + status = Int64(response.statusCode) ok = response.statusCode <= 299 && response.statusCode >= 200 } } @@ -71,12 +71,12 @@ func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> [String: String] { func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } - return OWCustomInfo(status: Int32(info.status), data: info.data) + return OWCustomInfo(status: Int64(info.status), data: info.data) } func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { guard let info = info else { return nil } - return OWCustomInfo(status: Int32(info.status), data: info.data) + return OWCustomInfo(status: Int64(info.status), data: info.data) } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { @@ -164,7 +164,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } } - func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) { + func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) { completion(OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url, webSignInType: Int(signInType)).mapError({$0})) } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ccf76534..8490df4b 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import diff --git a/pubspec.yaml b/pubspec.yaml index 6d25e603..d953057c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,13 +12,9 @@ dependencies: sdk: flutter dev_dependencies: - pigeon: - git: - url: git@github.com:flutter/packages.git - path: packages/pigeon - ref: 43bfaaf55c0bd6b550bf2cb9af940a00b046bd07 flutter_test: sdk: flutter + pigeon: 9.1.1 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec From 6e53bf238391bd251a37487b534a317e411b61fc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 22 Mar 2023 14:22:50 +0100 Subject: [PATCH 166/364] FP-75: Use extension function to map customInfo -> OWCustomInfo --- .../onegini/mobile/sdk/flutter/PigeonInterface.kt | 5 +++++ .../providers/CustomRegistrationActionImpl.kt | 6 ++---- .../CustomTwoStepRegistrationActionImpl.kt | 14 ++++---------- .../flutter/useCases/AuthenticateUserUseCase.kt | 4 ++-- .../sdk/flutter/useCases/RegistrationUseCase.kt | 4 ++-- 5 files changed, 15 insertions(+), 18 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 18d678aa..91dc20a4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -5,6 +5,7 @@ import android.util.Patterns import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn +import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler @@ -14,6 +15,7 @@ import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails @@ -286,3 +288,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { resourceRequestUseCase(type, details, callback) } } +fun CustomInfo.mapToOwCustomInfo(): OWCustomInfo { + return OWCustomInfo(this.status.toLong(), this.data) +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 51d22374..45aaf02e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -5,6 +5,7 @@ import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomReg import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo @@ -13,10 +14,7 @@ class CustomRegistrationActionImpl(private val providerId: String, private val n override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - val customInfoResponse = info?.let { - OWCustomInfo(info.status.toLong(), info.data) - } - nativeApi.n2fEventFinishCustomRegistration(customInfoResponse, providerId) {} + nativeApi.n2fEventFinishCustomRegistration(info?.mapToOwCustomInfo(), providerId) {} } override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 13197901..0310ac53 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -6,28 +6,22 @@ import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomReg import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import javax.inject.Inject -class CustomTwoStepRegistrationActionImpl constructor(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { +class CustomTwoStepRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null override fun initRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - val customInfoResponse = info?.let { - OWCustomInfo(info.status.toLong(), info.data) - } - nativeApi.n2fEventInitCustomRegistration(customInfoResponse, providerId) {} + nativeApi.n2fEventInitCustomRegistration(info?.mapToOwCustomInfo(), providerId) {} } override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback - - val customInfoResponse = info?.let { - OWCustomInfo(info.status.toLong(), info.data) - } - nativeApi.n2fEventFinishCustomRegistration(customInfoResponse, providerId) {} + nativeApi.n2fEventFinishCustomRegistration(info?.mapToOwCustomInfo(), providerId) {} } override fun getCustomRegistrationAction(): OneginiCustomRegistrationAction { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index ffcc703d..790eaee2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -8,6 +8,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile @@ -55,8 +56,7 @@ class AuthenticateUserUseCase @Inject constructor( when (customInfo) { null -> callback(Result.success(OWRegistrationResponse(owProfile))) else -> { - val owCustomInfo = OWCustomInfo(customInfo.status.toLong(), customInfo.data) - callback(Result.success(OWRegistrationResponse(owProfile, owCustomInfo))) + callback(Result.success(OWRegistrationResponse(owProfile, customInfo?.mapToOwCustomInfo()))) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index 485fefe1..4004ff85 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -8,6 +8,7 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile @@ -37,8 +38,7 @@ class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK when (customInfo) { null -> callback(Result.success(OWRegistrationResponse(user))) else -> { - val info = OWCustomInfo(customInfo.status.toLong(), customInfo.data) - callback(Result.success(OWRegistrationResponse(user, info))) + callback(Result.success(OWRegistrationResponse(user, customInfo.mapToOwCustomInfo()))) } } } From 2ab3f6550a5ce7d9d3300a84352b7d0110f41a59 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 22 Mar 2023 14:24:50 +0100 Subject: [PATCH 167/364] FP-75: Rename fpError -> deprecatedError This error is deprecatated and is only existent for compatibility reasons, it will be removed in the near future. --- lib/onegini_event_listener.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index d8d15301..b575752b 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,6 +1,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/model/onegini_error.dart' as fpError; +import 'package:onegini/model/onegini_error.dart' as deprecatedError; import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; import 'model/authentication_attempt.dart'; @@ -68,7 +68,8 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { void eventError(BuildContext? buildContext, PlatformException error); /// Called whenever error occured. - void showError(BuildContext? buildContext, fpError.OneginiError? error); + void showError( + BuildContext? buildContext, deprecatedError.OneginiError? error); /// Called when custom event was received. void eventOther(BuildContext? buildContext, Event event); @@ -165,7 +166,6 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { @override void n2fShowError(OWOneginiError error) { - // FIXME: use correct error code here. showError(_context, OneginiError(code: error.code, message: error.message)); } } From 0e663e09baf47bb5367fb63940b82ab705c0748c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 22 Mar 2023 14:51:21 +0100 Subject: [PATCH 168/364] FP-75: Small non-functional changes --- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 2 +- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 48315021..930103c0 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -25,7 +25,7 @@ class LoginHandler: NSObject { func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { pinChallenge = challenge - guard let error = challenge.error , error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue else { + guard challenge.error?.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue else { SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} return } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 4fdcb830..afc195f2 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -202,7 +202,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { func userClient(_: ONGUserClient, didReceiveCustomRegistrationInitChallenge challenge: ONGCustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationInitChallenge ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge - SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} + SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } func userClient(_: ONGUserClient, didReceiveCustomRegistrationFinish challenge: ONGCustomRegistrationChallenge) { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3b40b9ac..4eb9c33d 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -280,7 +280,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc registrar.addMethodCallDelegate(instance, channel: channel) // Init Pigeon communication let messenger: FlutterBinaryMessenger = registrar.messenger() - let api = SwiftOneginiPlugin.init() + let api = SwiftOneginiPlugin() UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: api) flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) From fd1709e6673d2a87050b1fb463214e635ae0e1e9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 22 Mar 2023 15:25:33 +0100 Subject: [PATCH 169/364] fp-69 removed unused code --- example/ios/Podfile.lock | 2 +- .../Handlers/AuthenticatorsHandler.swift | 18 +----------------- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 531de25e..d0defe9b 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 + url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index bbaade76..dee3ae7d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -6,7 +6,6 @@ protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool var notificationReceiver: AuthenticatorsNotificationReceiverProtocol? { get } } @@ -45,17 +44,7 @@ class AuthenticatorsHandler: NSObject { customAuthChallenge.sender.cancel(customAuthChallenge, underlyingError: nil) } } - - fileprivate func sortAuthenticatorsList(_ authenticators: Array) -> Array { - return authenticators.sorted { - if $0.type.rawValue == $1.type.rawValue { - return $0.name < $1.name - } else { - return $0.type.rawValue < $1.type.rawValue - } - } - } - + private func sendConnectorNotification(_ event: MobileAuthNotification, _ requestMessage: String?, _ error: SdkError?) { notificationReceiver?.sendNotification(event: event, requestMessage: requestMessage, error: error) @@ -111,11 +100,6 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.success) } - func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array { - let authenticatros = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile) - return sortAuthenticatorsList(Array(authenticatros)) - } - func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool { return ONGUserClient.sharedInstance().registeredAuthenticators(forUser: userProfile).first(where: {$0.type.rawValue == authenticatorType.rawValue }) != nil; } From c5721f6d7f72fa0b61f3d93a788be55ff890397c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 09:36:23 +0100 Subject: [PATCH 170/364] FP-62: Android: Use pigeon for sso usecase --- .../mobile/sdk/flutter/PigeonInterface.kt | 26 +++------------ .../GetAppToWebSingleSignOnUseCase.kt | 32 +++++++++---------- 2 files changed, 19 insertions(+), 39 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index be9bd374..a7312af1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -31,6 +31,7 @@ import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestD import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase @@ -71,6 +72,8 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase @Inject + lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase + @Inject lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase @Inject lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase @@ -184,28 +187,7 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun getAppToWebSingleSignOn(url: String, callback: (Result) -> Unit) { - // TODO NEEDS OWN USE CASE; https://onewelcome.atlassian.net/browse/FP-62 - if (!Patterns.WEB_URL.matcher(url).matches()) { - callback(Result.failure(SdkError(OneWelcomeWrapperErrors.MALFORMED_URL).pigeonError())) - return - } - val targetUri: Uri = Uri.parse(url) - - oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( - targetUri, - object : OneginiAppToWebSingleSignOnHandler { - override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { - callback(Result.success(OWAppToWebSingleSignOn(oneginiAppToWebSingleSignOn.token, oneginiAppToWebSingleSignOn.redirectUrl.toString()))) - } - - override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { - callback(Result.failure(SdkError( - code = oneginiSingleSignOnError.errorType, - message = oneginiSingleSignOnError.message - ).pigeonError())) - } - } - ) + getAppToWebSingleSignOnUseCase(url, callback) } override fun getAccessToken(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt index 33586491..49cfbcce 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt @@ -1,44 +1,42 @@ package com.onegini.mobile.sdk.flutter.useCases -import android.util.Patterns -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.MALFORMED_URL -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.URL_CANT_BE_NULL import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.facade.UriFacade import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import javax.inject.Inject import javax.inject.Singleton @Singleton class GetAppToWebSingleSignOnUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val uriFacade: UriFacade) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val url = call.argument("url") ?: return SdkError(URL_CANT_BE_NULL).flutterError(result) + operator fun invoke(url: String, callback: (Result) -> Unit) { val targetUri = uriFacade.parse(url) oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( targetUri, object : OneginiAppToWebSingleSignOnHandler { override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { - result.success( - Gson().toJson( - mapOf( - "token" to oneginiAppToWebSingleSignOn.token, - "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString() + callback( + Result.success( + OWAppToWebSingleSignOn( + oneginiAppToWebSingleSignOn.token, + oneginiAppToWebSingleSignOn.redirectUrl.toString() ) ) ) } override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { - SdkError( - code = oneginiSingleSignOnError.errorType, - message = oneginiSingleSignOnError.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = oneginiSingleSignOnError.errorType, + message = oneginiSingleSignOnError.message + ).pigeonError() + ) + ) } } ) From 86f0f98973da8cabcceb2712f45192bbc3432039 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 15:20:37 +0100 Subject: [PATCH 171/364] Update generated code --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 68 +++------- ios/Classes/Pigeon.swift | 118 +++++++++--------- lib/pigeon.dart | 2 +- 3 files changed, 79 insertions(+), 109 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index c275e6db..ac850844 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin @@ -31,6 +31,12 @@ private fun wrapError(exception: Throwable): List { } } +/** + * Error class for passing custom error details to Flutter via a thrown PlatformException. + * @property code The error code. + * @property message The error message. + * @property details The error details. Must be a datatype supported by the api codec. + */ class FlutterError ( val code: String, override val message: String? = null, @@ -96,7 +102,7 @@ data class OWCustomInfo ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWCustomInfo { val status = list[0].let { if (it is Int) it.toLong() else it as Long } - val data = list[1] as? String + val data = list[1] as String? return OWCustomInfo(status, data) } } @@ -193,7 +199,7 @@ data class OWRegistrationResponse ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWRegistrationResponse { val userProfile = OWUserProfile.fromList(list[0] as List) - val customInfo: OWCustomInfo? = (list[1] as? List)?.let { + val customInfo: OWCustomInfo? = (list[1] as List?)?.let { OWCustomInfo.fromList(it) } return OWRegistrationResponse(userProfile, customInfo) @@ -201,7 +207,7 @@ data class OWRegistrationResponse ( } fun toList(): List { return listOf( - userProfile?.toList(), + userProfile.toList(), customInfo?.toList(), ) } @@ -220,15 +226,15 @@ data class OWRequestDetails ( fun fromList(list: List): OWRequestDetails { val path = list[0] as String val method = HttpRequestMethod.ofRaw(list[1] as Int)!! - val headers = list[2] as? Map - val body = list[3] as? String + val headers = list[2] as Map? + val body = list[3] as String? return OWRequestDetails(path, method, headers, body) } } fun toList(): List { return listOf( path, - method?.raw, + method.raw, headers, body, ) @@ -438,10 +444,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val identityProviderIdArg = args[0] as? String - val scopesArg = args[1] as? List + val identityProviderIdArg = args[0] as String? + val scopesArg = args[1] as List? api.registerUser(identityProviderIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -460,7 +465,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } @@ -481,7 +485,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getIdentityProviders", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getIdentityProviders() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -500,7 +503,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.deregisterUser(profileIdArg) { result: Result -> @@ -520,7 +522,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -541,7 +542,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getAllAuthenticators(profileIdArg) { result: Result> -> @@ -562,7 +562,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAuthenticatedUserProfile() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -581,10 +580,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val registeredAuthenticatorIdArg = args[1] as? String + val registeredAuthenticatorIdArg = args[1] as String? api.authenticateUser(profileIdArg, registeredAuthenticatorIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -603,7 +601,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getNotRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -624,7 +621,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.changePin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -642,7 +638,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.setPreferredAuthenticator(authenticatorIdArg) { result: Result -> @@ -662,7 +657,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.deregisterAuthenticator(authenticatorIdArg) { result: Result -> @@ -682,7 +676,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.registerAuthenticator(authenticatorIdArg) { result: Result -> @@ -702,7 +695,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.logout", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.logout() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -720,7 +712,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.enrollMobileAuthentication() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -738,7 +729,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val dataArg = args[0] as String api.handleMobileAuthWithOtp(dataArg) { result: Result -> @@ -758,7 +748,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String api.getAppToWebSingleSignOn(urlArg) { result: Result -> @@ -779,7 +768,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAccessToken", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAccessToken() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -798,7 +786,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRedirectUrl", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getRedirectUrl() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -817,7 +804,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getUserProfiles", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getUserProfiles() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -836,7 +822,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.validatePinWithPolicy(pinArg) { result: Result -> @@ -856,9 +841,8 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateDevice", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val scopesArg = args[0] as? List + val scopesArg = args[0] as List? api.authenticateDevice(scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -876,10 +860,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val scopesArg = args[1] as? List + val scopesArg = args[1] as List? api.authenticateUserImplicitly(profileIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -897,10 +880,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String - val dataArg = args[1] as? String + val dataArg = args[1] as String? api.submitCustomRegistrationAction(identityProviderIdArg, dataArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -918,7 +900,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String val errorArg = args[1] as String @@ -939,7 +920,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintFallbackToPin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -957,7 +937,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -975,7 +954,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -993,7 +971,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1011,7 +988,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1029,7 +1005,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1047,7 +1022,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptAuthenticationRequest(pinArg) { result: Result -> @@ -1067,7 +1041,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyRegistrationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1085,7 +1058,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptRegistrationRequest(pinArg) { result: Result -> @@ -1105,7 +1077,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.cancelBrowserRegistration() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1170,7 +1141,6 @@ interface ResourceMethodApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.requestResource", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val typeArg = ResourceRequestType.ofRaw(args[0] as Int)!! val detailsArg = args[1] as OWRequestDetails diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index ed09e387..72fa631e 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -51,7 +51,7 @@ enum ResourceRequestType: Int { struct OWUserProfile { var profileId: String - static func fromList(_ list: [Any?]) -> OWUserProfile? { + static func fromList(_ list: [Any]) -> OWUserProfile? { let profileId = list[0] as! String return OWUserProfile( @@ -67,12 +67,12 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { - var status: Int32 + var status: Int64 var data: String? = nil - static func fromList(_ list: [Any?]) -> OWCustomInfo? { - let status = list[0] as! Int32 - let data = list[1] as? String + static func fromList(_ list: [Any]) -> OWCustomInfo? { + let status = list[0] as! Int64 + let data = list[1] as! String? return OWCustomInfo( status: status, @@ -92,7 +92,7 @@ struct OWIdentityProvider { var id: String var name: String - static func fromList(_ list: [Any?]) -> OWIdentityProvider? { + static func fromList(_ list: [Any]) -> OWIdentityProvider? { let id = list[0] as! String let name = list[1] as! String @@ -115,14 +115,14 @@ struct OWAuthenticator { var name: String var isRegistered: Bool var isPreferred: Bool - var authenticatorType: Int32 + var authenticatorType: Int64 - static func fromList(_ list: [Any?]) -> OWAuthenticator? { + static func fromList(_ list: [Any]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String let isRegistered = list[2] as! Bool let isPreferred = list[3] as! Bool - let authenticatorType = list[4] as! Int32 + let authenticatorType = list[4] as! Int64 return OWAuthenticator( id: id, @@ -148,7 +148,7 @@ struct OWAppToWebSingleSignOn { var token: String var redirectUrl: String - static func fromList(_ list: [Any?]) -> OWAppToWebSingleSignOn? { + static func fromList(_ list: [Any]) -> OWAppToWebSingleSignOn? { let token = list[0] as! String let redirectUrl = list[1] as! String @@ -170,11 +170,11 @@ struct OWRegistrationResponse { var userProfile: OWUserProfile var customInfo: OWCustomInfo? = nil - static func fromList(_ list: [Any?]) -> OWRegistrationResponse? { - let userProfile = OWUserProfile.fromList(list[0] as! [Any?])! + static func fromList(_ list: [Any]) -> OWRegistrationResponse? { + let userProfile = OWUserProfile.fromList(list[0] as! [Any])! var customInfo: OWCustomInfo? = nil - if let customInfoList = list[1] as? [Any?] { - customInfo = OWCustomInfo.fromList(customInfoList) + if let customInfoList = list[1] as! [Any]? { + customInfo = OWCustomInfo.fromList(customInfoList as [Any]) } return OWRegistrationResponse( @@ -197,11 +197,11 @@ struct OWRequestDetails { var headers: [String?: String?]? = nil var body: String? = nil - static func fromList(_ list: [Any?]) -> OWRequestDetails? { + static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String let method = HttpRequestMethod(rawValue: list[1] as! Int)! - let headers = list[2] as? [String?: String?] - let body = list[3] as? String + let headers = list[2] as! [String?: String?]? + let body = list[3] as! String? return OWRequestDetails( path: path, @@ -225,13 +225,13 @@ struct OWRequestResponse { var headers: [String?: String?] var body: String var ok: Bool - var status: Int32 + var status: Int64 - static func fromList(_ list: [Any?]) -> OWRequestResponse? { + static func fromList(_ list: [Any]) -> OWRequestResponse? { let headers = list[0] as! [String?: String?] let body = list[1] as! String let ok = list[2] as! Bool - let status = list[3] as! Int32 + let status = list[3] as! Int64 return OWRequestResponse( headers: headers, @@ -252,14 +252,14 @@ struct OWRequestResponse { /// Generated class from Pigeon that represents data sent in messages. struct OWAuthenticationAttempt { - var failedAttempts: Int32 - var maxAttempts: Int32 - var remainingAttempts: Int32 + var failedAttempts: Int64 + var maxAttempts: Int64 + var remainingAttempts: Int64 - static func fromList(_ list: [Any?]) -> OWAuthenticationAttempt? { - let failedAttempts = list[0] as! Int32 - let maxAttempts = list[1] as! Int32 - let remainingAttempts = list[2] as! Int32 + static func fromList(_ list: [Any]) -> OWAuthenticationAttempt? { + let failedAttempts = list[0] as! Int64 + let maxAttempts = list[1] as! Int64 + let remainingAttempts = list[2] as! Int64 return OWAuthenticationAttempt( failedAttempts: failedAttempts, @@ -278,11 +278,11 @@ struct OWAuthenticationAttempt { /// Generated class from Pigeon that represents data sent in messages. struct OWOneginiError { - var code: Int32 + var code: Int64 var message: String - static func fromList(_ list: [Any?]) -> OWOneginiError? { - let code = list[0] as! Int32 + static func fromList(_ list: [Any]) -> OWOneginiError? { + let code = list[0] as! Int64 let message = list[1] as! String return OWOneginiError( @@ -364,7 +364,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) @@ -415,9 +415,9 @@ class UserClientApiSetup { let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let identityProviderIdArg = args[0] as? String - let scopesArg = args[1] as? [String] + let args = message as! [Any] + let identityProviderIdArg = args[0] as! String? + let scopesArg = args[1] as! [String]? api.registerUser(identityProviderId: identityProviderIdArg, scopes: scopesArg) { result in switch result { case .success(let res): @@ -433,9 +433,9 @@ class UserClientApiSetup { let handleRegisteredUserUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String - let signInTypeArg = args[1] as! Int32 + let signInTypeArg = (args[1] is Int) ? Int64(args[1] as! Int) : args[1] as! Int64 api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { case .success: @@ -466,7 +466,7 @@ class UserClientApiSetup { let deregisterUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.deregisterUser(profileId: profileIdArg) { result in switch result { @@ -483,7 +483,7 @@ class UserClientApiSetup { let getRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -500,7 +500,7 @@ class UserClientApiSetup { let getAllAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAllAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getAllAuthenticators(profileId: profileIdArg) { result in switch result { @@ -532,9 +532,9 @@ class UserClientApiSetup { let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let registeredAuthenticatorIdArg = args[1] as? String + let registeredAuthenticatorIdArg = args[1] as! String? api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in switch result { case .success(let res): @@ -550,7 +550,7 @@ class UserClientApiSetup { let getNotRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getNotRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getNotRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -582,7 +582,7 @@ class UserClientApiSetup { let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { setPreferredAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.setPreferredAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -599,7 +599,7 @@ class UserClientApiSetup { let deregisterAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.deregisterAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -616,7 +616,7 @@ class UserClientApiSetup { let registerAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.registerAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -663,7 +663,7 @@ class UserClientApiSetup { let handleMobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) if let api = api { handleMobileAuthWithOtpChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let dataArg = args[0] as! String api.handleMobileAuthWithOtp(data: dataArg) { result in switch result { @@ -680,7 +680,7 @@ class UserClientApiSetup { let getAppToWebSingleSignOnChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAppToWebSingleSignOnChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String api.getAppToWebSingleSignOn(url: urlArg) { result in switch result { @@ -742,7 +742,7 @@ class UserClientApiSetup { let validatePinWithPolicyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", binaryMessenger: binaryMessenger, codec: codec) if let api = api { validatePinWithPolicyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.validatePinWithPolicy(pin: pinArg) { result in switch result { @@ -759,8 +759,8 @@ class UserClientApiSetup { let authenticateDeviceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateDevice", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateDeviceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let scopesArg = args[0] as? [String] + let args = message as! [Any] + let scopesArg = args[0] as! [String]? api.authenticateDevice(scopes: scopesArg) { result in switch result { case .success: @@ -776,9 +776,9 @@ class UserClientApiSetup { let authenticateUserImplicitlyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserImplicitlyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let scopesArg = args[1] as? [String] + let scopesArg = args[1] as! [String]? api.authenticateUserImplicitly(profileId: profileIdArg, scopes: scopesArg) { result in switch result { case .success: @@ -795,9 +795,9 @@ class UserClientApiSetup { let submitCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String - let dataArg = args[1] as? String + let dataArg = args[1] as! String? api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in switch result { case .success: @@ -813,7 +813,7 @@ class UserClientApiSetup { let cancelCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { cancelCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String let errorArg = args[1] as! String api.cancelCustomRegistrationAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in @@ -924,7 +924,7 @@ class UserClientApiSetup { let pinAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptAuthenticationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptAuthenticationRequest(pin: pinArg) { result in switch result { @@ -957,7 +957,7 @@ class UserClientApiSetup { let pinAcceptRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptRegistrationRequest(pin: pinArg) { result in switch result { @@ -1044,7 +1044,7 @@ class ResourceMethodApiSetup { let requestResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.requestResource", binaryMessenger: binaryMessenger, codec: codec) if let api = api { requestResourceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let typeArg = ResourceRequestType(rawValue: args[0] as! Int)! let detailsArg = args[1] as! OWRequestDetails api.requestResource(type: typeArg, details: detailsArg) { result in diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dea384c5..40d69d1d 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import From 3dddec1c5afcb548fb81f2dc1f083e6a67c134b2 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 15:25:43 +0100 Subject: [PATCH 172/364] Update Int32() to Int64() --- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 6 +++--- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 930103c0..0dc23509 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -30,9 +30,9 @@ class LoginHandler: NSObject { return } let authAttempt = OWAuthenticationAttempt( - failedAttempts: Int32(challenge.previousFailureCount), - maxAttempts: Int32(challenge.maxFailureCount), - remainingAttempts: Int32(challenge.remainingFailureCount)) + failedAttempts: Int64(challenge.previousFailureCount), + maxAttempts: Int64(challenge.maxFailureCount), + remainingAttempts: Int64(challenge.remainingFailureCount)) SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index afc195f2..3e258a2a 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -107,7 +107,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. FP-34 - SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int32(pinError.code), message: pinError.errorDescription)) {} + SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} From 881e65d97fce0e246264b2cab01151db29693e30 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 15:47:18 +0100 Subject: [PATCH 173/364] Fix a bug where pin auth events would not get sent correctly --- .../NativeBridge/Handlers/LoginHandler.swift | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 0dc23509..054145e1 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -23,17 +23,25 @@ class LoginHandler: NSObject { completion(.success) } + private func mapErrorFromPinChallenge(_ challenge: ONGPinChallenge) -> Error? { + if let error = challenge.error, error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue { + return error + } else { + return nil + } + } + func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { pinChallenge = challenge - guard challenge.error?.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue else { - SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} + guard mapErrorFromPinChallenge(challenge) == nil else { + let authAttempt = OWAuthenticationAttempt( + failedAttempts: Int64(challenge.previousFailureCount), + maxAttempts: Int64(challenge.maxFailureCount), + remainingAttempts: Int64(challenge.remainingFailureCount)) + SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} return } - let authAttempt = OWAuthenticationAttempt( - failedAttempts: Int64(challenge.previousFailureCount), - maxAttempts: Int64(challenge.maxFailureCount), - remainingAttempts: Int64(challenge.remainingFailureCount)) - SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} + SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} } func handleDidAuthenticateUser() { From afef7e39a67d95c003cc33c59bdd0ce6963a71f3 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 15:50:38 +0100 Subject: [PATCH 174/364] FP-34: Remove dart and pigeon apis for old error events + add invalidpin --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 12 ++----- example/lib/onegini_listener.dart | 11 +++---- ios/Classes/Pigeon.swift | 12 ++----- lib/onegini_event_listener.dart | 16 +++------ lib/pigeon.dart | 33 +++---------------- pigeons/onewelcome_pigeon_interface.dart | 6 +--- 6 files changed, 19 insertions(+), 71 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index ac850844..cdb1c643 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1320,16 +1320,8 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - /** Called when error event was received. */ - fun n2fEventError(errorArg: OWOneginiError, callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError", codec) - channel.send(listOf(errorArg)) { - callback() - } - } - /** Called whenever error occured. */ - fun n2fShowError(errorArg: OWOneginiError, callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError", codec) + fun n2fEventPinNotAllowed(errorArg: OWOneginiError, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed", codec) channel.send(listOf(errorArg)) { callback() } diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart index 08c9cdc3..e28f2d6d 100644 --- a/example/lib/onegini_listener.dart +++ b/example/lib/onegini_listener.dart @@ -47,12 +47,6 @@ class OneginiListener extends OneginiEventListener { showFlutterToast("${error.message} Code: ${error.code} "); } - @override - void showError(BuildContext buildContext, OneginiError error) { - showFlutterToast( - "${error.message} Code: ${error.code} " ?? "Something went wrong"); - } - @override void openPinScreenAuth(BuildContext buildContext) { Navigator.push( @@ -182,4 +176,9 @@ class OneginiListener extends OneginiEventListener { await Onegini.instance.userClient.handleRegisteredUserUrl(buildContext, url, signInType: WebSignInType.insideApp); } + + @override + void eventPinNotAllowed(OWOneginiError error) { + showFlutterToast("${error.message} Code: ${error.code}"); + } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 72fa631e..4439a577 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1223,16 +1223,8 @@ class NativeCallFlutterApi { completion() } } - /// Called when error event was received. - func n2fEventError(error errorArg: OWOneginiError, completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage([errorArg] as [Any?]) { _ in - completion() - } - } - /// Called whenever error occured. - func n2fShowError(error errorArg: OWOneginiError, completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError", binaryMessenger: binaryMessenger, codec: codec) + func n2fEventPinNotAllowed(error errorArg: OWOneginiError, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([errorArg] as [Any?]) { _ in completion() } diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index b575752b..7f2e9f95 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -67,13 +67,11 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { /// Called when error event was received. void eventError(BuildContext? buildContext, PlatformException error); - /// Called whenever error occured. - void showError( - BuildContext? buildContext, deprecatedError.OneginiError? error); - /// Called when custom event was received. void eventOther(BuildContext? buildContext, Event event); + void eventPinNotAllowed(OWOneginiError error); + @override void n2fCloseAuthOtp() { closeAuthOtp(_context); @@ -159,13 +157,7 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { } @override - void n2fEventError(OWOneginiError error) { - eventError(_context, - PlatformException(code: error.code.toString(), message: error.message)); - } - - @override - void n2fShowError(OWOneginiError error) { - showError(_context, OneginiError(code: error.code, message: error.message)); + void n2fEventPinNotAllowed(OWOneginiError error) { + eventPinNotAllowed(error); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 40d69d1d..39299c50 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1359,11 +1359,7 @@ abstract class NativeCallFlutterApi { /// Called when the FinishCustomRegistration event occurs and a response should be given void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); - /// Called when error event was received. - void n2fEventError(OWOneginiError error); - - /// Called whenever error occured. - void n2fShowError(OWOneginiError error); + void n2fEventPinNotAllowed(OWOneginiError error); static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { @@ -1605,38 +1601,19 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); - } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError was null.'); - final List args = (message as List?)!; - final OWOneginiError? arg_error = (args[0] as OWOneginiError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventError was null, expected non-null OWOneginiError.'); - api.n2fEventError(arg_error!); - return; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed was null.'); final List args = (message as List?)!; final OWOneginiError? arg_error = (args[0] as OWOneginiError?); assert(arg_error != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fShowError was null, expected non-null OWOneginiError.'); - api.n2fShowError(arg_error!); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed was null, expected non-null OWOneginiError.'); + api.n2fEventPinNotAllowed(arg_error!); return; }); } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 83ba0740..4382de22 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -286,9 +286,5 @@ abstract class NativeCallFlutterApi { void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId); - /// Called when error event was received. - void n2fEventError(OWOneginiError error); - - /// Called whenever error occured. - void n2fShowError(OWOneginiError error); + void n2fEventPinNotAllowed(OWOneginiError error); } From 73b820004dc416e1c4bed65a91ae47669b05e9ae Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 15:52:46 +0100 Subject: [PATCH 175/364] FP-34: iOS: Use new invalidPinEvent --- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 3e258a2a..a7ae6208 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -106,8 +106,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func handleDidReceivePinRegistrationChallenge(_ challenge: ONGCreatePinChallenge) { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { - // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. FP-34 - SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} + SwiftOneginiPlugin.flutterApi?.n2fEventPinNotAllowed(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} From ad7c7b581baf21cc61fc11f09dc5a95b398bbc23 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 23 Mar 2023 16:01:19 +0100 Subject: [PATCH 176/364] FP-69 added logic for otp on ios and example app wip --- .../handlers/MobileAuthOtpRequestHandler.kt | 10 +- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 70 +++------- example/lib/screens/user_screen.dart | 16 +-- .../NativeBridge/Errors/ErrorMapper.swift | 3 + .../NativeBridge/Handlers/LoginHandler.swift | 6 +- .../Handlers/MobileAuthHandler.swift | 76 ++++++++--- .../Handlers/RegistrationHandler.swift | 2 +- .../OneginiModuleSwift+OTP.swift | 16 ++- ios/Classes/Pigeon.swift | 120 +++++++++--------- ios/Classes/SwiftOneginiPlugin.swift | 24 ++-- lib/onegini_event_listener.dart | 5 +- lib/pigeon.dart | 8 +- pigeons/onewelcome_pigeon_interface.dart | 2 +- 13 files changed, 181 insertions(+), 177 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index aa5ae7cb..a6aff307 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -1,28 +1,20 @@ package com.onegini.mobile.sdk.flutter.handlers -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithOtpRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.models.OneginiEvent import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @Singleton class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiMobileAuthWithOtpRequestHandler { - private var userProfileId: String? = null - private var message: String? = null override fun startAuthentication( oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback: OneginiAcceptDenyCallback ) { - CALLBACK = oneginiAcceptDenyCallback - userProfileId = oneginiMobileAuthenticationRequest.userProfile.profileId - message = oneginiMobileAuthenticationRequest.message - nativeApi.n2fOpenAuthOtp(message ?: "") {} + nativeApi.n2fOpenAuthOtp(oneginiMobileAuthenticationRequest.message) {} } override fun finishAuthentication() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index c275e6db..4c46333e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin @@ -31,6 +31,12 @@ private fun wrapError(exception: Throwable): List { } } +/** + * Error class for passing custom error details to Flutter via a thrown PlatformException. + * @property code The error code. + * @property message The error message. + * @property details The error details. Must be a datatype supported by the api codec. + */ class FlutterError ( val code: String, override val message: String? = null, @@ -96,7 +102,7 @@ data class OWCustomInfo ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWCustomInfo { val status = list[0].let { if (it is Int) it.toLong() else it as Long } - val data = list[1] as? String + val data = list[1] as String? return OWCustomInfo(status, data) } } @@ -193,7 +199,7 @@ data class OWRegistrationResponse ( @Suppress("UNCHECKED_CAST") fun fromList(list: List): OWRegistrationResponse { val userProfile = OWUserProfile.fromList(list[0] as List) - val customInfo: OWCustomInfo? = (list[1] as? List)?.let { + val customInfo: OWCustomInfo? = (list[1] as List?)?.let { OWCustomInfo.fromList(it) } return OWRegistrationResponse(userProfile, customInfo) @@ -201,7 +207,7 @@ data class OWRegistrationResponse ( } fun toList(): List { return listOf( - userProfile?.toList(), + userProfile.toList(), customInfo?.toList(), ) } @@ -220,15 +226,15 @@ data class OWRequestDetails ( fun fromList(list: List): OWRequestDetails { val path = list[0] as String val method = HttpRequestMethod.ofRaw(list[1] as Int)!! - val headers = list[2] as? Map - val body = list[3] as? String + val headers = list[2] as Map? + val body = list[3] as String? return OWRequestDetails(path, method, headers, body) } } fun toList(): List { return listOf( path, - method?.raw, + method.raw, headers, body, ) @@ -438,10 +444,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val identityProviderIdArg = args[0] as? String - val scopesArg = args[1] as? List + val identityProviderIdArg = args[0] as String? + val scopesArg = args[1] as List? api.registerUser(identityProviderIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -460,7 +465,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String val signInTypeArg = args[1].let { if (it is Int) it.toLong() else it as Long } @@ -481,7 +485,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getIdentityProviders", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getIdentityProviders() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -500,7 +503,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.deregisterUser(profileIdArg) { result: Result -> @@ -520,7 +522,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -541,7 +542,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getAllAuthenticators(profileIdArg) { result: Result> -> @@ -562,7 +562,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAuthenticatedUserProfile() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -581,10 +580,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val registeredAuthenticatorIdArg = args[1] as? String + val registeredAuthenticatorIdArg = args[1] as String? api.authenticateUser(profileIdArg, registeredAuthenticatorIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -603,7 +601,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String api.getNotRegisteredAuthenticators(profileIdArg) { result: Result> -> @@ -624,7 +621,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.changePin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -642,7 +638,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.setPreferredAuthenticator(authenticatorIdArg) { result: Result -> @@ -662,7 +657,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.deregisterAuthenticator(authenticatorIdArg) { result: Result -> @@ -682,7 +676,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val authenticatorIdArg = args[0] as String api.registerAuthenticator(authenticatorIdArg) { result: Result -> @@ -702,7 +695,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.logout", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.logout() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -720,7 +712,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.enrollMobileAuthentication() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -738,7 +729,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val dataArg = args[0] as String api.handleMobileAuthWithOtp(dataArg) { result: Result -> @@ -758,7 +748,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val urlArg = args[0] as String api.getAppToWebSingleSignOn(urlArg) { result: Result -> @@ -779,7 +768,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAccessToken", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getAccessToken() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -798,7 +786,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRedirectUrl", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getRedirectUrl() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -817,7 +804,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getUserProfiles", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.getUserProfiles() { result: Result> -> val error = result.exceptionOrNull() if (error != null) { @@ -836,7 +822,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.validatePinWithPolicy(pinArg) { result: Result -> @@ -856,9 +841,8 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateDevice", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List - val scopesArg = args[0] as? List + val scopesArg = args[0] as List? api.authenticateDevice(scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -876,10 +860,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val profileIdArg = args[0] as String - val scopesArg = args[1] as? List + val scopesArg = args[1] as List? api.authenticateUserImplicitly(profileIdArg, scopesArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -897,10 +880,9 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String - val dataArg = args[1] as? String + val dataArg = args[1] as String? api.submitCustomRegistrationAction(identityProviderIdArg, dataArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -918,7 +900,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val identityProviderIdArg = args[0] as String val errorArg = args[1] as String @@ -939,7 +920,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintFallbackToPin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -957,7 +937,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -975,7 +954,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.fingerprintAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -993,7 +971,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1011,7 +988,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.otpAcceptAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1029,7 +1005,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyAuthenticationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1047,7 +1022,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptAuthenticationRequest(pinArg) { result: Result -> @@ -1067,7 +1041,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.pinDenyRegistrationRequest() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1085,7 +1058,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val pinArg = args[0] as String api.pinAcceptRegistrationRequest(pinArg) { result: Result -> @@ -1105,7 +1077,6 @@ interface UserClientApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", codec) if (api != null) { channel.setMessageHandler { _, reply -> - var wrapped = listOf() api.cancelBrowserRegistration() { result: Result -> val error = result.exceptionOrNull() if (error != null) { @@ -1170,7 +1141,6 @@ interface ResourceMethodApi { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.ResourceMethodApi.requestResource", codec) if (api != null) { channel.setMessageHandler { message, reply -> - var wrapped = listOf() val args = message as List val typeArg = ResourceRequestType.ofRaw(args[0] as Int)!! val detailsArg = args[1] as OWRequestDetails @@ -1253,7 +1223,7 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { } } /** Called to open OTP authentication. */ - fun n2fOpenAuthOtp(messageArg: String, callback: () -> Unit) { + fun n2fOpenAuthOtp(messageArg: String?, callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", codec) channel.send(listOf(messageArg)) { callback() diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 054bd769..e8083b6a 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -300,15 +300,13 @@ class Home extends StatelessWidget { MaterialPageRoute(builder: (_) => QrScanScreen()), ); if (data != null) { - var isSuccess = await Onegini.instance.userClient - .mobileAuthWithOtp(data) - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - if (isSuccess != null && isSuccess.isNotEmpty) - showFlutterToast(isSuccess); + await Onegini.instance.userClient + .handleMobileAuthWithOtp(data) + .catchError((error) { + if (error is PlatformException) { + showFlutterToast(error.message); + } + }).then((value) => showFlutterToast("OTP Authentication is successfull")); } } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 85820201..e47868d9 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -12,6 +12,7 @@ enum OneWelcomeWrapperError: Int { case unauthenticatedImplicitly = 8035 case methodArgumentNotFound = 8036 case authenticationNotInProgress = 8037 + case otpAuthenticationNotInProgress = 8039 // iOS only case providedUrlIncorrect = 8014 @@ -85,6 +86,8 @@ enum OneWelcomeWrapperError: Int { return "Registration is currently not in progress" case .authenticationNotInProgress: return "Authentication is currently not in progress" + case .otpAuthenticationNotInProgress: + return "OTP Authentication is currently not in progress" } } } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 930103c0..0dc23509 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -30,9 +30,9 @@ class LoginHandler: NSObject { return } let authAttempt = OWAuthenticationAttempt( - failedAttempts: Int32(challenge.previousFailureCount), - maxAttempts: Int32(challenge.maxFailureCount), - remainingAttempts: Int32(challenge.remainingFailureCount)) + failedAttempts: Int64(challenge.previousFailureCount), + maxAttempts: Int64(challenge.maxFailureCount), + remainingAttempts: Int64(challenge.remainingFailureCount)) SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} } diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index ebcd5586..e2bd9a7f 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -20,9 +20,10 @@ class MobileAuthHandler: NSObject { var authenticatorType: MobileAuthAuthenticatorType? var confirmation: ((Bool) -> Void)? var mobileAuthCompletion: ((Any?, SdkError?) -> Void)? - + + var mobileAuthCallback: ((Bool) -> Void)? var handleMobileAuthCompletion: ((Result) -> Void)? - + fileprivate func handleConfirmationMobileAuth(_ cancelled: Bool) { guard let confirmation = confirmation else { fatalError() } @@ -33,6 +34,7 @@ class MobileAuthHandler: NSObject { //MARK: - MobileAuthConnectorToHandlerProtocol extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { func handleMobileAuthWithOtp2(otp: String, completion: @escaping (Result) -> Void) { + Logger.log("handleMobileAuthWithOtp", sender: self) handleMobileAuthCompletion = completion guard ONGUserClient.sharedInstance().canHandleOTPMobileAuthRequest(otp) else { @@ -45,6 +47,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { } func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { + Logger.log("enrollMobileAuthentication", sender: self) guard let _ = ONGUserClient.sharedInstance().authenticatedUserProfile() else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return @@ -65,8 +68,31 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { completion(.failure(FlutterError(mappedError))) } } - - + + func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) { + Logger.log("acceptMobileAuthRequest", sender: self) + guard let callback = mobileAuthCallback else { + completion(.failure(FlutterError(SdkError(.otpAuthenticationNotInProgress)))) + return + } + + callback(true) + mobileAuthCallback = nil + completion(.success) + } + + func denyMobileAuthRequest(completion: @escaping (Result) -> Void) { + Logger.log("denyMobileAuthRequest", sender: self) + guard let callback = mobileAuthCallback else { + completion(.failure(FlutterError(SdkError(.otpAuthenticationNotInProgress)))) + return + } + + callback(false) + mobileAuthCallback = nil + completion(.success) + } + // todo delete func enrollForMobileAuth(_ completion: @escaping (Bool?, SdkError?) -> Void) { ONGClient.sharedInstance().userClient.enroll { enrolled, error in @@ -83,13 +109,13 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { } } } - + // todo delete func isUserEnrolledForMobileAuth() -> Bool { let userClient = ONGUserClient.sharedInstance() return isUserEnrolledForMobileAuth(userClient: userClient) } - + // delete func isUserEnrolledForMobileAuth(userClient: ONGUserClient) -> Bool { if let userProfile = userClient.authenticatedUserProfile() { @@ -97,7 +123,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { } return false } - + // delete; replaced for mobileAuthCompletion variable func handleMobileAuthConfirmation(cancelled: Bool) { switch authenticatorType { @@ -114,7 +140,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { break } } - + func handleOTPMobileAuth(_ otp: String , customRegistrationChallenge: ONGCustomRegistrationChallenge?, _ completion: @escaping (Any?, SdkError?) -> Void) { mobileAuthCompletion = completion @@ -125,7 +151,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { challenge.sender.respond(withData: otp, challenge: challenge) } - + func handleQrOTPMobileAuth(_ otp: String , customRegistrationChallenge: ONGCustomRegistrationChallenge?, _ completion: @escaping (Any?, SdkError?) -> Void) { mobileAuthCompletion = completion guard ONGUserClient.sharedInstance().canHandleOTPMobileAuthRequest(otp) else { @@ -139,13 +165,14 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { //MARK: - ONGMobileAuthRequestDelegate extension MobileAuthHandler: ONGMobileAuthRequestDelegate { func userClient(_: ONGUserClient, didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void, for request: ONGMobileAuthRequest) { - authenticatorType = .confirmation - self.confirmation = confirmation +// authenticatorType = .confirmation +// self.confirmation = confirmation // is this step needed??? dont think so? we resolve only after completion -// mobileAuthCompletion?(request.message, nil) - //FIXME: This message can clearly be nullable, we should support this. - SwiftOneginiPlugin.flutterApi?.n2fOpenAuthOtp(message: request.message ?? "") {} + // mobileAuthCompletion?(request.message, nil) + + mobileAuthCallback = confirmation + SwiftOneginiPlugin.flutterApi?.n2fOpenAuthOtp(message: request.message) {} } func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge, for request: ONGMobileAuthRequest) { @@ -163,19 +190,28 @@ extension MobileAuthHandler: ONGMobileAuthRequestDelegate { func userClient(_ userClient: ONGUserClient, didFailToHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, error: Error) { SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} if error.code == ONGGenericError.actionCancelled.rawValue { - mobileAuthCompletion?(false, SdkError(.authenticationCancelled)) + handleMobileAuthCompletion?(.failure(FlutterError(SdkError(.authenticationCancelled)))) + // todo remove +// mobileAuthCompletion?(false, SdkError(.authenticationCancelled)) } else { let mappedError = ErrorMapper().mapError(error) - mobileAuthCompletion?(false, mappedError) + handleMobileAuthCompletion?(.failure(FlutterError(mappedError))) +// mobileAuthCompletion?(false, mappedError) } + + handleMobileAuthCompletion = nil } func userClient(_ userClient: ONGUserClient, didHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, info customAuthenticatorInfo: ONGCustomInfo?) { - + // send event SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} - - // complete after finishing otp - mobileAuthCompletion?(request.message, nil) + + // complete handleOtpRequest + handleMobileAuthCompletion?(.success) + handleMobileAuthCompletion = nil + + // todo delete complete after finishing otp +// mobileAuthCompletion?(request.message, nil) } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index afc195f2..3e258a2a 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -107,7 +107,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { // FIXME: I believe we are dealing here with an invalid pin that was supplied, we should send such an event. FP-34 - SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int32(pinError.code), message: pinError.errorDescription)) {} + SwiftOneginiPlugin.flutterApi?.n2fShowError(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index 56448ec6..a2454d5a 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -3,12 +3,20 @@ import OneginiSDKiOS import Flutter extension OneginiModuleSwift { - public func handleMobileAuthWithOtp2(otp: String, completion: @escaping (Result) -> Void) { + func handleMobileAuthWithOtp2(_ otp: String, completion: @escaping (Result) -> Void) { bridgeConnector.toMobileAuthHandler.handleMobileAuthWithOtp2(otp: otp, completion: completion) } - - public func enrollMobileAuthentication() -> Void) { - bridgeConnector.toMobileAuthHandler.handleMobileAuthWithOtp2(otp: otp, completion: completion) + + func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { + bridgeConnector.toMobileAuthHandler.enrollMobileAuthentication(completion: completion) + } + + func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) { + bridgeConnector.toMobileAuthHandler.handleMobileAuthConfirmation(cancelled: false) + } + + func denyMobileAuthRequest(completion: @escaping (Result) -> Void) { + bridgeConnector.toMobileAuthHandler.handleMobileAuthConfirmation(cancelled: false) } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index ed09e387..fd758623 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -51,7 +51,7 @@ enum ResourceRequestType: Int { struct OWUserProfile { var profileId: String - static func fromList(_ list: [Any?]) -> OWUserProfile? { + static func fromList(_ list: [Any]) -> OWUserProfile? { let profileId = list[0] as! String return OWUserProfile( @@ -67,12 +67,12 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { - var status: Int32 + var status: Int64 var data: String? = nil - static func fromList(_ list: [Any?]) -> OWCustomInfo? { - let status = list[0] as! Int32 - let data = list[1] as? String + static func fromList(_ list: [Any]) -> OWCustomInfo? { + let status = list[0] as! Int64 + let data = list[1] as! String? return OWCustomInfo( status: status, @@ -92,7 +92,7 @@ struct OWIdentityProvider { var id: String var name: String - static func fromList(_ list: [Any?]) -> OWIdentityProvider? { + static func fromList(_ list: [Any]) -> OWIdentityProvider? { let id = list[0] as! String let name = list[1] as! String @@ -115,14 +115,14 @@ struct OWAuthenticator { var name: String var isRegistered: Bool var isPreferred: Bool - var authenticatorType: Int32 + var authenticatorType: Int64 - static func fromList(_ list: [Any?]) -> OWAuthenticator? { + static func fromList(_ list: [Any]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String let isRegistered = list[2] as! Bool let isPreferred = list[3] as! Bool - let authenticatorType = list[4] as! Int32 + let authenticatorType = list[4] as! Int64 return OWAuthenticator( id: id, @@ -148,7 +148,7 @@ struct OWAppToWebSingleSignOn { var token: String var redirectUrl: String - static func fromList(_ list: [Any?]) -> OWAppToWebSingleSignOn? { + static func fromList(_ list: [Any]) -> OWAppToWebSingleSignOn? { let token = list[0] as! String let redirectUrl = list[1] as! String @@ -170,11 +170,11 @@ struct OWRegistrationResponse { var userProfile: OWUserProfile var customInfo: OWCustomInfo? = nil - static func fromList(_ list: [Any?]) -> OWRegistrationResponse? { - let userProfile = OWUserProfile.fromList(list[0] as! [Any?])! + static func fromList(_ list: [Any]) -> OWRegistrationResponse? { + let userProfile = OWUserProfile.fromList(list[0] as! [Any])! var customInfo: OWCustomInfo? = nil - if let customInfoList = list[1] as? [Any?] { - customInfo = OWCustomInfo.fromList(customInfoList) + if let customInfoList = list[1] as! [Any]? { + customInfo = OWCustomInfo.fromList(customInfoList as [Any]) } return OWRegistrationResponse( @@ -197,11 +197,11 @@ struct OWRequestDetails { var headers: [String?: String?]? = nil var body: String? = nil - static func fromList(_ list: [Any?]) -> OWRequestDetails? { + static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String let method = HttpRequestMethod(rawValue: list[1] as! Int)! - let headers = list[2] as? [String?: String?] - let body = list[3] as? String + let headers = list[2] as! [String?: String?]? + let body = list[3] as! String? return OWRequestDetails( path: path, @@ -225,13 +225,13 @@ struct OWRequestResponse { var headers: [String?: String?] var body: String var ok: Bool - var status: Int32 + var status: Int64 - static func fromList(_ list: [Any?]) -> OWRequestResponse? { + static func fromList(_ list: [Any]) -> OWRequestResponse? { let headers = list[0] as! [String?: String?] let body = list[1] as! String let ok = list[2] as! Bool - let status = list[3] as! Int32 + let status = list[3] as! Int64 return OWRequestResponse( headers: headers, @@ -252,14 +252,14 @@ struct OWRequestResponse { /// Generated class from Pigeon that represents data sent in messages. struct OWAuthenticationAttempt { - var failedAttempts: Int32 - var maxAttempts: Int32 - var remainingAttempts: Int32 + var failedAttempts: Int64 + var maxAttempts: Int64 + var remainingAttempts: Int64 - static func fromList(_ list: [Any?]) -> OWAuthenticationAttempt? { - let failedAttempts = list[0] as! Int32 - let maxAttempts = list[1] as! Int32 - let remainingAttempts = list[2] as! Int32 + static func fromList(_ list: [Any]) -> OWAuthenticationAttempt? { + let failedAttempts = list[0] as! Int64 + let maxAttempts = list[1] as! Int64 + let remainingAttempts = list[2] as! Int64 return OWAuthenticationAttempt( failedAttempts: failedAttempts, @@ -278,11 +278,11 @@ struct OWAuthenticationAttempt { /// Generated class from Pigeon that represents data sent in messages. struct OWOneginiError { - var code: Int32 + var code: Int64 var message: String - static func fromList(_ list: [Any?]) -> OWOneginiError? { - let code = list[0] as! Int32 + static func fromList(_ list: [Any]) -> OWOneginiError? { + let code = list[0] as! Int64 let message = list[1] as! String return OWOneginiError( @@ -364,7 +364,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func handleRegisteredUserUrl(url: String, signInType: Int32, completion: @escaping (Result) -> Void) + func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) @@ -415,9 +415,9 @@ class UserClientApiSetup { let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let identityProviderIdArg = args[0] as? String - let scopesArg = args[1] as? [String] + let args = message as! [Any] + let identityProviderIdArg = args[0] as! String? + let scopesArg = args[1] as! [String]? api.registerUser(identityProviderId: identityProviderIdArg, scopes: scopesArg) { result in switch result { case .success(let res): @@ -433,9 +433,9 @@ class UserClientApiSetup { let handleRegisteredUserUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String - let signInTypeArg = args[1] as! Int32 + let signInTypeArg = (args[1] is Int) ? Int64(args[1] as! Int) : args[1] as! Int64 api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { case .success: @@ -466,7 +466,7 @@ class UserClientApiSetup { let deregisterUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.deregisterUser(profileId: profileIdArg) { result in switch result { @@ -483,7 +483,7 @@ class UserClientApiSetup { let getRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -500,7 +500,7 @@ class UserClientApiSetup { let getAllAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAllAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getAllAuthenticators(profileId: profileIdArg) { result in switch result { @@ -532,9 +532,9 @@ class UserClientApiSetup { let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let registeredAuthenticatorIdArg = args[1] as? String + let registeredAuthenticatorIdArg = args[1] as! String? api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in switch result { case .success(let res): @@ -550,7 +550,7 @@ class UserClientApiSetup { let getNotRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getNotRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String api.getNotRegisteredAuthenticators(profileId: profileIdArg) { result in switch result { @@ -582,7 +582,7 @@ class UserClientApiSetup { let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { setPreferredAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.setPreferredAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -599,7 +599,7 @@ class UserClientApiSetup { let deregisterAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.deregisterAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -616,7 +616,7 @@ class UserClientApiSetup { let registerAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let authenticatorIdArg = args[0] as! String api.registerAuthenticator(authenticatorId: authenticatorIdArg) { result in switch result { @@ -663,7 +663,7 @@ class UserClientApiSetup { let handleMobileAuthWithOtpChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.handleMobileAuthWithOtp", binaryMessenger: binaryMessenger, codec: codec) if let api = api { handleMobileAuthWithOtpChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let dataArg = args[0] as! String api.handleMobileAuthWithOtp(data: dataArg) { result in switch result { @@ -680,7 +680,7 @@ class UserClientApiSetup { let getAppToWebSingleSignOnChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAppToWebSingleSignOn", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAppToWebSingleSignOnChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let urlArg = args[0] as! String api.getAppToWebSingleSignOn(url: urlArg) { result in switch result { @@ -742,7 +742,7 @@ class UserClientApiSetup { let validatePinWithPolicyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.validatePinWithPolicy", binaryMessenger: binaryMessenger, codec: codec) if let api = api { validatePinWithPolicyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.validatePinWithPolicy(pin: pinArg) { result in switch result { @@ -759,8 +759,8 @@ class UserClientApiSetup { let authenticateDeviceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateDevice", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateDeviceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] - let scopesArg = args[0] as? [String] + let args = message as! [Any] + let scopesArg = args[0] as! [String]? api.authenticateDevice(scopes: scopesArg) { result in switch result { case .success: @@ -776,9 +776,9 @@ class UserClientApiSetup { let authenticateUserImplicitlyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly", binaryMessenger: binaryMessenger, codec: codec) if let api = api { authenticateUserImplicitlyChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let profileIdArg = args[0] as! String - let scopesArg = args[1] as? [String] + let scopesArg = args[1] as! [String]? api.authenticateUserImplicitly(profileId: profileIdArg, scopes: scopesArg) { result in switch result { case .success: @@ -795,9 +795,9 @@ class UserClientApiSetup { let submitCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String - let dataArg = args[1] as? String + let dataArg = args[1] as! String? api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in switch result { case .success: @@ -813,7 +813,7 @@ class UserClientApiSetup { let cancelCustomRegistrationActionChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction", binaryMessenger: binaryMessenger, codec: codec) if let api = api { cancelCustomRegistrationActionChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let identityProviderIdArg = args[0] as! String let errorArg = args[1] as! String api.cancelCustomRegistrationAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in @@ -924,7 +924,7 @@ class UserClientApiSetup { let pinAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptAuthenticationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptAuthenticationRequest(pin: pinArg) { result in switch result { @@ -957,7 +957,7 @@ class UserClientApiSetup { let pinAcceptRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinAcceptRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinAcceptRegistrationRequestChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let pinArg = args[0] as! String api.pinAcceptRegistrationRequest(pin: pinArg) { result in switch result { @@ -1044,7 +1044,7 @@ class ResourceMethodApiSetup { let requestResourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.ResourceMethodApi.requestResource", binaryMessenger: binaryMessenger, codec: codec) if let api = api { requestResourceChannel.setMessageHandler { message, reply in - let args = message as! [Any?] + let args = message as! [Any] let typeArg = ResourceRequestType(rawValue: args[0] as! Int)! let detailsArg = args[1] as! OWRequestDetails api.requestResource(type: typeArg, details: detailsArg) { result in @@ -1126,7 +1126,7 @@ class NativeCallFlutterApi { } } /// Called to open OTP authentication. - func n2fOpenAuthOtp(message messageArg: String, completion: @escaping () -> Void) { + func n2fOpenAuthOtp(message messageArg: String?, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([messageArg] as [Any?]) { _ in completion() diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index d79127bf..d438a7c6 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -81,15 +81,15 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { - // Will be implemented during the OTP rework in - // https://onewelcome.atlassian.net/browse/FP-69 - completion(.success) + OneginiModuleSwift.sharedInstance.enrollMobileAuthentication() { result in + completion(result.mapError { $0 }) + } } func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - // Will be implemented during the OTP rework in - // https://onewelcome.atlassian.net/browse/FP-69 - completion(.success) + OneginiModuleSwift.sharedInstance.handleMobileAuthWithOtp2(data) { result in + completion(result.mapError { $0 }) + } } func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) { @@ -129,15 +129,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.denyMobileAuthConfirmation() - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in https://onewelcome.atlassian.net/browse/FP-69 - completion(.success) + OneginiModuleSwift.sharedInstance.denyMobileAuthRequest() { result in + completion(result.mapError { $0 }) + } } func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.acceptMobileAuthConfirmation() - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in https://onewelcome.atlassian.net/browse/FP-69 - completion(.success) + OneginiModuleSwift.sharedInstance.acceptMobileAuthRequest() { result in + completion(result.mapError { $0 }) + } } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index b575752b..0c94b9c3 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -2,7 +2,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; import 'package:onegini/model/onegini_error.dart' as deprecatedError; import 'package:onegini/pigeon.dart'; -import 'constants/constants.dart'; import 'model/authentication_attempt.dart'; import 'model/onegini_error.dart'; import 'model/onegini_event.dart'; @@ -124,8 +123,8 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { } @override - void n2fOpenAuthOtp(String message) { - openAuthOtp(_context, message); + void n2fOpenAuthOtp(String? message) { + openAuthOtp(_context, message != null ? message : ""); } @override diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dea384c5..64a2edff 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.0.2), do not edit directly. +// Autogenerated from Pigeon (v9.1.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import @@ -1318,7 +1318,7 @@ abstract class NativeCallFlutterApi { void n2fHandleRegisteredUrl(String url); /// Called to open OTP authentication. - void n2fOpenAuthOtp(String message); + void n2fOpenAuthOtp(String? message); /// Called to close OTP authentication. void n2fCloseAuthOtp(); @@ -1397,9 +1397,7 @@ abstract class NativeCallFlutterApi { 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null, expected non-null String.'); - api.n2fOpenAuthOtp(arg_message!); + api.n2fOpenAuthOtp(arg_message); return; }); } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 83ba0740..f30b73f5 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -242,7 +242,7 @@ abstract class NativeCallFlutterApi { void n2fHandleRegisteredUrl(String url); /// Called to open OTP authentication. - void n2fOpenAuthOtp(String message); + void n2fOpenAuthOtp(String? message); /// Called to close OTP authentication. void n2fCloseAuthOtp(); From 0063f06a7197675a7039972aa6d868eb402e40e5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 16:02:49 +0100 Subject: [PATCH 177/364] FP-34: Android: Remove old error Events and use pinNotAllowedEvent --- .../onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index b4fe113f..85193a1f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -22,7 +22,7 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu } override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { - nativeApi.n2fEventError(OWOneginiError(oneginiPinValidationError.errorType.toLong(), oneginiPinValidationError.message ?: "")) {} + nativeApi.n2fEventPinNotAllowed(OWOneginiError(oneginiPinValidationError.errorType.toLong(), oneginiPinValidationError.message ?: "")) {} } override fun finishPinCreation() { From ba9f9a7ed3c6e641e3969136f89c022eb2368c27 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 23 Mar 2023 17:00:54 +0100 Subject: [PATCH 178/364] FP-34: Rename pinNotAllowed event --- example/lib/onegini_listener.dart | 2 +- lib/callbacks/onegini_pin_registration_callback.dart | 5 ++++- lib/onegini_event_listener.dart | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart index e28f2d6d..7b45c1fa 100644 --- a/example/lib/onegini_listener.dart +++ b/example/lib/onegini_listener.dart @@ -178,7 +178,7 @@ class OneginiListener extends OneginiEventListener { } @override - void eventPinNotAllowed(OWOneginiError error) { + void pinNotAllowed(OWOneginiError error) { showFlutterToast("${error.message} Code: ${error.code}"); } } diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index 9c104f36..a675e170 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -6,13 +6,16 @@ import '../onegini.dart'; /// A callback for pin REGISTRATION. class OneginiPinRegistrationCallback { final api = UserClientApi(); + /// Cancels pin registration request. Future denyAuthenticationRequest() async { await api.pinDenyRegistrationRequest(); } /// Accepts pin registration and sent [pin] to the OneginiSdk. - Future acceptAuthenticationRequest(BuildContext? context, String pin) async { + @Deprecated("message") + Future acceptAuthenticationRequest( + BuildContext? context, String pin) async { Onegini.instance.setEventContext(context); await api.pinAcceptRegistrationRequest(pin); diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 7f2e9f95..2fd79cc1 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -70,7 +70,7 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { /// Called when custom event was received. void eventOther(BuildContext? buildContext, Event event); - void eventPinNotAllowed(OWOneginiError error); + void pinNotAllowed(OWOneginiError error); @override void n2fCloseAuthOtp() { @@ -158,6 +158,6 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { @override void n2fEventPinNotAllowed(OWOneginiError error) { - eventPinNotAllowed(error); + pinNotAllowed(error); } } From f8a839bd381eef52f65c8774818be7e432a84ae4 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 23 Mar 2023 17:04:06 +0100 Subject: [PATCH 179/364] FP-Hotfixtests hot fox for some failing android tests --- .../mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt | 2 ++ .../java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index 20455726..af09ab5e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -30,6 +30,8 @@ class PinRegistrationRequestAcceptUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { + PinRequestHandler.CALLBACK = null + val result = pinRegistrationRequestAcceptUseCase("12345").exceptionOrNull() SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 211be6f9..bdbf1db0 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -122,7 +122,6 @@ class ResourceRequestUseCaseTests { private fun setupErrorFullResponseMock() { whenever(responseMock.code).thenReturn(400) - whenever(responseMock.isSuccessful).thenReturn(false) val headers = Headers.Builder().add("headerKey", "headerValue").build() whenever(responseMock.headers).thenReturn(headers) } From 406c54ad82a271cdf4bbacc0c99e2cd6d0ae5993 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 24 Mar 2023 10:10:45 +0100 Subject: [PATCH 180/364] FP-62: Update tests for SSO --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 - .../GetAppToWebSingleSignOnUseCaseTests.kt | 61 ++++++------------- 2 files changed, 20 insertions(+), 42 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 710d1211..9f1bb7b7 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -20,7 +20,6 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), QR_CODE_HAS_NO_DATA(8006, "QR-code does not have data"), METHOD_TO_CALL_NOT_FOUND(8007, "Method to call not found"), - URL_CANT_BE_NULL(8008, "Url can not be null"), MALFORMED_URL(8009, "Incorrect url format"), PREFERRED_AUTHENTICATOR_ERROR(8010, "Something went wrong when setting the preferred authenticator"), ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt index 0e565fa8..eb69aa84 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt @@ -3,15 +3,20 @@ package com.onegini.mobile.sdk import android.net.Uri import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler +import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.facade.UriFacade +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import junit.framework.TestCase.assertEquals +import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -31,10 +36,8 @@ class GetAppToWebSingleSignOnUseCaseTests { lateinit var oneginiSdk: OneginiSDK @Mock - lateinit var resultMock: MethodChannel.Result + lateinit var callbackMock: (Result) -> Unit - @Mock - lateinit var callMock: MethodCall @Mock private lateinit var uriFacade: UriFacade @@ -60,52 +63,36 @@ class GetAppToWebSingleSignOnUseCaseTests { } @Test - fun `When GetAppToWebSingleSignOn is called without a url argument, Then should fail with URL_CANT_BE_NULL error`() { - whenCalledWithNullUrl() - - getAppToWebSingleSignOnUseCase(callMock, resultMock) - - val message = URL_CANT_BE_NULL.message - verify(resultMock).error(eq(URL_CANT_BE_NULL.code.toString()), eq(message), any()) - } - - @Test - fun `When oginini getAppToWebSingleSignOn calls onSuccess on the handler, Then promise should resolve with a map containing the content from the result`() { - whenCalledWithUrl() + fun `When oginini getAppToWebSingleSignOn calls onSuccess on the handler, Then promise should resolve with a OWAppToWebSingleSignOn with the token and url`() { mockParseUri(correctUri) mockSingleSignOnObject() whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { it.getArgument(1).onSuccess(oneginiAppToWebSingleSignOn) } - getAppToWebSingleSignOnUseCase(callMock, resultMock) - - val argumentCaptor = argumentCaptor() - verify(resultMock).success(argumentCaptor.capture()) - // This will be reworked after FP-20 when we actually send the objects - val expectedResult = Gson().toJson( - mapOf( - "token" to oneginiAppToWebSingleSignOn.token, - "redirectUrl" to oneginiAppToWebSingleSignOn.redirectUrl.toString() - ) - ) - assertEquals(argumentCaptor.firstValue, expectedResult) + getAppToWebSingleSignOnUseCase(correctUri, callbackMock) + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull()?.token, oneginiAppToWebSingleSignOn.token) + Assert.assertEquals(firstValue.getOrNull()?.redirectUrl, oneginiAppToWebSingleSignOn.redirectUrl.toString()) + } } @Test fun `When oginini getAppToWebSingleSignOn calls onError on the handler, Then result should fail with the error message and code`() { mockParseUri(correctUri) - whenCalledWithUrl() whenSSOReturnsError() - getAppToWebSingleSignOnUseCase(callMock, resultMock) - - val message = oneginiAppToWebSingleSignOnError.message - verify(resultMock).error(eq(oneginiAppToWebSingleSignOnError.errorType.toString()), eq(message), any()) - } + getAppToWebSingleSignOnUseCase(correctUri, callbackMock) + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiAppToWebSingleSignOnError.errorType.toString(), oneginiAppToWebSingleSignOnError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } private fun mockSingleSignOnObject() { whenever(oneginiAppToWebSingleSignOn.token).thenReturn(mockedTokenString) @@ -124,12 +111,4 @@ class GetAppToWebSingleSignOnUseCaseTests { whenever(uriFacade.parse(uri)).thenReturn(parsedUri) } - private fun whenCalledWithUrl() { - whenever(callMock.argument("url")).thenReturn(correctUri) - } - - private fun whenCalledWithNullUrl() { - whenever(callMock.argument("url")).thenReturn(null) - } - } \ No newline at end of file From a7484836ab0fa603a3bdd570dfaf0f35b49da53e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 24 Mar 2023 10:14:18 +0100 Subject: [PATCH 181/364] FP-62: Fix newlines --- .../onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt index eb69aa84..55674431 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt @@ -110,5 +110,4 @@ class GetAppToWebSingleSignOnUseCaseTests { private fun mockParseUri(uri: String) { whenever(uriFacade.parse(uri)).thenReturn(parsedUri) } - -} \ No newline at end of file +} From aa4a08b83d02588531c1267b51298816397c9283 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 24 Mar 2023 10:28:44 +0100 Subject: [PATCH 182/364] FP-71: Remove isAuthenticatorRegistered function This api wasn't fully implemented in iOS and is not very useful, so let's just remove it while we still can :^) --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 3 - .../sdk/flutter/OneginiMethodsWrapper.kt | 5 - .../mobile/sdk/flutter/PigeonInterface.kt | 3 - .../mobile/sdk/flutter/constants/Constants.kt | 23 ++-- .../IsAuthenticatorRegisteredUseCase.kt | 40 ------ .../IsAuthenticatorRegisteredUseCaseTests.kt | 110 ---------------- ...ndler_IsAuthenticatorRegisteredTests.swift | 123 ------------------ .../Handlers/AuthenticatorsHandler.swift | 5 - 8 files changed, 9 insertions(+), 303 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt delete mode 100644 example/ios/OneginiTests/Handlers/AuthenticatorsHandler/AuthenticatorsHandler_IsAuthenticatorRegisteredTests.swift diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index bf336c35..513265a6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -25,9 +25,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { - // TODO: Move remaining methods to pigeon; https://onewelcome.atlassian.net/browse/FP-71 - Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) - // OTP Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, client) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 4160ee50..61922a19 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -8,15 +8,10 @@ import javax.inject.Singleton @Singleton class OneginiMethodsWrapper @Inject constructor( - private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, private val startAppUseCase: StartAppUseCase, ) { fun startApp(call: MethodCall, result: MethodChannel.Result) { startAppUseCase(call, result) } - - fun isAuthenticatorRegistered(call: MethodCall, result: MethodChannel.Result) { - isAuthenticatorRegisteredUseCase(call, result) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index d32d8031..4e85693e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -43,7 +43,6 @@ import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCas import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase -import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase @@ -94,8 +93,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase @Inject - lateinit var isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase - @Inject lateinit var logoutUseCase: LogoutUseCase @Inject lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt index 107cd326..df7ef2fd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt @@ -2,9 +2,7 @@ package com.onegini.mobile.sdk.flutter.constants interface Constants { companion object { - /** - * events - */ + /** events */ const val EVENT_ERROR = "eventError" const val EVENT_OPEN_PIN = "eventOpenPin" @@ -26,9 +24,7 @@ interface Constants { const val EVENT_HANDLE_REGISTERED_URL = "eventHandleRegisteredUrl" - /** - * MethodsName - */ + /** MethodsName */ const val METHOD_START_APP = "startApp" const val METHOD_SUBMIT_CUSTOM_REGISTRATION_ACTION = "submitCustomRegistrationAction" @@ -47,7 +43,7 @@ interface Constants { const val METHOD_GET_IMPLICIT_RESOURCE = "getImplicitResource" const val METHOD_GET_UNAUTHENTICATED_RESOURCE = "getUnauthenticatedResource" - //Registration + // Registration const val METHOD_REGISTER_USER = "registerUser" const val METHOD_HANDLE_REGISTERED_URL = "handleRegisteredUserUrl" const val METHOD_CANCEL_BROWSER_REGISTRATION = "cancelBrowserRegistration" @@ -56,7 +52,7 @@ interface Constants { const val METHOD_GET_IDENTITY_PROVIDERS = "getIdentityProviders" const val METHOD_DEREGISTER_USER = "deregisterUser" - // Authentication + // Authentication const val METHOD_ACCEPT_PIN_AUTHENTICATION_REQUEST = "acceptPinAuthenticationRequest" const val METHOD_DENY_PIN_AUTHENTICATION_REQUEST = "denyPinAuthenticationRequest" const val METHOD_GET_REGISTERED_AUTHENTICATORS = "getRegisteredAuthenticators" @@ -66,12 +62,13 @@ interface Constants { const val METHOD_REGISTER_AUTHENTICATOR = "registerAuthenticator" const val METHOD_DEREGISTER_AUTHENTICATOR = "deregisterAuthenticator" const val METHOD_AUTHENTICATE_USER = "authenticateUser" - const val METHOD_IS_AUTHENTICATOR_REGISTERED = "isAuthenticatorRegistered" const val METHOD_LOGOUT = "logout" // Fingerprint - const val METHOD_ACCEPT_FINGERPRINT_AUTHENTICATION_REQUEST = "acceptFingerprintAuthenticationRequest" - const val METHOD_DENY_FINGERPRINT_AUTHENTICATION_REQUEST = "denyFingerprintAuthenticationRequest" + const val METHOD_ACCEPT_FINGERPRINT_AUTHENTICATION_REQUEST = + "acceptFingerprintAuthenticationRequest" + const val METHOD_DENY_FINGERPRINT_AUTHENTICATION_REQUEST = + "denyFingerprintAuthenticationRequest" const val METHOD_FINGERPRINT_FALL_BACK_TO_PIN = "fingerprintFallbackToPin" // Otp @@ -83,9 +80,7 @@ interface Constants { const val METHOD_GET_ACCESS_TOKEN = "getAccessToken" const val METHOD_GET_AUTHENTICATED_USER_PROFILE = "getAuthenticatedUserProfile" - /** - * HTTP Response properties - */ + /** HTTP Response properties */ const val RESPONSE_STATUS_CODE = "statusCode" const val RESPONSE_HEADERS = "headers" const val RESPONSE_BODY = "body" diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt deleted file mode 100644 index 7a3d859e..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class IsAuthenticatorRegisteredUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("authenticatorId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - - val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).flutterError(result) - - val authenticator = getAuthenticatorById(authenticatorId, userProfile) - ?: return SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) - - result.success(authenticator.isRegistered) - } - - private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { - if (authenticatorId == null) return null - var foundAuthenticator: OneginiAuthenticator? = null - val oneginiAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - for (oneginiAuthenticator in oneginiAuthenticators) { - if (oneginiAuthenticator.id == authenticatorId) { - foundAuthenticator = oneginiAuthenticator - break - } - } - return foundAuthenticator - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt deleted file mode 100644 index 123b6c41..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt +++ /dev/null @@ -1,110 +0,0 @@ -package com.onegini.mobile.sdk - -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class IsAuthenticatorRegisteredUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall - - @Mock - lateinit var userProfile: UserProfile - - @Mock - lateinit var oneginiAuthenticator: OneginiAuthenticator - - @Spy - lateinit var resultSpy: MethodChannel.Result - - lateinit var isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase - - @Before - fun attach() { - isAuthenticatorRegisteredUseCase = IsAuthenticatorRegisteredUseCase(oneginiSdk) - } - - @Test - fun `should return error when user is not authenticated`() { - whenever(callMock.argument("authenticatorId")).thenReturn("TEST") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = NO_USER_PROFILE_IS_AUTHENTICATED.message - verify(resultSpy).error(eq(NO_USER_PROFILE_IS_AUTHENTICATED.code.toString()), eq(message), any()) - } - - @Test - fun `should return error when authenticator id is null`() { - whenever(callMock.argument("authenticatorId")).thenReturn("TEST") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) - } - - @Test - fun `should return error when authenticator id is not null but not found in SDK`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("test") - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) - } - - @Test - fun `should return true when authenticator id is registered`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("testId") - whenever(oneginiAuthenticator.isRegistered).thenReturn(true) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - verify(resultSpy).success(true) - } - - @Test - fun `should return false when authenticator id is not registered`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("testId") - whenever(oneginiAuthenticator.isRegistered).thenReturn(false) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - verify(resultSpy).success(false) - } -} \ No newline at end of file diff --git a/example/ios/OneginiTests/Handlers/AuthenticatorsHandler/AuthenticatorsHandler_IsAuthenticatorRegisteredTests.swift b/example/ios/OneginiTests/Handlers/AuthenticatorsHandler/AuthenticatorsHandler_IsAuthenticatorRegisteredTests.swift deleted file mode 100644 index 09621b9f..00000000 --- a/example/ios/OneginiTests/Handlers/AuthenticatorsHandler/AuthenticatorsHandler_IsAuthenticatorRegisteredTests.swift +++ /dev/null @@ -1,123 +0,0 @@ -// -// AuthenticatorsHandler_IsAuthenticatedTests.swift -// OneginiTests -// -// Created by Mateusz Mirkowski on 07/04/2021. -// - -import XCTest -@testable import onegini -import OneginiSDKiOS - -class AuthenticatorsHandler_IsAuthenticatorRegisteredTests: XCTestCase, AuthenticatorsNotificationReceiverProtocol { - var handler: AuthenticatorsHandler? - var authHandlerCallback: ((_ event: MobileAuthNotification, _ requestMessage: String?, _ error: SdkError?) -> ())? - - override func setUpWithError() throws { - try super.setUpWithError() - handler = AuthenticatorsHandler() - handler!.notificationReceiver = self - } - - override func tearDownWithError() throws { - handler = nil - authHandlerCallback = nil - try super.tearDownWithError() - } - - func sendNotification(event: MobileAuthNotification, requestMessage: String?, error: SdkError?) { - authHandlerCallback?(event, requestMessage, error) - } - - func testIsAuthenticatorRegisteredForPin() throws { - var expectation = self.expectation(description: "startOneginiModule") - OneginiModuleSwift.sharedInstance.startOneginiModule { (callback) in - expectation.fulfill() - } - waitForExpectations(timeout: 10, handler: nil) - - expectation = self.expectation(description: "isAuthenticatorRegistered") - - authHandlerCallback = { - (event, requestMessage, error) in - Logger.log("auth handler callback") - expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - let profile = ONGUserProfile(id: "121212")! - - let result = handler!.isAuthenticatorRegistered(.PIN, profile) - XCTAssertTrue(result) - } - - func testIsAuthenticatorRegisteredForBiometric() throws { - var expectation = self.expectation(description: "startOneginiModule") - OneginiModuleSwift.sharedInstance.startOneginiModule { (callback) in - expectation.fulfill() - } - waitForExpectations(timeout: 10, handler: nil) - - expectation = self.expectation(description: "isAuthenticatorRegistered") - - authHandlerCallback = { - (event, requestMessage, error) in - print("auth handler callback") - expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - let profile = ONGUserProfile(id: "121212")! - - let result = handler!.isAuthenticatorRegistered(.biometric, profile) - XCTAssertTrue(result) - } - - func testIsAuthenticatorRegisteredForTouchId() throws { - var expectation = self.expectation(description: "startOneginiModule") - OneginiModuleSwift.sharedInstance.startOneginiModule { (callback) in - expectation.fulfill() - } - waitForExpectations(timeout: 10, handler: nil) - - expectation = self.expectation(description: "isAuthenticatorRegistered") - - authHandlerCallback = { - (event, requestMessage, error) in - print("auth handler callback") - expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - let profile = ONGUserProfile(id: "121212")! - - let result = handler!.isAuthenticatorRegistered(.touchID, profile) - XCTAssertTrue(result) - } - - func testIsAuthenticatorRegisteredForCustom() throws { - var expectation = self.expectation(description: "startOneginiModule") - OneginiModuleSwift.sharedInstance.startOneginiModule { (callback) in - expectation.fulfill() - } - waitForExpectations(timeout: 10, handler: nil) - - expectation = self.expectation(description: "isAuthenticatorRegistered") - - authHandlerCallback = { - (event, requestMessage, error) in - print("auth handler callback") - expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - let profile = ONGUserProfile(id: "121212")! - - let result = handler!.isAuthenticatorRegistered(.custom, profile) - XCTAssertTrue(result) - } -} diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 9c60ce4d..90a68d57 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -7,7 +7,6 @@ protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func getAuthenticatorsListForUserProfile(_ userProfile: ONGUserProfile) -> Array - func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool } class AuthenticatorsHandler: NSObject { @@ -101,10 +100,6 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { let authenticatros = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile) return sortAuthenticatorsList(Array(authenticatros)) } - - func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool { - return ONGUserClient.sharedInstance().registeredAuthenticators(forUser: userProfile).first(where: {$0.type.rawValue == authenticatorType.rawValue }) != nil; - } } //MARK: - ONGAuthenticatorRegistrationDelegate From e210586b79b37a170450416f18ca76f5e6ce266a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 24 Mar 2023 15:42:45 +0100 Subject: [PATCH 183/364] FP-71: Move startApp to pigeon for iOS/Android This commit updates startApp to go through pigeon, for this we need to update a few types that get passed along and need to update how we create some of the main objects on the dart side. e.g. the native interface api. It also has some changes on how we deal with the config on the Android side. --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 20 +----- .../sdk/flutter/OneginiMethodsWrapper.kt | 17 ----- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 69 ++++++++++--------- .../mobile/sdk/flutter/PigeonInterface.kt | 11 +++ .../mobile/sdk/flutter/models/Config.kt | 9 --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 69 +++++++++++++++++-- .../sdk/flutter/useCases/StartAppUseCase.kt | 62 +++++++---------- example/lib/main.dart | 42 ++++++----- .../NativeBridge/OneginiModuleSwift.swift | 20 +++--- ios/Classes/Pigeon.swift | 63 +++++++++++++++-- .../SwiftOneginiPlugin+Base.swift | 20 ------ ios/Classes/SwiftOneginiPlugin.swift | 10 ++- ios/onegini.podspec | 2 +- lib/onegini.dart | 48 ++++--------- lib/pigeon.dart | 67 ++++++++++++++++-- lib/user_client.dart | 4 +- pigeons/onewelcome_pigeon_interface.dart | 21 ++++++ 17 files changed, 328 insertions(+), 226 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Config.kt delete mode 100644 ios/Classes/PluginExtensions/SwiftOneginiPlugin+Base.swift diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 513265a6..6aabfe23 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -1,33 +1,19 @@ package com.onegini.mobile.sdk.flutter -import com.onegini.mobile.sdk.android.client.OneginiClient +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.METHOD_TO_CALL_NOT_FOUND import com.onegini.mobile.sdk.flutter.constants.Constants import com.onegini.mobile.sdk.flutter.helpers.MobileAuthenticationObject import com.onegini.mobile.sdk.flutter.helpers.SdkError import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import javax.inject.Inject -class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: OneginiMethodsWrapper, private val oneginiSDK: OneginiSDK) : MethodChannel.MethodCallHandler { +class OnMethodCallMapper @Inject constructor(private val oneginiSDK: OneginiSDK) : MethodChannel.MethodCallHandler { override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { - try { - when (call.method) { - Constants.METHOD_START_APP -> oneginiMethodsWrapper.startApp(call, result) - else -> onSDKMethodCall(call, oneginiSDK.oneginiClient, result) - } - } catch (err: FlutterPluginException) { - SdkError(ONEWELCOME_SDK_NOT_INITIALIZED).flutterError(result) - } - } - - private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { // OTP - Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, client) - + Constants.METHOD_HANDLE_MOBILE_AUTH_WITH_OTP -> MobileAuthenticationObject.mobileAuthWithOtp(call.argument("data"), result, oneginiSDK.oneginiClient) else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt deleted file mode 100644 index 61922a19..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.onegini.mobile.sdk.flutter - -import com.onegini.mobile.sdk.flutter.useCases.* -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class OneginiMethodsWrapper @Inject constructor( - private val startAppUseCase: StartAppUseCase, -) { - - fun startApp(call: MethodCall, result: MethodChannel.Result) { - startAppUseCase(call, result) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index cdf13681..f5b82129 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -4,19 +4,23 @@ import android.content.Context import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.client.OneginiClientBuilder import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel -import com.onegini.mobile.sdk.flutter.handlers.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.CONFIG_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ONEWELCOME_SDK_NOT_INITIALIZED +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.SECURITY_CONTROLLER_NOT_FOUND +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException +import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.models.Config -import com.onegini.mobile.sdk.flutter.models.CustomIdentityProviderConfig +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomIdentityProvider import com.onegini.mobile.sdk.flutter.providers.CustomIdentityProvider import com.onegini.mobile.sdk.flutter.providers.CustomRegistrationAction import com.onegini.mobile.sdk.flutter.providers.CustomRegistrationActionImpl import com.onegini.mobile.sdk.flutter.providers.CustomTwoStepRegistrationActionImpl -import io.flutter.plugin.common.MethodChannel import java.util.concurrent.TimeUnit -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException -import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @@ -38,28 +42,29 @@ class OneginiSDK @Inject constructor( private var customRegistrationActions = ArrayList() - fun buildSDK(config: Config, result: MethodChannel.Result) { + fun buildSDK(securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: List?, + connectionTimeout: Long?, + readTimeout: Long?) { val clientBuilder = OneginiClientBuilder(applicationContext, createPinRequestHandler, pinAuthenticationRequestHandler) // handlers for optional functionalities .setBrowserRegistrationRequestHandler(browserRegistrationRequestHandler) .setFingerprintAuthenticationRequestHandler(fingerprintRequestHandler) .setMobileAuthWithOtpRequestHandler(mobileAuthWithOtpRequestHandler) - initProviders(clientBuilder, config.customIdentityProviderConfigs) - - val httpConnectionTimeout = config.httpConnectionTimeout - val httpReadTimeout = config.httpReadTimeout + initProviders(clientBuilder, customIdentityProviderConfigs) - if (httpConnectionTimeout != null) { - clientBuilder.setHttpConnectTimeout(TimeUnit.SECONDS.toMillis(httpConnectionTimeout.toLong()).toInt()) + if (connectionTimeout != null) { + clientBuilder.setHttpConnectTimeout(TimeUnit.SECONDS.toMillis(connectionTimeout).toInt()) } - if (httpReadTimeout != null) { - clientBuilder.setHttpReadTimeout(TimeUnit.SECONDS.toMillis(httpReadTimeout.toLong()).toInt()) + if (readTimeout != null) { + clientBuilder.setHttpReadTimeout(TimeUnit.SECONDS.toMillis(readTimeout).toInt()) } - setConfigModel(clientBuilder, config, result) + setConfigModel(clientBuilder, configModelClassName) + setSecurityController(clientBuilder, securityControllerClassName) - setSecurityController(clientBuilder, config, result) clientBuilder.build() } @@ -68,8 +73,8 @@ class OneginiSDK @Inject constructor( return customRegistrationActions } - private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List) { - customIdentityProviderConfigs.forEach { + private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List?) { + customIdentityProviderConfigs?.forEach { val action = when (it.isTwoStep) { true -> CustomTwoStepRegistrationActionImpl(it.providerId, nativeApi) false -> CustomRegistrationActionImpl(it.providerId, nativeApi) @@ -80,12 +85,12 @@ class OneginiSDK @Inject constructor( } } - private fun setConfigModel(clientBuilder: OneginiClientBuilder, config: Config, result: MethodChannel.Result) { - if (config.configModelClassName == null) { + private fun setConfigModel(clientBuilder: OneginiClientBuilder, configModelClassName: String?) { + if (configModelClassName == null) { return } try { - val clazz = Class.forName(config.configModelClassName) + val clazz = Class.forName(configModelClassName) val ctor = clazz.getConstructor() val `object` = ctor.newInstance() if (`object` is OneginiClientConfigModel) { @@ -93,28 +98,28 @@ class OneginiSDK @Inject constructor( } } catch (e: Exception) { e.message?.let { message -> - SdkError( + throw SdkError( code = CONFIG_ERROR.code, message = message - ).flutterError(result) - } ?: SdkError(CONFIG_ERROR).flutterError(result) + ) + } ?: throw SdkError(CONFIG_ERROR) } } - private fun setSecurityController(clientBuilder: OneginiClientBuilder, config: Config, result: MethodChannel.Result) { - if (config.securityControllerClassName == null) { + private fun setSecurityController(clientBuilder: OneginiClientBuilder, securityControllerClassName: String?) { + if (securityControllerClassName == null) { return } try { - val securityController = Class.forName(config.securityControllerClassName) + val securityController = Class.forName(securityControllerClassName) clientBuilder.setSecurityController(securityController) } catch (e: ClassNotFoundException) { e.message?.let { message -> - SdkError( + throw SdkError( code = SECURITY_CONTROLLER_NOT_FOUND.code, message = message - ).flutterError(result) - } ?: SdkError(SECURITY_CONTROLLER_NOT_FOUND).flutterError(result) + ) + } ?: throw SdkError(SECURITY_CONTROLLER_NOT_FOUND) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 4e85693e..772f486d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -12,6 +12,7 @@ import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse @@ -134,6 +135,16 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase @Inject lateinit var oneginiSDK: OneginiSDK + override fun startApplication( + securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: List?, + connectionTimeout: Long?, + readTimeout: Long?, + callback: (Result) -> Unit + ) { + startAppUseCase(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout, callback ) + } override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { registrationUseCase(identityProviderId, scopes, callback) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Config.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Config.kt deleted file mode 100644 index 67a44984..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Config.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.onegini.mobile.sdk.flutter.models - -data class Config( - val configModelClassName: String?, - val securityControllerClassName: String?, - val httpConnectionTimeout: Int?, - val httpReadTimeout: Int?, - val customIdentityProviderConfigs: ArrayList -) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index cdb1c643..b0af5e8b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -316,6 +316,28 @@ data class OWOneginiError ( } } +/** Generated class from Pigeon that represents data sent in messages. */ +data class OWCustomIdentityProvider ( + val providerId: String, + val isTwoStep: Boolean + +) { + companion object { + @Suppress("UNCHECKED_CAST") + fun fromList(list: List): OWCustomIdentityProvider { + val providerId = list[0] as String + val isTwoStep = list[1] as Boolean + return OWCustomIdentityProvider(providerId, isTwoStep) + } + } + fun toList(): List { + return listOf( + providerId, + isTwoStep, + ) + } +} + @Suppress("UNCHECKED_CAST") private object UserClientApiCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { @@ -332,20 +354,25 @@ private object UserClientApiCodec : StandardMessageCodec() { } 130.toByte() -> { return (readValue(buffer) as? List)?.let { - OWCustomInfo.fromList(it) + OWCustomIdentityProvider.fromList(it) } } 131.toByte() -> { return (readValue(buffer) as? List)?.let { - OWIdentityProvider.fromList(it) + OWCustomInfo.fromList(it) } } 132.toByte() -> { return (readValue(buffer) as? List)?.let { - OWRegistrationResponse.fromList(it) + OWIdentityProvider.fromList(it) } } 133.toByte() -> { + return (readValue(buffer) as? List)?.let { + OWRegistrationResponse.fromList(it) + } + } + 134.toByte() -> { return (readValue(buffer) as? List)?.let { OWUserProfile.fromList(it) } @@ -363,22 +390,26 @@ private object UserClientApiCodec : StandardMessageCodec() { stream.write(129) writeValue(stream, value.toList()) } - is OWCustomInfo -> { + is OWCustomIdentityProvider -> { stream.write(130) writeValue(stream, value.toList()) } - is OWIdentityProvider -> { + is OWCustomInfo -> { stream.write(131) writeValue(stream, value.toList()) } - is OWRegistrationResponse -> { + is OWIdentityProvider -> { stream.write(132) writeValue(stream, value.toList()) } - is OWUserProfile -> { + is OWRegistrationResponse -> { stream.write(133) writeValue(stream, value.toList()) } + is OWUserProfile -> { + stream.write(134) + writeValue(stream, value.toList()) + } else -> super.writeValue(stream, value) } } @@ -390,6 +421,7 @@ private object UserClientApiCodec : StandardMessageCodec() { * Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface UserClientApi { + fun startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: List?, connectionTimeout: Long?, readTimeout: Long?, callback: (Result) -> Unit) fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) @@ -440,6 +472,29 @@ interface UserClientApi { /** Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. */ @Suppress("UNCHECKED_CAST") fun setUp(binaryMessenger: BinaryMessenger, api: UserClientApi?) { + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.startApplication", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val securityControllerClassNameArg = args[0] as String? + val configModelClassNameArg = args[1] as String? + val customIdentityProviderConfigsArg = args[2] as List? + val connectionTimeoutArg = args[3].let { if (it is Int) it.toLong() else it as Long? } + val readTimeoutArg = args[4].let { if (it is Int) it.toLong() else it as Long? } + api.startApplication(securityControllerClassNameArg, configModelClassNameArg, customIdentityProviderConfigsArg, connectionTimeoutArg, readTimeoutArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerUser", codec) if (api != null) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt index f6071f37..01353207 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt @@ -1,66 +1,52 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiInitializationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiInitializationError import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ONEWELCOME_SDK_NOT_INITIALIZED import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.models.Config -import com.onegini.mobile.sdk.flutter.models.CustomIdentityProviderConfig -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomIdentityProvider import javax.inject.Inject import javax.inject.Singleton @Singleton class StartAppUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val customIdentityProviderConfigs = ArrayList() - call.argument>("customIdentityProviderConfigs")?.forEach { - customIdentityProviderConfigs.add(Gson().fromJson(it, CustomIdentityProviderConfig::class.java)) + operator fun invoke(securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: List?, + connectionTimeout: Long?, + readTimeout: Long?, + callback: (Result) -> Unit) { + try { + oneginiSDK.buildSDK(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout) + start(oneginiSDK.oneginiClient, callback) + } catch (error: SdkError) { + callback(Result.failure(error.pigeonError())) } - - val connectionTimeout = call.argument("connectionTimeout") - val readTimeout = call.argument("readTimeout") - val securityControllerClassName = call.argument("securityControllerClassName") - val configModelClassName = call.argument("configModelClassName") - val config = Config(configModelClassName, securityControllerClassName, connectionTimeout, readTimeout, customIdentityProviderConfigs) - - oneginiSDK.buildSDK(config, result) - start(oneginiSDK.oneginiClient, result) } - private fun start(oneginiClient: OneginiClient?, result: MethodChannel.Result) { + private fun start(oneginiClient: OneginiClient?, callback: (Result) -> Unit) { if (oneginiClient == null) { - SdkError(ONEWELCOME_SDK_NOT_INITIALIZED).flutterError(result) + callback(Result.failure(SdkError(ONEWELCOME_SDK_NOT_INITIALIZED).pigeonError())) } else { oneginiSDK.oneginiClient.start(object : OneginiInitializationHandler { override fun onSuccess(removedUserProfiles: Set) { - val removedUserProfileArray = getRemovedUserProfileArray(removedUserProfiles) - result.success(Gson().toJson(removedUserProfileArray)) + callback(Result.success(Unit)) } override fun onError(error: OneginiInitializationError) { - SdkError( - code = error.errorType, - message = error.message - ).flutterError(result) + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) } }) } } - - private fun getRemovedUserProfileArray(removedUserProfiles: Set): ArrayList> { - val removedUserProfileArray: ArrayList> = ArrayList() - for (userProfile in removedUserProfiles) { - val map = mutableMapOf() - map["isDefault"] = userProfile.isDefault - map["profileId"] = userProfile.profileId - removedUserProfileArray.add(map) - } - return removedUserProfileArray - } } diff --git a/example/lib/main.dart b/example/lib/main.dart index 4c043f6d..834fd15c 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; +import 'package:onegini/pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/screens/login_screen.dart'; @@ -56,29 +57,26 @@ class _BodyWidgetState extends State { void _startApplication() async { /// init Onegini sdk on native side - var removedUserProfiles = await Onegini.instance - .startApplication(OneginiListener(), - securityControllerClassName: - "com.onegini.mobile.onegini_example.SecurityController", - configModelClassName: - "com.onegini.mobile.onegini_example.OneginiConfigModel", - customIdentityProviderConfigs: [ - {"providerId": "2-way-otp-api", "isTwoStep": true} - ], - connectionTimeout: 5, - readTimeout: 25) - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - _appStarted = removedUserProfiles != null; - if (_appStarted) { - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => LoginScreen()), - ); + try { + await Onegini.instance.startApplication(OneginiListener(), + securityControllerClassName: + "com.onegini.mobile.onegini_example.SecurityController", + configModelClassName: + "com.onegini.mobile.onegini_example.OneginiConfigModel", + customIdentityProviderConfigs: [ + OWCustomIdentityProvider( + providerId: "2-way-otp-api", isTwoStep: true) + ], + connectionTimeout: 5, + readTimeout: 25); + } catch (error) { + showFlutterToast(error.message); } + + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (context) => LoginScreen()), + ); } @override diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index d6da89d4..7ca2881b 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -17,28 +17,26 @@ public class OneginiModuleSwift: NSObject { self.customRegIdentifiers = list } - func startOneginiModule(httpConnectionTimeout: TimeInterval = TimeInterval(5), callback: @escaping FlutterResult) { - ONGClientBuilder().setHttpRequestTimeout(httpConnectionTimeout) + func startOneginiModule(httpConnectionTimeout: Int64?, callback: @escaping (Result) -> Void) { + if let httpConnectionTimeout = httpConnectionTimeout { + ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout))) + } else { + ONGClientBuilder().setHttpRequestTimeout(TimeInterval(5)) + } ONGClientBuilder().build() ONGClient.sharedInstance().start { result, error in if let error = error { let mappedError = ErrorMapper().mapError(error) - callback(mappedError.flutterError()) + callback(.failure(mappedError.flutterError())) return } if !result { - callback(SdkError(.genericError).flutterError()) + callback(.failure(SdkError(.genericError).flutterError())) return } - - let profiles = ONGUserClient.sharedInstance().userProfiles() - let value: [[String: String?]] = profiles.compactMap({ ["profileId": $0.profileId] }) - - let data = String.stringify(json: value) - - callback(data) + callback(.success) } } diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 4439a577..86f7b8ba 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -298,6 +298,28 @@ struct OWOneginiError { } } +/// Generated class from Pigeon that represents data sent in messages. +struct OWCustomIdentityProvider { + var providerId: String + var isTwoStep: Bool + + static func fromList(_ list: [Any]) -> OWCustomIdentityProvider? { + let providerId = list[0] as! String + let isTwoStep = list[1] as! Bool + + return OWCustomIdentityProvider( + providerId: providerId, + isTwoStep: isTwoStep + ) + } + func toList() -> [Any?] { + return [ + providerId, + isTwoStep, + ] + } +} + private class UserClientApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -306,12 +328,14 @@ private class UserClientApiCodecReader: FlutterStandardReader { case 129: return OWAuthenticator.fromList(self.readValue() as! [Any]) case 130: - return OWCustomInfo.fromList(self.readValue() as! [Any]) + return OWCustomIdentityProvider.fromList(self.readValue() as! [Any]) case 131: - return OWIdentityProvider.fromList(self.readValue() as! [Any]) + return OWCustomInfo.fromList(self.readValue() as! [Any]) case 132: - return OWRegistrationResponse.fromList(self.readValue() as! [Any]) + return OWIdentityProvider.fromList(self.readValue() as! [Any]) case 133: + return OWRegistrationResponse.fromList(self.readValue() as! [Any]) + case 134: return OWUserProfile.fromList(self.readValue() as! [Any]) default: return super.readValue(ofType: type) @@ -327,18 +351,21 @@ private class UserClientApiCodecWriter: FlutterStandardWriter { } else if let value = value as? OWAuthenticator { super.writeByte(129) super.writeValue(value.toList()) - } else if let value = value as? OWCustomInfo { + } else if let value = value as? OWCustomIdentityProvider { super.writeByte(130) super.writeValue(value.toList()) - } else if let value = value as? OWIdentityProvider { + } else if let value = value as? OWCustomInfo { super.writeByte(131) super.writeValue(value.toList()) - } else if let value = value as? OWRegistrationResponse { + } else if let value = value as? OWIdentityProvider { super.writeByte(132) super.writeValue(value.toList()) - } else if let value = value as? OWUserProfile { + } else if let value = value as? OWRegistrationResponse { super.writeByte(133) super.writeValue(value.toList()) + } else if let value = value as? OWUserProfile { + super.writeByte(134) + super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -363,6 +390,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { + func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, completion: @escaping (Result) -> Void) func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) @@ -412,6 +440,27 @@ class UserClientApiSetup { static var codec: FlutterStandardMessageCodec { UserClientApiCodec.shared } /// Sets up an instance of `UserClientApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UserClientApi?) { + let startApplicationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.startApplication", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + startApplicationChannel.setMessageHandler { message, reply in + let args = message as! [Any] + let securityControllerClassNameArg = args[0] as! String? + let configModelClassNameArg = args[1] as! String? + let customIdentityProviderConfigsArg = args[2] as! [OWCustomIdentityProvider]? + let connectionTimeoutArg = (args[3] is Int) ? Int64(args[3] as! Int) : args[3] as! Int64? + let readTimeoutArg = (args[4] is Int) ? Int64(args[4] as! Int) : args[4] as! Int64? + api.startApplication(securityControllerClassName: securityControllerClassNameArg, configModelClassName: configModelClassNameArg, customIdentityProviderConfigs: customIdentityProviderConfigsArg, connectionTimeout: connectionTimeoutArg, readTimeout: readTimeoutArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + startApplicationChannel.setMessageHandler(nil) + } let registerUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerUserChannel.setMessageHandler { message, reply in diff --git a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Base.swift b/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Base.swift deleted file mode 100644 index 44fad2ed..00000000 --- a/ios/Classes/PluginExtensions/SwiftOneginiPlugin+Base.swift +++ /dev/null @@ -1,20 +0,0 @@ -import Foundation -import OneginiSDKiOS -import Flutter - -protocol OneginiPluginBaseProtocol { - func startApp(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void -} - -extension SwiftOneginiPlugin: OneginiPluginBaseProtocol { - func startApp(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { - guard let _arg = call.arguments as! [String: Any]?, - let _connectionTimeout = _arg["connectionTimeout"] as? Int - else { return; } - - let timeInterval = TimeInterval(_connectionTimeout); - ONGClientBuilder().setHttpRequestTimeout(timeInterval) - OneginiModuleSwift.sharedInstance.startOneginiModule(callback: result) - } -} - diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index d79127bf..d8f492d2 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -80,6 +80,13 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { + func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout) { result in + completion(result.mapError { $0 }) + } + } + + func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { // Will be implemented during the OTP rework in // https://onewelcome.atlassian.net/browse/FP-69 @@ -311,9 +318,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc switch call.method { - // base - case Constants.Routes.startApp: startApp(call, result) - // otp case Constants.Routes.handleMobileAuthWithOtp: handleMobileAuthWithOtp(call, result) diff --git a/ios/onegini.podspec b/ios/onegini.podspec index bae8e33e..84a96261 100644 --- a/ios/onegini.podspec +++ b/ios/onegini.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.platform = :ios, '13.0' # *************************** - s.dependency 'OneginiSDKiOS', '~> 12.1.0' + s.dependency 'OneginiSDKiOS' # *************************** # Flutter.framework does not contain a i386 slice. diff --git a/lib/onegini.dart b/lib/onegini.dart index d9c36f35..d8435e24 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -13,13 +13,16 @@ import 'model/onegini_removed_user_profile.dart'; /// The main class used to call methods. class Onegini { - Onegini._privateConstructor(); + final UserClientApi api = UserClientApi(); + late final UserClient userClient; - /// Reference to the Onegini instance. - static final Onegini _instance = Onegini._privateConstructor(); + Onegini._internal() { + userClient = UserClient(api); + } + + static final Onegini instance = Onegini._internal(); - /// Public access to the Onegini instance. - static Onegini get instance => _instance; + factory Onegini() => instance; /// Communication channel between flutter and native side. final MethodChannel channel = const MethodChannel('onegini'); @@ -30,8 +33,8 @@ class Onegini { /// Resource methods. ResourcesMethods resourcesMethods = ResourcesMethods(); + // UserClientApi is the flutter to native api created by the Pigeon package, see /pigeons/README.md /// User client methods. - UserClient userClient = UserClient(); /// Use this method when you want change [BuildContext] in your [OneginiEventListener] setEventContext(BuildContext? context) { @@ -39,40 +42,17 @@ class Onegini { } /// Initialize SDK and establish communication on [eventListener]. - Future> startApplication( + Future startApplication( OneginiEventListener eventListener, { String? securityControllerClassName, String? configModelClassName, - List>? customIdentityProviderConfigs, + List? customIdentityProviderConfigs, int? connectionTimeout, int? readTimeout, }) async { _eventListener = eventListener; - try { - var customIdentityProviderConfigsJson; - if (customIdentityProviderConfigs != null) { - customIdentityProviderConfigsJson = [ - for (var customIdentityProviderConfig - in customIdentityProviderConfigs) - json.encode(customIdentityProviderConfig) - ]; - } - NativeCallFlutterApi.setup(_eventListener); - - String removedUserProfiles = await channel - .invokeMethod(Constants.startAppMethod, { - 'securityControllerClassName': securityControllerClassName, - 'configModelClassName': configModelClassName, - 'customIdentityProviderConfigs': customIdentityProviderConfigsJson, - 'connectionTimeout': connectionTimeout, - 'readTimeout': readTimeout - }); - return removedUserProfileListFromJson(removedUserProfiles); - } on TypeError catch (error) { - throw PlatformException( - code: Constants.wrapperTypeError.code.toString(), - message: Constants.wrapperTypeError.message, - stacktrace: error.stackTrace?.toString()); - } + NativeCallFlutterApi.setup(_eventListener); + api.startApplication(securityControllerClassName, configModelClassName, + customIdentityProviderConfigs, connectionTimeout, readTimeout); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 39299c50..b17b45b1 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -320,6 +320,32 @@ class OWOneginiError { } } +class OWCustomIdentityProvider { + OWCustomIdentityProvider({ + required this.providerId, + required this.isTwoStep, + }); + + String providerId; + + bool isTwoStep; + + Object encode() { + return [ + providerId, + isTwoStep, + ]; + } + + static OWCustomIdentityProvider decode(Object result) { + result as List; + return OWCustomIdentityProvider( + providerId: result[0]! as String, + isTwoStep: result[1]! as bool, + ); + } +} + class _UserClientApiCodec extends StandardMessageCodec { const _UserClientApiCodec(); @override @@ -330,18 +356,21 @@ class _UserClientApiCodec extends StandardMessageCodec { } else if (value is OWAuthenticator) { buffer.putUint8(129); writeValue(buffer, value.encode()); - } else if (value is OWCustomInfo) { + } else if (value is OWCustomIdentityProvider) { buffer.putUint8(130); writeValue(buffer, value.encode()); - } else if (value is OWIdentityProvider) { + } else if (value is OWCustomInfo) { buffer.putUint8(131); writeValue(buffer, value.encode()); - } else if (value is OWRegistrationResponse) { + } else if (value is OWIdentityProvider) { buffer.putUint8(132); writeValue(buffer, value.encode()); - } else if (value is OWUserProfile) { + } else if (value is OWRegistrationResponse) { buffer.putUint8(133); writeValue(buffer, value.encode()); + } else if (value is OWUserProfile) { + buffer.putUint8(134); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -355,12 +384,14 @@ class _UserClientApiCodec extends StandardMessageCodec { case 129: return OWAuthenticator.decode(readValue(buffer)!); case 130: - return OWCustomInfo.decode(readValue(buffer)!); + return OWCustomIdentityProvider.decode(readValue(buffer)!); case 131: - return OWIdentityProvider.decode(readValue(buffer)!); + return OWCustomInfo.decode(readValue(buffer)!); case 132: - return OWRegistrationResponse.decode(readValue(buffer)!); + return OWIdentityProvider.decode(readValue(buffer)!); case 133: + return OWRegistrationResponse.decode(readValue(buffer)!); + case 134: return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -379,6 +410,28 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); + Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.startApplication', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, diff --git a/lib/user_client.dart b/lib/user_client.dart index a786b3e9..160aab12 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/pigeon.dart'; import 'constants/constants.dart'; @@ -7,7 +8,8 @@ import 'onegini.dart'; ///Сlass with basic methods available to the developer. class UserClient { - final api = UserClientApi(); + final UserClientApi api; + UserClient(this.api); ///Start registration flow. /// diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 4382de22..62f83a37 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -21,6 +21,12 @@ class OWUserProfile { OWUserProfile({required this.profileId}); } +class OWRemovedUserProfile { + String profileId; + + OWRemovedUserProfile(this.profileId); +} + class OWCustomInfo { int status; String? data; @@ -111,9 +117,24 @@ class OWOneginiError { OWOneginiError({required this.code, required this.message}); } +class OWCustomIdentityProvider { + String providerId; + bool isTwoStep; + OWCustomIdentityProvider(this.providerId, this.isTwoStep); +} + /// Flutter calls native @HostApi() abstract class UserClientApi { + @async + void startApplication( + String? securityControllerClassName, + String? configModelClassName, + List? customIdentityProviderConfigs, + int? connectionTimeout, + int? readTimeout, + ); + @async OWRegistrationResponse registerUser( String? identityProviderId, List? scopes); From 0c891cd6e83d0472c8d85fd2be08893840eb16cd Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 27 Mar 2023 10:32:37 +0200 Subject: [PATCH 184/364] FP-71: Android: Update startUseCase tests --- .../mobile/sdk/StartAppUseCaseTests.kt | 187 ++++++------------ 1 file changed, 62 insertions(+), 125 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt index 66cb0a34..8a046344 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt @@ -1,25 +1,21 @@ package com.onegini.mobile.sdk -import com.google.common.truth.Truth.assertThat -import com.google.gson.Gson import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiInitializationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiInitializationError -import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.models.Config -import com.onegini.mobile.sdk.flutter.models.CustomIdentityProviderConfig +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.StartAppUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel +import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock -import org.mockito.Spy import org.mockito.junit.MockitoJUnitRunner - import org.mockito.kotlin.* @RunWith(MockitoJUnitRunner::class) @@ -32,160 +28,101 @@ class StartAppUseCaseTests { lateinit var clientMock: OneginiClient @Mock - lateinit var callMock: MethodCall - - @Spy - lateinit var resultSpy: MethodChannel.Result + lateinit var callbackMock: (Result) -> Unit @Mock lateinit var oneginiInitializationError: OneginiInitializationError lateinit var startAppUseCase: StartAppUseCase + @Before fun attach() { startAppUseCase = StartAppUseCase(oneginiSdk) } - @Test - fun `should return UserProfile when start method returns single UserProfile`() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(setOf(UserProfile("QWERTY"))) - } - - startAppUseCase(callMock, resultSpy) - - val expectedList = setOf(mapOf("isDefault" to false, "profileId" to "QWERTY")) - val expectedResult = Gson().toJson(expectedList) - verify(resultSpy).success(expectedResult) - } + val errorCode = OneginiInitializationError.GENERAL_ERROR + val errorMessage = "General error" @Test - fun `should return error when when start method returns error`() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onError(oneginiInitializationError) - } - whenever(oneginiInitializationError.errorType).thenReturn(OneginiInitializationError.GENERAL_ERROR) - whenever(oneginiInitializationError.message).thenReturn("General error") + fun `When onError gets called by oneginiClient, Then should call callback with Result_failure with that error`() { - startAppUseCase(callMock, resultSpy) + whenCallsOnError() - val message = oneginiInitializationError.message - verify(resultSpy).error(eq(oneginiInitializationError.errorType.toString()), eq(message), any()) - } - @Test - fun `should return set of UserProfiles when start method returns set with UserProfiles`() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(setOf(UserProfile("QWERTY"), UserProfile("ASDFGH"))) - } - - startAppUseCase(callMock, resultSpy) - - val expectedList = setOf(mapOf("isDefault" to false, "profileId" to "QWERTY"), mapOf("isDefault" to false, "profileId" to "ASDFGH")) - val expectedResult = Gson().toJson(expectedList) - verify(resultSpy).success(expectedResult) - } + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock) - @Test - fun `should return empty set when start method returns empty set`() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiInitializationError.errorType.toString(), oneginiInitializationError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } - - startAppUseCase(callMock, resultSpy) - - val expectedList = emptySet() - val expectedResult = Gson().toJson(expectedList) - verify(resultSpy).success(expectedResult) } @Test - fun `should properly pass customIdentityProviderConfigs JSON string list within the config to the SDK when list contains two items`() { - whenever(callMock.argument>("customIdentityProviderConfigs")) - .thenReturn(arrayListOf(Gson().toJson(CustomIdentityProviderConfig("id1", false)), - Gson().toJson(CustomIdentityProviderConfig("id2", true)))) - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) - } - - startAppUseCase(callMock, resultSpy) + fun `When onSuccess gets called by oneginiClient, Then should call callback with Result_success`() { - argumentCaptor { - verify(oneginiSdk).buildSDK(capture(), eq(resultSpy)) - assertThat(firstValue.customIdentityProviderConfigs.size).isEqualTo(2) - assertThat(firstValue.customIdentityProviderConfigs[0].providerId).isEqualTo("id1") - assertThat(firstValue.customIdentityProviderConfigs[0].isTwoStep).isEqualTo(false) - assertThat(firstValue.customIdentityProviderConfigs[1].providerId).isEqualTo("id2") - assertThat(firstValue.customIdentityProviderConfigs[1].isTwoStep).isEqualTo(true) - } - } + whenCallsOnSuccess() - @Test - fun `should properly pass customIdentityProviderConfigs JSON string list within the config to the SDK when list contains one item`() { - whenever(callMock.argument>("customIdentityProviderConfigs")) - .thenReturn(arrayListOf(Gson().toJson(CustomIdentityProviderConfig("id1", false)))) - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) - } - startAppUseCase(callMock, resultSpy) + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock) - argumentCaptor { - verify(oneginiSdk).buildSDK(capture(), eq(resultSpy)) - assertThat(firstValue.customIdentityProviderConfigs.size).isEqualTo(1) - assertThat(firstValue.customIdentityProviderConfigs[0].providerId).isEqualTo("id1") - assertThat(firstValue.customIdentityProviderConfigs[0].isTwoStep).isEqualTo(false) + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + assertEquals(firstValue.isSuccess, true) } } - - @Test - fun `should properly pass connectionTimeout and readTimeout params to the SDK when provided`() { - whenever(callMock.argument("connectionTimeout")).thenReturn(5) - whenever(callMock.argument("readTimeout")).thenReturn(20) - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) - } - - startAppUseCase(callMock, resultSpy) - argumentCaptor { - verify(oneginiSdk).buildSDK(capture(), eq(resultSpy)) - assertThat(firstValue.httpConnectionTimeout).isEqualTo(5) - assertThat(firstValue.httpReadTimeout).isEqualTo(20) + @Test + fun `When OneginiSDK_buildSDK throws an exception Then we should reject with that error`() { + whenBuildSdkThrowsSdkError() + + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(errorCode.toString(), errorMessage) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } - @Test - fun `should properly pass securityControllerClassName and configModelClassName params to the SDK when provided`() { - whenever(callMock.argument("securityControllerClassName")).thenReturn("com.onegini.mobile.onegini_example.SecurityController") - whenever(callMock.argument("configModelClassName")).thenReturn("com.onegini.mobile.onegini_example.OneginiConfigModel") + private fun whenCallsOnError() { whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) + it.getArgument(0).onError(oneginiInitializationError) } + whenever(oneginiInitializationError.errorType).thenReturn(errorCode) + whenever(oneginiInitializationError.message).thenReturn(errorMessage) + } - startAppUseCase(callMock, resultSpy) - - argumentCaptor { - verify(oneginiSdk).buildSDK(capture(), eq(resultSpy)) - assertThat(firstValue.configModelClassName).isEqualTo("com.onegini.mobile.onegini_example.OneginiConfigModel") - assertThat(firstValue.securityControllerClassName).isEqualTo("com.onegini.mobile.onegini_example.SecurityController") + private fun whenBuildSdkThrowsSdkError() { + whenever(oneginiSdk.buildSDK(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())).thenAnswer { + throw SdkError( + code = errorCode, + message = errorMessage + ) } } - @Test - fun `should properly pass connectionTimeout and readTimeout params with zero values to the SDK when provided`() { - whenever(callMock.argument("connectionTimeout")).thenReturn(0) - whenever(callMock.argument("readTimeout")).thenReturn(0) + private fun whenCallsOnSuccess() { whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { it.getArgument(0).onSuccess(emptySet()) } - - startAppUseCase(callMock, resultSpy) - - argumentCaptor { - verify(oneginiSdk).buildSDK(capture(), eq(resultSpy)) - assertThat(firstValue.httpConnectionTimeout).isEqualTo(0) - assertThat(firstValue.httpReadTimeout).isEqualTo(0) - } } } From 24938ed6fd52785d07772fabccb4b4ec98de487d Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 27 Mar 2023 10:45:54 +0200 Subject: [PATCH 185/364] fp-69 fix accept and deny usecase --- .../useCases/OtpAcceptAuthenticationRequestUseCase.kt | 2 -- .../useCases/OtpDenyAuthenticationRequestUseCase.kt | 2 -- example/lib/screens/user_screen.dart | 10 ++++++---- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt index 60cb671b..88e811a4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt @@ -9,8 +9,6 @@ import javax.inject.Singleton @Singleton class OtpAcceptAuthenticationRequestUseCase @Inject constructor() { operator fun invoke(): Result { - MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() - return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) else -> { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt index 029c1ac9..835bdd6c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt @@ -9,8 +9,6 @@ import javax.inject.Singleton @Singleton class OtpDenyAuthenticationRequestUseCase @Inject constructor() { operator fun invoke(): Result { - MobileAuthOtpRequestHandler.CALLBACK?.denyAuthenticationRequest() - return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) else -> { diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 7a57f856..b562d40a 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -305,10 +305,12 @@ class Home extends StatelessWidget { authWithOpt(BuildContext context) async { Onegini.instance.setEventContext(context); - var data = await Navigator.push( - context, - MaterialPageRoute(builder: (_) => QrScanScreen()), - ); + // var data = await Navigator.push( + // context, + // MaterialPageRoute(builder: (_) => QrScanScreen()), + // ); + var data = "eyJ0cmFuc2FjdGlvbl9pZCI6IjJlYmQwMmNkLTdhYTctNDkxNS04NTEzLTczZjg2MTRhOTVkNiIsIm90cCI6IjZLVFJFSmplckQwNHNGTllGY3JXd0E9PSJ9"; + if (data != null) { await Onegini.instance.userClient .handleMobileAuthWithOtp(data) From f6e3ddb9764097ce7d03f702eb6338d02d81d215 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 27 Mar 2023 14:10:31 +0200 Subject: [PATCH 186/364] fp-69, added error to ios to prevent multiple handle mobile auths at the same time, removed unused usecase form android with isauthenticatorregistered --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 1 - .../sdk/flutter/OneWelcomeWrapperErrors.kt | 5 - .../sdk/flutter/OneginiMethodsWrapper.kt | 5 - .../mobile/sdk/flutter/PigeonInterface.kt | 9 -- .../IsAuthenticatorRegisteredUseCase.kt | 40 ------- .../IsAuthenticatorRegisteredUseCaseTests.kt | 110 ------------------ example/lib/screens/user_screen.dart | 9 +- .../NativeBridge/Errors/ErrorMapper.swift | 13 ++- .../Handlers/AuthenticatorsHandler.swift | 5 - .../Handlers/MobileAuthHandler.swift | 5 + 10 files changed, 17 insertions(+), 185 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt index 655fcc13..2dfe03a3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt @@ -25,7 +25,6 @@ class OnMethodCallMapper @Inject constructor(private val oneginiMethodsWrapper: private fun onSDKMethodCall(call: MethodCall, client: OneginiClient, result: MethodChannel.Result) { when (call.method) { // TODO: Move remaining methods to pigeon; https://onewelcome.atlassian.net/browse/FP-71 - Constants.METHOD_IS_AUTHENTICATOR_REGISTERED -> oneginiMethodsWrapper.isAuthenticatorRegistered(call, result) else -> SdkError(METHOD_TO_CALL_NOT_FOUND).flutterError(result) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 9f1bb7b7..ce0986dd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -9,8 +9,6 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), - USER_NOT_AUTHENTICATED_IMPLICITLY(8035, "The requested action requires you to be authenticated implicitly"), - METHOD_ARGUMENT_NOT_FOUND(8036, "The passed argument from Flutter could not be found"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), @@ -18,10 +16,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), - QR_CODE_HAS_NO_DATA(8006, "QR-code does not have data"), METHOD_TO_CALL_NOT_FOUND(8007, "Method to call not found"), - MALFORMED_URL(8009, "Incorrect url format"), - PREFERRED_AUTHENTICATOR_ERROR(8010, "Something went wrong when setting the preferred authenticator"), ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt index 4160ee50..61922a19 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiMethodsWrapper.kt @@ -8,15 +8,10 @@ import javax.inject.Singleton @Singleton class OneginiMethodsWrapper @Inject constructor( - private val isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase, private val startAppUseCase: StartAppUseCase, ) { fun startApp(call: MethodCall, result: MethodChannel.Result) { startAppUseCase(call, result) } - - fun isAuthenticatorRegistered(call: MethodCall, result: MethodChannel.Result) { - isAuthenticatorRegisteredUseCase(call, result) - } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 2f825959..81dd386b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -1,12 +1,6 @@ package com.onegini.mobile.sdk.flutter -import android.net.Uri -import android.util.Patterns -import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler -import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError -import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo @@ -41,7 +35,6 @@ import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCas import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase -import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase @@ -94,8 +87,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase @Inject - lateinit var isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase - @Inject lateinit var logoutUseCase: LogoutUseCase @Inject lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt deleted file mode 100644 index 7a3d859e..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsAuthenticatorRegisteredUseCase.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class IsAuthenticatorRegisteredUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(call: MethodCall, result: MethodChannel.Result) { - val authenticatorId = call.argument("authenticatorId") - ?: return SdkError(METHOD_ARGUMENT_NOT_FOUND).flutterError(result) - - val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).flutterError(result) - - val authenticator = getAuthenticatorById(authenticatorId, userProfile) - ?: return SdkError(AUTHENTICATOR_NOT_FOUND).flutterError(result) - - result.success(authenticator.isRegistered) - } - - private fun getAuthenticatorById(authenticatorId: String?, userProfile: UserProfile): OneginiAuthenticator? { - if (authenticatorId == null) return null - var foundAuthenticator: OneginiAuthenticator? = null - val oneginiAuthenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - for (oneginiAuthenticator in oneginiAuthenticators) { - if (oneginiAuthenticator.id == authenticatorId) { - foundAuthenticator = oneginiAuthenticator - break - } - } - return foundAuthenticator - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt deleted file mode 100644 index 123b6c41..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/IsAuthenticatorRegisteredUseCaseTests.kt +++ /dev/null @@ -1,110 +0,0 @@ -package com.onegini.mobile.sdk - -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.useCases.IsAuthenticatorRegisteredUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.Spy -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.any -import org.mockito.kotlin.eq -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class IsAuthenticatorRegisteredUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var clientMock: OneginiClient - @Mock - lateinit var callMock: MethodCall - - @Mock - lateinit var userProfile: UserProfile - - @Mock - lateinit var oneginiAuthenticator: OneginiAuthenticator - - @Spy - lateinit var resultSpy: MethodChannel.Result - - lateinit var isAuthenticatorRegisteredUseCase: IsAuthenticatorRegisteredUseCase - - @Before - fun attach() { - isAuthenticatorRegisteredUseCase = IsAuthenticatorRegisteredUseCase(oneginiSdk) - } - - @Test - fun `should return error when user is not authenticated`() { - whenever(callMock.argument("authenticatorId")).thenReturn("TEST") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = NO_USER_PROFILE_IS_AUTHENTICATED.message - verify(resultSpy).error(eq(NO_USER_PROFILE_IS_AUTHENTICATED.code.toString()), eq(message), any()) - } - - @Test - fun `should return error when authenticator id is null`() { - whenever(callMock.argument("authenticatorId")).thenReturn("TEST") - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) - } - - @Test - fun `should return error when authenticator id is not null but not found in SDK`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("test") - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - val message = AUTHENTICATOR_NOT_FOUND.message - verify(resultSpy).error(eq(AUTHENTICATOR_NOT_FOUND.code.toString()), eq(message), any()) - } - - @Test - fun `should return true when authenticator id is registered`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("testId") - whenever(oneginiAuthenticator.isRegistered).thenReturn(true) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - verify(resultSpy).success(true) - } - - @Test - fun `should return false when authenticator id is not registered`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(userProfile) - whenever(callMock.argument("authenticatorId")).thenReturn("testId") - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(userProfile)).thenReturn(setOf(oneginiAuthenticator)) - whenever(oneginiAuthenticator.id).thenReturn("testId") - whenever(oneginiAuthenticator.isRegistered).thenReturn(false) - - isAuthenticatorRegisteredUseCase(callMock,resultSpy) - - verify(resultSpy).success(false) - } -} \ No newline at end of file diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index b562d40a..6181161f 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -305,11 +305,10 @@ class Home extends StatelessWidget { authWithOpt(BuildContext context) async { Onegini.instance.setEventContext(context); - // var data = await Navigator.push( - // context, - // MaterialPageRoute(builder: (_) => QrScanScreen()), - // ); - var data = "eyJ0cmFuc2FjdGlvbl9pZCI6IjJlYmQwMmNkLTdhYTctNDkxNS04NTEzLTczZjg2MTRhOTVkNiIsIm90cCI6IjZLVFJFSmplckQwNHNGTllGY3JXd0E9PSJ9"; + var data = await Navigator.push( + context, + MaterialPageRoute(builder: (_) => QrScanScreen()), + ); if (data != null) { await Onegini.instance.userClient diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index e47868d9..c7df9a8c 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -31,6 +31,7 @@ enum OneWelcomeWrapperError: Int { case unsupportedPinAction = 8029 case unsupportedCustomRegistrationAction = 8030 case authenticatorRegistrationCancelled = 8031 + case mobileAuthInProgress = 8041 func message() -> String { switch self { @@ -79,15 +80,17 @@ enum OneWelcomeWrapperError: Int { case .authenticatorRegistrationCancelled: return "The authenticator-registration was cancelled." case .unauthenticatedImplicitly: - return "The requested action requires you to be authenticated implicitly" + return "The requested action requires you to be authenticated implicitly." case .methodArgumentNotFound: - return "The passed argument from Flutter could not be found" + return "The passed argument from Flutter could not be found." case .registrationNotInProgress: - return "Registration is currently not in progress" + return "Registration is currently not in progress." case .authenticationNotInProgress: - return "Authentication is currently not in progress" + return "Authentication is currently not in progress." case .otpAuthenticationNotInProgress: - return "OTP Authentication is currently not in progress" + return "OTP Authentication is currently not in progress." + case .mobileAuthInProgress: + return "Mobile Authentication is already in progress. Please cancel the previous authentication attempt." } } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 7140219e..56f4c400 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -6,7 +6,6 @@ protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool } class AuthenticatorsHandler: NSObject { @@ -85,10 +84,6 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { ONGUserClient.sharedInstance().preferredAuthenticator = authenticator completion(.success) } - - func isAuthenticatorRegistered(_ authenticatorType: ONGAuthenticatorType, _ userProfile: ONGUserProfile) -> Bool { - return ONGUserClient.sharedInstance().registeredAuthenticators(forUser: userProfile).first(where: {$0.type.rawValue == authenticatorType.rawValue }) != nil; - } } //MARK: - ONGAuthenticatorRegistrationDelegate diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index 395364b3..0a606466 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -17,6 +17,11 @@ class MobileAuthHandler: NSObject { extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { func handleMobileAuthWithOtp2(otp: String, completion: @escaping (Result) -> Void) { Logger.log("handleMobileAuthWithOtp", sender: self) + if (handleMobileAuthCompletion != nil) { + completion(.failure(FlutterError(SdkError(.mobileAuthInProgress)))) + return + } + handleMobileAuthCompletion = completion guard ONGUserClient.sharedInstance().canHandleOTPMobileAuthRequest(otp) else { From 254ebddf9275b5d0a3f91a03edbeee1304a669d8 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 27 Mar 2023 14:12:45 +0200 Subject: [PATCH 187/364] fp-69 rename function --- ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift | 4 ++-- .../ModuleExtensions/OneginiModuleSwift+OTP.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index 0a606466..7b12d640 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -2,7 +2,7 @@ import Foundation import OneginiSDKiOS protocol MobileAuthConnectorToHandlerProtocol: AnyObject { - func handleMobileAuthWithOtp2(otp: String, completion: @escaping (Result) -> Void) + func handleMobileAuthWithOtp(otp: String, completion: @escaping (Result) -> Void) func enrollMobileAuthentication(completion: @escaping (Result) -> Void) func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) func denyMobileAuthRequest(completion: @escaping (Result) -> Void) @@ -15,7 +15,7 @@ class MobileAuthHandler: NSObject { //MARK: - MobileAuthConnectorToHandlerProtocol extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { - func handleMobileAuthWithOtp2(otp: String, completion: @escaping (Result) -> Void) { + func handleMobileAuthWithOtp(otp: String, completion: @escaping (Result) -> Void) { Logger.log("handleMobileAuthWithOtp", sender: self) if (handleMobileAuthCompletion != nil) { completion(.failure(FlutterError(SdkError(.mobileAuthInProgress)))) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index c27d28a0..9afcca83 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -4,7 +4,7 @@ import Flutter extension OneginiModuleSwift { func handleMobileAuthWithOtp2(_ otp: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toMobileAuthHandler.handleMobileAuthWithOtp2(otp: otp, completion: completion) + bridgeConnector.toMobileAuthHandler.handleMobileAuthWithOtp(otp: otp, completion: completion) } func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { From 856768f9e333fe5c75b787ca024bfe620dde5b67 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 27 Mar 2023 15:07:58 +0200 Subject: [PATCH 188/364] Update the iOS TokenServer configuration --- .../Configuration/OneginiConfigModel.h | 0 .../ios/Configuration/OneginiConfigModel.m | 29 ++++++++++++++ example/ios/Runner.xcodeproj/project.pbxproj | 37 +++++++++++++----- .../Configuration/CloudFlareIncECCCA3.cer | Bin 977 -> 0 bytes 4 files changed, 56 insertions(+), 10 deletions(-) rename example/ios/{Runner => }/Configuration/OneginiConfigModel.h (100%) mode change 100644 => 100755 create mode 100755 example/ios/Configuration/OneginiConfigModel.m delete mode 100644 example/ios/Runner/Configuration/CloudFlareIncECCCA3.cer diff --git a/example/ios/Runner/Configuration/OneginiConfigModel.h b/example/ios/Configuration/OneginiConfigModel.h old mode 100644 new mode 100755 similarity index 100% rename from example/ios/Runner/Configuration/OneginiConfigModel.h rename to example/ios/Configuration/OneginiConfigModel.h diff --git a/example/ios/Configuration/OneginiConfigModel.m b/example/ios/Configuration/OneginiConfigModel.m new file mode 100755 index 00000000..486e4e1c --- /dev/null +++ b/example/ios/Configuration/OneginiConfigModel.m @@ -0,0 +1,29 @@ +#import "OneginiConfigModel.h" + +@implementation OneginiConfigModel + +// Config model generated by SDK Configurator version: v5.1.0 + ++ (NSArray *)certificates +{ + return @[@"MIIDzTCCArWgAwIBAgIQCjeHZF5ftIwiTv0b7RQMPDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJJRTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTIwMDEyNzEyNDgwOFoXDTI0MTIzMTIzNTk1OVowSjELMAkGA1UEBhMCVVMxGTAXBgNVBAoTEENsb3VkZmxhcmUsIEluYy4xIDAeBgNVBAMTF0Nsb3VkZmxhcmUgSW5jIEVDQyBDQS0zMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEua1NZpkUC0bsH4HRKlAenQMVLzQSfS2WuIg4m4Vfj7+7Te9hRsTJc9QkT+DuHM5ss1FxL2ruTAUJd9NyYqSb16OCAWgwggFkMB0GA1UdDgQWBBSlzjfq67B1DpRniLRF+tkkEIeWHzAfBgNVHSMEGDAWgBTlnVkwgkdYzKz6CFQ2hns6tQRN8DAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMBIGA1UdEwEB/wQIMAYBAf8CAQAwNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wOgYDVR0fBDMwMTAvoC2gK4YpaHR0cDovL2NybDMuZGlnaWNlcnQuY29tL09tbmlyb290MjAyNS5jcmwwbQYDVR0gBGYwZDA3BglghkgBhv1sAQEwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzALBglghkgBhv1sAQIwCAYGZ4EMAQIBMAgGBmeBDAECAjAIBgZngQwBAgMwDQYJKoZIhvcNAQELBQADggEBAAUkHd0bsCrrmNaF4zlNXmtXnYJX/OvoMaJXkGUFvhZEOFp3ArnPEELG4ZKk40Un+ABHLGioVplTVI+tnkDB0A+21w0LOEhsUCxJkAZbZB2LzEgwLt4I4ptJIsCSDBFelpKU1fwg3FZs5ZKTv3ocwDfjhUkV+ivhdDkYD7fa86JXWGBPzI6UAPxGezQxPk1HgoE6y/SJXQ7vTQ1unBuCJN0yJV0ReFEQPaA1IwQvZW+cwdFD19Ae8zFnWSfda9J1CZMRJCQUzym+5iPDuI9yP+kHyCREU3qzuWFloUwOxkgAyXVjBYdwRVKD05WdRerw6DEdfgkfCv4+3ao8XnTSrLE=", @"MIIGEzCCA/ugAwIBAgIQfVtRJrR2uhHbdBYLvFMNpzANBgkqhkiG9w0BAQwFADCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTgxMTAyMDAwMDAwWhcNMzAxMjMxMjM1OTU5WjCBjzELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTcwNQYDVQQDEy5TZWN0aWdvIFJTQSBEb21haW4gVmFsaWRhdGlvbiBTZWN1cmUgU2VydmVyIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1nMz1tc8INAA0hdFuNY+B6I/x0HuMjDJsGz99J/LEpgPLT+NTQEMgg8Xf2Iu6bhIefsWg06t1zIlk7cHv7lQP6lMw0Aq6Tn/2YHKHxYyQdqAJrkjeocgHuP/IJo8lURvh3UGkEC0MpMWCRAIIz7S3YcPb11RFGoKacVPAXJpz9OTTG0EoKMbgn6xmrntxZ7FN3ifmgg0+1YuWMQJDgZkW7w33PGfKGioVrCSo1yfu4iYCBskHaswha6vsC6eep3BwEIc4gLw6uBK0u+QDrTBQBbwb4VCSmT3pDCg/r8uoydajotYuK3DGReEY+1vVv2Dy2A0xHS+5p3b4eTlygxfFQIDAQABo4IBbjCCAWowHwYDVR0jBBgwFoAUU3m/WqorSs9UgOHYm8Cd8rIDZsswHQYDVR0OBBYEFI2MXsRUrYrhd+mb+ZsF4bgBjWHhMA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAbBgNVHSAEFDASMAYGBFUdIAAwCAYGZ4EMAQIBMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDB2BggrBgEFBQcBAQRqMGgwPwYIKwYBBQUHMAKGM2h0dHA6Ly9jcnQudXNlcnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FBZGRUcnVzdENBLmNydDAlBggrBgEFBQcwAYYZaHR0cDovL29jc3AudXNlcnRydXN0LmNvbTANBgkqhkiG9w0BAQwFAAOCAgEAMr9hvQ5Iw0/HukdN+Jx4GQHcEx2Ab/zDcLRSmjEzmldS+zGea6TvVKqJjUAXaPgREHzSyrHxVYbH7rM2kYb2OVG/Rr8PoLq0935JxCo2F57kaDl6r5ROVm+yezu/Coa9zcV3HAO4OLGiH19+24rcRki2aArPsrW04jTkZ6k4Zgle0rj8nSg6F0AnwnJOKf0hPHzPE/uWLMUxRP0T7dWbqWlod3zu4f+k+TY4CFM5ooQ0nBnzvg6s1SQ36yOoeNDT5++SR2RiOSLvxvcRviKFxmZEJCaOEDKNyJOuB56DPi/Z+fVGjmO+wea03KbNIaiGCpXZLoUmGv38sbZXQm2V0TP2ORQGgkE49Y9Y3IBbpNV9lXj9p5v//cWoaasm56ekBYdbqbe4oyALl6lFhd2zi+WJN44pDfwGF/Y4QA5C5BIG+3vzxhFoYt/jmPQT2BVPi7Fp2RBgvGQq6jG35LWjOhSbJuMLe/0CjraZwTiXWTb2qHSihrZe68Zk6s+go/lunrotEbaGmAhYLcmsJWTyXnW0OMGuf1pGg+pRyrbxmRE1a6Vqe8YAsOf4vmSyrcjC8azjUeqkk+B5yOGBQMkKW+ESPMFgKuOXwIlCypTPRpgSabuY0MLTDXJLR27lk8QyKGOHQ+SwMj4K00u/I5sUKUErmgQfky3xxzlIPK1aEn8="]; //Base64Certificates +} + ++ (NSDictionary *)configuration +{ + return @{ + @"ONGAppIdentifier" : @"FlutterExampleApp", + @"ONGAppPlatform" : @"ios", + @"ONGAppVersion" : @"1.0.3", + @"ONGAppBaseURL" : @"https://token-mobile.test.onegini.com", + @"ONGResourceBaseURL" : @"https://token-mobile.test.onegini.com/resources/", + @"ONGRedirectURL" : @"oneginiexample://loginsuccess", + }; +} + ++ (NSString *)serverPublicKey +{ + return @"4B8E698FEAA9F0A1E99644E77E1AB9EF5F63FBBFBA5EE52D881AADB2C0373336"; +} + +@end \ No newline at end of file diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 7310f0e2..8552c716 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -9,18 +9,18 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 21494DE316E6F87D4D59DE55 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4112D1722747CEA547F2E0C4 /* Pods_Runner.framework */; }; + 28A93267F79A7889DCBC875F /* OneginiConfigModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D0D87A64393A8E085BE3504 /* OneginiConfigModel.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 5DAAA2DD8C61D6DFC7F05D95 /* Pods_OneginiTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 33AB902096C9984BE9456033 /* Pods_OneginiTests.framework */; }; 5F07F1B8260DFCFC0073BA5E /* OneginiTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F07F1B7260DFCFC0073BA5E /* OneginiTests.swift */; }; 5F1ADDDF26146EE30055B23D /* OneginiUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F1ADDDE26146EE30055B23D /* OneginiUITests.swift */; }; 5F1ADDEE2614701E0055B23D /* RegistrationHandler_SignUpUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F1ADDED2614701E0055B23D /* RegistrationHandler_SignUpUITests.swift */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7B51F5CB5B39172B445BFA9B /* OneginiConfigModel.h in Headers */ = {isa = PBXBuildFile; fileRef = D68EE1BDDE796AE8E888D809 /* OneginiConfigModel.h */; }; 94C43332D07B64C1B7A60E45 /* Pods_Runner_OneginiUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F24C3F0D8D766862386EA2A6 /* Pods_Runner_OneginiUITests.framework */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - F0D3E8D12576F7FD009D2C24 /* CloudFlareIncECCCA3.cer in Resources */ = {isa = PBXBuildFile; fileRef = F0D3E8CE2576F7FD009D2C24 /* CloudFlareIncECCCA3.cer */; }; - F0D3E8D22576F7FD009D2C24 /* OneginiConfigModel.m in Sources */ = {isa = PBXBuildFile; fileRef = F0D3E8CF2576F7FD009D2C24 /* OneginiConfigModel.m */; }; F0D3E8D32576F7FD009D2C24 /* SecurityController.m in Sources */ = {isa = PBXBuildFile; fileRef = F0D3E8D02576F7FD009D2C24 /* SecurityController.m */; }; /* End PBXBuildFile section */ @@ -62,6 +62,7 @@ 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 4112D1722747CEA547F2E0C4 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 46DA2568900E1EC5AD1BFC14 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 4D0D87A64393A8E085BE3504 /* OneginiConfigModel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OneginiConfigModel.m; path = Configuration/OneginiConfigModel.m; sourceTree = ""; }; 5F07F133260DEC5B0073BA5E /* onegini.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = onegini.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5F07F13D260DEE2E0073BA5E /* OneginiCrypto.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = OneginiCrypto.xcframework; path = ../../ios/OneginiCrypto.xcframework; sourceTree = ""; }; 5F07F13F260DEE340073BA5E /* OneginiSDKiOS.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = OneginiSDKiOS.xcframework; path = ../../ios/OneginiSDKiOS.xcframework; sourceTree = ""; }; @@ -93,11 +94,9 @@ 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C2D65814B20E7A11AA736665 /* Pods-OneginiTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OneginiTests.profile.xcconfig"; path = "Target Support Files/Pods-OneginiTests/Pods-OneginiTests.profile.xcconfig"; sourceTree = ""; }; C80B56987111D82D8A6197FA /* Pods-Runner-OneginiUITests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner-OneginiUITests.profile.xcconfig"; path = "Target Support Files/Pods-Runner-OneginiUITests/Pods-Runner-OneginiUITests.profile.xcconfig"; sourceTree = ""; }; + D68EE1BDDE796AE8E888D809 /* OneginiConfigModel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OneginiConfigModel.h; path = Configuration/OneginiConfigModel.h; sourceTree = ""; }; EB280849B0D91DEAE8BBF20D /* Pods-OneginiTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OneginiTests.debug.xcconfig"; path = "Target Support Files/Pods-OneginiTests/Pods-OneginiTests.debug.xcconfig"; sourceTree = ""; }; F0D3E8CC2576F7FD009D2C24 /* SecurityController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SecurityController.h; sourceTree = ""; }; - F0D3E8CD2576F7FD009D2C24 /* OneginiConfigModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OneginiConfigModel.h; sourceTree = ""; }; - F0D3E8CE2576F7FD009D2C24 /* CloudFlareIncECCCA3.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = CloudFlareIncECCCA3.cer; sourceTree = ""; }; - F0D3E8CF2576F7FD009D2C24 /* OneginiConfigModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OneginiConfigModel.m; sourceTree = ""; }; F0D3E8D02576F7FD009D2C24 /* SecurityController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SecurityController.m; sourceTree = ""; }; F24C3F0D8D766862386EA2A6 /* Pods_Runner_OneginiUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner_OneginiUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -181,6 +180,15 @@ path = Pods; sourceTree = ""; }; + 749122FEC13FCA5CCF36EF16 /* Configuration */ = { + isa = PBXGroup; + children = ( + 4D0D87A64393A8E085BE3504 /* OneginiConfigModel.m */, + D68EE1BDDE796AE8E888D809 /* OneginiConfigModel.h */, + ); + name = Configuration; + sourceTree = ""; + }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -202,6 +210,7 @@ 97C146EF1CF9000F007C117D /* Products */, 5F837D4545C2413D32620243 /* Pods */, A3B0D248D7723B5FC7E80294 /* Frameworks */, + 749122FEC13FCA5CCF36EF16 /* Configuration */, ); sourceTree = ""; }; @@ -252,9 +261,6 @@ F0D3E8CB2576F7DE009D2C24 /* Configuration */ = { isa = PBXGroup; children = ( - F0D3E8CE2576F7FD009D2C24 /* CloudFlareIncECCCA3.cer */, - F0D3E8CD2576F7FD009D2C24 /* OneginiConfigModel.h */, - F0D3E8CF2576F7FD009D2C24 /* OneginiConfigModel.m */, F0D3E8CC2576F7FD009D2C24 /* SecurityController.h */, F0D3E8D02576F7FD009D2C24 /* SecurityController.m */, ); @@ -263,6 +269,17 @@ }; /* End PBXGroup section */ +/* Begin PBXHeadersBuildPhase section */ + 0A48863FD05407DF316B5CCC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 7B51F5CB5B39172B445BFA9B /* OneginiConfigModel.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + /* Begin PBXNativeTarget section */ 5F07F1B4260DFCFC0073BA5E /* OneginiTests */ = { isa = PBXNativeTarget; @@ -315,6 +332,7 @@ 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, 5AD0ACD69BCF01EDFCCC5CD0 /* [CP] Embed Pods Frameworks */, + 0A48863FD05407DF316B5CCC /* Headers */, ); buildRules = ( ); @@ -390,7 +408,6 @@ files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - F0D3E8D12576F7FD009D2C24 /* CloudFlareIncECCCA3.cer in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); @@ -554,9 +571,9 @@ buildActionMask = 2147483647; files = ( 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - F0D3E8D22576F7FD009D2C24 /* OneginiConfigModel.m in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, F0D3E8D32576F7FD009D2C24 /* SecurityController.m in Sources */, + 28A93267F79A7889DCBC875F /* OneginiConfigModel.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/example/ios/Runner/Configuration/CloudFlareIncECCCA3.cer b/example/ios/Runner/Configuration/CloudFlareIncECCCA3.cer deleted file mode 100644 index 41c742136ce864a9d7a90253af5b9f1642672d5f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 977 zcmXqLVm@oo#I$t*GZP~dlK_`_drDmVmL4U)ztV3-cx()K**LY@JlekVGBR?rG8jY| zavN~6F^96S2{U=R8VVT*fH+*joKA^3C7HSTMX83u27(|lZecFx%B0kykfPG!5$TL_^TCF>a~7|20v6GupaWE5PTofVuNb&U-o4TRa)fgU?& z%f!gW0cJ2WvNJm|uJH~+wF~f<3+6ixw*`u`X)lPy3=-aSj=vX@87@M_kE(< zk(0$&RQw;jlR1~OIj~Sa>zxlPXZhu#q$RVjFK%MYFlb^-F^~m1L6(n2j74PWIrCSq zHCN$=R=`s=2OK>IX#19_0NGK++PScAyZxse78E zhJl)a3XE^S*d~!tQc_^0ub-b>T%ebdnVy-PT2!K!oS$o81u{vV#n`~mK!1Vm0_`?U zsM6%39Agxv`u@3jnMJ_3GcqtT)dNZ! z` Date: Tue, 28 Mar 2023 13:52:38 +0200 Subject: [PATCH 189/364] FP-69 Rework ios otp again to swift otp, and handle two ios cases of unauthenticated and only allowing one otp flow at the time, additionally reworked CALLBACK to callback on android, and moved the callback logic into companion object for accept- and deny-mobileauthenticationrequestusecases --- .../BrowserRegistrationRequestHandler.kt | 10 +-- .../handlers/MobileAuthOtpRequestHandler.kt | 28 ++++++- .../PinAuthenticationRequestHandler.kt | 4 +- .../sdk/flutter/handlers/PinRequestHandler.kt | 4 +- .../CancelBrowserRegistrationUseCase.kt | 4 +- .../EnrollMobileAuthenticationUseCase.kt | 3 - .../HandleMobileAuthWithOtpUseCase.kt | 18 ++-- .../OtpAcceptAuthenticationRequestUseCase.kt | 11 +-- .../OtpDenyAuthenticationRequestUseCase.kt | 11 +-- .../PinAuthenticationRequestAcceptUseCase.kt | 2 +- .../PinAuthenticationRequestDenyUseCase.kt | 2 +- .../PinRegistrationRequestAcceptUseCase.kt | 2 +- .../PinRegistrationRequestDenyUseCase.kt | 2 +- .../CancelBrowserRegistrationUseCaseTest.kt | 4 +- .../EnrollMobileAuthenticationUseCaseTest.kt | 14 ---- .../sdk/HandleMobileAuthWithOtpUseCaseTest.kt | 16 ---- ...pAcceptAuthenticationRequestUseCaseTest.kt | 6 +- ...OtpDenyAuthenticationRequestUseCaseTest.kt | 6 +- ...nAuthenticationRequestAcceptUseCaseTest.kt | 4 +- ...PinAuthenticationRequestDenyUseCaseTest.kt | 4 +- ...PinRegistrationRequestAcceptUseCaseTest.kt | 4 +- .../PinRegistrationRequestDenyUseCaseTest.kt | 4 +- example/lib/screens/user_screen.dart | 19 +++-- .../NativeBridge/Errors/ErrorMapper.swift | 2 +- .../Handlers/MobileAuthHandler.swift | 82 ++++++++++--------- 25 files changed, 127 insertions(+), 139 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt index 110786bf..a1cb2407 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt @@ -12,7 +12,7 @@ import javax.inject.Singleton class BrowserRegistrationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiBrowserRegistrationRequestHandler { companion object { - var CALLBACK: OneginiBrowserRegistrationCallback? = null + var callback: OneginiBrowserRegistrationCallback? = null /** * Finish registration action with result from web browser @@ -20,15 +20,15 @@ class BrowserRegistrationRequestHandler @Inject constructor(private val nativeAp * https://onewelcome.atlassian.net/browse/FP-35 */ fun handleRegistrationCallback(uri: Uri) { - if (CALLBACK != null) { - CALLBACK?.handleRegistrationCallback(uri) - CALLBACK = null + if (callback != null) { + callback?.handleRegistrationCallback(uri) + callback = null } } } override fun startRegistration(uri: Uri, oneginiBrowserRegistrationCallback: OneginiBrowserRegistrationCallback) { - CALLBACK = oneginiBrowserRegistrationCallback + callback = oneginiBrowserRegistrationCallback nativeApi.n2fHandleRegisteredUrl(uri.toString()) {} } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index a6aff307..b6997f66 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -3,6 +3,8 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithOtpRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @@ -13,7 +15,7 @@ class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: Nat oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback: OneginiAcceptDenyCallback ) { - CALLBACK = oneginiAcceptDenyCallback + callback = oneginiAcceptDenyCallback nativeApi.n2fOpenAuthOtp(oneginiMobileAuthenticationRequest.message) {} } @@ -22,6 +24,28 @@ class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: Nat } companion object { - var CALLBACK: OneginiAcceptDenyCallback? = null + var callback: OneginiAcceptDenyCallback? = null + + fun acceptAuthenticationRequest(): Result { + return when (val authenticationRequestCallback = callback) { + null -> Result.failure(SdkError(OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + authenticationRequestCallback.acceptAuthenticationRequest() + callback = null + Result.success(Unit) + } + } + } + + fun denyAuthenticationRequest(): Result { + return when (val authenticationRequestCallback = callback) { + null -> Result.failure(SdkError(OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + else -> { + authenticationRequestCallback.denyAuthenticationRequest() + callback = null + Result.success(Unit) + } + } + } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index 87289d92..a159132a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -12,11 +12,11 @@ import javax.inject.Singleton @Singleton class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiPinAuthenticationRequestHandler { companion object { - var CALLBACK: OneginiPinCallback? = null + var callback: OneginiPinCallback? = null } override fun startAuthentication(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, attemptCounter: AuthenticationAttemptCounter) { - CALLBACK = oneginiPinCallback + callback = oneginiPinCallback nativeApi.n2fOpenPinScreenAuth { } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index 85193a1f..52e06820 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -13,11 +13,11 @@ import javax.inject.Singleton class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiCreatePinRequestHandler { companion object { - var CALLBACK: OneginiPinCallback? = null + var callback: OneginiPinCallback? = null } override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { - CALLBACK = oneginiPinCallback + callback = oneginiPinCallback nativeApi.n2fOpenPinRequestScreen { } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt index 779277b4..9adba62a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt @@ -7,11 +7,11 @@ import javax.inject.Inject class CancelBrowserRegistrationUseCase @Inject constructor() { operator fun invoke(): Result { - return when (val browserCallback = BrowserRegistrationRequestHandler.CALLBACK) { + return when (val browserCallback = BrowserRegistrationRequestHandler.callback) { null -> Result.failure(SdkError(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) else -> { browserCallback.denyRegistration() - BrowserRegistrationRequestHandler.CALLBACK = null + BrowserRegistrationRequestHandler.callback = null Result.success(Unit) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt index 4d7d70c3..4d056f57 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt @@ -13,9 +13,6 @@ class EnrollMobileAuthenticationUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, ) { operator fun invoke(callback: (Result) -> Unit) { - oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - oneginiSDK.oneginiClient.userClient.enrollUserForMobileAuth(object : OneginiMobileAuthEnrollmentHandler { override fun onSuccess() { callback(Result.success(Unit)) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt index c7b34c17..0554ea52 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleMobileAuthWithOtpUseCase.kt @@ -2,18 +2,16 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthWithOtpHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthWithOtpError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject +import javax.inject.Singleton +@Singleton class HandleMobileAuthWithOtpUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, ) { operator fun invoke(data: String, callback: (Result) -> Unit) { - oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - oneginiSDK.oneginiClient.userClient.handleMobileAuthWithOtp( data, object : OneginiMobileAuthWithOtpHandler { @@ -22,10 +20,14 @@ class HandleMobileAuthWithOtpUseCase @Inject constructor( } override fun onError(otpError: OneginiMobileAuthWithOtpError) { - callback(Result.failure(SdkError( - code = otpError.errorType, - message = otpError.message - ).pigeonError())) + callback( + Result.failure( + SdkError( + code = otpError.errorType, + message = otpError.message + ).pigeonError() + ) + ) } } ) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt index 88e811a4..26315dc0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt @@ -1,21 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton class OtpAcceptAuthenticationRequestUseCase @Inject constructor() { operator fun invoke(): Result { - return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { - null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - otpCallback.acceptAuthenticationRequest() - MobileAuthOtpRequestHandler.CALLBACK = null - Result.success(Unit) - } - } + return MobileAuthOtpRequestHandler.acceptAuthenticationRequest() } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt index 835bdd6c..af84d2dc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt @@ -1,21 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton class OtpDenyAuthenticationRequestUseCase @Inject constructor() { operator fun invoke(): Result { - return when (val otpCallback = MobileAuthOtpRequestHandler.CALLBACK) { - null -> Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - otpCallback.denyAuthenticationRequest() - MobileAuthOtpRequestHandler.CALLBACK = null - Result.success(Unit) - } - } + return MobileAuthOtpRequestHandler.denyAuthenticationRequest() } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt index 4b9e33bf..00cbdf6c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt @@ -9,7 +9,7 @@ import javax.inject.Singleton @Singleton class PinAuthenticationRequestAcceptUseCase @Inject constructor() { operator fun invoke(pin: String): Result { - return when (val pinCallback = PinAuthenticationRequestHandler.CALLBACK) { + return when (val pinCallback = PinAuthenticationRequestHandler.callback) { null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) else -> { pinCallback.acceptAuthenticationRequest(pin.toCharArray()) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt index 25977947..c9a42123 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt @@ -9,7 +9,7 @@ import javax.inject.Singleton @Singleton class PinAuthenticationRequestDenyUseCase @Inject constructor() { operator fun invoke(): Result { - return when (val pinCallback = PinAuthenticationRequestHandler.CALLBACK) { + return when (val pinCallback = PinAuthenticationRequestHandler.callback) { null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) else -> { pinCallback.denyAuthenticationRequest() diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt index 93a85544..3bef9aad 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt @@ -9,7 +9,7 @@ import javax.inject.Singleton @Singleton class PinRegistrationRequestAcceptUseCase @Inject constructor() { operator fun invoke(pin: String): Result { - return when (val pinCallback = PinRequestHandler.CALLBACK) { + return when (val pinCallback = PinRequestHandler.callback) { null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) else -> { pinCallback.acceptAuthenticationRequest(pin.toCharArray()) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt index ccde27fc..1c13097e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt @@ -9,7 +9,7 @@ import javax.inject.Singleton @Singleton class PinRegistrationRequestDenyUseCase @Inject constructor() { operator fun invoke(): Result { - return when (val pinCallback = PinRequestHandler.CALLBACK) { + return when (val pinCallback = PinRequestHandler.callback) { null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) else -> { pinCallback.denyAuthenticationRequest() diff --git a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt index 7b79620b..c4ba45c1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt @@ -26,7 +26,7 @@ class CancelBrowserRegistrationUseCaseTest { @Test fun `When no browser registration callback is set, Then it should resolve with an error`() { - BrowserRegistrationRequestHandler.CALLBACK = null + BrowserRegistrationRequestHandler.callback = null val result = cancelBrowserRegistrationUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS, result) @@ -34,7 +34,7 @@ class CancelBrowserRegistrationUseCaseTest { @Test fun `When a pin browser registration callback is set, Then it should resolve successfully`() { - BrowserRegistrationRequestHandler.CALLBACK = oneginiBrowserCallbackMock + BrowserRegistrationRequestHandler.callback = oneginiBrowserCallbackMock val result = cancelBrowserRegistrationUseCase().getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt index cde70fb3..5eab6bc2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt @@ -41,20 +41,6 @@ class EnrollMobileAuthenticationUseCaseTest { whenever(enrollErrorMock.message).thenReturn("General error") } - @Test - fun `When there is no authenticated user during the enrollment, Then it should resolve with an error`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - enrollMobileAuthenticationUseCase(callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - - val expected = SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError() - SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) - } - } - @Test fun `When the sdk returns an enrollment error, Then it should resolve with an error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) diff --git a/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt index c2cb33ef..ca37a5a4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt @@ -4,10 +4,8 @@ import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthWithOtpHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthWithOtpError import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import org.junit.Assert @@ -42,20 +40,6 @@ class HandleMobileAuthWithOtpUseCaseTest { whenever(otpErrorMock.message).thenReturn("General error") } - @Test - fun `When there is no authenticated user during the otp authentication, Then it should resolve with an error`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - - handleMobileAuthWithOtpUseCase("otp_password", callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - - val expected = SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError() - SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) - } - } - @Test fun `When the sdk returns an otp authentication error, Then it should resolve with an error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt index ef3b1d32..c3bffbe7 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt @@ -15,7 +15,7 @@ import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class OtpAcceptAuthenticationRequestUseCaseTest { @Mock - lateinit var oneginiOtpCallbackMock: OneginiAcceptDenyCallback + lateinit var oneginiAcceptDenyCallback: OneginiAcceptDenyCallback lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase @@ -26,7 +26,7 @@ class OtpAcceptAuthenticationRequestUseCaseTest { @Test fun `When no otp authentication callback is set, Then it should resolve with an error`() { - MobileAuthOtpRequestHandler.CALLBACK = null + MobileAuthOtpRequestHandler.callback = null val result = otpAcceptAuthenticationRequestUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) @@ -34,7 +34,7 @@ class OtpAcceptAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - MobileAuthOtpRequestHandler.CALLBACK = oneginiOtpCallbackMock + MobileAuthOtpRequestHandler.callback = oneginiAcceptDenyCallback val result = otpAcceptAuthenticationRequestUseCase().getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt index b4d76738..ac716f56 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -15,7 +15,7 @@ import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class OtpDenyAuthenticationRequestUseCaseTest { @Mock - lateinit var oneginiOtpCallbackMock: OneginiAcceptDenyCallback + lateinit var oneginiAcceptDenyCallback: OneginiAcceptDenyCallback lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase @@ -26,7 +26,7 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Test fun `When no otp authentication callback is set, Then it should resolve with an error`() { - MobileAuthOtpRequestHandler.CALLBACK = null + MobileAuthOtpRequestHandler.callback = null val result = otpDenyAuthenticationRequestUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) @@ -34,7 +34,7 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - MobileAuthOtpRequestHandler.CALLBACK = oneginiOtpCallbackMock + MobileAuthOtpRequestHandler.callback = oneginiAcceptDenyCallback val result = otpDenyAuthenticationRequestUseCase().getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 22a633e2..4d74f200 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -30,7 +30,7 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinAuthenticationRequestHandler.CALLBACK = null + PinAuthenticationRequestHandler.callback = null val result = pinAuthenticationRequestAcceptUseCase("12345").exceptionOrNull() SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) @@ -38,7 +38,7 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinAuthenticationRequestHandler.CALLBACK = oneginiPinCallbackMock + PinAuthenticationRequestHandler.callback = oneginiPinCallbackMock val result = pinAuthenticationRequestAcceptUseCase("12345").getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index 249a80a8..5fd37b6b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -30,7 +30,7 @@ class PinAuthenticationRequestDenyUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinAuthenticationRequestHandler.CALLBACK = null + PinAuthenticationRequestHandler.callback = null val result = pinAuthenticationRequestDenyUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) @@ -38,7 +38,7 @@ class PinAuthenticationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinAuthenticationRequestHandler.CALLBACK = oneginiPinCallbackMock + PinAuthenticationRequestHandler.callback = oneginiPinCallbackMock val result = pinAuthenticationRequestDenyUseCase().getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index af09ab5e..3df1e785 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -30,7 +30,7 @@ class PinRegistrationRequestAcceptUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinRequestHandler.CALLBACK = null + PinRequestHandler.callback = null val result = pinRegistrationRequestAcceptUseCase("12345").exceptionOrNull() SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) @@ -38,7 +38,7 @@ class PinRegistrationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinRequestHandler.CALLBACK = oneginiPinCallbackMock + PinRequestHandler.callback = oneginiPinCallbackMock val result = pinRegistrationRequestAcceptUseCase("12345").getOrNull() Assert.assertEquals(Unit, result) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index a4c8e70d..0dd0748f 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -30,7 +30,7 @@ class PinRegistrationRequestDenyUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinRequestHandler.CALLBACK = null + PinRequestHandler.callback = null val result = pinRegistrationRequestDenyUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) @@ -38,7 +38,7 @@ class PinRegistrationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinRequestHandler.CALLBACK = oneginiPinCallbackMock + PinRequestHandler.callback = oneginiPinCallbackMock val result = pinRegistrationRequestDenyUseCase().getOrNull() Assert.assertEquals(Unit, result) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6181161f..4705b6ee 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -296,28 +296,33 @@ class Home extends StatelessWidget { enrollMobileAuthentication() async { await Onegini.instance.userClient .enrollMobileAuthentication() + .then((value) => showFlutterToast("Mobile Authentication enrollment success")) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); } - }).then((value) => showFlutterToast("Mobile Authentication enrollment success")); + }); } authWithOpt(BuildContext context) async { Onegini.instance.setEventContext(context); - var data = await Navigator.push( - context, - MaterialPageRoute(builder: (_) => QrScanScreen()), - ); + // var data = await Navigator.push( + // context, + // MaterialPageRoute(builder: (_) => QrScanScreen()), + // ); + + var data = "eyJ0cmFuc2FjdGlvbl9pZCI6ImZhOTEwYTI2LTE1N2YtNGNkMy04YzczLWFjYzM0NzNlZmRlMyIsIm90cCI6ImZXbDdmcUxOSHdTaTBGQ0VRcHRvTUE9PSJ9"; if (data != null) { await Onegini.instance.userClient .handleMobileAuthWithOtp(data) + .then((value) => showFlutterToast("OTP1 Authentication is successfull")) .catchError((error) { if (error is PlatformException) { - showFlutterToast(error.message); + print("otp1"); + print(error.message); } - }).then((value) => showFlutterToast("OTP Authentication is successfull")); + }); } } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index c7df9a8c..5bff117e 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -90,7 +90,7 @@ enum OneWelcomeWrapperError: Int { case .otpAuthenticationNotInProgress: return "OTP Authentication is currently not in progress." case .mobileAuthInProgress: - return "Mobile Authentication is already in progress. Please cancel the previous authentication attempt." + return "Mobile Authentication is already in progress and can not be performed concurrently." } } } diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index 7b12d640..4323880b 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -6,48 +6,42 @@ protocol MobileAuthConnectorToHandlerProtocol: AnyObject { func enrollMobileAuthentication(completion: @escaping (Result) -> Void) func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) func denyMobileAuthRequest(completion: @escaping (Result) -> Void) + func setMobileAuthCallback(didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void) } class MobileAuthHandler: NSObject { var mobileAuthCallback: ((Bool) -> Void)? - var handleMobileAuthCompletion: ((Result) -> Void)? + var flowStarted: Bool = false } //MARK: - MobileAuthConnectorToHandlerProtocol extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { func handleMobileAuthWithOtp(otp: String, completion: @escaping (Result) -> Void) { Logger.log("handleMobileAuthWithOtp", sender: self) - if (handleMobileAuthCompletion != nil) { - completion(.failure(FlutterError(SdkError(.mobileAuthInProgress)))) + + // Check to prevent breaking iOS SDK; https://onewelcome.atlassian.net/browse/SDKIOS-987 + guard let _ = SharedUserClient.instance.authenticatedUserProfile else { + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - handleMobileAuthCompletion = completion - - guard ONGUserClient.sharedInstance().canHandleOTPMobileAuthRequest(otp) else { - handleMobileAuthCompletion = nil - completion(.failure(FlutterError(SdkError(.cantHandleOTP)))) + // Prevent concurrent OTP mobile authentication flows at same time; https://onewelcome.atlassian.net/browse/SDKIOS-989 + if (flowStarted) { + completion(.failure(FlutterError(.mobileAuthInProgress))) return } - ONGUserClient.sharedInstance().handleOTPMobileAuthRequest(otp, delegate: self) + flowStarted = true + + let delegate = MobileAuthDelegate(handleMobileAuthCompletion: completion) + SharedUserClient.instance.handleOTPMobileAuthRequest(otp: otp, delegate: delegate) } func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { Logger.log("enrollMobileAuthentication", sender: self) - guard let _ = ONGUserClient.sharedInstance().authenticatedUserProfile() else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) - return - } - - ONGClient.sharedInstance().userClient.enroll { enrolled, error in + SharedUserClient.instance.enrollMobileAuth { error in guard let error = error else { - if enrolled == true { - completion(.success) - } else { - completion(.failure(FlutterError(SdkError(.enrollmentFailed)))) - } - + completion(.success) return } @@ -79,43 +73,57 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { mobileAuthCallback = nil completion(.success) } -} -//MARK: - ONGMobileAuthRequestDelegate -extension MobileAuthHandler: ONGMobileAuthRequestDelegate { - func userClient(_: ONGUserClient, didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void, for request: ONGMobileAuthRequest) { + func setMobileAuthCallback(didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void) { mobileAuthCallback = confirmation + } + + func finishMobileAuthenticationFlow() { + flowStarted = false + } +} + +//MARK: - MobileAuthRequestDelegate +class MobileAuthDelegate: MobileAuthRequestDelegate { + private var handleMobileAuthCompletion: (Result) -> Void + + init(handleMobileAuthCompletion: @escaping (Result) -> Void) { + self.handleMobileAuthCompletion = handleMobileAuthCompletion + } + + func userClient(_ userClient: UserClient, didReceiveConfirmation confirmation: @escaping (Bool) -> Void, for request: MobileAuthRequest) { + BridgeConnector.shared?.toMobileAuthHandler.setMobileAuthCallback(didReceiveConfirmationChallenge: confirmation) SwiftOneginiPlugin.flutterApi?.n2fOpenAuthOtp(message: request.message) {} } - func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge, for request: ONGMobileAuthRequest) { - //@todo will need this for PUSH + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge, for request: MobileAuthRequest) { + //@todo will need this for PUSH } - func userClient(_: ONGUserClient, didReceive challenge: ONGBiometricChallenge, for request: ONGMobileAuthRequest) { + func userClient(_ userClient: UserClient, didReceiveBiometricChallenge challenge: BiometricChallenge, for request: MobileAuthRequest) { //@todo will need this for PUSH } - func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishAuthenticationChallenge, for request: ONGMobileAuthRequest) { + func userClient(_ userClient: UserClient, didReceiveCustomAuthFinishAuthenticationChallenge challenge: CustomAuthFinishAuthenticationChallenge, for request: MobileAuthRequest) { //@todo will need this for PUSH Custom } - func userClient(_ userClient: ONGUserClient, didFailToHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, error: Error) { + func userClient(_ userClient: UserClient, didFailToHandleRequest request: MobileAuthRequest, authenticator: Authenticator?, error: Error) { + BridgeConnector.shared?.toMobileAuthHandler.finishMobileAuthenticationFlow() SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} + if error.code == ONGGenericError.actionCancelled.rawValue { - handleMobileAuthCompletion?(.failure(FlutterError(SdkError(.authenticationCancelled)))) + self.handleMobileAuthCompletion(.failure(FlutterError(SdkError(.authenticationCancelled)))) } else { let mappedError = ErrorMapper().mapError(error) - handleMobileAuthCompletion?(.failure(FlutterError(mappedError))) + self.handleMobileAuthCompletion(.failure(FlutterError(mappedError))) } - - handleMobileAuthCompletion = nil } - func userClient(_ userClient: ONGUserClient, didHandle request: ONGMobileAuthRequest, authenticator: ONGAuthenticator?, info customAuthenticatorInfo: ONGCustomInfo?) { + func userClient(_ userClient: UserClient, didHandleRequest request: MobileAuthRequest, authenticator: Authenticator?, info customAuthenticatorInfo: CustomInfo?) { + BridgeConnector.shared?.toMobileAuthHandler.finishMobileAuthenticationFlow() SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} - handleMobileAuthCompletion?(.success) - handleMobileAuthCompletion = nil + self.handleMobileAuthCompletion(.success) } } From 4a8600a2e440cb06cb07cc149c959c4bbb2b04c3 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 11:12:32 +0200 Subject: [PATCH 190/364] FP-71: Android: Remove no longer required files after pigeon impl. --- .../mobile/sdk/flutter/OnMethodCallMapper.kt | 14 ---- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 - .../mobile/sdk/flutter/OneginiPlugin.kt | 13 +--- .../mobile/sdk/flutter/constants/Constants.kt | 78 ------------------- 4 files changed, 2 insertions(+), 104 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt deleted file mode 100644 index d7e1e363..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OnMethodCallMapper.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.onegini.mobile.sdk.flutter - -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.METHOD_TO_CALL_NOT_FOUND -import com.onegini.mobile.sdk.flutter.constants.Constants -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import javax.inject.Inject - -class OnMethodCallMapper @Inject constructor(private val oneginiSDK: OneginiSDK) : MethodChannel.MethodCallHandler { - - override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index ce0986dd..0e8b90ca 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -16,7 +16,6 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), - METHOD_TO_CALL_NOT_FOUND(8007, "Method to call not found"), ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index 23aea0b6..cbaf1272 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -13,18 +13,12 @@ import javax.inject.Inject /** OneginiPlugin */ class OneginiPlugin : FlutterPlugin, PigeonInterface() { - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private lateinit var channel: MethodChannel - private lateinit var eventChannel: EventChannel + /// The api that will handle calls from Native -> Flutter lateinit var nativeApi : NativeCallFlutterApi - @Inject - lateinit var onMethodCallMapper: OnMethodCallMapper override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { // Pigeon setup + // We extend PigeonInterface which has all the implementations for when Flutters calls a native method. UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) ResourceMethodApi.setUp(flutterPluginBinding.binaryMessenger, this) nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) @@ -33,12 +27,9 @@ class OneginiPlugin : FlutterPlugin, PigeonInterface() { .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext, nativeApi)) .build() component.inject(this) - channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onegini") - channel.setMethodCallHandler(onMethodCallMapper) } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { UserClientApi.setUp(binding.binaryMessenger, null) - channel.setMethodCallHandler(null) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt index df7ef2fd..6a05701b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt @@ -2,84 +2,6 @@ package com.onegini.mobile.sdk.flutter.constants interface Constants { companion object { - /** events */ - const val EVENT_ERROR = "eventError" - - const val EVENT_OPEN_PIN = "eventOpenPin" - const val EVENT_CLOSE_PIN = "eventClosePin" - const val EVENT_OPEN_PIN_AUTH = "eventOpenPinAuth" - const val EVENT_CLOSE_PIN_AUTH = "eventClosePinAuth" - const val EVENT_NEXT_AUTHENTICATION_ATTEMPT = "eventNextAuthenticationAttempt" - - const val EVENT_OPEN_FINGERPRINT_AUTH = "eventOpenFingerprintAuth" - const val EVENT_RECEIVED_FINGERPRINT_AUTH = "eventReceivedFingerprintAuth" - const val EVENT_SHOW_SCANNING_FINGERPRINT_AUTH = "eventShowScanningFingerprintAuth" - const val EVENT_CLOSE_FINGERPRINT_AUTH = "eventCloseFingerprintAuth" - - const val EVENT_OPEN_AUTH_OTP = "eventOpenAuthOtp" - const val EVENT_CLOSE_AUTH_OTP = "eventCloseAuthOtp" - - const val EVENT_INIT_CUSTOM_REGISTRATION = "eventInitCustomRegistration" - const val EVENT_FINISH_CUSTOM_REGISTRATION = "eventFinishCustomRegistration" - - const val EVENT_HANDLE_REGISTERED_URL = "eventHandleRegisteredUrl" - - /** MethodsName */ - const val METHOD_START_APP = "startApp" - - const val METHOD_SUBMIT_CUSTOM_REGISTRATION_ACTION = "submitCustomRegistrationAction" - const val METHOD_CANCEL_CUSTOM_REGISTRATION_ACTION = "cancelCustomRegistrationAction" - - const val METHOD_GET_APP_TO_WEB_SINGLE_SIGN_ON = "getAppToWebSingleSignOn" - const val METHOD_CHANGE_PIN = "changePin" - const val METHOD_GET_USER_PROFILES = "getUserProfiles" - const val METHOD_GET_REDIRECT_URL = "getRedirectUrl" - - // Resources - const val METHOD_AUTHENTICATE_DEVICE = "authenticateDevice" - const val METHOD_AUTHENTICATE_USER_IMPLICITLY = "authenticateUserImplicitly" - const val METHOD_GET_RESOURCE_ANONYMOUS = "getResourceAnonymous" - const val METHOD_GET_RESOURCE = "getResource" - const val METHOD_GET_IMPLICIT_RESOURCE = "getImplicitResource" - const val METHOD_GET_UNAUTHENTICATED_RESOURCE = "getUnauthenticatedResource" - - // Registration - const val METHOD_REGISTER_USER = "registerUser" - const val METHOD_HANDLE_REGISTERED_URL = "handleRegisteredUserUrl" - const val METHOD_CANCEL_BROWSER_REGISTRATION = "cancelBrowserRegistration" - const val METHOD_DENY_PIN_REGISTRATION_REQUEST = "denyPinRegistrationRequest" - const val METHOD_ACCEPT_PIN_REGISTRATION_REQUEST = "acceptPinRegistrationRequest" - const val METHOD_GET_IDENTITY_PROVIDERS = "getIdentityProviders" - const val METHOD_DEREGISTER_USER = "deregisterUser" - - // Authentication - const val METHOD_ACCEPT_PIN_AUTHENTICATION_REQUEST = "acceptPinAuthenticationRequest" - const val METHOD_DENY_PIN_AUTHENTICATION_REQUEST = "denyPinAuthenticationRequest" - const val METHOD_GET_REGISTERED_AUTHENTICATORS = "getRegisteredAuthenticators" - const val METHOD_GET_ALL_NOT_REGISTERED_AUTHENTICATORS = "getAllNotRegisteredAuthenticators" - const val METHOD_GET_ALL_AUTHENTICATORS = "getAllAuthenticators" - const val METHOD_SET_PREFERRED_AUTHENTICATOR = "setPreferredAuthenticator" - const val METHOD_REGISTER_AUTHENTICATOR = "registerAuthenticator" - const val METHOD_DEREGISTER_AUTHENTICATOR = "deregisterAuthenticator" - const val METHOD_AUTHENTICATE_USER = "authenticateUser" - const val METHOD_LOGOUT = "logout" - - // Fingerprint - const val METHOD_ACCEPT_FINGERPRINT_AUTHENTICATION_REQUEST = - "acceptFingerprintAuthenticationRequest" - const val METHOD_DENY_FINGERPRINT_AUTHENTICATION_REQUEST = - "denyFingerprintAuthenticationRequest" - const val METHOD_FINGERPRINT_FALL_BACK_TO_PIN = "fingerprintFallbackToPin" - - // Otp - const val METHOD_HANDLE_MOBILE_AUTH_WITH_OTP = "handleMobileAuthWithOtp" - const val METHOD_ACCEPT_OTP_AUTHENTICATION_REQUEST = "acceptOtpAuthenticationRequest" - const val METHOD_DENY_OTP_AUTHENTICATION_REQUEST = "denyOtpAuthenticationRequest" - - const val METHOD_VALIDATE_PIN_WITH_POLICY = "validatePinWithPolicy" - const val METHOD_GET_ACCESS_TOKEN = "getAccessToken" - const val METHOD_GET_AUTHENTICATED_USER_PROFILE = "getAuthenticatedUserProfile" - /** HTTP Response properties */ const val RESPONSE_STATUS_CODE = "statusCode" const val RESPONSE_HEADERS = "headers" From 9cefeb853bdcfd23f9c187c96315d26f633b70d9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 29 Mar 2023 11:14:31 +0200 Subject: [PATCH 191/364] FP-69 readd qr logic --- example/lib/screens/user_screen.dart | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 4705b6ee..e760f444 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -306,12 +306,10 @@ class Home extends StatelessWidget { authWithOpt(BuildContext context) async { Onegini.instance.setEventContext(context); - // var data = await Navigator.push( - // context, - // MaterialPageRoute(builder: (_) => QrScanScreen()), - // ); - - var data = "eyJ0cmFuc2FjdGlvbl9pZCI6ImZhOTEwYTI2LTE1N2YtNGNkMy04YzczLWFjYzM0NzNlZmRlMyIsIm90cCI6ImZXbDdmcUxOSHdTaTBGQ0VRcHRvTUE9PSJ9"; + var data = await Navigator.push( + context, + MaterialPageRoute(builder: (_) => QrScanScreen()), + ); if (data != null) { await Onegini.instance.userClient From 9875f3ce3eb669c673b03c975e3ec9c0e96e18f7 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 11:21:27 +0200 Subject: [PATCH 192/364] FP-71: Fixup podspec --- example/ios/Podfile.lock | 2 +- ios/onegini.podspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index d0defe9b..531de25e 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de + url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/ios/onegini.podspec b/ios/onegini.podspec index 84a96261..bae8e33e 100644 --- a/ios/onegini.podspec +++ b/ios/onegini.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.platform = :ios, '13.0' # *************************** - s.dependency 'OneginiSDKiOS' + s.dependency 'OneginiSDKiOS', '~> 12.1.0' # *************************** # Flutter.framework does not contain a i386 slice. From 54b809295e2b1967ab7c4e1dd0b7965393e75a30 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 11:24:19 +0200 Subject: [PATCH 193/364] FP-71: iOS: Remove no longer needed files/constants --- ios/Classes/Constants.swift | 17 ----------------- ios/Classes/SwiftOneginiPlugin.swift | 25 ------------------------- 2 files changed, 42 deletions(-) delete mode 100644 ios/Classes/Constants.swift diff --git a/ios/Classes/Constants.swift b/ios/Classes/Constants.swift deleted file mode 100644 index 341ae2fe..00000000 --- a/ios/Classes/Constants.swift +++ /dev/null @@ -1,17 +0,0 @@ -import Foundation - -enum Constants { - enum Routes { - - static let startApp = "startApp" - - //otp - static let handleMobileAuthWithOtp = "handleMobileAuthWithOtp" - - //resources - static let getResourceAnonymous = "getResourceAnonymous" - static let getResource = "getResource" - static let getImplicitResource = "getImplicitResource" - static let unauthenticatedRequest = "getUnauthenticatedResource" - } -} diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 2fb4c9da..130ca7c4 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -292,11 +292,6 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc static var flutterApi: NativeCallFlutterApi? public static func register(with registrar: FlutterPluginRegistrar) { - // FIXME: We can remove this once we have moved all functions to Pigeon - // Init old communication - let channel = FlutterMethodChannel(name: "onegini", binaryMessenger: registrar.messenger()) - let instance = SwiftOneginiPlugin() - registrar.addMethodCallDelegate(instance, channel: channel) // Init Pigeon communication let messenger: FlutterBinaryMessenger = registrar.messenger() let api = SwiftOneginiPlugin() @@ -304,24 +299,4 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: api) flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - Logger.log("call.method: \(call.method)", sender: self, logType: .log) - let _arg = call.arguments as! [String: Any]? - if ((_arg) != nil) { - for key in _arg!.keys { - Logger.log("key: " + key) - let val = _arg?[key] - Logger.log("value: " + String(describing: val)) - } - } - - switch call.method { - - default: do { - Logger.log("Method wasn't handled: " + call.method) - result(FlutterMethodNotImplemented) - } - } - } } From 329658309c0a11ada8247bbb7516f832585a1feb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 11:25:57 +0200 Subject: [PATCH 194/364] FP-71: Remove unused helper class --- .../NativeBridge/Helpers/Extensions.swift | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 ios/Classes/NativeBridge/Helpers/Extensions.swift diff --git a/ios/Classes/NativeBridge/Helpers/Extensions.swift b/ios/Classes/NativeBridge/Helpers/Extensions.swift deleted file mode 100644 index de4cb2d5..00000000 --- a/ios/Classes/NativeBridge/Helpers/Extensions.swift +++ /dev/null @@ -1,28 +0,0 @@ -import Foundation - -extension String { - static func stringify(json: Any, prettyPrinted: Bool = false) -> String { - var options: JSONSerialization.WritingOptions = [] - if prettyPrinted { - options = JSONSerialization.WritingOptions.prettyPrinted - } - - do { - let data = try JSONSerialization.data(withJSONObject: json, options: options) - if let string = String(data: data, encoding: String.Encoding.utf8) { - return string - } - } catch { - Logger.log("String.stringify.error: \(error)") - } - - return "" - } - - func base64Encoded() -> String? { - if let data = self.data(using: .utf8) { - return data.base64EncodedString() - } - return nil - } -} From a2a1810fbb1c1528cd08c9c231906ff70168f5e6 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 11:42:31 +0200 Subject: [PATCH 195/364] FP-57: Rename browser-authentication error to browser Registration --- .../com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 2 +- .../sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt | 4 ++-- .../mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index ce0986dd..1ac4d564 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -12,7 +12,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), - BROWSER_AUTHENTICATION_NOT_IN_PROGRESS(8040, "Browser Authentication is currently not in progress"), + BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt index 9adba62a..8ae66654 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt @@ -2,13 +2,13 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS import javax.inject.Inject class CancelBrowserRegistrationUseCase @Inject constructor() { operator fun invoke(): Result { return when (val browserCallback = BrowserRegistrationRequestHandler.callback) { - null -> Result.failure(SdkError(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + null -> Result.failure(SdkError(BROWSER_REGISTRATION_NOT_IN_PROGRESS).pigeonError()) else -> { browserCallback.denyRegistration() BrowserRegistrationRequestHandler.callback = null diff --git a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt index c4ba45c1..6ab75bf9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt @@ -1,7 +1,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiBrowserRegistrationCallback -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase @@ -29,7 +29,7 @@ class CancelBrowserRegistrationUseCaseTest { BrowserRegistrationRequestHandler.callback = null val result = cancelBrowserRegistrationUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(BROWSER_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(BROWSER_REGISTRATION_NOT_IN_PROGRESS, result) } @Test From 53454f8195f28295528a882f543ca7e9a835e107 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 29 Mar 2023 16:31:30 +0200 Subject: [PATCH 196/364] FP-33 Add recommended flutter linter and perform fixes on highlighted issues --- analysis_options.yaml | 29 +++++++++++++++++++ example/ios/Podfile.lock | 2 +- example/lib/onegini_listener.dart | 2 -- example/lib/screens/pin_request_screen.dart | 2 +- example/lib/screens/user_screen.dart | 1 - .../onegini_pin_registration_callback.dart | 1 - .../onegini_registration_callback.dart | 1 - lib/model/onegini_error.dart | 8 ++--- lib/onegini.dart | 2 +- lib/onegini_event_listener.dart | 3 -- pubspec.yaml | 1 + 11 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 analysis_options.yaml diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 00000000..61b6c4de --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 531de25e..d0defe9b 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -78,7 +78,7 @@ SPEC CHECKSUMS: qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 + url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart index 7b45c1fa..a217ef02 100644 --- a/example/lib/onegini_listener.dart +++ b/example/lib/onegini_listener.dart @@ -1,10 +1,8 @@ // @dart = 2.10 -import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/model/authentication_attempt.dart'; -import 'package:onegini/model/onegini_error.dart'; import 'package:onegini/model/onegini_event.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/onegini_event_listener.dart'; diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index d8f48258..046a0cb4 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -24,7 +24,7 @@ class PinRequestScreen extends StatefulWidget { } class _PinRequestScreenState extends State { - var pinCode = new List(5); + var pinCode = List.filled(5, ""); enterNum(String num) { for (var i = 0; i < pinCode.length; i++) { diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 054bd769..0f22f2d4 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -12,7 +12,6 @@ import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:onegini/pigeon.dart'; -import 'package:onegini/model/request_details.dart'; import '../main.dart'; import 'login_screen.dart'; diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index a675e170..146edae8 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -13,7 +13,6 @@ class OneginiPinRegistrationCallback { } /// Accepts pin registration and sent [pin] to the OneginiSdk. - @Deprecated("message") Future acceptAuthenticationRequest( BuildContext? context, String pin) async { Onegini.instance.setEventContext(context); diff --git a/lib/callbacks/onegini_registration_callback.dart b/lib/callbacks/onegini_registration_callback.dart index 60188aa0..cd043b5c 100644 --- a/lib/callbacks/onegini_registration_callback.dart +++ b/lib/callbacks/onegini_registration_callback.dart @@ -1,6 +1,5 @@ import 'package:onegini/pigeon.dart'; -import '../onegini.dart'; /// A callback for registration. class OneginiRegistrationCallback { diff --git a/lib/model/onegini_error.dart b/lib/model/onegini_error.dart index f30b89e0..44f2ab72 100644 --- a/lib/model/onegini_error.dart +++ b/lib/model/onegini_error.dart @@ -20,10 +20,10 @@ OneginiError oneginiErrorFromJson(dynamic data) { if (value != null) { return OneginiError.fromJson(value); } else { - var _error = OneginiError(); - _error.code = 8001; - _error.message = data; - return _error; + var error = OneginiError(); + error.code = 8001; + error.message = data; + return error; } } diff --git a/lib/onegini.dart b/lib/onegini.dart index d9c36f35..209c7f05 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -49,7 +49,7 @@ class Onegini { }) async { _eventListener = eventListener; try { - var customIdentityProviderConfigsJson; + List? customIdentityProviderConfigsJson; if (customIdentityProviderConfigs != null) { customIdentityProviderConfigsJson = [ for (var customIdentityProviderConfig diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 2fd79cc1..320fc152 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,10 +1,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/model/onegini_error.dart' as deprecatedError; import 'package:onegini/pigeon.dart'; -import 'constants/constants.dart'; import 'model/authentication_attempt.dart'; -import 'model/onegini_error.dart'; import 'model/onegini_event.dart'; /// Extend from this class to describe the events that will take place inside OneginiSDK diff --git a/pubspec.yaml b/pubspec.yaml index d953057c..081d31b5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,6 +12,7 @@ dependencies: sdk: flutter dev_dependencies: + flutter_lints: ^2.0.1 flutter_test: sdk: flutter pigeon: 9.1.1 From b7560097b57042eebe30655eb386d67c28225c01 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 14:56:57 +0200 Subject: [PATCH 197/364] FP-57: Don't expose the pin cr. callback and throw correct error when not in progress Previously we exposed the callback through a companion object. This is not desirable as anything can happen to that object outside of the class. This commit moves all the logic into the handler class and exposes two public methods to interact with the callback which will throw errors if the callback is null. This commit also updates the error thrown during pin creation as pin creation should not give the error for registration_not_in_progress as it's something else. --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../flutter/errors/FlutterPluginException.kt | 3 +- .../sdk/flutter/handlers/PinRequestHandler.kt | 22 +++++++++++-- .../mobile/sdk/flutter/helpers/SdkError.kt | 2 +- .../PinRegistrationRequestAcceptUseCase.kt | 13 ++------ .../PinRegistrationRequestDenyUseCase.kt | 13 ++------ ...PinRegistrationRequestAcceptUseCaseTest.kt | 32 ++++++++++++++----- .../PinRegistrationRequestDenyUseCaseTest.kt | 27 ++++++++++++---- 8 files changed, 74 insertions(+), 39 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 1ac4d564..b56d785c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -13,6 +13,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), + PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt index 1237c039..977d8775 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt @@ -1,7 +1,8 @@ package com.onegini.mobile.sdk.flutter.errors import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.helpers.SdkError -class FlutterPluginException constructor(var errorType: Int, message: String): Exception(message) { +class FlutterPluginException constructor(var errorType: Int, message: String): SdkError(errorType, message) { constructor(error: OneWelcomeWrapperErrors) : this(error.code, error.message) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index 52e06820..99e894e0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -4,6 +4,9 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.android.handlers.request.OneginiCreatePinRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PIN_CREATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWOneginiError import javax.inject.Inject @@ -12,9 +15,7 @@ import javax.inject.Singleton @Singleton class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiCreatePinRequestHandler { - companion object { - var callback: OneginiPinCallback? = null - } + private var callback: OneginiPinCallback? = null override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { callback = oneginiPinCallback @@ -26,6 +27,21 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu } override fun finishPinCreation() { + callback = null nativeApi.n2fClosePin { } } + + fun onPinProvided(pin: CharArray): Result { + return callback?.let { + it.acceptAuthenticationRequest(pin) + Result.success(Unit) + } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun cancelPin(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index 3c07acbe..b1722132 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -10,7 +10,7 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import io.flutter.plugin.common.MethodChannel import okhttp3.Response -class SdkError: Exception { +open class SdkError: Exception { private val code: Int override val message: String private val details: MutableMap = mutableMapOf() diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt index 3bef9aad..9a71e2ef 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt @@ -1,20 +1,13 @@ package com.onegini.mobile.sdk.flutter.useCases +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinRegistrationRequestAcceptUseCase @Inject constructor() { +class PinRegistrationRequestAcceptUseCase @Inject constructor(private val pinRequestHandler: PinRequestHandler) { operator fun invoke(pin: String): Result { - return when (val pinCallback = PinRequestHandler.callback) { - null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - pinCallback.acceptAuthenticationRequest(pin.toCharArray()) - Result.success(Unit) - } - } + return pinRequestHandler.onPinProvided(pin.toCharArray()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt index 1c13097e..19839947 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt @@ -1,20 +1,13 @@ package com.onegini.mobile.sdk.flutter.useCases +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinRegistrationRequestDenyUseCase @Inject constructor() { +class PinRegistrationRequestDenyUseCase @Inject constructor(private val pinRequestHandler: PinRequestHandler) { operator fun invoke(): Result { - return when (val pinCallback = PinRequestHandler.callback) { - null -> Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - pinCallback.denyAuthenticationRequest() - Result.success(Unit) - } - } + return pinRequestHandler.cancelPin() } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index 3df1e785..47940f81 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestAcceptUseCase import org.junit.Assert import org.junit.Before @@ -21,26 +23,40 @@ class PinRegistrationRequestAcceptUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var nativeApi: NativeCallFlutterApi + + @Mock + lateinit var oneginiPinCallback: OneginiPinCallback + lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase + lateinit var pinRequestHandler: PinRequestHandler + @Before - fun attach() { - pinRegistrationRequestAcceptUseCase = PinRegistrationRequestAcceptUseCase() + fun setup() { + pinRequestHandler = PinRequestHandler(nativeApi) + pinRegistrationRequestAcceptUseCase = PinRegistrationRequestAcceptUseCase(pinRequestHandler) } @Test - fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinRequestHandler.callback = null - + fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinRegistrationRequestAcceptUseCase("12345").exceptionOrNull() - SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) + + SdkErrorAssert.assertEquals(PIN_CREATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinRequestHandler.callback = oneginiPinCallbackMock + WhenPinCreationStarted() val result = pinRegistrationRequestAcceptUseCase("12345").getOrNull() + Assert.assertEquals(Unit, result) } + + private fun WhenPinCreationStarted() { + // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler + pinRequestHandler.startPinCreation(UserProfile("123456"), oneginiPinCallback, 5) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index 0dd0748f..b4dc4ffe 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestDenyUseCase import org.junit.Assert import org.junit.Before @@ -21,26 +23,39 @@ class PinRegistrationRequestDenyUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var nativeApi: NativeCallFlutterApi + + @Mock + lateinit var oneginiPinCallback: OneginiPinCallback + lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase + lateinit var pinRequestHandler: PinRequestHandler + @Before fun attach() { - pinRegistrationRequestDenyUseCase = PinRegistrationRequestDenyUseCase() + pinRequestHandler = PinRequestHandler(nativeApi) + pinRegistrationRequestDenyUseCase = PinRegistrationRequestDenyUseCase(pinRequestHandler) } @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinRequestHandler.callback = null - val result = pinRegistrationRequestDenyUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(REGISTRATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(PIN_CREATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinRequestHandler.callback = oneginiPinCallbackMock + WhenPinCreationStarted() val result = pinRegistrationRequestDenyUseCase().getOrNull() Assert.assertEquals(Unit, result) } + + + private fun WhenPinCreationStarted() { + // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler + pinRequestHandler.startPinCreation(UserProfile("123456"), oneginiPinCallback, 5) + } } From c07c53bbd73170db96179083a42a6d6a127d510b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 15:12:57 +0200 Subject: [PATCH 198/364] FP-57: Move pinAuthentication callback nullchecking to handler Previously we were exposing the pin callback through a companion object. This commit removes the companion object and exposes calls for it through public methods that throw if the callback does not exist --- .../PinAuthenticationRequestHandler.kt | 22 +++++++++++-- .../PinAuthenticationRequestAcceptUseCase.kt | 13 ++------ .../PinAuthenticationRequestDenyUseCase.kt | 13 ++------ ...nAuthenticationRequestAcceptUseCaseTest.kt | 28 +++++++++++++---- ...PinAuthenticationRequestDenyUseCaseTest.kt | 31 +++++++++++++++---- 5 files changed, 72 insertions(+), 35 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index a159132a..a4f098fd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -4,6 +4,9 @@ import com.onegini.mobile.sdk.android.handlers.request.OneginiPinAuthenticationR import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticationAttempt import javax.inject.Inject @@ -11,9 +14,7 @@ import javax.inject.Singleton @Singleton class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiPinAuthenticationRequestHandler { - companion object { - var callback: OneginiPinCallback? = null - } + private var callback: OneginiPinCallback? = null override fun startAuthentication(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, attemptCounter: AuthenticationAttemptCounter) { callback = oneginiPinCallback @@ -27,5 +28,20 @@ class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: override fun finishAuthentication() { nativeApi.n2fClosePinAuth { } + callback = null + } + + fun acceptAuthenticationRequest(pin: CharArray): Result { + return callback?.let { + it.acceptAuthenticationRequest(pin) + Result.success(Unit) + } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun denyAuthenticationRequest(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt index 00cbdf6c..b2f84901 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt @@ -1,20 +1,13 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinAuthenticationRequestAcceptUseCase @Inject constructor() { +class PinAuthenticationRequestAcceptUseCase @Inject constructor(private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler) { operator fun invoke(pin: String): Result { - return when (val pinCallback = PinAuthenticationRequestHandler.callback) { - null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - pinCallback.acceptAuthenticationRequest(pin.toCharArray()) - Result.success(Unit) - } - } + return pinAuthenticationRequestHandler.acceptAuthenticationRequest(pin.toCharArray()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt index c9a42123..229ef25a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt @@ -1,20 +1,13 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinAuthenticationRequestDenyUseCase @Inject constructor() { +class PinAuthenticationRequestDenyUseCase @Inject constructor(private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler) { operator fun invoke(): Result { - return when (val pinCallback = PinAuthenticationRequestHandler.callback) { - null -> Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - pinCallback.denyAuthenticationRequest() - Result.success(Unit) - } - } + return pinAuthenticationRequestHandler.denyAuthenticationRequest() } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 4d74f200..5fa6d539 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -1,9 +1,12 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUseCase import org.junit.Assert import org.junit.Before @@ -21,26 +24,39 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var nativeApi: NativeCallFlutterApi + + @Mock + lateinit var authenticationAttemptCounter: AuthenticationAttemptCounter + lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase + lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler @Before - fun attach() { - pinAuthenticationRequestAcceptUseCase = PinAuthenticationRequestAcceptUseCase() + fun before() { + pinAuthenticationRequestHandler = PinAuthenticationRequestHandler(nativeApi) + pinAuthenticationRequestAcceptUseCase = PinAuthenticationRequestAcceptUseCase(pinAuthenticationRequestHandler) } @Test - fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinAuthenticationRequestHandler.callback = null - + fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinAuthenticationRequestAcceptUseCase("12345").exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinAuthenticationRequestHandler.callback = oneginiPinCallbackMock + WhenPinAuthenticationStarted() val result = pinAuthenticationRequestAcceptUseCase("12345").getOrNull() + Assert.assertEquals(Unit, result) } + + private fun WhenPinAuthenticationStarted() { + // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler + pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index 5fd37b6b..e47bbfa5 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -1,9 +1,13 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback +import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi +import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCase import org.junit.Assert import org.junit.Before @@ -21,26 +25,41 @@ class PinAuthenticationRequestDenyUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var nativeApi: NativeCallFlutterApi + + @Mock + lateinit var authenticationAttemptCounter: AuthenticationAttemptCounter + lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase + lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler + + @Before - fun attach() { - pinAuthenticationRequestDenyUseCase = PinAuthenticationRequestDenyUseCase() + fun before() { + pinAuthenticationRequestHandler = PinAuthenticationRequestHandler(nativeApi) + pinAuthenticationRequestDenyUseCase = PinAuthenticationRequestDenyUseCase(pinAuthenticationRequestHandler) } @Test - fun `When no pin registration callback is set, Then it should resolve with an error`() { - PinAuthenticationRequestHandler.callback = null - + fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinAuthenticationRequestDenyUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - PinAuthenticationRequestHandler.callback = oneginiPinCallbackMock + WhenPinAuthenticationStarted() val result = pinAuthenticationRequestDenyUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + private fun WhenPinAuthenticationStarted() { + // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler + pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) + } } From 8166b6c9b02a44830fac1c25ad5bae75cea15398 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 15:42:39 +0200 Subject: [PATCH 199/364] FP-57: Move fingerprint callback checking to handler Previously, we exposed the callback through a companion object. This commit makes the callback not staticly accessible and adds public methods to communicate with the callback. --- ...FingerprintAuthenticationRequestHandler.kt | 24 +++++++++++++++++-- ...printAuthenticationRequestAcceptUseCase.kt | 12 ++-------- ...erprintAuthenticationRequestDenyUseCase.kt | 12 ++-------- .../FingerprintFallbackToPinUseCase.kt | 12 ++-------- ...tAuthenticationRequestAcceptUseCaseTest.kt | 21 ++++++++++++---- ...intAuthenticationRequestDenyUseCaseTest.kt | 21 ++++++++++++---- .../FingerprintFallbackToPinUseCaseTest.kt | 20 ++++++++++++---- 7 files changed, 76 insertions(+), 46 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt index 74f4bbf0..f11cfcd0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt @@ -3,6 +3,8 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiFingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject import javax.inject.Singleton @@ -10,6 +12,7 @@ import javax.inject.Singleton @Singleton class FingerprintAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiFingerprintAuthenticationRequestHandler { + private var fingerprintCallback: OneginiFingerprintCallback? = null override fun startAuthentication(userProfile: UserProfile, oneginiFingerprintCallback: OneginiFingerprintCallback) { fingerprintCallback = oneginiFingerprintCallback nativeApi.n2fOpenFingerprintScreen { } @@ -27,7 +30,24 @@ class FingerprintAuthenticationRequestHandler @Inject constructor(private val na nativeApi.n2fCloseFingerprintScreen { } } - companion object { - var fingerprintCallback: OneginiFingerprintCallback? = null + fun acceptAuthenticationRequest(): Result { + return fingerprintCallback?.let { + it.acceptAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun denyAuthenticationRequest(): Result { + return fingerprintCallback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun fallbackToPin(): Result { + return fingerprintCallback?.let { + it.fallbackToPin() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt index a4761031..9c21ea6a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestAcceptUseCase.kt @@ -1,20 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton -class FingerprintAuthenticationRequestAcceptUseCase @Inject constructor() { +class FingerprintAuthenticationRequestAcceptUseCase @Inject constructor(private val fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler) { operator fun invoke(): Result { - return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { - null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - fingerprintCallback.acceptAuthenticationRequest() - Result.success(Unit) - } - } + return fingerprintAuthenticationRequestHandler.acceptAuthenticationRequest() } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt index 0c32dc14..94c3aa30 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintAuthenticationRequestDenyUseCase.kt @@ -1,20 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton -class FingerprintAuthenticationRequestDenyUseCase @Inject constructor() { +class FingerprintAuthenticationRequestDenyUseCase @Inject constructor(private val fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler) { operator fun invoke(): Result { - return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { - null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - fingerprintCallback.denyAuthenticationRequest() - Result.success(Unit) - } - } + return fingerprintAuthenticationRequestHandler.denyAuthenticationRequest() } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt index 233d36de..03aac076 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/FingerprintFallbackToPinUseCase.kt @@ -1,20 +1,12 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler -import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject import javax.inject.Singleton @Singleton -class FingerprintFallbackToPinUseCase @Inject constructor() { +class FingerprintFallbackToPinUseCase @Inject constructor(private val fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler) { operator fun invoke(): Result { - return when (val fingerprintCallback = FingerprintAuthenticationRequestHandler.fingerprintCallback) { - null -> Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - fingerprintCallback.fallbackToPin() - Result.success(Unit) - } - } + return fingerprintAuthenticationRequestHandler.fallbackToPin() } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index b172c725..649c86e0 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestAcceptUseCase import org.junit.Assert import org.junit.Before @@ -18,26 +20,35 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + @Mock + lateinit var nativeApi: NativeCallFlutterApi + lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { - fingerprintAuthenticationRequestAcceptUseCase = FingerprintAuthenticationRequestAcceptUseCase() + fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) + fingerprintAuthenticationRequestAcceptUseCase = FingerprintAuthenticationRequestAcceptUseCase(fingerprintAuthenticationRequestHandler) } @Test - fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = null - + fun `When no fingerprint authentication callback is set, Then it should fail with an error`() { val result = fingerprintAuthenticationRequestAcceptUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + WhenFingerPrintHasStarted() val result = fingerprintAuthenticationRequestAcceptUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + fun WhenFingerPrintHasStarted() { + fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index 98194dd6..989bbf4c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestDenyUseCase import org.junit.Assert import org.junit.Before @@ -18,26 +20,35 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + @Mock + lateinit var nativeApi: NativeCallFlutterApi + lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase + lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { - fingerprintAuthenticationRequestDenyUseCase = FingerprintAuthenticationRequestDenyUseCase() + fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) + fingerprintAuthenticationRequestDenyUseCase = FingerprintAuthenticationRequestDenyUseCase(fingerprintAuthenticationRequestHandler) } @Test - fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = null - + fun `When no fingerprint authentication callback is set, Then it should fail with an error`() { val result = fingerprintAuthenticationRequestDenyUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + WhenFingerPrintHasStarted() val result = fingerprintAuthenticationRequestDenyUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + fun WhenFingerPrintHasStarted() { + fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 618facf7..1fd68ca1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase import org.junit.Assert import org.junit.Before @@ -18,26 +20,36 @@ class FingerprintFallbackToPinUseCaseTest { @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback + @Mock + lateinit var nativeApi: NativeCallFlutterApi + lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { - fingerprintFallbackToPinUseCase = FingerprintFallbackToPinUseCase() + fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) + fingerprintFallbackToPinUseCase = FingerprintFallbackToPinUseCase(fingerprintAuthenticationRequestHandler) } @Test fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = null - val result = fingerprintFallbackToPinUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - FingerprintAuthenticationRequestHandler.fingerprintCallback = oneginiFingerprintCallbackMock + WhenFingerPrintHasStarted() val result = fingerprintFallbackToPinUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + fun WhenFingerPrintHasStarted() { + fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) + } + } From c2f4761a3b18292b929b2d62dafd43dce8d988b9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 29 Mar 2023 16:56:59 +0200 Subject: [PATCH 200/364] fp-69 process feedback --- .../Handlers/MobileAuthHandler.swift | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index 4323880b..85aaa861 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -6,12 +6,12 @@ protocol MobileAuthConnectorToHandlerProtocol: AnyObject { func enrollMobileAuthentication(completion: @escaping (Result) -> Void) func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) func denyMobileAuthRequest(completion: @escaping (Result) -> Void) - func setMobileAuthCallback(didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void) + func setMobileAuthCallback(_ confirmation: @escaping (Bool) -> Void) } class MobileAuthHandler: NSObject { - var mobileAuthCallback: ((Bool) -> Void)? - var flowStarted: Bool = false + private var mobileAuthCallback: ((Bool) -> Void)? + private var isFlowInProgress: Bool = false } //MARK: - MobileAuthConnectorToHandlerProtocol @@ -20,18 +20,18 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { Logger.log("handleMobileAuthWithOtp", sender: self) // Check to prevent breaking iOS SDK; https://onewelcome.atlassian.net/browse/SDKIOS-987 - guard let _ = SharedUserClient.instance.authenticatedUserProfile else { + guard SharedUserClient.instance.authenticatedUserProfile != nil else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } // Prevent concurrent OTP mobile authentication flows at same time; https://onewelcome.atlassian.net/browse/SDKIOS-989 - if (flowStarted) { + guard !isFlowInProgress else { completion(.failure(FlutterError(.mobileAuthInProgress))) return } - flowStarted = true + isFlowInProgress = true let delegate = MobileAuthDelegate(handleMobileAuthCompletion: completion) SharedUserClient.instance.handleOTPMobileAuthRequest(otp: otp, delegate: delegate) @@ -74,12 +74,12 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { completion(.success) } - func setMobileAuthCallback(didReceiveConfirmationChallenge confirmation: @escaping (Bool) -> Void) { + func setMobileAuthCallback(_ confirmation: @escaping (Bool) -> Void) { mobileAuthCallback = confirmation } func finishMobileAuthenticationFlow() { - flowStarted = false + isFlowInProgress = false } } @@ -92,20 +92,20 @@ class MobileAuthDelegate: MobileAuthRequestDelegate { } func userClient(_ userClient: UserClient, didReceiveConfirmation confirmation: @escaping (Bool) -> Void, for request: MobileAuthRequest) { - BridgeConnector.shared?.toMobileAuthHandler.setMobileAuthCallback(didReceiveConfirmationChallenge: confirmation) + BridgeConnector.shared?.toMobileAuthHandler.setMobileAuthCallback(confirmation) SwiftOneginiPlugin.flutterApi?.n2fOpenAuthOtp(message: request.message) {} } func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge, for request: MobileAuthRequest) { - //@todo will need this for PUSH + // todo: will need this for PUSH } func userClient(_ userClient: UserClient, didReceiveBiometricChallenge challenge: BiometricChallenge, for request: MobileAuthRequest) { - //@todo will need this for PUSH + // todo: will need this for PUSH } func userClient(_ userClient: UserClient, didReceiveCustomAuthFinishAuthenticationChallenge challenge: CustomAuthFinishAuthenticationChallenge, for request: MobileAuthRequest) { - //@todo will need this for PUSH Custom + // todo: will need this for PUSH Custom } func userClient(_ userClient: UserClient, didFailToHandleRequest request: MobileAuthRequest, authenticator: Authenticator?, error: Error) { @@ -113,10 +113,10 @@ class MobileAuthDelegate: MobileAuthRequestDelegate { SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} if error.code == ONGGenericError.actionCancelled.rawValue { - self.handleMobileAuthCompletion(.failure(FlutterError(SdkError(.authenticationCancelled)))) + handleMobileAuthCompletion(.failure(FlutterError(SdkError(.authenticationCancelled)))) } else { let mappedError = ErrorMapper().mapError(error) - self.handleMobileAuthCompletion(.failure(FlutterError(mappedError))) + handleMobileAuthCompletion(.failure(FlutterError(mappedError))) } } @@ -124,6 +124,6 @@ class MobileAuthDelegate: MobileAuthRequestDelegate { BridgeConnector.shared?.toMobileAuthHandler.finishMobileAuthenticationFlow() SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} - self.handleMobileAuthCompletion(.success) + handleMobileAuthCompletion(.success) } } From 071f2c448d1e8a510054151c5e85d87be2b0a8cc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 16:48:03 +0200 Subject: [PATCH 201/364] FP-57: Update OTP authentication handler to not expose callback +tests This commit makes the callback private. It also updates the tests to work with the callback no longer being staticly accessible. It also adds tests to verify we're actaully calling the correct method on the onegini sdk callback. --- .../handlers/MobileAuthOtpRequestHandler.kt | 40 ++++++++----------- .../OtpAcceptAuthenticationRequestUseCase.kt | 4 +- .../OtpDenyAuthenticationRequestUseCase.kt | 4 +- ...pAcceptAuthenticationRequestUseCaseTest.kt | 32 +++++++++++++-- ...OtpDenyAuthenticationRequestUseCaseTest.kt | 34 ++++++++++++++-- 5 files changed, 78 insertions(+), 36 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index b6997f66..77af5f81 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithOtpRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject @@ -11,6 +11,9 @@ import javax.inject.Singleton @Singleton class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiMobileAuthWithOtpRequestHandler { + + private var callback: OneginiAcceptDenyCallback? = null + override fun startAuthentication( oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback: OneginiAcceptDenyCallback @@ -21,31 +24,20 @@ class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: Nat override fun finishAuthentication() { nativeApi.n2fCloseAuthOtp {} + callback = null } - companion object { - var callback: OneginiAcceptDenyCallback? = null - - fun acceptAuthenticationRequest(): Result { - return when (val authenticationRequestCallback = callback) { - null -> Result.failure(SdkError(OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - authenticationRequestCallback.acceptAuthenticationRequest() - callback = null - Result.success(Unit) - } - } - } + fun acceptAuthenticationRequest(): Result { + return callback?.let { + it.acceptAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } - fun denyAuthenticationRequest(): Result { - return when (val authenticationRequestCallback = callback) { - null -> Result.failure(SdkError(OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - else -> { - authenticationRequestCallback.denyAuthenticationRequest() - callback = null - Result.success(Unit) - } - } - } + fun denyAuthenticationRequest(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt index 26315dc0..26f9217c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpAcceptAuthenticationRequestUseCase.kt @@ -5,8 +5,8 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class OtpAcceptAuthenticationRequestUseCase @Inject constructor() { +class OtpAcceptAuthenticationRequestUseCase @Inject constructor(private val mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler) { operator fun invoke(): Result { - return MobileAuthOtpRequestHandler.acceptAuthenticationRequest() + return mobileAuthOtpRequestHandler.acceptAuthenticationRequest() } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt index af84d2dc..08529496 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/OtpDenyAuthenticationRequestUseCase.kt @@ -5,8 +5,8 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class OtpDenyAuthenticationRequestUseCase @Inject constructor() { +class OtpDenyAuthenticationRequestUseCase @Inject constructor(private val mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler) { operator fun invoke(): Result { - return MobileAuthOtpRequestHandler.denyAuthenticationRequest() + return mobileAuthOtpRequestHandler.denyAuthenticationRequest() } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt index c3bffbe7..01e2a4b1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback +import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase import org.junit.Assert import org.junit.Before @@ -11,32 +13,54 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class OtpAcceptAuthenticationRequestUseCaseTest { @Mock lateinit var oneginiAcceptDenyCallback: OneginiAcceptDenyCallback + @Mock + lateinit var oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest + + @Mock + lateinit var nativeApi: NativeCallFlutterApi + lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler @Before fun attach() { - otpAcceptAuthenticationRequestUseCase = OtpAcceptAuthenticationRequestUseCase() + mobileAuthOtpRequestHandler = MobileAuthOtpRequestHandler(nativeApi) + otpAcceptAuthenticationRequestUseCase = OtpAcceptAuthenticationRequestUseCase(mobileAuthOtpRequestHandler) } @Test fun `When no otp authentication callback is set, Then it should resolve with an error`() { - MobileAuthOtpRequestHandler.callback = null - val result = otpAcceptAuthenticationRequestUseCase().exceptionOrNull() + SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - MobileAuthOtpRequestHandler.callback = oneginiAcceptDenyCallback + WhenOTPAuthenticationHasStarted() val result = otpAcceptAuthenticationRequestUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + @Test + fun `When a otp authentication callback is set, Then it should call the accept on the sdk callback`() { + WhenOTPAuthenticationHasStarted() + + otpAcceptAuthenticationRequestUseCase().getOrNull() + + verify(oneginiAcceptDenyCallback).acceptAuthenticationRequest() + } + + private fun WhenOTPAuthenticationHasStarted() { + mobileAuthOtpRequestHandler.startAuthentication(oneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt index ac716f56..aa110d85 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback +import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler +import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase import org.junit.Assert import org.junit.Before @@ -11,32 +13,56 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class OtpDenyAuthenticationRequestUseCaseTest { @Mock lateinit var oneginiAcceptDenyCallback: OneginiAcceptDenyCallback + @Mock + lateinit var oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest + + @Mock + lateinit var nativeApi: NativeCallFlutterApi + lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase + lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler + @Before fun attach() { - otpDenyAuthenticationRequestUseCase = OtpDenyAuthenticationRequestUseCase() + mobileAuthOtpRequestHandler = MobileAuthOtpRequestHandler(nativeApi) + otpDenyAuthenticationRequestUseCase = OtpDenyAuthenticationRequestUseCase(mobileAuthOtpRequestHandler) + } @Test fun `When no otp authentication callback is set, Then it should resolve with an error`() { - MobileAuthOtpRequestHandler.callback = null - val result = otpDenyAuthenticationRequestUseCase().exceptionOrNull() SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) } @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - MobileAuthOtpRequestHandler.callback = oneginiAcceptDenyCallback + WhenOTPAuthenticationHasStarted() val result = otpDenyAuthenticationRequestUseCase().getOrNull() + Assert.assertEquals(Unit, result) } + + @Test + fun `When a otp authentication callback is set, Then it should call the deny on the sdk callback`() { + WhenOTPAuthenticationHasStarted() + + otpDenyAuthenticationRequestUseCase().getOrNull() + + verify(oneginiAcceptDenyCallback).denyAuthenticationRequest() + } + + private fun WhenOTPAuthenticationHasStarted() { + mobileAuthOtpRequestHandler.startAuthentication(oneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback) + } + } From 202ec400f00e9c3966ff271cf3434e2a5576e133 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 16:51:44 +0200 Subject: [PATCH 202/364] FP-57: Add more tests for PinAuthentication deny/accept --- .../sdk/PinAuthenticationRequestAcceptUseCaseTest.kt | 10 ++++++++++ .../sdk/PinAuthenticationRequestDenyUseCaseTest.kt | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 5fa6d539..445d2d72 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -14,6 +14,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinAuthenticationRequestAcceptUseCaseTest { @@ -55,6 +56,15 @@ class PinAuthenticationRequestAcceptUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin registration callback is set, Then it should call accept on the sdk callback`() { + WhenPinAuthenticationStarted() + + pinAuthenticationRequestAcceptUseCase("12345") + + verify(oneginiPinCallbackMock).acceptAuthenticationRequest("12345".toCharArray()) + } + private fun WhenPinAuthenticationStarted() { // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index e47bbfa5..24e3c494 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -15,6 +15,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinAuthenticationRequestDenyUseCaseTest { @@ -58,6 +59,15 @@ class PinAuthenticationRequestDenyUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin registration callback is set, Then it should call deny on the sdk callback`() { + WhenPinAuthenticationStarted() + + pinAuthenticationRequestDenyUseCase() + + verify(oneginiPinCallbackMock).denyAuthenticationRequest() + } + private fun WhenPinAuthenticationStarted() { // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) From 648992ef12d442bebdb08c83aa00d15ea743567a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 16:53:15 +0200 Subject: [PATCH 203/364] FP-57: Add more tests for PinRegistration accept/deny --- .../sdk/PinRegistrationRequestAcceptUseCaseTest.kt | 11 +++++++++++ .../sdk/PinRegistrationRequestDenyUseCaseTest.kt | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index 47940f81..a0dbc18a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -13,6 +13,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestAcceptUseCaseTest { @@ -55,6 +56,16 @@ class PinRegistrationRequestAcceptUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin registration callback is set, Then it should call accept on the sdk callback`() { + WhenPinCreationStarted() + + pinRegistrationRequestAcceptUseCase("12345") + + verify(oneginiPinCallback).acceptAuthenticationRequest("12345".toCharArray()) + } + + private fun WhenPinCreationStarted() { // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler pinRequestHandler.startPinCreation(UserProfile("123456"), oneginiPinCallback, 5) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index b4dc4ffe..a5c29496 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -13,6 +13,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestDenyUseCaseTest { @@ -53,6 +54,15 @@ class PinRegistrationRequestDenyUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin registration callback is set, Then it should call deny on the sdk callback`() { + WhenPinCreationStarted() + + pinRegistrationRequestDenyUseCase() + + verify(oneginiPinCallback).denyAuthenticationRequest() + } + private fun WhenPinCreationStarted() { // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler From adf5dae71e500d7a3757c63268589e38b6d74afc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 29 Mar 2023 16:56:03 +0200 Subject: [PATCH 204/364] FP-57: Add extra tests for fingerprint accept/deny/fallback --- ...ingerprintAuthenticationRequestAcceptUseCaseTest.kt | 10 ++++++++++ .../FingerprintAuthenticationRequestDenyUseCaseTest.kt | 10 ++++++++++ .../mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt | 10 ++++++++++ 3 files changed, 30 insertions(+) diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index 649c86e0..456d72f2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -13,6 +13,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintAuthenticationRequestAcceptUseCaseTest { @@ -48,6 +49,15 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin authentication callback is set, Then it should call accept on the sdk callback`() { + WhenFingerPrintHasStarted() + + fingerprintAuthenticationRequestAcceptUseCase() + + verify(oneginiFingerprintCallbackMock).acceptAuthenticationRequest() + } + fun WhenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index 989bbf4c..6f5afe2b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -13,6 +13,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintAuthenticationRequestDenyUseCaseTest { @@ -48,6 +49,15 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin authentication callback is set, Then it should call deny on the sdk callback`() { + WhenFingerPrintHasStarted() + + fingerprintAuthenticationRequestDenyUseCase() + + verify(oneginiFingerprintCallbackMock).denyAuthenticationRequest() + } + fun WhenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 1fd68ca1..7882e769 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -13,6 +13,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintFallbackToPinUseCaseTest { @@ -48,6 +49,15 @@ class FingerprintFallbackToPinUseCaseTest { Assert.assertEquals(Unit, result) } + @Test + fun `When a pin authentication callback is set, Then it should call fallbackToPin on the sdk callback`() { + WhenFingerPrintHasStarted() + + fingerprintFallbackToPinUseCase() + + verify(oneginiFingerprintCallbackMock).fallbackToPin() + } + fun WhenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } From 0de9b0e684d1de74dca99a48c6f804f312559adf Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 30 Mar 2023 13:17:00 +0200 Subject: [PATCH 205/364] fp-hotfix-pin fix for setting pin --- example/lib/screens/pin_request_screen.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index 046a0cb4..021fbfc2 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -24,7 +24,7 @@ class PinRequestScreen extends StatefulWidget { } class _PinRequestScreenState extends State { - var pinCode = List.filled(5, ""); + var pinCode = List.filled(5, null); enterNum(String num) { for (var i = 0; i < pinCode.length; i++) { From 678752ff4c5fe5a3666f47264ae4296f5a53a1c0 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 13:22:34 +0200 Subject: [PATCH 206/364] FP-71: Fix a bug where async function was not awaiting call --- lib/onegini.dart | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/onegini.dart b/lib/onegini.dart index d8435e24..3ec6e094 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -52,7 +52,11 @@ class Onegini { }) async { _eventListener = eventListener; NativeCallFlutterApi.setup(_eventListener); - api.startApplication(securityControllerClassName, configModelClassName, - customIdentityProviderConfigs, connectionTimeout, readTimeout); + await api.startApplication( + securityControllerClassName, + configModelClassName, + customIdentityProviderConfigs, + connectionTimeout, + readTimeout); } } From 2a77ac90ce027f0745b631720df5ed8b0073b1bc Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 13:35:39 +0200 Subject: [PATCH 207/364] FP-71: Comment styling change --- .../com/onegini/mobile/sdk/flutter/constants/Constants.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt index 6a05701b..4a57bf3f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk.flutter.constants interface Constants { companion object { - /** HTTP Response properties */ + // HTTP Response properties const val RESPONSE_STATUS_CODE = "statusCode" const val RESPONSE_HEADERS = "headers" const val RESPONSE_BODY = "body" From 1a58969d80d15b216a7a34464adc7197945084d4 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 13:52:21 +0200 Subject: [PATCH 208/364] FP-57: Implement failure on callback missing for custom registration --- .../Handlers/RegistrationHandler.swift | 27 +++++++++---------- .../OneginiModuleSwift+Register.swift | 8 +++--- ios/Classes/SwiftOneginiPlugin.swift | 12 ++++----- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index a7ae6208..d41f12db 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -1,14 +1,5 @@ import OneginiSDKiOS -protocol RegistrationConnectorToHandlerProtocol { - func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) - func processRedirectURL(url: String, webSignInType: Int) -> Result - func cancelBrowserRegistration() - func submitCustomRegistrationSuccess(_ data: String?) - func cancelCustomRegistration(_ error: String) - func currentChallenge() -> ONGCustomRegistrationChallenge? -} - enum WebSignInType: Int { case insideApp case safari @@ -131,7 +122,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { } } -extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { +extension RegistrationHandler { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { signUpCompletion = completion @@ -162,14 +153,22 @@ extension RegistrationHandler : RegistrationConnectorToHandlerProtocol { return .success } - func submitCustomRegistrationSuccess(_ data: String?) { - guard let customRegistrationChallenge = self.customRegistrationChallenge else { return } + func submitCustomRegistrationSuccess(_ data: String?, _ completion: @escaping (Result) -> Void) { + guard let customRegistrationChallenge = self.customRegistrationChallenge else { + completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) + return + } customRegistrationChallenge.sender.respond(withData: data, challenge: customRegistrationChallenge) + completion(.success) } - func cancelCustomRegistration(_ error: String) { - guard let customRegistrationChallenge = self.customRegistrationChallenge else { return } + func cancelCustomRegistration(_ error: String, _ completion: @escaping (Result) -> Void) { + guard let customRegistrationChallenge = self.customRegistrationChallenge else { + completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) + return + } customRegistrationChallenge.sender.cancel(customRegistrationChallenge) + completion(.success) } func cancelBrowserRegistration() { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 0d03bbac..afe6ac10 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -35,12 +35,12 @@ extension OneginiModuleSwift { return true } - func submitCustomRegistrationSuccess(_ data: String?) { - bridgeConnector.toRegistrationHandler.submitCustomRegistrationSuccess(data) + func submitCustomRegistrationSuccess(_ data: String?, completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationHandler.submitCustomRegistrationSuccess(data, completion) } - func submitCustomRegistrationError(_ error: String) { - bridgeConnector.toRegistrationHandler.cancelCustomRegistration(error) + func submitCustomRegistrationError(_ error: String, _ completion: @escaping (Result) -> Void) { + bridgeConnector.toRegistrationHandler.cancelCustomRegistration(error, completion) } public func cancelBrowserRegistration() -> Void { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 2d826b6b..d288d070 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -99,15 +99,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success) + OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) { result in + completion(result.mapError { $0 }) + } } func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success) + OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) { result in + completion(result.mapError { $0 }) + } } func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) { From 8c1fd6713cdbbb13740adedc91e30ef6956d7e1c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 14:40:47 +0200 Subject: [PATCH 209/364] FP-71: Codestyle changes --- ios/Classes/NativeBridge/OneginiModuleSwift.swift | 6 +----- ios/Classes/SwiftOneginiPlugin.swift | 8 ++++++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index 7ca2881b..c17bcdb3 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -18,11 +18,7 @@ public class OneginiModuleSwift: NSObject { } func startOneginiModule(httpConnectionTimeout: Int64?, callback: @escaping (Result) -> Void) { - if let httpConnectionTimeout = httpConnectionTimeout { - ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout))) - } else { - ONGClientBuilder().setHttpRequestTimeout(TimeInterval(5)) - } + ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout ?? 5))) ONGClientBuilder().build() ONGClient.sharedInstance().start { result, error in diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 130ca7c4..79f9a868 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -80,13 +80,17 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { - func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, completion: @escaping (Result) -> Void) { + func startApplication(securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: [OWCustomIdentityProvider]?, + connectionTimeout: Int64?, + readTimeout: Int64?, + completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout) { result in completion(result.mapError { $0 }) } } - func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.enrollMobileAuthentication() { result in completion(result.mapError { $0 }) From dd5a4e4102a111a180d1abde10c6c25d4909acf6 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 14:15:55 +0200 Subject: [PATCH 210/364] FP-57: iOS: Add failure on callback missing for browser registration --- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 3 +++ .../NativeBridge/Handlers/RegistrationHandler.swift | 8 ++++++-- .../ModuleExtensions/OneginiModuleSwift+Register.swift | 4 ++-- ios/Classes/SwiftOneginiPlugin.swift | 6 +++--- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 5bff117e..bb8889f4 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -13,6 +13,7 @@ enum OneWelcomeWrapperError: Int { case methodArgumentNotFound = 8036 case authenticationNotInProgress = 8037 case otpAuthenticationNotInProgress = 8039 + case browserRegistrationNotInProgress = 8040 // iOS only case providedUrlIncorrect = 8014 @@ -91,6 +92,8 @@ enum OneWelcomeWrapperError: Int { return "OTP Authentication is currently not in progress." case .mobileAuthInProgress: return "Mobile Authentication is already in progress and can not be performed concurrently." + case .browserRegistrationNotInProgress: + return "Browser registration is currently not in progress." } } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index d41f12db..3f1ff042 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -171,8 +171,12 @@ extension RegistrationHandler { completion(.success) } - func cancelBrowserRegistration() { - handleRedirectURL(url: nil) + func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) { + guard let browserRegistrationChallenge = self.browserRegistrationChallenge else { + completion(.failure(FlutterError(.browserRegistrationNotInProgress))) + return + } + browserRegistrationChallenge.sender.cancel(browserRegistrationChallenge) } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index afe6ac10..9fdca67b 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -43,8 +43,8 @@ extension OneginiModuleSwift { bridgeConnector.toRegistrationHandler.cancelCustomRegistration(error, completion) } - public func cancelBrowserRegistration() -> Void { - bridgeConnector.toRegistrationHandler.cancelBrowserRegistration() + public func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) -> Void { + bridgeConnector.toRegistrationHandler.cancelBrowserRegistration(completion) } func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index d288d070..517ff3bd 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -165,9 +165,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() - // FIXME: in the above function the completion is actually not yet used as that would create way to big of a refactor, so let's do it later in FP-?? - completion(.success) + OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() { result in + completion(result.mapError { $0 }) + } } func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { From ad18a8957705b4c05165609dca0c4257167bba70 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 15:06:26 +0200 Subject: [PATCH 211/364] FP-32: iOS: Install swiftlint pod --- example/ios/Podfile | 1 + example/ios/Podfile.lock | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/example/ios/Podfile b/example/ios/Podfile index 2a346f5f..6e6e4dad 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -33,6 +33,7 @@ require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelpe flutter_ios_podfile_setup target 'Runner' do + pod 'SwiftLint' use_frameworks! use_modular_headers! diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 531de25e..1ccd1fcb 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -28,6 +28,7 @@ PODS: - qr_code_scanner (0.2.0): - Flutter - MTBBarcodeScanner + - SwiftLint (0.50.3) - Toast (4.0.0) - Typhoon (4.0.9): - Typhoon/DeallocNotifier (= 4.0.9) @@ -45,12 +46,14 @@ DEPENDENCIES: - fluttertoast (from `.symlinks/plugins/fluttertoast/ios`) - onegini (from `.symlinks/plugins/onegini/ios`) - qr_code_scanner (from `.symlinks/plugins/qr_code_scanner/ios`) + - SwiftLint - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) SPEC REPOS: https://github.com/CocoaPods/Specs.git: - AFNetworking - MTBBarcodeScanner + - SwiftLint - Toast - Typhoon https://repo.onewelcome.com/artifactory/api/pods/cocoapods-public: @@ -76,10 +79,11 @@ SPEC CHECKSUMS: onegini: bcef895403897119a1f340413bc75b8c1328624c OneginiSDKiOS: 81e27e24e901cfe41e09f46b8c673fd5b5b855e9 qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e + SwiftLint: 77f7cb2b9bb81ab4a12fcc86448ba3f11afa50c6 Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 -PODFILE CHECKSUM: 1cb5957d05b3b5aee795396ab15eb158c5d9d312 +PODFILE CHECKSUM: e49c186fd5db1b7547d2a80e7096f4e0713e90f9 COCOAPODS: 1.11.3 From e6239ddf099a70a1af00a839f6d8ed92aee91ebf Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 15:10:53 +0200 Subject: [PATCH 212/364] FP-32: iOS: Add swiftlint in run script before build --- example/ios/Runner.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 8552c716..6b9ecbf2 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -483,7 +483,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; + shellScript = "${PODS_ROOT}/SwiftLint/swiftlint --fix && ${PODS_ROOT}/SwiftLint/swiftlint\n/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; }; 9F3EB958C6EFC2D5B75EAB9F /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; From 6d5f2773ea976aaed2b503a53515339c95e9f8ab Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 15:56:15 +0200 Subject: [PATCH 213/364] FP-32: Add .swiftlint.yml to exclude tests and include the devpod Flutter projects get set up by default without being able to compile the plugin by itself. It will add all the code as a development pod so we will need to add this one a bit hackish through the symlink that it creates. We also exclude the tests for now. --- example/ios/.swiftlint.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 example/ios/.swiftlint.yml diff --git a/example/ios/.swiftlint.yml b/example/ios/.swiftlint.yml new file mode 100644 index 00000000..0de63b0b --- /dev/null +++ b/example/ios/.swiftlint.yml @@ -0,0 +1,8 @@ +line_length: 200 +excluded: + - OneginiTests + - OneginiUITests + - .symlinks/plugins/onegini/ios/Classes/Pigeon.swift + +included: + - .symlinks/plugins/onegini/ios From 60e4229526906a32e471dd933a638a4eb6d12f42 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 16:00:05 +0200 Subject: [PATCH 214/364] FP-32: Lint AppDelegate.swift and remove unused code --- example/ios/Runner/AppDelegate.swift | 67 ++++++++++++++-------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift index 7bb3fd55..85d7686f 100644 --- a/example/ios/Runner/AppDelegate.swift +++ b/example/ios/Runner/AppDelegate.swift @@ -1,34 +1,33 @@ -import UIKit -import Flutter -import onegini -import OneginiSDKiOS - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - let exampleCustomEventIdentifier: String = "exemple_events" - - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - - let controller : FlutterViewController = window?.rootViewController as! FlutterViewController - - let methodChannel = FlutterMethodChannel(name: "example", - binaryMessenger: controller.binaryMessenger) - - let eventChannel = FlutterEventChannel(name: exampleCustomEventIdentifier, - binaryMessenger: controller.binaryMessenger) - - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } - - override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { - - let isOneginiUrlCallback: Bool = OneginiModuleSwift.sharedInstance.handleDeepLinkCallbackUrl(url) - debugPrint(isOneginiUrlCallback) - - return true - } -} +import UIKit + +import Flutter + +import onegini + +import OneginiSDKiOS + +@UIApplicationMain + +@objc class AppDelegate: FlutterAppDelegate { + override func application( + + _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + + } + + override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + + let isOneginiUrlCallback: Bool = OneginiModuleSwift.sharedInstance.handleDeepLinkCallbackUrl(url) + + debugPrint(isOneginiUrlCallback) + + return true + + } + +} From 07128dfb01c7b3b9e93c2c3be12fc61849cee868 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 16:09:23 +0200 Subject: [PATCH 215/364] FP-32: Change line endings to LF --- ios/Classes/SwiftOneginiPlugin.swift | 612 +++++++++++++-------------- 1 file changed, 306 insertions(+), 306 deletions(-) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 98a2c668..3383fccb 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -1,306 +1,306 @@ -import Flutter -import UIKit -import OneginiSDKiOS - -extension FlutterError: Error {} - -extension FlutterError { - convenience init(_ error: OneWelcomeWrapperError) { - let flutterError = SdkError(error).flutterError() - self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) - } - convenience init(_ error: SdkError) { - let flutterError = error.flutterError() - self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) - } -} - -extension OWUserProfile { - init(_ profile: UserProfile) { - self.profileId = profile.profileId - } - init(_ profile: ONGUserProfile) { - self.profileId = profile.profileId - } -} - -extension OWCustomInfo { - init(_ info: CustomInfo) { - status = Int64(info.status) - data = info.data - } - init(_ info: ONGCustomInfo) { - status = Int64(info.status) - data = info.data - } -} - -extension OWAuthenticator { - init(_ authenticator: ONGAuthenticator) { - id = authenticator.identifier - name = authenticator.name - isPreferred = authenticator.isPreferred - isRegistered = authenticator.isRegistered - authenticatorType = Int64(authenticator.type.rawValue) - } -} - -extension OWIdentityProvider { - init(_ identityProvider: ONGIdentityProvider) { - id = identityProvider.identifier - name = identityProvider.name - } -} - -extension OWRequestResponse { - init(_ response: ONGResourceResponse) { - headers = toOWRequestHeaders(response.allHeaderFields) - body = String(data: response.data ?? Data(), encoding: .utf8) ?? "" - status = Int64(response.statusCode) - ok = response.statusCode <= 299 && response.statusCode >= 200 - } -} - -extension Result where Success == Void { - public static var success: Result { .success(()) } -} - -func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> [String: String] { - return headers.filter { $0.key is String && $0.value is String } as? [String: String] ?? [:] -} - -func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { - guard let info = info else { return nil } - return OWCustomInfo(status: Int64(info.status), data: info.data) -} - -func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { - guard let info = info else { return nil } - return OWCustomInfo(status: Int64(info.status), data: info.data) -} - -public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { - func startApplication(securityControllerClassName: String?, - configModelClassName: String?, - customIdentityProviderConfigs: [OWCustomIdentityProvider]?, - connectionTimeout: Int64?, - readTimeout: Int64?, - completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout) { result in - completion(result.mapError { $0 }) - } - } - - func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.enrollMobileAuthentication() { result in - completion(result.mapError { $0 }) - } - } - - func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.handleMobileAuthWithOtp2(data) { result in - completion(result.mapError { $0 }) - } - } - - func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.requestResource(type, details) { result in - completion(result.mapError { $0 }) - } - } - - func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) { result in - completion(result.mapError { $0 }) - } - } - - func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) { result in - completion(result.mapError { $0 }) - } - } - - func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) { - Logger.log("fingerprintFallbackToPin is Android only and should not be called on iOS") - // FIXME: We should actually reject here with a specific error - completion(.success) - } - - func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - Logger.log("fingerprintDenyAuthenticationRequest is Android only and should not be called on iOS") - // FIXME: We should actually reject here with a specific error - completion(.success) - } - - func fingerprintAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - Logger.log("fingerprintAcceptAuthenticationRequest is Android only and should not be called on iOS") - // FIXME: We should actually reject here with a specific error - completion(.success) - } - - func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.denyMobileAuthRequest() { result in - completion(result.mapError { $0 }) - } - } - - func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.acceptMobileAuthRequest() { result in - completion(result.mapError { $0 }) - } - } - - func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest() { result in - completion(result.mapError { $0 }) - } - } - - func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin) { result in - completion(result.mapError { $0 }) - } - } - - func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest() { result in - completion(result.mapError { $0 }) - } - } - - func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin) { result in - completion(result.mapError { $0 }) - } - } - - func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() { result in - completion(result.mapError { $0 }) - } - } - - func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.registerUser(identityProviderId, scopes: scopes) { result in - completion(result.mapError { $0 }) - } - } - - func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url, webSignInType: Int(signInType)).mapError({$0})) - } - - func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getIdentityProviders().mapError { $0 }) - } - - func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.deregisterUser(profileId: profileId) { result in - completion(result.mapError { $0 }) - } - } - - func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError { $0 }) - } - - func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError { $0 }) - } - - func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError { $0 }) - } - - func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorId: registeredAuthenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError { $0 }) - } - - func changePin(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.changePin() { result in - completion(result.mapError { $0 }) - } - } - - func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.registerAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func logout(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.logOut(){ result in - completion(result.mapError { $0 }) - } - } - - func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - - } - - func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.runSingleSignOn(url) { result in - completion(result.mapError { $0 }) - } - } - - func getAccessToken(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAccessToken().mapError { $0 }) - } - - func getRedirectUrl(completion: @escaping (Result) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRedirectUrl().mapError { $0 }) - } - - func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getUserProfiles().mapError { $0 }) - } - - func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.validatePinWithPolicy(pin) { result in - completion(result.mapError { $0 }) - } - } - - func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.authenticateDevice(scopes) { result in - completion(result.mapError { $0 }) - } - } - - func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.authenticateUserImplicitly(profileId, scopes) { result in - completion(result.mapError { $0 }) - } - } - - static var flutterApi: NativeCallFlutterApi? - - public static func register(with registrar: FlutterPluginRegistrar) { - // Init Pigeon communication - let messenger: FlutterBinaryMessenger = registrar.messenger() - let api = SwiftOneginiPlugin() - UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) - ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: api) - flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) - } -} +import Flutter +import UIKit +import OneginiSDKiOS + +extension FlutterError: Error {} + +extension FlutterError { + convenience init(_ error: OneWelcomeWrapperError) { + let flutterError = SdkError(error).flutterError() + self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) + } + convenience init(_ error: SdkError) { + let flutterError = error.flutterError() + self.init(code: flutterError.code, message: flutterError.message, details: flutterError.details) + } +} + +extension OWUserProfile { + init(_ profile: UserProfile) { + self.profileId = profile.profileId + } + init(_ profile: ONGUserProfile) { + self.profileId = profile.profileId + } +} + +extension OWCustomInfo { + init(_ info: CustomInfo) { + status = Int64(info.status) + data = info.data + } + init(_ info: ONGCustomInfo) { + status = Int64(info.status) + data = info.data + } +} + +extension OWAuthenticator { + init(_ authenticator: ONGAuthenticator) { + id = authenticator.identifier + name = authenticator.name + isPreferred = authenticator.isPreferred + isRegistered = authenticator.isRegistered + authenticatorType = Int64(authenticator.type.rawValue) + } +} + +extension OWIdentityProvider { + init(_ identityProvider: ONGIdentityProvider) { + id = identityProvider.identifier + name = identityProvider.name + } +} + +extension OWRequestResponse { + init(_ response: ONGResourceResponse) { + headers = toOWRequestHeaders(response.allHeaderFields) + body = String(data: response.data ?? Data(), encoding: .utf8) ?? "" + status = Int64(response.statusCode) + ok = response.statusCode <= 299 && response.statusCode >= 200 + } +} + +extension Result where Success == Void { + public static var success: Result { .success(()) } +} + +func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> [String: String] { + return headers.filter { $0.key is String && $0.value is String } as? [String: String] ?? [:] +} + +func toOWCustomInfo(_ info: CustomInfo?) -> OWCustomInfo? { + guard let info = info else { return nil } + return OWCustomInfo(status: Int64(info.status), data: info.data) +} + +func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { + guard let info = info else { return nil } + return OWCustomInfo(status: Int64(info.status), data: info.data) +} + +public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { + func startApplication(securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: [OWCustomIdentityProvider]?, + connectionTimeout: Int64?, + readTimeout: Int64?, + completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout) { result in + completion(result.mapError { $0 }) + } + } + + func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.enrollMobileAuthentication() { result in + completion(result.mapError { $0 }) + } + } + + func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.handleMobileAuthWithOtp2(data) { result in + completion(result.mapError { $0 }) + } + } + + func requestResource(type: ResourceRequestType, details: OWRequestDetails, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.requestResource(type, details) { result in + completion(result.mapError { $0 }) + } + } + + func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) { result in + completion(result.mapError { $0 }) + } + } + + func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) { result in + completion(result.mapError { $0 }) + } + } + + func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) { + Logger.log("fingerprintFallbackToPin is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success) + } + + func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { + Logger.log("fingerprintDenyAuthenticationRequest is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success) + } + + func fingerprintAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { + Logger.log("fingerprintAcceptAuthenticationRequest is Android only and should not be called on iOS") + // FIXME: We should actually reject here with a specific error + completion(.success) + } + + func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.denyMobileAuthRequest() { result in + completion(result.mapError { $0 }) + } + } + + func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.acceptMobileAuthRequest() { result in + completion(result.mapError { $0 }) + } + } + + func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest() { result in + completion(result.mapError { $0 }) + } + } + + func pinAcceptAuthenticationRequest(pin: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.pinAcceptAuthenticationRequest(pin) { result in + completion(result.mapError { $0 }) + } + } + + func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest() { result in + completion(result.mapError { $0 }) + } + } + + func pinAcceptRegistrationRequest(pin: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.pinAcceptRegistrationRequest(pin) { result in + completion(result.mapError { $0 }) + } + } + + func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() { result in + completion(result.mapError { $0 }) + } + } + + func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.registerUser(identityProviderId, scopes: scopes) { result in + completion(result.mapError { $0 }) + } + } + + func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.handleRegisteredProcessUrl(url, webSignInType: Int(signInType)).mapError({$0})) + } + + func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getIdentityProviders().mapError { $0 }) + } + + func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.deregisterUser(profileId: profileId) { result in + completion(result.mapError { $0 }) + } + } + + func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError { $0 }) + } + + func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError { $0 }) + } + + func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError { $0 }) + } + + func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorId: registeredAuthenticatorId) { result in + completion(result.mapError { $0 }) + } + } + + func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError { $0 }) + } + + func changePin(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.changePin() { result in + completion(result.mapError { $0 }) + } + } + + func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId) { result in + completion(result.mapError { $0 }) + } + } + + func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId) { result in + completion(result.mapError { $0 }) + } + } + + func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.registerAuthenticator(authenticatorId) { result in + completion(result.mapError { $0 }) + } + } + + func logout(completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.logOut(){ result in + completion(result.mapError { $0 }) + } + } + + func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { + + } + + func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.runSingleSignOn(url) { result in + completion(result.mapError { $0 }) + } + } + + func getAccessToken(completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getAccessToken().mapError { $0 }) + } + + func getRedirectUrl(completion: @escaping (Result) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getRedirectUrl().mapError { $0 }) + } + + func getUserProfiles(completion: @escaping (Result<[OWUserProfile], Error>) -> Void) { + completion(OneginiModuleSwift.sharedInstance.getUserProfiles().mapError { $0 }) + } + + func validatePinWithPolicy(pin: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.validatePinWithPolicy(pin) { result in + completion(result.mapError { $0 }) + } + } + + func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.authenticateDevice(scopes) { result in + completion(result.mapError { $0 }) + } + } + + func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.authenticateUserImplicitly(profileId, scopes) { result in + completion(result.mapError { $0 }) + } + } + + static var flutterApi: NativeCallFlutterApi? + + public static func register(with registrar: FlutterPluginRegistrar) { + // Init Pigeon communication + let messenger: FlutterBinaryMessenger = registrar.messenger() + let api = SwiftOneginiPlugin() + UserClientApiSetup.setUp(binaryMessenger: messenger, api: api) + ResourceMethodApiSetup.setUp(binaryMessenger: messenger, api: api) + flutterApi = NativeCallFlutterApi(binaryMessenger: registrar.messenger()) + } +} From 23d8a3e3ba577cb00bf520b992e3c4029090620c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 16:10:35 +0200 Subject: [PATCH 216/364] FP-32: swiftlint --autofix, no manual changes --- .../Connectors/BridgeConnector.swift | 2 +- .../NativeBridge/Errors/ErrorExtension.swift | 3 +- .../NativeBridge/Errors/ErrorMapper.swift | 5 +- .../NativeBridge/Errors/SdkError.swift | 10 ++-- .../Handlers/AppToWebHandler.swift | 4 +- .../Handlers/AuthenticatorsHandler.swift | 30 +++++----- .../Handlers/BrowserHandler.swift | 11 ++-- .../Handlers/ChangePinHandler.swift | 6 +- .../Handlers/DeregisterUserHandler.swift | 2 +- .../NativeBridge/Handlers/Logger.swift | 14 ++--- .../NativeBridge/Handlers/LoginHandler.swift | 14 ++--- .../Handlers/MobileAuthHandler.swift | 8 +-- .../Handlers/RegistrationHandler.swift | 56 +++++++++---------- .../Handlers/ResourcesHandler.swift | 2 +- .../OneginiModuleSwift+Auth.swift | 16 +++--- .../OneginiModuleSwift+Pin.swift | 14 ++--- .../OneginiModuleSwift+Register.swift | 39 ++++++------- .../NativeBridge/OneginiModuleSwift.swift | 17 +++--- ios/Classes/SwiftOneginiPlugin.swift | 22 ++++---- 19 files changed, 132 insertions(+), 143 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index 9178043d..ef8c8ef0 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -8,7 +8,7 @@ class BridgeConnector { let toRegistrationHandler = RegistrationHandler() let toChangePinHandler: ChangePinHandler let toMobileAuthHandler = MobileAuthHandler() - public static var shared:BridgeConnector? + public static var shared: BridgeConnector? init() { self.toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationHandler) diff --git a/ios/Classes/NativeBridge/Errors/ErrorExtension.swift b/ios/Classes/NativeBridge/Errors/ErrorExtension.swift index f521eba6..3104934b 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorExtension.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorExtension.swift @@ -3,6 +3,5 @@ import OneginiSDKiOS extension Error { var domain: String { return (self as NSError).domain } var code: Int { return (self as NSError).code } - var userInfo: Dictionary { return (self as NSError).userInfo } + var userInfo: [String: Any] { return (self as NSError).userInfo } } - diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index bb8889f4..f120666d 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -14,7 +14,7 @@ enum OneWelcomeWrapperError: Int { case authenticationNotInProgress = 8037 case otpAuthenticationNotInProgress = 8039 case browserRegistrationNotInProgress = 8040 - + // iOS only case providedUrlIncorrect = 8014 case loginCanceled = 8015 @@ -101,8 +101,7 @@ enum OneWelcomeWrapperError: Int { class ErrorMapper { func mapError(_ error: Error) -> SdkError { Logger.log("Error domain: \(error.domain)") - + return SdkError(code: error.code, errorDescription: error.localizedDescription) } } - diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index fa5ba9be..6e316ff4 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -5,7 +5,7 @@ import OneginiSDKiOS class SdkError: Error { var code: Int var errorDescription: String - var details: Dictionary = [:] + var details: [String: Any?] = [:] // Only error codes init(code: Int, errorDescription: String) { @@ -75,7 +75,7 @@ private extension SdkError { } func setInfoDetails(_ info: [String: Any?]?) { - if (info == nil) { + if info == nil { details["userInfo"] = [:] } else { details["userInfo"] = info @@ -83,8 +83,8 @@ private extension SdkError { } func setResponseDetails(_ response: ONGResourceResponse?, _ iosCode: Int?, _ iosMessage: String?) { - if (response == nil) { - details["response"] = Dictionary() + if response == nil { + details["response"] = [String: Any?]() } else { details["response"] = response?.toJSON() } @@ -101,7 +101,7 @@ private extension SdkError { } private extension ONGResourceResponse { - func toJSON() -> Dictionary { + func toJSON() -> [String: Any?] { return ["statusCode": statusCode, "headers": allHeaderFields, "url": rawResponse.url?.absoluteString, diff --git a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift index 53d07500..4c9c1183 100644 --- a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift @@ -1,12 +1,12 @@ import Foundation import OneginiSDKiOS -//MARK: - +// MARK: - protocol AppToWebHandlerProtocol: AnyObject { func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) } -//MARK: - +// MARK: - class AppToWebHandler: AppToWebHandlerProtocol { func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) { ONGUserClient.sharedInstance().appToWebSingleSignOn(withTargetUrl: targetURL) { (url, token, error) in diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 56f4c400..f8b6608d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -1,7 +1,7 @@ import Foundation import OneginiSDKiOS -//MARK: - +// MARK: - protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) @@ -13,7 +13,7 @@ class AuthenticatorsHandler: NSObject { var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? var registrationCompletion: ((Result) -> Void)? var deregistrationCompletion: ((Result) -> Void)? - + func handlePin(pin: String?) { guard let customAuthChallenge = self.customAuthChallenge else { guard let pinChallenge = self.pinChallenge else { return } @@ -37,7 +37,7 @@ class AuthenticatorsHandler: NSObject { } } -//MARK: - BridgeToAuthenticatorsHandlerProtocol +// MARK: - BridgeToAuthenticatorsHandlerProtocol extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { @@ -50,43 +50,43 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotFound))) return } - registrationCompletion = completion; + registrationCompletion = completion ONGUserClient.sharedInstance().register(authenticator, delegate: self) } - func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { + func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } - - if(authenticator.isRegistered != true) { + + if authenticator.isRegistered != true { completion(.failure(FlutterError(.authenticatorNotRegistered))) return } - - deregistrationCompletion = completion; + + deregistrationCompletion = completion ONGUserClient.sharedInstance().deregister(authenticator, delegate: self) } - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String,_ completion: @escaping (Result) -> Void) { + func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } - + // FIXME: Doesnt the sdk give us an error by itself? - if(!authenticator.isRegistered) { + if !authenticator.isRegistered { completion(.failure(FlutterError(.authenticatorNotRegistered))) return } - + ONGUserClient.sharedInstance().preferredAuthenticator = authenticator completion(.success) } } -//MARK: - ONGAuthenticatorRegistrationDelegate +// MARK: - ONGAuthenticatorRegistrationDelegate extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge) { Logger.log("[AUTH] userClient didReceive ONGPinChallenge", sender: self) @@ -98,7 +98,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { } func userClient(_: ONGUserClient, didFailToRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { - Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender:self) + Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) } else { diff --git a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift index 035eca5c..2f7cb741 100644 --- a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift @@ -9,7 +9,7 @@ protocol BrowserHandlerToRegisterHandlerProtocol: AnyObject { func handleRedirectURL(url: URL?) } -//MARK: - BrowserHandlerProtocol +// MARK: - BrowserHandlerProtocol @available(iOS 12.0, *) class BrowserViewController: NSObject, BrowserHandlerProtocol { var webAuthSession: ASWebAuthenticationSession? @@ -29,9 +29,8 @@ class BrowserViewController: NSObject, BrowserHandlerProtocol { openInternalBrowser(url: url) } - } - + private func openExternalBrowser(url: URL) { guard UIApplication.shared.canOpenURL(url) else { Logger.log("can't open external browser url: \(url.absoluteString)", logType: .error) @@ -42,7 +41,7 @@ class BrowserViewController: NSObject, BrowserHandlerProtocol { Logger.log("opened external browser url: \(value)") } } - + private func openInternalBrowser(url: URL) { let scheme = URL(string: ONGClient.sharedInstance().configModel.redirectURL)!.scheme webAuthSession = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme, completionHandler: { callbackURL, error in @@ -74,12 +73,12 @@ class BrowserViewController: NSObject, BrowserHandlerProtocol { } -//MARK: - ASWebAuthenticationPresentationContextProviding +// MARK: - ASWebAuthenticationPresentationContextProviding @available(iOS 12.0, *) extension BrowserViewController: ASWebAuthenticationPresentationContextProviding { func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { Logger.log("presentationAnchor for session", sender: self) - + let anchor: ASPresentationAnchor = UIApplication.shared.keyWindow ?? ASPresentationAnchor() return anchor } diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 43575520..159acebc 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -28,11 +28,11 @@ extension ChangePinHandler: ONGChangePinDelegate { loginHandler.handleDidAuthenticateUser() registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } - + func userClient(_: ONGUserClient, didFailToChangePinForUser _: ONGUserProfile, error: Error) { loginHandler.handleDidFailToAuthenticateUser() registrationHandler.handleDidFailToRegister() - + let mappedError = ErrorMapper().mapError(error) changePinCompletion?(.failure(FlutterError(mappedError))) changePinCompletion = nil @@ -42,6 +42,6 @@ extension ChangePinHandler: ONGChangePinDelegate { registrationHandler.handleDidRegisterUser() changePinCompletion?(.success) changePinCompletion = nil - + } } diff --git a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift index 0c42d1e8..3c0d11b8 100644 --- a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift @@ -11,7 +11,7 @@ class DeregisterUserHandler: DeregisterUserHandlerProtocol { completion(.failure(FlutterError(.userProfileDoesNotExist))) return } - + ONGUserClient.sharedInstance().deregisterUser(profile) { _, error in if let error = error { let mappedError = ErrorMapper().mapError(error) diff --git a/ios/Classes/NativeBridge/Handlers/Logger.swift b/ios/Classes/NativeBridge/Handlers/Logger.swift index 173201c9..2b0de47c 100644 --- a/ios/Classes/NativeBridge/Handlers/Logger.swift +++ b/ios/Classes/NativeBridge/Handlers/Logger.swift @@ -8,24 +8,24 @@ import Foundation class Logger { - + enum LogType: String { case debug = "debug" case log = "log" case warning = "warning" case error = "error" } - + static var enable = true - + static func log(_ message: String, sender: Any? = nil, logType: LogType = .debug) { - + if !enable { return } - + var m: String = "[\(logType.rawValue)]" - + if let s = sender { m = "\(m)[\(type(of: s))]" } @@ -41,5 +41,5 @@ class Logger { } #endif } - + } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index d015b361..48e22bd7 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -4,7 +4,7 @@ import Flutter class LoginHandler: NSObject { var pinChallenge: ONGPinChallenge? var loginCompletion: ((Result) -> Void)? - + func handlePin(pin: String, completion: (Result) -> Void) { guard let pinChallenge = pinChallenge else { completion(.failure(FlutterError(.authenticationNotInProgress))) @@ -13,7 +13,7 @@ class LoginHandler: NSObject { pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) completion(.success) } - + func cancelPinAuthentication(completion: (Result) -> Void) { guard let pinChallenge = pinChallenge else { completion(.failure(FlutterError(.authenticationNotInProgress))) @@ -22,7 +22,7 @@ class LoginHandler: NSObject { pinChallenge.sender.cancel(pinChallenge) completion(.success) } - + private func mapErrorFromPinChallenge(_ challenge: ONGPinChallenge) -> Error? { if let error = challenge.error, error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue { return error @@ -30,7 +30,7 @@ class LoginHandler: NSObject { return nil } } - + func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { pinChallenge = challenge guard mapErrorFromPinChallenge(challenge) == nil else { @@ -44,12 +44,12 @@ class LoginHandler: NSObject { SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} } - + func handleDidAuthenticateUser() { pinChallenge = nil SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} } - + func handleDidFailToAuthenticateUser() { guard pinChallenge != nil else { return } SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} @@ -72,7 +72,7 @@ extension LoginHandler: ONGAuthenticationDelegate { func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishAuthenticationChallenge) { // We don't support custom authenticators in FlutterPlugin right now. } - + func userClient(_ userClient: ONGUserClient, didAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, info customAuthInfo: ONGCustomInfo?) { handleDidAuthenticateUser() loginCompletion?(.success(OWRegistrationResponse(userProfile: OWUserProfile(userProfile), diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index 85aaa861..dfe78a0c 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -14,8 +14,8 @@ class MobileAuthHandler: NSObject { private var isFlowInProgress: Bool = false } -//MARK: - MobileAuthConnectorToHandlerProtocol -extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { +// MARK: - MobileAuthConnectorToHandlerProtocol +extension MobileAuthHandler: MobileAuthConnectorToHandlerProtocol { func handleMobileAuthWithOtp(otp: String, completion: @escaping (Result) -> Void) { Logger.log("handleMobileAuthWithOtp", sender: self) @@ -45,7 +45,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { return } - let mappedError = ErrorMapper().mapError(error); + let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) } } @@ -83,7 +83,7 @@ extension MobileAuthHandler : MobileAuthConnectorToHandlerProtocol { } } -//MARK: - MobileAuthRequestDelegate +// MARK: - MobileAuthRequestDelegate class MobileAuthDelegate: MobileAuthRequestDelegate { private var handleMobileAuthCompletion: (Result) -> Void diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 3f1ff042..fb09f097 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -3,7 +3,7 @@ import OneginiSDKiOS enum WebSignInType: Int { case insideApp case safari - + init(rawValue: Int) { switch rawValue { case 1: self = .safari @@ -20,58 +20,58 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { var browserConntroller: BrowserHandlerProtocol? var signUpCompletion: ((Result) -> Void)? - + // Should not be needed func currentChallenge() -> ONGCustomRegistrationChallenge? { return self.customRegistrationChallenge } - + // FIXME: why do we need this? - func identityProviders() -> Array { + func identityProviders() -> [ONGIdentityProvider] { var list = Array(ONGUserClient.sharedInstance().identityProviders()) - + let listOutput: [String]? = OneginiModuleSwift.sharedInstance.customRegIdentifiers.filter { (_id) -> Bool in let element = list.first { (provider) -> Bool in return provider.identifier == _id } - + return element == nil } - + listOutput?.forEach { (_providerId) in let identityProvider = ONGIdentityProvider() identityProvider.name = _providerId identityProvider.identifier = _providerId - + list.append(identityProvider) } - + return list } - + func presentBrowserUserRegistrationView(registrationUserURL: URL, webSignInType: WebSignInType) { guard let browserController = browserConntroller else { browserConntroller = BrowserViewController(registerHandlerProtocol: self) browserConntroller?.handleUrl(url: registrationUserURL, webSignInType: webSignInType) return } - + browserController.handleUrl(url: registrationUserURL, webSignInType: webSignInType) } func handleRedirectURL(url: URL?) { Logger.log("handleRedirectURL url: \(url?.absoluteString ?? "nil")", sender: self) guard let browserRegistrationChallenge = self.browserRegistrationChallenge else { - //FIXME: Registration not in progress error here + // FIXME: Registration not in progress error here signUpCompletion?(.failure(FlutterError(.genericError))) return } - + guard let url = url else { browserRegistrationChallenge.sender.cancel(browserRegistrationChallenge) return } - + browserRegistrationChallenge.sender.respond(with: url, challenge: browserRegistrationChallenge) } @@ -83,7 +83,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge.sender.respond(withCreatedPin: pin, challenge: createPinChallenge) completion(.success) } - + func cancelPinRegistration(completion: (Result) -> Void) { guard let createPinChallenge = self.createPinChallenge else { completion(.failure(FlutterError(.registrationNotInProgress))) @@ -92,8 +92,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge.sender.cancel(createPinChallenge) completion(.success) } - - + func handleDidReceivePinRegistrationChallenge(_ challenge: ONGCreatePinChallenge) { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { @@ -103,9 +102,9 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} } } - + func handleDidFailToRegister() { - if (createPinChallenge == nil && customRegistrationChallenge == nil && browserRegistrationChallenge == nil) { + if createPinChallenge == nil && customRegistrationChallenge == nil && browserRegistrationChallenge == nil { return } createPinChallenge = nil @@ -132,27 +131,27 @@ extension RegistrationHandler { identityProvider?.name = _providerId identityProvider?.identifier = _providerId } - + ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) } func processRedirectURL(url: String, webSignInType: Int) -> Result { let webSignInType = WebSignInType(rawValue: webSignInType) guard let url = URL.init(string: url) else { - //FIXME: This doesn't seem right, we're canceling the whole registration here??? + // FIXME: This doesn't seem right, we're canceling the whole registration here??? signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return .failure(FlutterError(.providedUrlIncorrect)) } - + if webSignInType != .insideApp && !UIApplication.shared.canOpenURL(url) { signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return .failure(FlutterError(.providedUrlIncorrect)) } - + presentBrowserUserRegistrationView(registrationUserURL: url, webSignInType: webSignInType) return .success } - + func submitCustomRegistrationSuccess(_ data: String?, _ completion: @escaping (Result) -> Void) { guard let customRegistrationChallenge = self.customRegistrationChallenge else { completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) @@ -161,7 +160,7 @@ extension RegistrationHandler { customRegistrationChallenge.sender.respond(withData: data, challenge: customRegistrationChallenge) completion(.success) } - + func cancelCustomRegistration(_ error: String, _ completion: @escaping (Result) -> Void) { guard let customRegistrationChallenge = self.customRegistrationChallenge else { completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) @@ -182,7 +181,7 @@ extension RegistrationHandler { extension RegistrationHandler: ONGRegistrationDelegate { func userClient(_: ONGUserClient, didReceive challenge: ONGBrowserRegistrationChallenge) { - Logger.log("didReceive ONGBrowserRegistrationChallenge", sender: self) + Logger.log("didReceive ONGBrowserRegistrationChallenge", sender: self) browserRegistrationChallenge = challenge debugPrint(challenge.url) @@ -223,12 +222,11 @@ extension RegistrationHandler: ONGRegistrationDelegate { } } } - -fileprivate func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { + +private func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { if let error = challenge.error { return ErrorMapper().mapError(error) } else { return nil } } - diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index bd2b6992..73a668c2 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -9,7 +9,7 @@ protocol FetchResourcesHandlerProtocol: AnyObject { func requestResource(_ type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) } -//MARK: - +// MARK: - class ResourcesHandler: FetchResourcesHandlerProtocol { func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 2001d71b..bec50dc3 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -6,7 +6,7 @@ extension OneginiModuleSwift { func getIdentityProviders() -> Result<[OWIdentityProvider], FlutterError> { let providers = ONGClient.sharedInstance().userClient.identityProviders() - return .success(providers.compactMap { OWIdentityProvider($0) } ) + return .success(providers.compactMap { OWIdentityProvider($0) }) } func logOut(callback: @escaping (Result) -> Void) { @@ -24,23 +24,23 @@ extension OneginiModuleSwift { } func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { - + guard let url = URL(string: path) else { completion(.failure(FlutterError(.providedUrlIncorrect))) return } bridgeConnector.toAppToWebHandler.signInAppToWeb(targetURL: url, completion: completion) } - + func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { - + guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) return } - + let authenticator = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile).first(where: { $0.identifier == authenticatorId }) - + bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in completion(result) } @@ -53,7 +53,7 @@ extension OneginiModuleSwift { } bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) } - + func deregisterAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) @@ -68,7 +68,7 @@ extension OneginiModuleSwift { } return .success(OWUserProfile(profile)) } - + func getAccessToken() -> Result { guard let accessToken = ONGUserClient.sharedInstance().accessToken else { return .failure(FlutterError(.noUserProfileIsAuthenticated)) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift index 4c1abc74..2829a8dd 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Pin.swift @@ -7,27 +7,26 @@ extension OneginiModuleSwift { func pinAcceptAuthenticationRequest(_ pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toLoginHandler.handlePin(pin: pin, completion: completion) } - + func pinDenyAuthenticationRequest(_ completion: @escaping (Result) -> Void) { bridgeConnector.toLoginHandler.cancelPinAuthentication(completion: completion) } - + func pinAcceptRegistrationRequest(_ pin: String, completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.handlePin(pin: pin, completion: completion) } - + func pinDenyRegistrationRequest(_ completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.cancelPinRegistration(completion: completion) } - - + func changePin(completion: @escaping (Result) -> Void) { bridgeConnector.toChangePinHandler.changePin(completion: completion) } - + func validatePinWithPolicy(_ pin: String, completion: @escaping (Result) -> Void) { // FIXME: Move this out of this file - ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (value, error) in + ONGUserClient.sharedInstance().validatePin(withPolicy: pin) { (_, error) in guard let error = error else { completion(.success) return @@ -36,4 +35,3 @@ extension OneginiModuleSwift { } } } - diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index 9fdca67b..fe0adc97 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -2,8 +2,6 @@ import Foundation import OneginiSDKiOS import Flutter - - extension OneginiModuleSwift { func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) { @@ -13,70 +11,69 @@ extension OneginiModuleSwift { func registerUser(_ identityProviderId: String? = nil, scopes: [String]? = nil, completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.registerUser(identityProviderId, scopes: scopes, completion: completion) } - + func handleRegisteredProcessUrl(_ url: String, webSignInType: Int) -> Result { return bridgeConnector.toRegistrationHandler.processRedirectURL(url: url, webSignInType: webSignInType) } - + public func handleDeepLinkCallbackUrl(_ url: URL) -> Bool { guard let schemeLibrary = URL.init(string: ONGClient.sharedInstance().configModel.redirectURL)?.scheme else { - //FIXME: We should propagate an error here to the caller, not through events. + // FIXME: We should propagate an error here to the caller, not through events. return false } - + guard let scheme = url.scheme, scheme.compare(schemeLibrary, options: .caseInsensitive) == .orderedSame else { let value = ["url_scheme": url.scheme, "library_scheme": schemeLibrary, "url": url.absoluteString] - //FIXME: We should propagate an error here to the caller, not through events. + // FIXME: We should propagate an error here to the caller, not through events. return false } - + bridgeConnector.toRegistrationHandler.handleRedirectURL(url: url) return true } - + func submitCustomRegistrationSuccess(_ data: String?, completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.submitCustomRegistrationSuccess(data, completion) } - + func submitCustomRegistrationError(_ error: String, _ completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.cancelCustomRegistration(error, completion) } - - public func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) -> Void { + + public func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.cancelBrowserRegistration(completion) } - + func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { bridgeConnector.toAuthenticatorsHandler.registerAuthenticator(authenticatorId, completion) } - + func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { return .failure(FlutterError(.userProfileDoesNotExist)) } let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) - return .success(registeredAuthenticators.compactMap { OWAuthenticator($0) } ) + return .success(registeredAuthenticators.compactMap { OWAuthenticator($0) }) } - + func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { return .failure(FlutterError(.userProfileDoesNotExist)) } let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) - return .success(notRegisteredAuthenticators.compactMap { OWAuthenticator($0) } ) + return .success(notRegisteredAuthenticators.compactMap { OWAuthenticator($0) }) } - + func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { return .failure(FlutterError(.userProfileDoesNotExist)) } let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) - return .success(allAuthenticators.compactMap { OWAuthenticator($0) } ) + return .success(allAuthenticators.compactMap { OWAuthenticator($0) }) } - + func getRedirectUrl() -> Result { return .success(ONGClient.sharedInstance().configModel.redirectURL) } } - diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index c17bcdb3..b476d530 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -3,20 +3,20 @@ import OneginiSDKiOS import Flutter public class OneginiModuleSwift: NSObject { - + var bridgeConnector: BridgeConnector - public var customRegIdentifiers = [String]() + public var customRegIdentifiers = [String]() static public let sharedInstance = OneginiModuleSwift() - + override init() { self.bridgeConnector = BridgeConnector() super.init() } - + func configureCustomRegIdentifiers(_ list: [String]) { self.customRegIdentifiers = list } - + func startOneginiModule(httpConnectionTimeout: Int64?, callback: @escaping (Result) -> Void) { ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout ?? 5))) ONGClientBuilder().build() @@ -27,7 +27,7 @@ public class OneginiModuleSwift: NSObject { callback(.failure(mappedError.flutterError())) return } - + if !result { callback(.failure(SdkError(.genericError).flutterError())) return @@ -35,10 +35,9 @@ public class OneginiModuleSwift: NSObject { callback(.success) } } - + func getUserProfiles() -> Result<[OWUserProfile], FlutterError> { let profiles = ONGUserClient.sharedInstance().userProfiles() - return .success(profiles.compactMap { OWUserProfile($0) } ) + return .success(profiles.compactMap { OWUserProfile($0) }) } } - diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 3383fccb..07b23f94 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -65,7 +65,7 @@ extension Result where Success == Void { public static var success: Result { .success(()) } } -func toOWRequestHeaders(_ headers: [AnyHashable : Any]) -> [String: String] { +func toOWRequestHeaders(_ headers: [AnyHashable: Any]) -> [String: String] { return headers.filter { $0.key is String && $0.value is String } as? [String: String] ?? [:] } @@ -92,7 +92,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func enrollMobileAuthentication(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.enrollMobileAuthentication() { result in + OneginiModuleSwift.sharedInstance.enrollMobileAuthentication { result in completion(result.mapError { $0 }) } } @@ -140,19 +140,19 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func otpDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.denyMobileAuthRequest() { result in + OneginiModuleSwift.sharedInstance.denyMobileAuthRequest { result in completion(result.mapError { $0 }) } } func otpAcceptAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.acceptMobileAuthRequest() { result in + OneginiModuleSwift.sharedInstance.acceptMobileAuthRequest { result in completion(result.mapError { $0 }) } } func pinDenyAuthenticationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest() { result in + OneginiModuleSwift.sharedInstance.pinDenyAuthenticationRequest { result in completion(result.mapError { $0 }) } } @@ -164,7 +164,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func pinDenyRegistrationRequest(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest() { result in + OneginiModuleSwift.sharedInstance.pinDenyRegistrationRequest { result in completion(result.mapError { $0 }) } } @@ -176,7 +176,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func cancelBrowserRegistration(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.cancelBrowserRegistration() { result in + OneginiModuleSwift.sharedInstance.cancelBrowserRegistration { result in completion(result.mapError { $0 }) } } @@ -224,7 +224,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func changePin(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.changePin() { result in + OneginiModuleSwift.sharedInstance.changePin { result in completion(result.mapError { $0 }) } } @@ -248,13 +248,13 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func logout(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.logOut(){ result in + OneginiModuleSwift.sharedInstance.logOut { result in completion(result.mapError { $0 }) } } func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - + } func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { @@ -294,7 +294,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } static var flutterApi: NativeCallFlutterApi? - + public static func register(with registrar: FlutterPluginRegistrar) { // Init Pigeon communication let messenger: FlutterBinaryMessenger = registrar.messenger() From e2f4772f2423f120867249f054af906a5f8607aa Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 16:13:41 +0200 Subject: [PATCH 217/364] FP-32: Fix and disable some swiftlint errors --- .../NativeBridge/Errors/ErrorMapper.swift | 1 + ios/Classes/NativeBridge/Errors/SdkError.swift | 8 ++++---- .../Handlers/AuthenticatorsHandler.swift | 8 ++++---- ios/Classes/NativeBridge/Handlers/Logger.swift | 1 + .../Handlers/RegistrationHandler.swift | 16 ++++++++-------- 5 files changed, 18 insertions(+), 16 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index f120666d..2838e26a 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -1,3 +1,4 @@ +// swiftlint:disable cyclomatic_complexity import OneginiSDKiOS enum OneWelcomeWrapperError: Int { diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index 6e316ff4..6066ddd7 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -57,14 +57,14 @@ class SdkError: Error { } func flutterError() -> FlutterError { - let _error = FlutterError(code: "\(self.code)", message: self.errorDescription, details: details) + let error = FlutterError(code: "\(self.code)", message: self.errorDescription, details: details) - return _error + return error } static func convertToFlutter(_ error: SdkError?) -> FlutterError { - let _error = error ?? SdkError(.genericError) - return _error.flutterError() + let error = error ?? SdkError(.genericError) + return error.flutterError() } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index f8b6608d..a4d7cf2d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -18,8 +18,8 @@ class AuthenticatorsHandler: NSObject { guard let customAuthChallenge = self.customAuthChallenge else { guard let pinChallenge = self.pinChallenge else { return } - if let _pin = pin { - pinChallenge.sender.respond(withPin: _pin, challenge: pinChallenge) + if let pin = pin { + pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) } else { pinChallenge.sender.cancel(pinChallenge) @@ -28,8 +28,8 @@ class AuthenticatorsHandler: NSObject { return } - if let _pin = pin { - customAuthChallenge.sender.respond(withData: _pin, challenge: customAuthChallenge) + if let pin = pin { + customAuthChallenge.sender.respond(withData: pin, challenge: customAuthChallenge) } else { customAuthChallenge.sender.cancel(customAuthChallenge, underlyingError: nil) diff --git a/ios/Classes/NativeBridge/Handlers/Logger.swift b/ios/Classes/NativeBridge/Handlers/Logger.swift index 2b0de47c..d9d3239f 100644 --- a/ios/Classes/NativeBridge/Handlers/Logger.swift +++ b/ios/Classes/NativeBridge/Handlers/Logger.swift @@ -1,3 +1,4 @@ +// swiftlint:disable identifier_name // // Logger.swift // onegini diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index fb09f097..cad71c60 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -30,18 +30,18 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func identityProviders() -> [ONGIdentityProvider] { var list = Array(ONGUserClient.sharedInstance().identityProviders()) - let listOutput: [String]? = OneginiModuleSwift.sharedInstance.customRegIdentifiers.filter { (_id) -> Bool in + let listOutput: [String]? = OneginiModuleSwift.sharedInstance.customRegIdentifiers.filter { (providerId) -> Bool in let element = list.first { (provider) -> Bool in - return provider.identifier == _id + return provider.identifier == providerId } return element == nil } - listOutput?.forEach { (_providerId) in + listOutput?.forEach { (providerId) in let identityProvider = ONGIdentityProvider() - identityProvider.name = _providerId - identityProvider.identifier = _providerId + identityProvider.name = providerId + identityProvider.identifier = providerId list.append(identityProvider) } @@ -126,10 +126,10 @@ extension RegistrationHandler { signUpCompletion = completion var identityProvider = identityProviders().first(where: { $0.identifier == providerId}) - if let _providerId = providerId, identityProvider == nil { + if let providerId = providerId, identityProvider == nil { identityProvider = ONGIdentityProvider() - identityProvider?.name = _providerId - identityProvider?.identifier = _providerId + identityProvider?.name = providerId + identityProvider?.identifier = providerId } ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) From fc5b3f114d9c0f65dc63fcdbb01551d5bd23e8c8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 16:56:55 +0200 Subject: [PATCH 218/364] FP-53: Use SwiftApi in LogoutHandler --- ios/Classes/NativeBridge/Handlers/LogoutHandler.swift | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift index 3e85de50..acd3bc52 100644 --- a/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LogoutHandler.swift @@ -7,12 +7,7 @@ protocol LogoutHandlerProtocol: AnyObject { class LogoutHandler: LogoutHandlerProtocol { func logout(completion: @escaping (Result) -> Void) { - let userClient = ONGUserClient.sharedInstance() - guard userClient.authenticatedUserProfile() != nil else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) - return - } - userClient.logoutUser { _, error in + SharedUserClient.instance.logoutUser { _, error in if let error = error { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) From 1fcb036fe0db195f3d74aa65e2be49e138be6736 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 30 Mar 2023 17:01:15 +0200 Subject: [PATCH 219/364] FP-54: Use SwiftApi in DeregisterUserHandler --- .../NativeBridge/Handlers/DeregisterUserHandler.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift index 3c0d11b8..6e7a275f 100644 --- a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift @@ -7,12 +7,11 @@ protocol DeregisterUserHandlerProtocol: AnyObject { class DeregisterUserHandler: DeregisterUserHandlerProtocol { func deregister(profileId: String, completion: @escaping (Result) -> Void) { - guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { + guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { completion(.failure(FlutterError(.userProfileDoesNotExist))) return } - - ONGUserClient.sharedInstance().deregisterUser(profile) { _, error in + SharedUserClient.instance.deregister(user: profile) { error in if let error = error { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) From 6e7709fd849f6e19c42ef0728756f88672315236 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 10:04:29 +0200 Subject: [PATCH 220/364] FP-55: iOS: Use SwiftApi for AppToWebSingleSignOn --- ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift index 4c9c1183..64820bb3 100644 --- a/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AppToWebHandler.swift @@ -1,15 +1,13 @@ import Foundation import OneginiSDKiOS -// MARK: - -protocol AppToWebHandlerProtocol: AnyObject { +protocol AppToWebHandlerProtocol { func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) } -// MARK: - class AppToWebHandler: AppToWebHandlerProtocol { func signInAppToWeb(targetURL: URL, completion: @escaping (Result) -> Void) { - ONGUserClient.sharedInstance().appToWebSingleSignOn(withTargetUrl: targetURL) { (url, token, error) in + SharedUserClient.instance.appToWebSingleSignOn(with: targetURL) { (url, token, error) in if let url = url, let token = token { completion(.success(OWAppToWebSingleSignOn(token: token, redirectUrl: url.absoluteString))) } else if let error = error { From b8c028362cb25eb4e7ecd07cb03dedf3886dcf8b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 10:51:09 +0200 Subject: [PATCH 221/364] FP-52: Use SwiftApi for login/Pin authentication --- .../NativeBridge/Handlers/LoginHandler.swift | 28 +++++++++++-------- .../OneginiModuleSwift+Auth.swift | 5 ++-- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 48e22bd7..fad4e5d8 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -2,7 +2,7 @@ import OneginiSDKiOS import Flutter class LoginHandler: NSObject { - var pinChallenge: ONGPinChallenge? + var pinChallenge: PinChallenge? var loginCompletion: ((Result) -> Void)? func handlePin(pin: String, completion: (Result) -> Void) { @@ -10,7 +10,7 @@ class LoginHandler: NSObject { completion(.failure(FlutterError(.authenticationNotInProgress))) return } - pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) + pinChallenge.sender.respond(with: pin, to: pinChallenge) completion(.success) } @@ -23,7 +23,7 @@ class LoginHandler: NSObject { completion(.success) } - private func mapErrorFromPinChallenge(_ challenge: ONGPinChallenge) -> Error? { + private func mapErrorFromPinChallenge(_ challenge: PinChallenge) -> Error? { if let error = challenge.error, error.code != ONGAuthenticationError.touchIDAuthenticatorFailure.rawValue { return error } else { @@ -31,7 +31,7 @@ class LoginHandler: NSObject { } } - func handleDidReceiveChallenge(_ challenge: ONGPinChallenge) { + func handleDidReceiveChallenge(_ challenge: PinChallenge) { pinChallenge = challenge guard mapErrorFromPinChallenge(challenge) == nil else { let authAttempt = OWAuthenticationAttempt( @@ -58,28 +58,32 @@ class LoginHandler: NSObject { } extension LoginHandler { - func authenticateUser(_ profile: ONGUserProfile, authenticator: ONGAuthenticator?, completion: @escaping (Result) -> Void) { + func authenticateUser(_ profile: UserProfile, authenticator: Authenticator?, completion: @escaping (Result) -> Void) { loginCompletion = completion - ONGUserClient.sharedInstance().authenticateUser(profile, authenticator: authenticator, delegate: self) + SharedUserClient.instance.authenticateUserWith(profile: profile, authenticator: authenticator, delegate: self) } } -extension LoginHandler: ONGAuthenticationDelegate { - func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge) { +extension LoginHandler: AuthenticationDelegate { + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { handleDidReceiveChallenge(challenge) } - func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishAuthenticationChallenge) { + func userClient(_ userClient: UserClient, didStartAuthenticationForUser profile: UserProfile, authenticator: Authenticator) { + // unused + } + + func userClient(_ userClient: UserClient, didReceiveCustomAuthFinishAuthenticationChallenge challenge: CustomAuthFinishAuthenticationChallenge) { // We don't support custom authenticators in FlutterPlugin right now. } - func userClient(_ userClient: ONGUserClient, didAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, info customAuthInfo: ONGCustomInfo?) { + func userClient(_ userClient: UserClient, didAuthenticateUser profile: UserProfile, authenticator: Authenticator, info customAuthInfo: CustomInfo?) { handleDidAuthenticateUser() - loginCompletion?(.success(OWRegistrationResponse(userProfile: OWUserProfile(userProfile), + loginCompletion?(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(customAuthInfo)))) } - func userClient(_ userClient: ONGUserClient, didFailToAuthenticateUser userProfile: ONGUserProfile, authenticator: ONGAuthenticator, error: Error) { + func userClient(_ userClient: UserClient, didFailToAuthenticateUser profile: UserProfile, authenticator: Authenticator, error: Error) { handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index bec50dc3..38f1ccc3 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -34,12 +34,11 @@ extension OneginiModuleSwift { func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { - guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { + guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) return } - - let authenticator = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile).first(where: { $0.identifier == authenticatorId }) + let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.identifier == authenticatorId }) bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in completion(result) From 2a5b18b65a6f7ba05b3c49b8ba0c064734081ba4 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 10:51:31 +0200 Subject: [PATCH 222/364] FP-52: Use SwiftApi for changepin --- .../Handlers/ChangePinHandler.swift | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 159acebc..bb8687e0 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -15,33 +15,36 @@ class ChangePinHandler: NSObject { extension ChangePinHandler { func changePin(completion: @escaping (Result) -> Void) { changePinCompletion = completion - ONGUserClient.sharedInstance().changePin(self) + SharedUserClient.instance.changePin(delegate: self) } } -extension ChangePinHandler: ONGChangePinDelegate { - func userClient(_ userClient: ONGUserClient, didReceive challenge: ONGPinChallenge) { +extension ChangePinHandler: ChangePinDelegate { + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { loginHandler.handleDidReceiveChallenge(challenge) } - func userClient(_: ONGUserClient, didReceive challenge: ONGCreatePinChallenge) { + func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { loginHandler.handleDidAuthenticateUser() registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } - func userClient(_: ONGUserClient, didFailToChangePinForUser _: ONGUserProfile, error: Error) { - loginHandler.handleDidFailToAuthenticateUser() - registrationHandler.handleDidFailToRegister() - - let mappedError = ErrorMapper().mapError(error) - changePinCompletion?(.failure(FlutterError(mappedError))) - changePinCompletion = nil + func userClient(_ userClient: UserClient, didStartPinChangeForUser profile: UserProfile) { + // Unused } - func userClient(_: ONGUserClient, didChangePinForUser _: ONGUserProfile) { + func userClient(_ userClient: UserClient, didChangePinForUser profile: UserProfile) { registrationHandler.handleDidRegisterUser() changePinCompletion?(.success) changePinCompletion = nil + } + func userClient(_ userClient: UserClient, didFailToChangePinForUser profile: UserProfile, error: Error) { + loginHandler.handleDidFailToAuthenticateUser() + registrationHandler.handleDidFailToRegister() + + let mappedError = ErrorMapper().mapError(error) + changePinCompletion?(.failure(FlutterError(mappedError))) + changePinCompletion = nil } } From 5fe6f7621db1b71b2c35a1ccf57cd79c95f831aa Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 10:51:43 +0200 Subject: [PATCH 223/364] FP-52: Use SwiftApi for registration / pin Creation --- .../Handlers/RegistrationHandler.swift | 94 ++++++------------- 1 file changed, 31 insertions(+), 63 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index cad71c60..86caa6eb 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -14,41 +14,12 @@ enum WebSignInType: Int { class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { - var createPinChallenge: ONGCreatePinChallenge? - var browserRegistrationChallenge: ONGBrowserRegistrationChallenge? - var customRegistrationChallenge: ONGCustomRegistrationChallenge? + var createPinChallenge: CreatePinChallenge? + var browserRegistrationChallenge: BrowserRegistrationChallenge? + var customRegistrationChallenge: CustomRegistrationChallenge? var browserConntroller: BrowserHandlerProtocol? - var signUpCompletion: ((Result) -> Void)? - // Should not be needed - func currentChallenge() -> ONGCustomRegistrationChallenge? { - return self.customRegistrationChallenge - } - - // FIXME: why do we need this? - func identityProviders() -> [ONGIdentityProvider] { - var list = Array(ONGUserClient.sharedInstance().identityProviders()) - - let listOutput: [String]? = OneginiModuleSwift.sharedInstance.customRegIdentifiers.filter { (providerId) -> Bool in - let element = list.first { (provider) -> Bool in - return provider.identifier == providerId - } - - return element == nil - } - - listOutput?.forEach { (providerId) in - let identityProvider = ONGIdentityProvider() - identityProvider.name = providerId - identityProvider.identifier = providerId - - list.append(identityProvider) - } - - return list - } - func presentBrowserUserRegistrationView(registrationUserURL: URL, webSignInType: WebSignInType) { guard let browserController = browserConntroller else { browserConntroller = BrowserViewController(registerHandlerProtocol: self) @@ -72,7 +43,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { return } - browserRegistrationChallenge.sender.respond(with: url, challenge: browserRegistrationChallenge) + browserRegistrationChallenge.sender.respond(with: url, to: browserRegistrationChallenge) } func handlePin(pin: String, completion: (Result) -> Void) { @@ -80,7 +51,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { completion(.failure(FlutterError(.registrationNotInProgress))) return } - createPinChallenge.sender.respond(withCreatedPin: pin, challenge: createPinChallenge) + createPinChallenge.sender.respond(with: pin, to: createPinChallenge) completion(.success) } @@ -93,7 +64,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { completion(.success) } - func handleDidReceivePinRegistrationChallenge(_ challenge: ONGCreatePinChallenge) { + func handleDidReceivePinRegistrationChallenge(_ challenge: CreatePinChallenge) { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { SwiftOneginiPlugin.flutterApi?.n2fEventPinNotAllowed(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} @@ -124,15 +95,8 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { extension RegistrationHandler { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { signUpCompletion = completion - - var identityProvider = identityProviders().first(where: { $0.identifier == providerId}) - if let providerId = providerId, identityProvider == nil { - identityProvider = ONGIdentityProvider() - identityProvider?.name = providerId - identityProvider?.identifier = providerId - } - - ONGUserClient.sharedInstance().registerUser(with: identityProvider, scopes: scopes, delegate: self) + let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) + SharedUserClient.instance.registerUserWith(identityProvider: identityProvider, scopes: scopes, delegate: self) } func processRedirectURL(url: String, webSignInType: Int) -> Result { @@ -157,7 +121,7 @@ extension RegistrationHandler { completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) return } - customRegistrationChallenge.sender.respond(withData: data, challenge: customRegistrationChallenge) + customRegistrationChallenge.sender.respond(with: data, to: customRegistrationChallenge) completion(.success) } @@ -179,8 +143,13 @@ extension RegistrationHandler { } } -extension RegistrationHandler: ONGRegistrationDelegate { - func userClient(_: ONGUserClient, didReceive challenge: ONGBrowserRegistrationChallenge) { +extension RegistrationHandler: RegistrationDelegate { + func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { + Logger.log("didReceivePinRegistrationChallenge ONGCreatePinChallenge", sender: self) + handleDidReceivePinRegistrationChallenge(challenge) + } + + func userClient(_ userClient: UserClient, didReceiveBrowserRegistrationChallenge challenge: BrowserRegistrationChallenge) { Logger.log("didReceive ONGBrowserRegistrationChallenge", sender: self) browserRegistrationChallenge = challenge debugPrint(challenge.url) @@ -188,31 +157,30 @@ extension RegistrationHandler: ONGRegistrationDelegate { SwiftOneginiPlugin.flutterApi?.n2fHandleRegisteredUrl(url: challenge.url.absoluteString) {} } - func userClient(_: ONGUserClient, didReceivePinRegistrationChallenge challenge: ONGCreatePinChallenge) { - Logger.log("didReceivePinRegistrationChallenge ONGCreatePinChallenge", sender: self) - handleDidReceivePinRegistrationChallenge(challenge) - } - - func userClient(_ userClient: ONGUserClient, didRegisterUser userProfile: ONGUserProfile, identityProvider: ONGIdentityProvider, info: ONGCustomInfo?) { - handleDidRegisterUser() - signUpCompletion?(.success( - OWRegistrationResponse(userProfile: OWUserProfile(userProfile), - customInfo: toOWCustomInfo(info)))) - } - - func userClient(_: ONGUserClient, didReceiveCustomRegistrationInitChallenge challenge: ONGCustomRegistrationChallenge) { + func userClient(_ userClient: UserClient, didReceiveCustomRegistrationInitChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationInitChallenge ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } - func userClient(_: ONGUserClient, didReceiveCustomRegistrationFinish challenge: ONGCustomRegistrationChallenge) { + func userClient(_ userClient: UserClient, didReceiveCustomRegistrationFinishChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationFinish ONGCustomRegistrationChallenge", sender: self) customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventFinishCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } - func userClient(_ userClient: ONGUserClient, didFailToRegisterWith identityProvider: ONGIdentityProvider, error: Error) { + func userClientDidStartRegistration(_ userClient: UserClient) { + // Unused + } + + func userClient(_ userClient: UserClient, didRegisterUser profile: UserProfile, with identityProvider: IdentityProvider, info: CustomInfo?) { + handleDidRegisterUser() + signUpCompletion?(.success( + OWRegistrationResponse(userProfile: OWUserProfile(profile), + customInfo: toOWCustomInfo(info)))) + } + + func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { signUpCompletion?(.failure(FlutterError(.registrationCancelled))) @@ -223,7 +191,7 @@ extension RegistrationHandler: ONGRegistrationDelegate { } } -private func mapErrorFromPinChallenge(_ challenge: ONGCreatePinChallenge) -> SdkError? { +private func mapErrorFromPinChallenge(_ challenge: CreatePinChallenge) -> SdkError? { if let error = challenge.error { return ErrorMapper().mapError(error) } else { From 7ac7b76e8e0a92f0717846ae79a11672743f9c42 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 10:52:03 +0200 Subject: [PATCH 224/364] FP-52: Use SwiftApi for authenticators --- .../Handlers/AuthenticatorsHandler.swift | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index a4d7cf2d..b1cf63b1 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -1,7 +1,6 @@ import Foundation import OneginiSDKiOS -// MARK: - protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) @@ -9,7 +8,7 @@ protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { } class AuthenticatorsHandler: NSObject { - var pinChallenge: ONGPinChallenge? + var pinChallenge: PinChallenge? var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? var registrationCompletion: ((Result) -> Void)? var deregistrationCompletion: ((Result) -> Void)? @@ -19,7 +18,7 @@ class AuthenticatorsHandler: NSObject { guard let pinChallenge = self.pinChallenge else { return } if let pin = pin { - pinChallenge.sender.respond(withPin: pin, challenge: pinChallenge) + pinChallenge.sender.respond(with: pin, to: pinChallenge) } else { pinChallenge.sender.cancel(pinChallenge) @@ -37,21 +36,21 @@ class AuthenticatorsHandler: NSObject { } } -// MARK: - BridgeToAuthenticatorsHandlerProtocol extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } // We don't have to check if the authenticator is already registered as the sdk will do that for us. - guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile).first(where: { $0.identifier == authenticatorId }) else { + let authenticators = SharedUserClient.instance.authenticators(.all, for: profile) + guard let authenticator = authenticators.first(where: { $0.identifier == authenticatorId }) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } registrationCompletion = completion - ONGUserClient.sharedInstance().register(authenticator, delegate: self) + SharedUserClient.instance.register(authenticator: authenticator, delegate: self) } func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { @@ -86,18 +85,21 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } } -// MARK: - ONGAuthenticatorRegistrationDelegate -extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { - func userClient(_: ONGUserClient, didReceive challenge: ONGPinChallenge) { - Logger.log("[AUTH] userClient didReceive ONGPinChallenge", sender: self) +extension AuthenticatorsHandler: AuthenticatorRegistrationDelegate { + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { + Logger.log("[AUTH] userClient didReceive PinChallenge", sender: self) BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) } - func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthFinishRegistrationChallenge) { + func userClient(_ userClient: UserClient, didReceiveCustomAuthFinishRegistrationChallenge challenge: CustomAuthFinishRegistrationChallenge) { // We currently don't support custom authenticators } - func userClient(_: ONGUserClient, didFailToRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { + func userClient(_ userClient: UserClient, didStartRegistering authenticator: Authenticator, for userProfile: UserProfile) { + // Unused + } + + func userClient(_ userClient: UserClient, didFailToRegister authenticator: Authenticator, for userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) @@ -107,7 +109,7 @@ extension AuthenticatorsHandler: ONGAuthenticatorRegistrationDelegate { } } - func userClient(_: ONGUserClient, didRegister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, info _: ONGCustomInfo?) { + func userClient(_ userClient: UserClient, didRegister authenticator: Authenticator, for userProfile: UserProfile, info customAuthInfo: CustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() registrationCompletion?(.success) From 8b9f275aaf3b8951c39f333de285326b368b33fd Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 11:15:30 +0200 Subject: [PATCH 225/364] FP-32: Remove empty lines added because of wrong line endings This file had CRLF endings instead of LF and SwiftLint converts this to LF but will add extra newlines by accident. This commit removes those newlines. --- example/ios/Runner/AppDelegate.swift | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift index 85d7686f..76197c5d 100644 --- a/example/ios/Runner/AppDelegate.swift +++ b/example/ios/Runner/AppDelegate.swift @@ -1,33 +1,20 @@ import UIKit - import Flutter - import onegini - import OneginiSDKiOS @UIApplicationMain - @objc class AppDelegate: FlutterAppDelegate { override func application( - _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { - let isOneginiUrlCallback: Bool = OneginiModuleSwift.sharedInstance.handleDeepLinkCallbackUrl(url) - debugPrint(isOneginiUrlCallback) - return true - } - } From 74110b18a666ce66e0cc1b51b616d5b91001898c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 11:21:21 +0200 Subject: [PATCH 226/364] FP-32: Match swiftlint.yml with ios native sdk --- example/ios/.swiftlint.yml | 56 +++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/example/ios/.swiftlint.yml b/example/ios/.swiftlint.yml index 0de63b0b..e36d81bd 100644 --- a/example/ios/.swiftlint.yml +++ b/example/ios/.swiftlint.yml @@ -1,8 +1,56 @@ -line_length: 200 -excluded: +# By default, SwiftLint uses a set of sensible default rules you can adjust: +disabled_rules: # rule identifiers turned on by default to exclude from running + +opt_in_rules: # some rules are turned off by default, so you need to opt-in + - empty_count # Find all the available rules by running: `swiftlint rules` + +analyzer_rules: # Rules run by `swiftlint analyze` + - explicit_self + +included: # paths to include during linting. `--path` is ignored if present. + - .symlinks/plugins/onegini/ios + +excluded: # paths to ignore during linting. Takes precedence over `included`. + - .swiftlint.yml - OneginiTests - OneginiUITests - .symlinks/plugins/onegini/ios/Classes/Pigeon.swift -included: - - .symlinks/plugins/onegini/ios +# If true, SwiftLint will not fail if no lintable files are found. +allow_zero_lintable_files: false + +# configurable rules can be customized from this configuration file +# binary rules can set their severity level +# rules that have both warning and error levels, can set just the warning level +# implicitly +line_length: 200 # originally 110 +# they can set both implicitly with an array +type_body_length: + warning: 400 + +# or they can set both explicitly +file_length: + warning: 500 + error: 1200 +# naming rules can set warnings/errors for min_length and max_length +# additionally they can set excluded names +type_name: + min_length: 4 # only warning + max_length: # warning and error + warning: 40 + error: 50 + excluded: iPhone # excluded via string +identifier_name: + min_length: # only min_length + warning: 3 + error: 3 + excluded: # excluded via string array + - id + - x + - y +function_body_length: + warning: 50 +function_parameter_count: # TODO: originally default was error: 5 + warning: 5 + error: 10 +reporter: "xcode" # reporter type (xcode, json, csv, markdown etc.) From 733e9372a6d7bb888584b62303100632fe95a7f5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 11:29:57 +0200 Subject: [PATCH 227/364] FP-32: Move closure parameters to same line as opening brace --- ios/Classes/NativeBridge/OneginiModuleSwift.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index b476d530..dce323a6 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -20,8 +20,7 @@ public class OneginiModuleSwift: NSObject { func startOneginiModule(httpConnectionTimeout: Int64?, callback: @escaping (Result) -> Void) { ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout ?? 5))) ONGClientBuilder().build() - ONGClient.sharedInstance().start { - result, error in + ONGClient.sharedInstance().start { result, error in if let error = error { let mappedError = ErrorMapper().mapError(error) callback(.failure(mappedError.flutterError())) From 2fd2296e1efce96bd2c83edd7dc0ada4196fe6ad Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 14:13:42 +0200 Subject: [PATCH 228/364] FP-52: Use SwiftApi for setpref. and deregister authenticator methods --- .../Handlers/AuthenticatorsHandler.swift | 36 ++++++++++--------- .../OneginiModuleSwift+Auth.swift | 4 +-- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index b1cf63b1..2950faaf 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -3,8 +3,8 @@ import OneginiSDKiOS protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) } class AuthenticatorsHandler: NSObject { @@ -53,8 +53,8 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { SharedUserClient.instance.register(authenticator: authenticator, delegate: self) } - func deregisterAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { + func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } @@ -65,11 +65,11 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } deregistrationCompletion = completion - ONGUserClient.sharedInstance().deregister(authenticator, delegate: self) + SharedUserClient.instance.deregister(authenticator: authenticator, delegate: self) } - func setPreferredAuthenticator(_ userProfile: ONGUserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let authenticator = ONGUserClient.sharedInstance().allAuthenticators(forUser: userProfile).first(where: {$0.identifier == authenticatorId}) else { + func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } @@ -79,8 +79,7 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotRegistered))) return } - - ONGUserClient.sharedInstance().preferredAuthenticator = authenticator + SharedUserClient.instance.setPreferred(authenticator: authenticator) completion(.success) } } @@ -116,17 +115,18 @@ extension AuthenticatorsHandler: AuthenticatorRegistrationDelegate { } } -extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { - func userClient(_: ONGUserClient, didDeregister _: ONGAuthenticator, forUser _: ONGUserProfile) { - Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) - deregistrationCompletion?(.success) +extension AuthenticatorsHandler: AuthenticatorDeregistrationDelegate { + + func userClient(_ userClient: UserClient, didStartDeregistering authenticator: Authenticator, forUser userProfile: UserProfile) { + // Unused } - func userClient(_: ONGUserClient, didReceive challenge: ONGCustomAuthDeregistrationChallenge) { - // We currently don't support custom authenticators + func userClient(_ userClient: UserClient, didDeregister authenticator: Authenticator, forUser userProfile: UserProfile) { + Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) + deregistrationCompletion?(.success) } - func userClient(_: ONGUserClient, didFailToDeregister authenticator: ONGAuthenticator, forUser _: ONGUserProfile, error: Error) { + func userClient(_ userClient: UserClient, didFailToDeregister authenticator: Authenticator, forUser userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { deregistrationCompletion?(.failure(FlutterError(.authenticatorDeregistrationCancelled))) @@ -135,4 +135,8 @@ extension AuthenticatorsHandler: ONGAuthenticatorDeregistrationDelegate { deregistrationCompletion?(.failure(FlutterError(mappedError))) } } + + func userClient(_ userClient: UserClient, didReceiveCustomAuthDeregistrationChallenge challenge: CustomAuthDeregistrationChallenge) { + // We currently don't support custom authenticators + } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 38f1ccc3..49e52e03 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -46,7 +46,7 @@ extension OneginiModuleSwift { } func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { - guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } @@ -54,7 +54,7 @@ extension OneginiModuleSwift { } func deregisterAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { - guard let profile = ONGClient.sharedInstance().userClient.authenticatedUserProfile() else { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } From 077c282759a33f489de3effa1278f4986c29ee26 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 14:27:38 +0200 Subject: [PATCH 229/364] FP-81: Create new delegate on authenticator method calls Previously we were overwriting the stored callback on calling a method twice in a row. This would result in the answer back to Flutter never occuring because it would try to call the last completion twice. This would result in the Future in Flutter never resolving. This commit fixes that by creating seperate delegate objects for every call. These are handled correctly by the underlying native sdk so we don't have to worry about that. --- .../Handlers/AuthenticatorsHandler.swift | 63 +++++++------------ 1 file changed, 22 insertions(+), 41 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 2950faaf..6da80d64 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -1,42 +1,13 @@ import Foundation import OneginiSDKiOS -protocol BridgeToAuthenticatorsHandlerProtocol: AnyObject { +protocol BridgeToAuthenticatorsHandlerProtocol { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) } -class AuthenticatorsHandler: NSObject { - var pinChallenge: PinChallenge? - var customAuthChallenge: ONGCustomAuthFinishRegistrationChallenge? - var registrationCompletion: ((Result) -> Void)? - var deregistrationCompletion: ((Result) -> Void)? - - func handlePin(pin: String?) { - guard let customAuthChallenge = self.customAuthChallenge else { - guard let pinChallenge = self.pinChallenge else { return } - - if let pin = pin { - pinChallenge.sender.respond(with: pin, to: pinChallenge) - - } else { - pinChallenge.sender.cancel(pinChallenge) - } - - return - } - - if let pin = pin { - customAuthChallenge.sender.respond(withData: pin, challenge: customAuthChallenge) - - } else { - customAuthChallenge.sender.cancel(customAuthChallenge, underlyingError: nil) - } - } -} - -extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { +class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) @@ -49,8 +20,8 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotFound))) return } - registrationCompletion = completion - SharedUserClient.instance.register(authenticator: authenticator, delegate: self) + let delegate = AuthenticatorRegistrationDelegateImpl(completion) + SharedUserClient.instance.register(authenticator: authenticator, delegate: delegate) } func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { @@ -63,9 +34,8 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotRegistered))) return } - - deregistrationCompletion = completion - SharedUserClient.instance.deregister(authenticator: authenticator, delegate: self) + let delegate = AuthenticatorDeregistrationDelegateImpl(completion) + SharedUserClient.instance.deregister(authenticator: authenticator, delegate: delegate) } func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { @@ -84,7 +54,13 @@ extension AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } } -extension AuthenticatorsHandler: AuthenticatorRegistrationDelegate { +class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { + private var registrationCompletion: ((Result) -> Void)? + + init(_ completion: ((Result) -> Void)?) { + registrationCompletion = completion + } + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { Logger.log("[AUTH] userClient didReceive PinChallenge", sender: self) BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) @@ -115,7 +91,12 @@ extension AuthenticatorsHandler: AuthenticatorRegistrationDelegate { } } -extension AuthenticatorsHandler: AuthenticatorDeregistrationDelegate { +class AuthenticatorDeregistrationDelegateImpl: AuthenticatorDeregistrationDelegate { + private var deregistrationCompletion: ((Result) -> Void) + + init(_ completion: @escaping (Result) -> Void) { + deregistrationCompletion = completion + } func userClient(_ userClient: UserClient, didStartDeregistering authenticator: Authenticator, forUser userProfile: UserProfile) { // Unused @@ -123,16 +104,16 @@ extension AuthenticatorsHandler: AuthenticatorDeregistrationDelegate { func userClient(_ userClient: UserClient, didDeregister authenticator: Authenticator, forUser userProfile: UserProfile) { Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) - deregistrationCompletion?(.success) + deregistrationCompletion(.success) } func userClient(_ userClient: UserClient, didFailToDeregister authenticator: Authenticator, forUser userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { - deregistrationCompletion?(.failure(FlutterError(.authenticatorDeregistrationCancelled))) + deregistrationCompletion(.failure(FlutterError(.authenticatorDeregistrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - deregistrationCompletion?(.failure(FlutterError(mappedError))) + deregistrationCompletion(.failure(FlutterError(mappedError))) } } From 77867f5f462fec7413607fb7750770e279cb0bb4 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 14:35:30 +0200 Subject: [PATCH 230/364] FP-81: Create new delegate on changePin calls Previously we were overwriting the stored callback on calling a method twice in a row. This would result in the answer back to Flutter never occuring because it would try to call the last completion twice. This would result in the Future in Flutter never resolving. This commit fixes that by creating seperate delegate objects for every call. These are handled correctly by the underlying native sdk so we don't have to worry about that. --- .../Connectors/BridgeConnector.swift | 3 +- .../Handlers/ChangePinHandler.swift | 41 ++++++++----------- 2 files changed, 18 insertions(+), 26 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index ef8c8ef0..33b88624 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -6,12 +6,11 @@ class BridgeConnector { var toDeregisterUserHandler = DeregisterUserHandler() let toAuthenticatorsHandler: AuthenticatorsHandler = AuthenticatorsHandler() let toRegistrationHandler = RegistrationHandler() - let toChangePinHandler: ChangePinHandler + let toChangePinHandler = ChangePinHandler() let toMobileAuthHandler = MobileAuthHandler() public static var shared: BridgeConnector? init() { - self.toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationHandler) BridgeConnector.shared = self } } diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index bb8687e0..ce32478b 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -1,32 +1,27 @@ import OneginiSDKiOS import Flutter -class ChangePinHandler: NSObject { - var changePinCompletion: ((Result) -> Void)? - private let loginHandler: LoginHandler - private let registrationHandler: RegistrationHandler - - init(loginHandler: LoginHandler, registrationHandler: RegistrationHandler) { - self.loginHandler = loginHandler - self.registrationHandler = registrationHandler +class ChangePinHandler { + func changePin(completion: @escaping (Result) -> Void) { + let delegate = ChangePinDelegateImpl(completion: completion) + SharedUserClient.instance.changePin(delegate: delegate) } -} + } -extension ChangePinHandler { - func changePin(completion: @escaping (Result) -> Void) { +class ChangePinDelegateImpl: ChangePinDelegate { + private var changePinCompletion: ((Result) -> Void) + + init(completion: @escaping (Result) -> Void) { changePinCompletion = completion - SharedUserClient.instance.changePin(delegate: self) } - } -extension ChangePinHandler: ChangePinDelegate { func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { - loginHandler.handleDidReceiveChallenge(challenge) + BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) } func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { - loginHandler.handleDidAuthenticateUser() - registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) + BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() + BridgeConnector.shared?.toRegistrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } func userClient(_ userClient: UserClient, didStartPinChangeForUser profile: UserProfile) { @@ -34,17 +29,15 @@ extension ChangePinHandler: ChangePinDelegate { } func userClient(_ userClient: UserClient, didChangePinForUser profile: UserProfile) { - registrationHandler.handleDidRegisterUser() - changePinCompletion?(.success) - changePinCompletion = nil + BridgeConnector.shared?.toRegistrationHandler.handleDidRegisterUser() + changePinCompletion(.success) } func userClient(_ userClient: UserClient, didFailToChangePinForUser profile: UserProfile, error: Error) { - loginHandler.handleDidFailToAuthenticateUser() - registrationHandler.handleDidFailToRegister() + BridgeConnector.shared?.toLoginHandler.handleDidFailToAuthenticateUser() + BridgeConnector.shared?.toRegistrationHandler.handleDidFailToRegister() let mappedError = ErrorMapper().mapError(error) - changePinCompletion?(.failure(FlutterError(mappedError))) - changePinCompletion = nil + changePinCompletion(.failure(FlutterError(mappedError))) } } From 92e992e08bd6de206b47b59040df1e823e964f8c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 14:45:21 +0200 Subject: [PATCH 231/364] FP-81: Create new delegate on authenticateUser calls Previously we were overwriting the stored callback on calling a method twice in a row. This would result in the answer back to Flutter never occuring because it would try to call the last completion twice. This would result in the Future in Flutter never resolving. This commit fixes that by creating seperate delegate objects for every call. These are handled correctly by the underlying native sdk so we don't have to worry about that. --- .../NativeBridge/Handlers/LoginHandler.swift | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index fad4e5d8..ceddda7a 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -1,9 +1,8 @@ import OneginiSDKiOS import Flutter -class LoginHandler: NSObject { +class LoginHandler { var pinChallenge: PinChallenge? - var loginCompletion: ((Result) -> Void)? func handlePin(pin: String, completion: (Result) -> Void) { guard let pinChallenge = pinChallenge else { @@ -55,18 +54,22 @@ class LoginHandler: NSObject { SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} pinChallenge = nil } -} -extension LoginHandler { func authenticateUser(_ profile: UserProfile, authenticator: Authenticator?, completion: @escaping (Result) -> Void) { - loginCompletion = completion - SharedUserClient.instance.authenticateUserWith(profile: profile, authenticator: authenticator, delegate: self) + let delegate = AuthenticationDelegateImpl(completion) + SharedUserClient.instance.authenticateUserWith(profile: profile, authenticator: authenticator, delegate: delegate) } } -extension LoginHandler: AuthenticationDelegate { +class AuthenticationDelegateImpl: AuthenticationDelegate { + private var loginCompletion: (Result) -> Void + + init(_ completion: @escaping (Result) -> Void) { + loginCompletion = completion + } + func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { - handleDidReceiveChallenge(challenge) + BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) } func userClient(_ userClient: UserClient, didStartAuthenticationForUser profile: UserProfile, authenticator: Authenticator) { @@ -78,19 +81,19 @@ extension LoginHandler: AuthenticationDelegate { } func userClient(_ userClient: UserClient, didAuthenticateUser profile: UserProfile, authenticator: Authenticator, info customAuthInfo: CustomInfo?) { - handleDidAuthenticateUser() - loginCompletion?(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), + BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() + loginCompletion(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(customAuthInfo)))) } func userClient(_ userClient: UserClient, didFailToAuthenticateUser profile: UserProfile, authenticator: Authenticator, error: Error) { - handleDidFailToAuthenticateUser() + BridgeConnector.shared?.toLoginHandler.handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { - loginCompletion?(.failure(FlutterError(.loginCanceled))) + loginCompletion(.failure(FlutterError(.loginCanceled))) } else { let mappedError = ErrorMapper().mapError(error) - loginCompletion?(.failure(FlutterError(mappedError))) + loginCompletion(.failure(FlutterError(mappedError))) } } } From 26cc178e948a5c4edb78286bc201ad56619c4f8d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 31 Mar 2023 16:13:50 +0200 Subject: [PATCH 232/364] FP-81: Create new delegate object with promise completion on calling register We create a new delegate object when calling registerUser with the Future completion. This makes sure that when we call registerUser twice we don't break our Futures. Note: We had some code which would make the Future fail if somehow the browserRegistrationChallenge was gone when the internal browser would either cancel or succeed. This has been removed and we will have to make sure that we never set this object to nil except when we responded to the Future. This implementation is not perfect, but it is clearly better and can be improved later when we don't have to handle the browser inside the sdk. --- .../Handlers/BrowserHandler.swift | 7 ++- .../Handlers/RegistrationHandler.swift | 55 ++++++++++--------- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift index 2f7cb741..b8dba09b 100644 --- a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift @@ -5,8 +5,9 @@ protocol BrowserHandlerProtocol { func handleUrl(url: URL, webSignInType: WebSignInType) } -protocol BrowserHandlerToRegisterHandlerProtocol: AnyObject { - func handleRedirectURL(url: URL?) +protocol BrowserHandlerToRegisterHandlerProtocol { + func handleRedirectURL(url: URL) + func handleCancelFromBrowser() } // MARK: - BrowserHandlerProtocol @@ -68,7 +69,7 @@ class BrowserViewController: NSObject, BrowserHandlerProtocol { private func cancelButtonPressed() { Logger.log("cancelButtonPressed", sender: self) - registerHandler.handleRedirectURL(url: nil) + registerHandler.handleCancelFromBrowser() } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 86caa6eb..4e37bb40 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -18,7 +18,6 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { var browserRegistrationChallenge: BrowserRegistrationChallenge? var customRegistrationChallenge: CustomRegistrationChallenge? var browserConntroller: BrowserHandlerProtocol? - var signUpCompletion: ((Result) -> Void)? func presentBrowserUserRegistrationView(registrationUserURL: URL, webSignInType: WebSignInType) { guard let browserController = browserConntroller else { @@ -30,20 +29,21 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { browserController.handleUrl(url: registrationUserURL, webSignInType: webSignInType) } - func handleRedirectURL(url: URL?) { - Logger.log("handleRedirectURL url: \(url?.absoluteString ?? "nil")", sender: self) - guard let browserRegistrationChallenge = self.browserRegistrationChallenge else { - // FIXME: Registration not in progress error here - signUpCompletion?(.failure(FlutterError(.genericError))) + func handleRedirectURL(url: URL) { + Logger.log("handleRedirectURL url: \(url.absoluteString)", sender: self) + // FIXME: browserRegistrationChallenge is only set to nil when we finish or fail registration, so this will work but will need a refactor if the internal browser ever gets removed. + guard let browserRegistrationChallenge = browserRegistrationChallenge else { return } + browserRegistrationChallenge.sender.respond(with: url, to: browserRegistrationChallenge) + } - guard let url = url else { - browserRegistrationChallenge.sender.cancel(browserRegistrationChallenge) + func handleCancelFromBrowser() { + // FIXME: browserRegistrationChallenge is only set to nil when we finish or fail registration, so this will work but will need a refactor if the internal browser ever gets removed. + guard let browserRegistrationChallenge = browserRegistrationChallenge else { return } - - browserRegistrationChallenge.sender.respond(with: url, to: browserRegistrationChallenge) + browserRegistrationChallenge.sender.cancel(browserRegistrationChallenge) } func handlePin(pin: String, completion: (Result) -> Void) { @@ -90,25 +90,20 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { browserRegistrationChallenge = nil SwiftOneginiPlugin.flutterApi?.n2fClosePin {} } -} -extension RegistrationHandler { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { - signUpCompletion = completion let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) - SharedUserClient.instance.registerUserWith(identityProvider: identityProvider, scopes: scopes, delegate: self) + let delegate = RegistrationDelegateImpl(completion) + SharedUserClient.instance.registerUserWith(identityProvider: identityProvider, scopes: scopes, delegate: delegate) } func processRedirectURL(url: String, webSignInType: Int) -> Result { let webSignInType = WebSignInType(rawValue: webSignInType) guard let url = URL.init(string: url) else { - // FIXME: This doesn't seem right, we're canceling the whole registration here??? - signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return .failure(FlutterError(.providedUrlIncorrect)) } if webSignInType != .insideApp && !UIApplication.shared.canOpenURL(url) { - signUpCompletion?(.failure(FlutterError(.providedUrlIncorrect))) return .failure(FlutterError(.providedUrlIncorrect)) } @@ -143,15 +138,21 @@ extension RegistrationHandler { } } -extension RegistrationHandler: RegistrationDelegate { +class RegistrationDelegateImpl: RegistrationDelegate { + private let signUpCompletion: ((Result) -> Void) + + init(_ completion: @escaping (Result) -> Void) { + signUpCompletion = completion + } + func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { Logger.log("didReceivePinRegistrationChallenge ONGCreatePinChallenge", sender: self) - handleDidReceivePinRegistrationChallenge(challenge) + BridgeConnector.shared?.toRegistrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } func userClient(_ userClient: UserClient, didReceiveBrowserRegistrationChallenge challenge: BrowserRegistrationChallenge) { Logger.log("didReceive ONGBrowserRegistrationChallenge", sender: self) - browserRegistrationChallenge = challenge + BridgeConnector.shared?.toRegistrationHandler.browserRegistrationChallenge = challenge debugPrint(challenge.url) SwiftOneginiPlugin.flutterApi?.n2fHandleRegisteredUrl(url: challenge.url.absoluteString) {} @@ -159,13 +160,13 @@ extension RegistrationHandler: RegistrationDelegate { func userClient(_ userClient: UserClient, didReceiveCustomRegistrationInitChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationInitChallenge ONGCustomRegistrationChallenge", sender: self) - customRegistrationChallenge = challenge + BridgeConnector.shared?.toRegistrationHandler.customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } func userClient(_ userClient: UserClient, didReceiveCustomRegistrationFinishChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationFinish ONGCustomRegistrationChallenge", sender: self) - customRegistrationChallenge = challenge + BridgeConnector.shared?.toRegistrationHandler.customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventFinishCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } @@ -174,19 +175,19 @@ extension RegistrationHandler: RegistrationDelegate { } func userClient(_ userClient: UserClient, didRegisterUser profile: UserProfile, with identityProvider: IdentityProvider, info: CustomInfo?) { - handleDidRegisterUser() - signUpCompletion?(.success( + BridgeConnector.shared?.toRegistrationHandler.handleDidRegisterUser() + signUpCompletion(.success( OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(info)))) } func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { - handleDidFailToRegister() + BridgeConnector.shared?.toRegistrationHandler.handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { - signUpCompletion?(.failure(FlutterError(.registrationCancelled))) + signUpCompletion(.failure(FlutterError(.registrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - signUpCompletion?(.failure(FlutterError(mappedError))) + signUpCompletion(.failure(FlutterError(mappedError))) } } } From 09ca4b7d1303c8dd6fa26c07167926c34fb095d0 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 3 Apr 2023 11:06:01 +0200 Subject: [PATCH 233/364] FP-81: Directly pass in the registrationHandler into the delegate Previously we were accessing the registrationHandler through a global object. This commit changes this by passing it into the constructor. --- .../Handlers/RegistrationHandler.swift | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 4e37bb40..238b9919 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -93,7 +93,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) - let delegate = RegistrationDelegateImpl(completion) + let delegate = RegistrationDelegateImpl(completion, self) SharedUserClient.instance.registerUserWith(identityProvider: identityProvider, scopes: scopes, delegate: delegate) } @@ -140,19 +140,21 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { class RegistrationDelegateImpl: RegistrationDelegate { private let signUpCompletion: ((Result) -> Void) + private let registrationHandler: RegistrationHandler - init(_ completion: @escaping (Result) -> Void) { + init(_ completion: @escaping (Result) -> Void, _ registrationHandler: RegistrationHandler) { signUpCompletion = completion + self.registrationHandler = registrationHandler } func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { Logger.log("didReceivePinRegistrationChallenge ONGCreatePinChallenge", sender: self) - BridgeConnector.shared?.toRegistrationHandler.handleDidReceivePinRegistrationChallenge(challenge) + registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } func userClient(_ userClient: UserClient, didReceiveBrowserRegistrationChallenge challenge: BrowserRegistrationChallenge) { Logger.log("didReceive ONGBrowserRegistrationChallenge", sender: self) - BridgeConnector.shared?.toRegistrationHandler.browserRegistrationChallenge = challenge + registrationHandler.browserRegistrationChallenge = challenge debugPrint(challenge.url) SwiftOneginiPlugin.flutterApi?.n2fHandleRegisteredUrl(url: challenge.url.absoluteString) {} @@ -160,13 +162,13 @@ class RegistrationDelegateImpl: RegistrationDelegate { func userClient(_ userClient: UserClient, didReceiveCustomRegistrationInitChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationInitChallenge ONGCustomRegistrationChallenge", sender: self) - BridgeConnector.shared?.toRegistrationHandler.customRegistrationChallenge = challenge + registrationHandler.customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventInitCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } func userClient(_ userClient: UserClient, didReceiveCustomRegistrationFinishChallenge challenge: CustomRegistrationChallenge) { Logger.log("didReceiveCustomRegistrationFinish ONGCustomRegistrationChallenge", sender: self) - BridgeConnector.shared?.toRegistrationHandler.customRegistrationChallenge = challenge + registrationHandler.customRegistrationChallenge = challenge SwiftOneginiPlugin.flutterApi?.n2fEventFinishCustomRegistration(customInfo: toOWCustomInfo(challenge.info), providerId: challenge.identityProvider.identifier) {} } @@ -175,14 +177,14 @@ class RegistrationDelegateImpl: RegistrationDelegate { } func userClient(_ userClient: UserClient, didRegisterUser profile: UserProfile, with identityProvider: IdentityProvider, info: CustomInfo?) { - BridgeConnector.shared?.toRegistrationHandler.handleDidRegisterUser() + registrationHandler.handleDidRegisterUser() signUpCompletion(.success( OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(info)))) } func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { - BridgeConnector.shared?.toRegistrationHandler.handleDidFailToRegister() + registrationHandler.handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { signUpCompletion(.failure(FlutterError(.registrationCancelled))) } else { From c6cd0adf3f19c491d9d8c5b7c4f88cb96fc791c2 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 3 Apr 2023 11:13:09 +0200 Subject: [PATCH 234/364] FP-81: Directly pass in the loginHandler into the delegate Previously we were accessing the loginHandler through a global object. This commit changes this by passing it into the constructor. --- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index ceddda7a..71c9faeb 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -56,20 +56,22 @@ class LoginHandler { } func authenticateUser(_ profile: UserProfile, authenticator: Authenticator?, completion: @escaping (Result) -> Void) { - let delegate = AuthenticationDelegateImpl(completion) + let delegate = AuthenticationDelegateImpl(completion, self) SharedUserClient.instance.authenticateUserWith(profile: profile, authenticator: authenticator, delegate: delegate) } } class AuthenticationDelegateImpl: AuthenticationDelegate { private var loginCompletion: (Result) -> Void + private let loginHandler: LoginHandler - init(_ completion: @escaping (Result) -> Void) { + init(_ completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler) { loginCompletion = completion + self.loginHandler = loginHandler } func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { - BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) + loginHandler.handleDidReceiveChallenge(challenge) } func userClient(_ userClient: UserClient, didStartAuthenticationForUser profile: UserProfile, authenticator: Authenticator) { @@ -81,13 +83,13 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { } func userClient(_ userClient: UserClient, didAuthenticateUser profile: UserProfile, authenticator: Authenticator, info customAuthInfo: CustomInfo?) { - BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() + loginHandler.handleDidAuthenticateUser() loginCompletion(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(customAuthInfo)))) } func userClient(_ userClient: UserClient, didFailToAuthenticateUser profile: UserProfile, authenticator: Authenticator, error: Error) { - BridgeConnector.shared?.toLoginHandler.handleDidFailToAuthenticateUser() + loginHandler.handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { loginCompletion(.failure(FlutterError(.loginCanceled))) From 06a819b6db805cb9e253902aaec2d1f6c2b05c82 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 3 Apr 2023 11:13:50 +0200 Subject: [PATCH 235/364] FP-81: Directly pass in the handlers into delegate for changePin Previously we were accessing the login/register handler through a global object. This commit changes this by passing it into the init. --- .../Connectors/BridgeConnector.swift | 3 ++- .../Handlers/ChangePinHandler.swift | 26 +++++++++++++------ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index 33b88624..123cc80b 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -6,11 +6,12 @@ class BridgeConnector { var toDeregisterUserHandler = DeregisterUserHandler() let toAuthenticatorsHandler: AuthenticatorsHandler = AuthenticatorsHandler() let toRegistrationHandler = RegistrationHandler() - let toChangePinHandler = ChangePinHandler() + let toChangePinHandler: ChangePinHandler let toMobileAuthHandler = MobileAuthHandler() public static var shared: BridgeConnector? init() { + toChangePinHandler = ChangePinHandler(toLoginHandler, toRegistrationHandler) BridgeConnector.shared = self } } diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index ce32478b..4207742a 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -2,26 +2,36 @@ import OneginiSDKiOS import Flutter class ChangePinHandler { + private let loginHandler: LoginHandler + private let registrationHandler: RegistrationHandler + init(_ loginHandler: LoginHandler, _ registrationHandler: RegistrationHandler) { + self.loginHandler = loginHandler + self.registrationHandler = registrationHandler + } func changePin(completion: @escaping (Result) -> Void) { - let delegate = ChangePinDelegateImpl(completion: completion) + let delegate = ChangePinDelegateImpl(completion: completion, loginHandler, registrationHandler) SharedUserClient.instance.changePin(delegate: delegate) } } class ChangePinDelegateImpl: ChangePinDelegate { private var changePinCompletion: ((Result) -> Void) + private let loginHandler: LoginHandler + private let registrationHandler: RegistrationHandler - init(completion: @escaping (Result) -> Void) { + init(completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler, _ registrationHandler: RegistrationHandler) { changePinCompletion = completion + self.loginHandler = loginHandler + self.registrationHandler = registrationHandler } func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { - BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) + loginHandler.handleDidReceiveChallenge(challenge) } func userClient(_ userClient: UserClient, didReceiveCreatePinChallenge challenge: CreatePinChallenge) { - BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() - BridgeConnector.shared?.toRegistrationHandler.handleDidReceivePinRegistrationChallenge(challenge) + loginHandler.handleDidAuthenticateUser() + registrationHandler.handleDidReceivePinRegistrationChallenge(challenge) } func userClient(_ userClient: UserClient, didStartPinChangeForUser profile: UserProfile) { @@ -29,13 +39,13 @@ class ChangePinDelegateImpl: ChangePinDelegate { } func userClient(_ userClient: UserClient, didChangePinForUser profile: UserProfile) { - BridgeConnector.shared?.toRegistrationHandler.handleDidRegisterUser() + registrationHandler.handleDidRegisterUser() changePinCompletion(.success) } func userClient(_ userClient: UserClient, didFailToChangePinForUser profile: UserProfile, error: Error) { - BridgeConnector.shared?.toLoginHandler.handleDidFailToAuthenticateUser() - BridgeConnector.shared?.toRegistrationHandler.handleDidFailToRegister() + loginHandler.handleDidFailToAuthenticateUser() + registrationHandler.handleDidFailToRegister() let mappedError = ErrorMapper().mapError(error) changePinCompletion(.failure(FlutterError(mappedError))) From ef8a57cb7f5c653ca5fc4069237f755432e6780a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 3 Apr 2023 11:52:32 +0200 Subject: [PATCH 236/364] FP-81: Rename completions and make them const --- .../NativeBridge/Handlers/ChangePinHandler.swift | 10 +++++----- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 10 +++++----- .../NativeBridge/Handlers/RegistrationHandler.swift | 10 +++++----- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 4207742a..35e5d689 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -12,15 +12,15 @@ class ChangePinHandler { let delegate = ChangePinDelegateImpl(completion: completion, loginHandler, registrationHandler) SharedUserClient.instance.changePin(delegate: delegate) } - } +} class ChangePinDelegateImpl: ChangePinDelegate { - private var changePinCompletion: ((Result) -> Void) + private let completion: ((Result) -> Void) private let loginHandler: LoginHandler private let registrationHandler: RegistrationHandler init(completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler, _ registrationHandler: RegistrationHandler) { - changePinCompletion = completion + self.completion = completion self.loginHandler = loginHandler self.registrationHandler = registrationHandler } @@ -40,7 +40,7 @@ class ChangePinDelegateImpl: ChangePinDelegate { func userClient(_ userClient: UserClient, didChangePinForUser profile: UserProfile) { registrationHandler.handleDidRegisterUser() - changePinCompletion(.success) + completion(.success) } func userClient(_ userClient: UserClient, didFailToChangePinForUser profile: UserProfile, error: Error) { @@ -48,6 +48,6 @@ class ChangePinDelegateImpl: ChangePinDelegate { registrationHandler.handleDidFailToRegister() let mappedError = ErrorMapper().mapError(error) - changePinCompletion(.failure(FlutterError(mappedError))) + completion(.failure(FlutterError(mappedError))) } } diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 71c9faeb..d1ef9da9 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -62,11 +62,11 @@ class LoginHandler { } class AuthenticationDelegateImpl: AuthenticationDelegate { - private var loginCompletion: (Result) -> Void + private let completion: (Result) -> Void private let loginHandler: LoginHandler init(_ completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler) { - loginCompletion = completion + self.completion = completion self.loginHandler = loginHandler } @@ -84,7 +84,7 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { func userClient(_ userClient: UserClient, didAuthenticateUser profile: UserProfile, authenticator: Authenticator, info customAuthInfo: CustomInfo?) { loginHandler.handleDidAuthenticateUser() - loginCompletion(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), + completion(.success(OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(customAuthInfo)))) } @@ -92,10 +92,10 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { loginHandler.handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { - loginCompletion(.failure(FlutterError(.loginCanceled))) + completion(.failure(FlutterError(.loginCanceled))) } else { let mappedError = ErrorMapper().mapError(error) - loginCompletion(.failure(FlutterError(mappedError))) + completion(.failure(FlutterError(mappedError))) } } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 238b9919..fc97965c 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -139,11 +139,11 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { } class RegistrationDelegateImpl: RegistrationDelegate { - private let signUpCompletion: ((Result) -> Void) + private let completion: ((Result) -> Void) private let registrationHandler: RegistrationHandler init(_ completion: @escaping (Result) -> Void, _ registrationHandler: RegistrationHandler) { - signUpCompletion = completion + self.completion = completion self.registrationHandler = registrationHandler } @@ -178,7 +178,7 @@ class RegistrationDelegateImpl: RegistrationDelegate { func userClient(_ userClient: UserClient, didRegisterUser profile: UserProfile, with identityProvider: IdentityProvider, info: CustomInfo?) { registrationHandler.handleDidRegisterUser() - signUpCompletion(.success( + completion(.success( OWRegistrationResponse(userProfile: OWUserProfile(profile), customInfo: toOWCustomInfo(info)))) } @@ -186,10 +186,10 @@ class RegistrationDelegateImpl: RegistrationDelegate { func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { registrationHandler.handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { - signUpCompletion(.failure(FlutterError(.registrationCancelled))) + completion(.failure(FlutterError(.registrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - signUpCompletion(.failure(FlutterError(mappedError))) + completion(.failure(FlutterError(mappedError))) } } } From 992ee899d6418607d91e5e357864dcc26b7d1097 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 3 Apr 2023 11:52:48 +0200 Subject: [PATCH 237/364] FP-81: Rename completion + make const + dont use global loginhandler --- .../Connectors/BridgeConnector.swift | 3 +- .../Handlers/AuthenticatorsHandler.swift | 35 +++++++++++-------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index 123cc80b..df83fa85 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -4,7 +4,7 @@ class BridgeConnector { let toResourceFetchHandler: FetchResourcesHandlerProtocol = ResourcesHandler() var toLogoutUserHandler = LogoutHandler() var toDeregisterUserHandler = DeregisterUserHandler() - let toAuthenticatorsHandler: AuthenticatorsHandler = AuthenticatorsHandler() + let toAuthenticatorsHandler: AuthenticatorsHandler let toRegistrationHandler = RegistrationHandler() let toChangePinHandler: ChangePinHandler let toMobileAuthHandler = MobileAuthHandler() @@ -12,6 +12,7 @@ class BridgeConnector { init() { toChangePinHandler = ChangePinHandler(toLoginHandler, toRegistrationHandler) + toAuthenticatorsHandler = AuthenticatorsHandler(toLoginHandler) BridgeConnector.shared = self } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 6da80d64..c2b5cb8d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -8,6 +8,11 @@ protocol BridgeToAuthenticatorsHandlerProtocol { } class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { + private let loginHandler: LoginHandler + + init(_ loginHandler: LoginHandler) { + self.loginHandler = loginHandler + } func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) @@ -20,7 +25,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotFound))) return } - let delegate = AuthenticatorRegistrationDelegateImpl(completion) + let delegate = AuthenticatorRegistrationDelegateImpl(completion, loginHandler) SharedUserClient.instance.register(authenticator: authenticator, delegate: delegate) } @@ -55,15 +60,17 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { - private var registrationCompletion: ((Result) -> Void)? + private let completion: ((Result) -> Void) + private let loginHandler: LoginHandler - init(_ completion: ((Result) -> Void)?) { - registrationCompletion = completion + init(_ completion: (@escaping (Result) -> Void), _ loginHandler: LoginHandler) { + self.completion = completion + self.loginHandler = loginHandler } func userClient(_ userClient: UserClient, didReceivePinChallenge challenge: PinChallenge) { Logger.log("[AUTH] userClient didReceive PinChallenge", sender: self) - BridgeConnector.shared?.toLoginHandler.handleDidReceiveChallenge(challenge) + loginHandler.handleDidReceiveChallenge(challenge) } func userClient(_ userClient: UserClient, didReceiveCustomAuthFinishRegistrationChallenge challenge: CustomAuthFinishRegistrationChallenge) { @@ -77,25 +84,25 @@ class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { func userClient(_ userClient: UserClient, didFailToRegister authenticator: Authenticator, for userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { - registrationCompletion?(.failure(FlutterError(.authenticatorRegistrationCancelled))) + completion(.failure(FlutterError(.authenticatorRegistrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - registrationCompletion?(.failure(FlutterError(mappedError))) + completion(.failure(FlutterError(mappedError))) } } func userClient(_ userClient: UserClient, didRegister authenticator: Authenticator, for userProfile: UserProfile, info customAuthInfo: CustomInfo?) { Logger.log("[AUTH] userClient didRegister ONGAuthenticator", sender: self) - BridgeConnector.shared?.toLoginHandler.handleDidAuthenticateUser() - registrationCompletion?(.success) + loginHandler.handleDidAuthenticateUser() + completion(.success) } } class AuthenticatorDeregistrationDelegateImpl: AuthenticatorDeregistrationDelegate { - private var deregistrationCompletion: ((Result) -> Void) + private let completion: ((Result) -> Void) init(_ completion: @escaping (Result) -> Void) { - deregistrationCompletion = completion + self.completion = completion } func userClient(_ userClient: UserClient, didStartDeregistering authenticator: Authenticator, forUser userProfile: UserProfile) { @@ -104,16 +111,16 @@ class AuthenticatorDeregistrationDelegateImpl: AuthenticatorDeregistrationDelega func userClient(_ userClient: UserClient, didDeregister authenticator: Authenticator, forUser userProfile: UserProfile) { Logger.log("[AUTH] userClient didDeregister ONGAuthenticator", sender: self) - deregistrationCompletion(.success) + completion(.success) } func userClient(_ userClient: UserClient, didFailToDeregister authenticator: Authenticator, forUser userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { - deregistrationCompletion(.failure(FlutterError(.authenticatorDeregistrationCancelled))) + completion(.failure(FlutterError(.authenticatorDeregistrationCancelled))) } else { let mappedError = ErrorMapper().mapError(error) - deregistrationCompletion(.failure(FlutterError(mappedError))) + completion(.failure(FlutterError(mappedError))) } } From 673a07f8d6d022331fa64eff17527c5685e78751 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 3 Apr 2023 16:44:31 +0200 Subject: [PATCH 238/364] FP-38 Integrate absolute paths on android; bump ios sdk to 12.1.1 to contain bug fix for absolute resource urls; extend startapp function with additional resource urls to allow absolute urls on iOS as defined in 12.1.1 --- .../onegini/mobile/sdk/flutter/PigeonInterface.kt | 3 ++- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 5 +++-- .../sdk/flutter/useCases/ResourceRequestUseCase.kt | 12 ++++++++---- example/ios/Podfile.lock | 8 ++++---- example/lib/main.dart | 3 ++- .../NativeBridge/Handlers/ResourcesHandler.swift | 1 + ios/Classes/NativeBridge/OneginiModuleSwift.swift | 3 ++- ios/Classes/Pigeon.swift | 5 +++-- ios/Classes/SwiftOneginiPlugin.swift | 3 ++- ios/onegini.podspec | 4 ++-- lib/onegini.dart | 4 +++- lib/pigeon.dart | 4 ++-- pigeons/onewelcome_pigeon_interface.dart | 1 + 13 files changed, 35 insertions(+), 21 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index a2efc5ad..01081782 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -135,9 +135,10 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { customIdentityProviderConfigs: List?, connectionTimeout: Long?, readTimeout: Long?, + additionalResourceUrls: List?, // iOS only callback: (Result) -> Unit ) { - startAppUseCase(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout, callback ) + startAppUseCase(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout, callback) } override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index d8c1cf88..08d462fc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -421,7 +421,7 @@ private object UserClientApiCodec : StandardMessageCodec() { * Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface UserClientApi { - fun startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: List?, connectionTimeout: Long?, readTimeout: Long?, callback: (Result) -> Unit) + fun startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: List?, connectionTimeout: Long?, readTimeout: Long?, additionalResourceUrls: List?, callback: (Result) -> Unit) fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) @@ -482,7 +482,8 @@ interface UserClientApi { val customIdentityProviderConfigsArg = args[2] as List? val connectionTimeoutArg = args[3].let { if (it is Int) it.toLong() else it as Long? } val readTimeoutArg = args[4].let { if (it is Int) it.toLong() else it as Long? } - api.startApplication(securityControllerClassNameArg, configModelClassNameArg, customIdentityProviderConfigsArg, connectionTimeoutArg, readTimeoutArg) { result: Result -> + val additionalResourceUrlsArg = args[5] as List? + api.startApplication(securityControllerClassNameArg, configModelClassNameArg, customIdentityProviderConfigsArg, connectionTimeoutArg, readTimeoutArg, additionalResourceUrlsArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index b0d46755..526f3b73 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -19,6 +19,8 @@ import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.io.IOException +import java.net.MalformedURLException +import java.net.URL import javax.inject.Inject import javax.inject.Singleton @@ -49,12 +51,14 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini } private fun getCompleteResourceUrl(path: String): String { - // TODO Add support for multiple base resource urls; https://onewelcome.atlassian.net/browse/FP-38 val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - return when (path.startsWith(resourceBaseUrl)) { - true -> path - else -> resourceBaseUrl + path + // Check for absolute or relative url + return try { + URL(path) + path + } catch (e: MalformedURLException) { + resourceBaseUrl + path } } diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 1ccd1fcb..769468f9 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -19,9 +19,9 @@ PODS: - Flutter - Toast - MTBBarcodeScanner (5.0.11) - - onegini (1.2.0): + - onegini (1.2.1): - Flutter - - OneginiSDKiOS (~> 12.1.0) + - OneginiSDKiOS (~> 12.1.1) - OneginiSDKiOS (12.1.1): - AFNetworking (~> 4.0.1) - Typhoon (~> 4.0.8) @@ -76,13 +76,13 @@ SPEC CHECKSUMS: Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 fluttertoast: eb263d302cc92e04176c053d2385237e9f43fad0 MTBBarcodeScanner: f453b33c4b7dfe545d8c6484ed744d55671788cb - onegini: bcef895403897119a1f340413bc75b8c1328624c + onegini: b50096e5ee0b261f160acf4437bba6a85a5188d0 OneginiSDKiOS: 81e27e24e901cfe41e09f46b8c673fd5b5b855e9 qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e SwiftLint: 77f7cb2b9bb81ab4a12fcc86448ba3f11afa50c6 Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 + url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de PODFILE CHECKSUM: e49c186fd5db1b7547d2a80e7096f4e0713e90f9 diff --git a/example/lib/main.dart b/example/lib/main.dart index 834fd15c..a9bd3a50 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -68,7 +68,8 @@ class _BodyWidgetState extends State { providerId: "2-way-otp-api", isTwoStep: true) ], connectionTimeout: 5, - readTimeout: 25); + readTimeout: 25, + additionalResourceUrls: []); } catch (error) { showFlutterToast(error.message); } diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 73a668c2..7ee9b0e3 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -65,6 +65,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { private extension ResourcesHandler { func generateONGResourceRequest(_ details: OWRequestDetails) -> ONGResourceRequest { Logger.log("generateONGResourceRequest", sender: self) + return ONGResourceRequest(path: details.path, method: details.method.stringValue, body: details.body?.data(using: .utf8), diff --git a/ios/Classes/NativeBridge/OneginiModuleSwift.swift b/ios/Classes/NativeBridge/OneginiModuleSwift.swift index dce323a6..c1afcc0b 100644 --- a/ios/Classes/NativeBridge/OneginiModuleSwift.swift +++ b/ios/Classes/NativeBridge/OneginiModuleSwift.swift @@ -17,8 +17,9 @@ public class OneginiModuleSwift: NSObject { self.customRegIdentifiers = list } - func startOneginiModule(httpConnectionTimeout: Int64?, callback: @escaping (Result) -> Void) { + func startOneginiModule(httpConnectionTimeout: Int64?, additionalResourceUrls: [String]?, callback: @escaping (Result) -> Void) { ONGClientBuilder().setHttpRequestTimeout(TimeInterval(Double(httpConnectionTimeout ?? 5))) + ONGClientBuilder().setAdditionalResourceUrls(additionalResourceUrls ?? []) ONGClientBuilder().build() ONGClient.sharedInstance().start { result, error in if let error = error { diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 8ee4b9ca..2a469ea5 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -390,7 +390,7 @@ class UserClientApiCodec: FlutterStandardMessageCodec { /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserClientApi { - func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, completion: @escaping (Result) -> Void) + func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, additionalResourceUrls: [String]?, completion: @escaping (Result) -> Void) func registerUser(identityProviderId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) @@ -449,7 +449,8 @@ class UserClientApiSetup { let customIdentityProviderConfigsArg = args[2] as! [OWCustomIdentityProvider]? let connectionTimeoutArg = (args[3] is Int) ? Int64(args[3] as! Int) : args[3] as! Int64? let readTimeoutArg = (args[4] is Int) ? Int64(args[4] as! Int) : args[4] as! Int64? - api.startApplication(securityControllerClassName: securityControllerClassNameArg, configModelClassName: configModelClassNameArg, customIdentityProviderConfigs: customIdentityProviderConfigsArg, connectionTimeout: connectionTimeoutArg, readTimeout: readTimeoutArg) { result in + let additionalResourceUrlsArg = args[5] as! [String]? + api.startApplication(securityControllerClassName: securityControllerClassNameArg, configModelClassName: configModelClassNameArg, customIdentityProviderConfigs: customIdentityProviderConfigsArg, connectionTimeout: connectionTimeoutArg, readTimeout: readTimeoutArg, additionalResourceUrls: additionalResourceUrlsArg) { result in switch result { case .success: reply(wrapResult(nil)) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 07b23f94..5124b708 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -85,8 +85,9 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc customIdentityProviderConfigs: [OWCustomIdentityProvider]?, connectionTimeout: Int64?, readTimeout: Int64?, + additionalResourceUrls: [String]?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout) { result in + OneginiModuleSwift.sharedInstance.startOneginiModule(httpConnectionTimeout: connectionTimeout, additionalResourceUrls: additionalResourceUrls) { result in completion(result.mapError { $0 }) } } diff --git a/ios/onegini.podspec b/ios/onegini.podspec index bae8e33e..3ca69701 100644 --- a/ios/onegini.podspec +++ b/ios/onegini.podspec @@ -4,7 +4,7 @@ # Pod::Spec.new do |s| s.name = 'onegini' - s.version = '1.2.0' + s.version = '1.2.1' s.summary = 'Onegini Mobile Flutter plugin' s.description = <<-DESC The Onegini Flutter Plugin is a plugin that allows you to utilize the Onegini Mobile SDKs in your Flutter applications. @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.platform = :ios, '13.0' # *************************** - s.dependency 'OneginiSDKiOS', '~> 12.1.0' + s.dependency 'OneginiSDKiOS', '~> 12.1.1' # *************************** # Flutter.framework does not contain a i386 slice. diff --git a/lib/onegini.dart b/lib/onegini.dart index 3ec6e094..21f5629d 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -49,6 +49,7 @@ class Onegini { List? customIdentityProviderConfigs, int? connectionTimeout, int? readTimeout, + List? additionalResourceUrls, }) async { _eventListener = eventListener; NativeCallFlutterApi.setup(_eventListener); @@ -57,6 +58,7 @@ class Onegini { configModelClassName, customIdentityProviderConfigs, connectionTimeout, - readTimeout); + readTimeout, + additionalResourceUrls); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dda3df5f..d1b92236 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -410,12 +410,12 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout) async { + Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout, List? arg_additionalResourceUrls) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.startApplication', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout]) as List?; + await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout, arg_additionalResourceUrls]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index a081f3f4..1a151c97 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -133,6 +133,7 @@ abstract class UserClientApi { List? customIdentityProviderConfigs, int? connectionTimeout, int? readTimeout, + List? additionalResourceUrls ); @async From bc9936cb00a802d19d39bc80e64299eba2a57b63 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 4 Apr 2023 09:18:55 +0200 Subject: [PATCH 239/364] FP-30 Auto formatting and removed unused imports --- .../flutter/FlutterOneWelcomeSdkComponent.kt | 1 - .../sdk/flutter/OneWelcomeWrapperErrors.kt | 36 ++-- .../mobile/sdk/flutter/OneginiPlugin.kt | 36 ++-- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 178 +++++++++--------- .../mobile/sdk/flutter/PigeonInterface.kt | 47 ++++- .../sdk/flutter/activity/ActivityWebView.kt | 57 +++--- .../mobile/sdk/flutter/constants/Constants.kt | 14 +- .../flutter/errors/FlutterErrorExtension.kt | 2 +- .../flutter/errors/FlutterPluginException.kt | 4 +- .../mobile/sdk/flutter/facade/UriFacade.kt | 4 +- .../sdk/flutter/facade/UriFacadeImpl.kt | 13 +- .../BrowserRegistrationRequestHandler.kt | 37 ++-- ...FingerprintAuthenticationRequestHandler.kt | 81 ++++---- .../handlers/MobileAuthOtpRequestHandler.kt | 52 ++--- .../PinAuthenticationRequestHandler.kt | 61 +++--- .../sdk/flutter/handlers/PinRequestHandler.kt | 68 +++---- .../mobile/sdk/flutter/helpers/SdkError.kt | 148 +++++++-------- .../mobile/sdk/flutter/module/FacadeModule.kt | 5 +- .../module/FlutterOneWelcomeSdkModule.kt | 1 - .../providers/CustomIdentityProvider.kt | 12 +- .../providers/CustomRegistrationAction.kt | 1 - .../providers/CustomRegistrationActionImpl.kt | 1 - .../CustomTwoStepRegistrationActionImpl.kt | 2 - .../useCases/AuthenticateUserUseCase.kt | 1 - .../DeregisterAuthenticatorUseCase.kt | 2 - .../flutter/useCases/DeregisterUserUseCase.kt | 1 - .../EnrollMobileAuthenticationUseCase.kt | 13 +- .../GetAppToWebSingleSignOnUseCase.kt | 56 +++--- .../useCases/HandleRegisteredUrlUseCase.kt | 31 +-- .../PinAuthenticationRequestAcceptUseCase.kt | 1 - .../PinAuthenticationRequestDenyUseCase.kt | 1 - .../PinRegistrationRequestAcceptUseCase.kt | 1 - .../PinRegistrationRequestDenyUseCase.kt | 1 - .../useCases/RegisterAuthenticatorUseCase.kt | 2 - .../flutter/useCases/RegistrationUseCase.kt | 71 +++---- .../useCases/ResourceRequestUseCase.kt | 2 +- .../sdk/flutter/useCases/StartAppUseCase.kt | 64 ++++--- .../mobile/sdk/ChangePinUseCaseTests.kt | 1 - .../DeregisterAuthenticatorUseCaseTests.kt | 1 - .../mobile/sdk/DeregisterUserUseCaseTests.kt | 1 - .../EnrollMobileAuthenticationUseCaseTest.kt | 2 - ...tAuthenticationRequestAcceptUseCaseTest.kt | 1 - ...intAuthenticationRequestDenyUseCaseTest.kt | 2 +- .../FingerprintFallbackToPinUseCaseTest.kt | 2 - .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 1 - .../GetAppToWebSingleSignOnUseCaseTests.kt | 126 ++++++------- ...GetAuthenticatedUserProfileUseCaseTests.kt | 1 - .../sdk/GetIdentityProvidersUseCaseTests.kt | 1 - .../mobile/sdk/GetRedirectUrlUseCaseTests.kt | 1 - ...GetRegisteredAuthenticatorsUseCaseTests.kt | 149 ++++++++------- ...OtpDenyAuthenticationRequestUseCaseTest.kt | 1 - ...nAuthenticationRequestAcceptUseCaseTest.kt | 1 - ...PinAuthenticationRequestDenyUseCaseTest.kt | 3 - ...PinRegistrationRequestAcceptUseCaseTest.kt | 1 - .../PinRegistrationRequestDenyUseCaseTest.kt | 1 - .../sdk/RegisterAuthenticatorUseCaseTests.kt | 1 - .../mobile/sdk/RegistrationUseCaseTests.kt | 1 - .../mobile/sdk/ResourceRequestUseCaseTests.kt | 11 +- .../SetPreferredAuthenticatorUseCaseTests.kt | 1 - .../mobile/sdk/StartAppUseCaseTests.kt | 164 ++++++++-------- .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 1 - 61 files changed, 807 insertions(+), 776 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt index 6f847e58..108fd1d4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/FlutterOneWelcomeSdkComponent.kt @@ -8,6 +8,5 @@ import javax.inject.Singleton @Component(modules = [FlutterOneWelcomeSdkModule::class, FacadeModule::class]) @Singleton interface FlutterOneWelcomeSdkComponent { - fun inject(oneginiPlugin: OneginiPlugin) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 0ee23280..3ae938b9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -1,24 +1,24 @@ package com.onegini.mobile.sdk.flutter enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { - GENERIC_ERROR(8000, "Something went wrong"), - USER_PROFILE_DOES_NOT_EXIST(8001, "The requested User profile does not exist"), - NO_USER_PROFILE_IS_AUTHENTICATED(8002, "There is currently no User Profile authenticated"), - AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), - HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), - ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + GENERIC_ERROR(8000, "Something went wrong"), + USER_PROFILE_DOES_NOT_EXIST(8001, "The requested User profile does not exist"), + NO_USER_PROFILE_IS_AUTHENTICATED(8002, "There is currently no User Profile authenticated"), + AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), + HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), + ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), - AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), - FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), - OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), - BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), - PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), + REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), + AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), + FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), + OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), + BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), + PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), - // Errors that only occur on Android - IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), - ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), - CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), - SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), - UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), + // Errors that only occur on Android + IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), + ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), + CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), + SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), + UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index cbaf1272..ac9360f9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -6,30 +6,26 @@ import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceMethodApi import io.flutter.embedding.engine.plugins.FlutterPlugin -import io.flutter.plugin.common.EventChannel -import io.flutter.plugin.common.MethodChannel -import javax.inject.Inject - /** OneginiPlugin */ class OneginiPlugin : FlutterPlugin, PigeonInterface() { - /// The api that will handle calls from Native -> Flutter - lateinit var nativeApi : NativeCallFlutterApi + /// The api that will handle calls from Native -> Flutter + lateinit var nativeApi: NativeCallFlutterApi - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - // Pigeon setup - // We extend PigeonInterface which has all the implementations for when Flutters calls a native method. - UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) - ResourceMethodApi.setUp(flutterPluginBinding.binaryMessenger, this) - nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) + override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + // Pigeon setup + // We extend PigeonInterface which has all the implementations for when Flutters calls a native method. + UserClientApi.setUp(flutterPluginBinding.binaryMessenger, this) + ResourceMethodApi.setUp(flutterPluginBinding.binaryMessenger, this) + nativeApi = NativeCallFlutterApi(flutterPluginBinding.binaryMessenger) - val component = DaggerFlutterOneWelcomeSdkComponent.builder() - .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext, nativeApi)) - .build() - component.inject(this) - } + val component = DaggerFlutterOneWelcomeSdkComponent.builder() + .flutterOneWelcomeSdkModule(FlutterOneWelcomeSdkModule(flutterPluginBinding.applicationContext, nativeApi)) + .build() + component.inject(this) + } - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { - UserClientApi.setUp(binding.binaryMessenger, null) - } + override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + UserClientApi.setUp(binding.binaryMessenger, null) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index f5b82129..7177feb2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -26,100 +26,106 @@ import javax.inject.Singleton @Singleton class OneginiSDK @Inject constructor( - private val applicationContext: Context, - private val browserRegistrationRequestHandler: BrowserRegistrationRequestHandler, - private val fingerprintRequestHandler: FingerprintAuthenticationRequestHandler, - private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler, - private val createPinRequestHandler: PinRequestHandler, - private val mobileAuthWithOtpRequestHandler: MobileAuthOtpRequestHandler, - private val nativeApi: NativeCallFlutterApi, -){ - - val oneginiClient: OneginiClient - get() = OneginiClient.getInstance()?.let {client -> - return client - } ?: throw FlutterPluginException(ONEWELCOME_SDK_NOT_INITIALIZED) - - private var customRegistrationActions = ArrayList() - - fun buildSDK(securityControllerClassName: String?, - configModelClassName: String?, - customIdentityProviderConfigs: List?, - connectionTimeout: Long?, - readTimeout: Long?) { - val clientBuilder = OneginiClientBuilder(applicationContext, createPinRequestHandler, pinAuthenticationRequestHandler) // handlers for optional functionalities - .setBrowserRegistrationRequestHandler(browserRegistrationRequestHandler) - .setFingerprintAuthenticationRequestHandler(fingerprintRequestHandler) - .setMobileAuthWithOtpRequestHandler(mobileAuthWithOtpRequestHandler) - - initProviders(clientBuilder, customIdentityProviderConfigs) - - if (connectionTimeout != null) { - clientBuilder.setHttpConnectTimeout(TimeUnit.SECONDS.toMillis(connectionTimeout).toInt()) - } - - if (readTimeout != null) { - clientBuilder.setHttpReadTimeout(TimeUnit.SECONDS.toMillis(readTimeout).toInt()) - } - - setConfigModel(clientBuilder, configModelClassName) - setSecurityController(clientBuilder, securityControllerClassName) - - - clientBuilder.build() + private val applicationContext: Context, + private val browserRegistrationRequestHandler: BrowserRegistrationRequestHandler, + private val fingerprintRequestHandler: FingerprintAuthenticationRequestHandler, + private val pinAuthenticationRequestHandler: PinAuthenticationRequestHandler, + private val createPinRequestHandler: PinRequestHandler, + private val mobileAuthWithOtpRequestHandler: MobileAuthOtpRequestHandler, + private val nativeApi: NativeCallFlutterApi, +) { + + val oneginiClient: OneginiClient + get() = OneginiClient.getInstance()?.let { client -> + return client + } ?: throw FlutterPluginException(ONEWELCOME_SDK_NOT_INITIALIZED) + + private var customRegistrationActions = ArrayList() + + fun buildSDK( + securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: List?, + connectionTimeout: Long?, + readTimeout: Long? + ) { + val clientBuilder = OneginiClientBuilder( + applicationContext, + createPinRequestHandler, + pinAuthenticationRequestHandler + ) // handlers for optional functionalities + .setBrowserRegistrationRequestHandler(browserRegistrationRequestHandler) + .setFingerprintAuthenticationRequestHandler(fingerprintRequestHandler) + .setMobileAuthWithOtpRequestHandler(mobileAuthWithOtpRequestHandler) + + initProviders(clientBuilder, customIdentityProviderConfigs) + + if (connectionTimeout != null) { + clientBuilder.setHttpConnectTimeout(TimeUnit.SECONDS.toMillis(connectionTimeout).toInt()) } - fun getCustomRegistrationActions(): ArrayList { - return customRegistrationActions + if (readTimeout != null) { + clientBuilder.setHttpReadTimeout(TimeUnit.SECONDS.toMillis(readTimeout).toInt()) } - private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List?) { - customIdentityProviderConfigs?.forEach { - val action = when (it.isTwoStep) { - true -> CustomTwoStepRegistrationActionImpl(it.providerId, nativeApi) - false -> CustomRegistrationActionImpl(it.providerId, nativeApi) - } + setConfigModel(clientBuilder, configModelClassName) + setSecurityController(clientBuilder, securityControllerClassName) - customRegistrationActions.add(action) - clientBuilder.addCustomIdentityProvider(CustomIdentityProvider(action)) - } + + clientBuilder.build() + } + + fun getCustomRegistrationActions(): ArrayList { + return customRegistrationActions + } + + private fun initProviders(clientBuilder: OneginiClientBuilder, customIdentityProviderConfigs: List?) { + customIdentityProviderConfigs?.forEach { + val action = when (it.isTwoStep) { + true -> CustomTwoStepRegistrationActionImpl(it.providerId, nativeApi) + false -> CustomRegistrationActionImpl(it.providerId, nativeApi) + } + + customRegistrationActions.add(action) + clientBuilder.addCustomIdentityProvider(CustomIdentityProvider(action)) } + } - private fun setConfigModel(clientBuilder: OneginiClientBuilder, configModelClassName: String?) { - if (configModelClassName == null) { - return - } - try { - val clazz = Class.forName(configModelClassName) - val ctor = clazz.getConstructor() - val `object` = ctor.newInstance() - if (`object` is OneginiClientConfigModel) { - clientBuilder.setConfigModel(`object`) - } - } catch (e: Exception) { - e.message?.let { message -> - throw SdkError( - code = CONFIG_ERROR.code, - message = message - ) - } ?: throw SdkError(CONFIG_ERROR) - } + private fun setConfigModel(clientBuilder: OneginiClientBuilder, configModelClassName: String?) { + if (configModelClassName == null) { + return + } + try { + val clazz = Class.forName(configModelClassName) + val ctor = clazz.getConstructor() + val `object` = ctor.newInstance() + if (`object` is OneginiClientConfigModel) { + clientBuilder.setConfigModel(`object`) + } + } catch (e: Exception) { + e.message?.let { message -> + throw SdkError( + code = CONFIG_ERROR.code, + message = message + ) + } ?: throw SdkError(CONFIG_ERROR) } + } - private fun setSecurityController(clientBuilder: OneginiClientBuilder, securityControllerClassName: String?) { - if (securityControllerClassName == null) { - return - } - try { - val securityController = Class.forName(securityControllerClassName) - clientBuilder.setSecurityController(securityController) - } catch (e: ClassNotFoundException) { - e.message?.let { message -> - throw SdkError( - code = SECURITY_CONTROLLER_NOT_FOUND.code, - message = message - ) - } ?: throw SdkError(SECURITY_CONTROLLER_NOT_FOUND) - } + private fun setSecurityController(clientBuilder: OneginiClientBuilder, securityControllerClassName: String?) { + if (securityControllerClassName == null) { + return + } + try { + val securityController = Class.forName(securityControllerClassName) + clientBuilder.setSecurityController(securityController) + } catch (e: ClassNotFoundException) { + e.message?.let { message -> + throw SdkError( + code = SECURITY_CONTROLLER_NOT_FOUND.code, + message = message + ) + } ?: throw SdkError(SECURITY_CONTROLLER_NOT_FOUND) } + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index a2efc5ad..21c769a6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -55,78 +55,115 @@ import javax.inject.Inject open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase + @Inject lateinit var authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase + @Inject lateinit var authenticateUserUseCase: AuthenticateUserUseCase + @Inject lateinit var cancelCustomRegistrationActionUseCase: CancelCustomRegistrationActionUseCase + @Inject lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase + @Inject lateinit var deregisterUserUseCase: DeregisterUserUseCase + @Inject lateinit var getAccessTokenUseCase: GetAccessTokenUseCase + @Inject lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase + @Inject lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase + @Inject lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase + @Inject lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase + @Inject lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase + @Inject lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase + @Inject lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase + @Inject lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase + @Inject lateinit var getUserProfilesUseCase: GetUserProfilesUseCase + @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase + @Inject lateinit var logoutUseCase: LogoutUseCase + @Inject lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase + @Inject lateinit var registrationUseCase: RegistrationUseCase + @Inject lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase + @Inject lateinit var startAppUseCase: StartAppUseCase + @Inject lateinit var submitCustomRegistrationActionUseCase: SubmitCustomRegistrationActionUseCase + @Inject lateinit var changePinUseCase: ChangePinUseCase + @Inject lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase + @Inject lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase + @Inject lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase + @Inject lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase + @Inject lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase + @Inject lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase + @Inject lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + @Inject lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase + @Inject lateinit var enrollMobileAuthenticationUseCase: EnrollMobileAuthenticationUseCase + @Inject lateinit var handleMobileAuthWithOtpUseCase: HandleMobileAuthWithOtpUseCase + @Inject lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase + @Inject lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + @Inject lateinit var oneginiSDK: OneginiSDK override fun startApplication( @@ -137,7 +174,14 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { readTimeout: Long?, callback: (Result) -> Unit ) { - startAppUseCase(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout, callback ) + startAppUseCase( + securityControllerClassName, + configModelClassName, + customIdentityProviderConfigs, + connectionTimeout, + readTimeout, + callback + ) } override fun registerUser(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { @@ -286,6 +330,7 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { resourceRequestUseCase(type, details, callback) } } + fun CustomInfo.mapToOwCustomInfo(): OWCustomInfo { return OWCustomInfo(this.status.toLong(), this.data) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt index 0b4e8679..89d952a4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/activity/ActivityWebView.kt @@ -12,36 +12,35 @@ import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase import javax.inject.Inject +class ActivityWebView : Activity() { + @Inject + lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase -class ActivityWebView: Activity() { - @Inject - lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase - - @SuppressLint("SetJavaScriptEnabled") - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.layout_webview) - val redirectUrl = intent.getStringExtra("redirectUrl") - val redirectUri = Uri.parse(redirectUrl) - val myWebView: WebView = findViewById(R.id.webview) - myWebView.settings.javaScriptEnabled = true - myWebView.webViewClient = object : WebViewClient() { - override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { - val url = request?.url - if (url?.scheme == redirectUri.scheme) { - BrowserRegistrationRequestHandler.handleRegistrationCallback(url!!) - finish() - return true - } - return super.shouldOverrideUrlLoading(view, request) - } - } - val url = intent.getStringExtra("url") - if (url == null || url.isEmpty()) { - cancelBrowserRegistrationUseCase() - finish() - } else { - myWebView.loadUrl(url) + @SuppressLint("SetJavaScriptEnabled") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.layout_webview) + val redirectUrl = intent.getStringExtra("redirectUrl") + val redirectUri = Uri.parse(redirectUrl) + val myWebView: WebView = findViewById(R.id.webview) + myWebView.settings.javaScriptEnabled = true + myWebView.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { + val url = request?.url + if (url?.scheme == redirectUri.scheme) { + BrowserRegistrationRequestHandler.handleRegistrationCallback(url!!) + finish() + return true } + return super.shouldOverrideUrlLoading(view, request) + } + } + val url = intent.getStringExtra("url") + if (url == null || url.isEmpty()) { + cancelBrowserRegistrationUseCase() + finish() + } else { + myWebView.loadUrl(url) } + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt index 4a57bf3f..fbad090c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/constants/Constants.kt @@ -1,11 +1,11 @@ package com.onegini.mobile.sdk.flutter.constants interface Constants { - companion object { - // HTTP Response properties - const val RESPONSE_STATUS_CODE = "statusCode" - const val RESPONSE_HEADERS = "headers" - const val RESPONSE_BODY = "body" - const val RESPONSE_URL = "url" - } + companion object { + // HTTP Response properties + const val RESPONSE_STATUS_CODE = "statusCode" + const val RESPONSE_HEADERS = "headers" + const val RESPONSE_BODY = "body" + const val RESPONSE_URL = "url" + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt index 9f37198a..8c602dd4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt @@ -4,5 +4,5 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import io.flutter.plugin.common.MethodChannel fun MethodChannel.Result.wrapperError(error: OneWelcomeWrapperErrors) { - this.error(error.code.toString(), error.message, null) + this.error(error.code.toString(), error.message, null) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt index 977d8775..20c04df5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterPluginException.kt @@ -3,6 +3,6 @@ package com.onegini.mobile.sdk.flutter.errors import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.helpers.SdkError -class FlutterPluginException constructor(var errorType: Int, message: String): SdkError(errorType, message) { - constructor(error: OneWelcomeWrapperErrors) : this(error.code, error.message) +class FlutterPluginException constructor(var errorType: Int, message: String) : SdkError(errorType, message) { + constructor(error: OneWelcomeWrapperErrors) : this(error.code, error.message) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt index f1101d65..7085e605 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacade.kt @@ -3,6 +3,6 @@ package com.onegini.mobile.sdk.flutter.facade import android.net.Uri interface UriFacade { - fun parse(string: String): Uri - fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri + fun parse(string: String): Uri + fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt index a1fa14a7..c94bcbf5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt @@ -1,4 +1,3 @@ - package com.onegini.mobile.sdk.flutter.facade import javax.inject.Singleton @@ -7,11 +6,11 @@ import android.net.Uri @Singleton class UriFacadeImpl @Inject constructor() : UriFacade { - override fun parse(string: String): Uri { - return Uri.parse(string) - } + override fun parse(string: String): Uri { + return Uri.parse(string) + } - override fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri { - return Uri.withAppendedPath(baseUri, pathSegment) - } + override fun withAppendedPath(baseUri: Uri, pathSegment: String): Uri { + return Uri.withAppendedPath(baseUri, pathSegment) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt index a1cb2407..8f18b97a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/BrowserRegistrationRequestHandler.kt @@ -9,26 +9,27 @@ import javax.inject.Singleton // TODO Put functions into use cases; https://onewelcome.atlassian.net/browse/FP-35 @Singleton -class BrowserRegistrationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiBrowserRegistrationRequestHandler { +class BrowserRegistrationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi) : + OneginiBrowserRegistrationRequestHandler { - companion object { - var callback: OneginiBrowserRegistrationCallback? = null + companion object { + var callback: OneginiBrowserRegistrationCallback? = null - /** - * Finish registration action with result from web browser - * TODO: Move this to use-case after browser logic rework - * https://onewelcome.atlassian.net/browse/FP-35 - */ - fun handleRegistrationCallback(uri: Uri) { - if (callback != null) { - callback?.handleRegistrationCallback(uri) - callback = null - } - } + /** + * Finish registration action with result from web browser + * TODO: Move this to use-case after browser logic rework + * https://onewelcome.atlassian.net/browse/FP-35 + */ + fun handleRegistrationCallback(uri: Uri) { + if (callback != null) { + callback?.handleRegistrationCallback(uri) + callback = null + } } + } - override fun startRegistration(uri: Uri, oneginiBrowserRegistrationCallback: OneginiBrowserRegistrationCallback) { - callback = oneginiBrowserRegistrationCallback - nativeApi.n2fHandleRegisteredUrl(uri.toString()) {} - } + override fun startRegistration(uri: Uri, oneginiBrowserRegistrationCallback: OneginiBrowserRegistrationCallback) { + callback = oneginiBrowserRegistrationCallback + nativeApi.n2fHandleRegisteredUrl(uri.toString()) {} + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt index f11cfcd0..e066feb3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt @@ -10,44 +10,45 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class FingerprintAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiFingerprintAuthenticationRequestHandler { - - private var fingerprintCallback: OneginiFingerprintCallback? = null - override fun startAuthentication(userProfile: UserProfile, oneginiFingerprintCallback: OneginiFingerprintCallback) { - fingerprintCallback = oneginiFingerprintCallback - nativeApi.n2fOpenFingerprintScreen { } - } - - override fun onNextAuthenticationAttempt() { - nativeApi.n2fReceivedFingerprint { } - } - - override fun onFingerprintCaptured() { - nativeApi.n2fShowScanningFingerprint { } - } - - override fun finishAuthentication() { - nativeApi.n2fCloseFingerprintScreen { } - } - - fun acceptAuthenticationRequest(): Result { - return fingerprintCallback?.let { - it.acceptAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } - - fun denyAuthenticationRequest(): Result { - return fingerprintCallback?.let { - it.denyAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } - - fun fallbackToPin(): Result { - return fingerprintCallback?.let { - it.fallbackToPin() - Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } +class FingerprintAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi) : + OneginiFingerprintAuthenticationRequestHandler { + + private var fingerprintCallback: OneginiFingerprintCallback? = null + override fun startAuthentication(userProfile: UserProfile, oneginiFingerprintCallback: OneginiFingerprintCallback) { + fingerprintCallback = oneginiFingerprintCallback + nativeApi.n2fOpenFingerprintScreen { } + } + + override fun onNextAuthenticationAttempt() { + nativeApi.n2fReceivedFingerprint { } + } + + override fun onFingerprintCaptured() { + nativeApi.n2fShowScanningFingerprint { } + } + + override fun finishAuthentication() { + nativeApi.n2fCloseFingerprintScreen { } + } + + fun acceptAuthenticationRequest(): Result { + return fingerprintCallback?.let { + it.acceptAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun denyAuthenticationRequest(): Result { + return fingerprintCallback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun fallbackToPin(): Result { + return fingerprintCallback?.let { + it.fallbackToPin() + Result.success(Unit) + } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index 77af5f81..3de0acda 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -10,34 +10,34 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiMobileAuthWithOtpRequestHandler { +class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi) : + OneginiMobileAuthWithOtpRequestHandler { + private var callback: OneginiAcceptDenyCallback? = null - private var callback: OneginiAcceptDenyCallback? = null + override fun startAuthentication( + oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest, + oneginiAcceptDenyCallback: OneginiAcceptDenyCallback + ) { + callback = oneginiAcceptDenyCallback + nativeApi.n2fOpenAuthOtp(oneginiMobileAuthenticationRequest.message) {} + } - override fun startAuthentication( - oneginiMobileAuthenticationRequest: OneginiMobileAuthenticationRequest, - oneginiAcceptDenyCallback: OneginiAcceptDenyCallback - ) { - callback = oneginiAcceptDenyCallback - nativeApi.n2fOpenAuthOtp(oneginiMobileAuthenticationRequest.message) {} - } + override fun finishAuthentication() { + nativeApi.n2fCloseAuthOtp {} + callback = null + } - override fun finishAuthentication() { - nativeApi.n2fCloseAuthOtp {} - callback = null - } + fun acceptAuthenticationRequest(): Result { + return callback?.let { + it.acceptAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } - fun acceptAuthenticationRequest(): Result { - return callback?.let { - it.acceptAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } - - fun denyAuthenticationRequest(): Result { - return callback?.let { - it.denyAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } + fun denyAuthenticationRequest(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index a4f098fd..35a0c6bd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -13,35 +13,44 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiPinAuthenticationRequestHandler { - private var callback: OneginiPinCallback? = null +class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi) : + OneginiPinAuthenticationRequestHandler { + private var callback: OneginiPinCallback? = null - override fun startAuthentication(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, attemptCounter: AuthenticationAttemptCounter) { - callback = oneginiPinCallback - nativeApi.n2fOpenPinScreenAuth { } - } + override fun startAuthentication( + userProfile: UserProfile, + oneginiPinCallback: OneginiPinCallback, + attemptCounter: AuthenticationAttemptCounter + ) { + callback = oneginiPinCallback + nativeApi.n2fOpenPinScreenAuth { } + } - override fun onNextAuthenticationAttempt(attemptCounter: AuthenticationAttemptCounter) { - val authenticationAttempt = OWAuthenticationAttempt(attemptCounter.failedAttempts.toLong(), attemptCounter.maxAttempts.toLong(), attemptCounter.remainingAttempts.toLong()); - nativeApi.n2fNextAuthenticationAttempt(authenticationAttempt) {} - } + override fun onNextAuthenticationAttempt(attemptCounter: AuthenticationAttemptCounter) { + val authenticationAttempt = OWAuthenticationAttempt( + attemptCounter.failedAttempts.toLong(), + attemptCounter.maxAttempts.toLong(), + attemptCounter.remainingAttempts.toLong() + ); + nativeApi.n2fNextAuthenticationAttempt(authenticationAttempt) {} + } - override fun finishAuthentication() { - nativeApi.n2fClosePinAuth { } - callback = null - } + override fun finishAuthentication() { + nativeApi.n2fClosePinAuth { } + callback = null + } - fun acceptAuthenticationRequest(pin: CharArray): Result { - return callback?.let { - it.acceptAuthenticationRequest(pin) - Result.success(Unit) - } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } + fun acceptAuthenticationRequest(pin: CharArray): Result { + return callback?.let { + it.acceptAuthenticationRequest(pin) + Result.success(Unit) + } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } - fun denyAuthenticationRequest(): Result { - return callback?.let { - it.denyAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) - } + fun denyAuthenticationRequest(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index 99e894e0..3a647c6a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -5,7 +5,6 @@ import com.onegini.mobile.sdk.android.handlers.request.OneginiCreatePinRequestHa import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PIN_CREATION_NOT_IN_PROGRESS -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWOneginiError @@ -13,35 +12,40 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi): OneginiCreatePinRequestHandler { - - private var callback: OneginiPinCallback? = null - - override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { - callback = oneginiPinCallback - nativeApi.n2fOpenPinRequestScreen { } - } - - override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { - nativeApi.n2fEventPinNotAllowed(OWOneginiError(oneginiPinValidationError.errorType.toLong(), oneginiPinValidationError.message ?: "")) {} - } - - override fun finishPinCreation() { - callback = null - nativeApi.n2fClosePin { } - } - - fun onPinProvided(pin: CharArray): Result { - return callback?.let { - it.acceptAuthenticationRequest(pin) - Result.success(Unit) - } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) - } - - fun cancelPin(): Result { - return callback?.let { - it.denyAuthenticationRequest() - Result.success(Unit) - } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) - } +class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlutterApi) : OneginiCreatePinRequestHandler { + + private var callback: OneginiPinCallback? = null + + override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { + callback = oneginiPinCallback + nativeApi.n2fOpenPinRequestScreen { } + } + + override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { + nativeApi.n2fEventPinNotAllowed( + OWOneginiError( + oneginiPinValidationError.errorType.toLong(), + oneginiPinValidationError.message ?: "" + ) + ) {} + } + + override fun finishPinCreation() { + callback = null + nativeApi.n2fClosePin { } + } + + fun onPinProvided(pin: CharArray): Result { + return callback?.let { + it.acceptAuthenticationRequest(pin) + Result.success(Unit) + } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } + + fun cancelPin(): Result { + return callback?.let { + it.denyAuthenticationRequest() + Result.success(Unit) + } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index b1722132..f95b7dc2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -10,82 +10,82 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import io.flutter.plugin.common.MethodChannel import okhttp3.Response -open class SdkError: Exception { - private val code: Int - override val message: String - private val details: MutableMap = mutableMapOf() - - // Only error codes - constructor( - code: Int, - message: String?, - ) { - this.code = code - this.message = message ?: GENERIC_ERROR.message - - setGenericDetails() +open class SdkError : Exception { + private val code: Int + override val message: String + private val details: MutableMap = mutableMapOf() + + // Only error codes + constructor( + code: Int, + message: String?, + ) { + this.code = code + this.message = message ?: GENERIC_ERROR.message + + setGenericDetails() + } + + constructor( + wrapperError: OneWelcomeWrapperErrors + ) { + this.code = wrapperError.code + this.message = wrapperError.message + + setGenericDetails() + } + + // Error codes with httpResponse information + constructor( + code: Int, + message: String?, + httpResponse: Response, + ) { + this.code = code + this.message = message ?: GENERIC_ERROR.message + + setGenericDetails() + setResponseDetails(httpResponse) + } + + constructor( + wrapperError: OneWelcomeWrapperErrors, + httpResponse: Response, + ) { + this.code = wrapperError.code + this.message = wrapperError.message + + setGenericDetails() + setResponseDetails(httpResponse) + } + + private fun setGenericDetails() { + details["code"] = code.toString() + details["message"] = message + } + + private fun setResponseDetails(httpResponse: Response) { + val response: MutableMap = mutableMapOf() + + response[RESPONSE_URL] = httpResponse.request.url.toString() + response[RESPONSE_STATUS_CODE] = httpResponse.code.toString() + response[RESPONSE_HEADERS] = httpResponse.headers.toMap() + + val bodyString = httpResponse.body?.string() + + response[RESPONSE_BODY] = when (bodyString) { + null -> "" + else -> bodyString } - constructor( - wrapperError: OneWelcomeWrapperErrors - ) { - this.code = wrapperError.code - this.message = wrapperError.message + details["response"] = response + } - setGenericDetails() - } - - // Error codes with httpResponse information - constructor( - code: Int, - message: String?, - httpResponse: Response, - ) { - this.code = code - this.message = message ?: GENERIC_ERROR.message - - setGenericDetails() - setResponseDetails(httpResponse) - } - - constructor( - wrapperError: OneWelcomeWrapperErrors, - httpResponse: Response, - ) { - this.code = wrapperError.code - this.message = wrapperError.message - - setGenericDetails() - setResponseDetails(httpResponse) - } - - private fun setGenericDetails() { - details["code"] = code.toString() - details["message"] = message - } - - private fun setResponseDetails(httpResponse: Response) { - val response: MutableMap = mutableMapOf() + fun flutterError(result: MethodChannel.Result) { + result.error(code.toString(), message, details) + } - response[RESPONSE_URL] = httpResponse.request.url.toString() - response[RESPONSE_STATUS_CODE] = httpResponse.code.toString() - response[RESPONSE_HEADERS] = httpResponse.headers.toMap() - - val bodyString = httpResponse.body?.string() - - response[RESPONSE_BODY] = when (bodyString) { - null -> "" - else -> bodyString - } - - details["response"] = response - } - - fun flutterError(result: MethodChannel.Result) { - result.error(code.toString(), message, details) - } - - fun pigeonError(): FlutterError { - return FlutterError(code.toString(), message, details) - } + fun pigeonError(): FlutterError { + return FlutterError(code.toString(), message, details) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt index 61b4ea37..bdb65a59 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FacadeModule.kt @@ -7,7 +7,6 @@ import dagger.Module @Module interface FacadeModule { - - @Binds - fun bindUriFacade(uriFacade: UriFacadeImpl): UriFacade + @Binds + fun bindUriFacade(uriFacade: UriFacadeImpl): UriFacade } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt index 2a2b340c..5bfeb2c0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/module/FlutterOneWelcomeSdkModule.kt @@ -8,7 +8,6 @@ import javax.inject.Singleton @Module class FlutterOneWelcomeSdkModule(private val applicationContext: Context, private val nativeApi: NativeCallFlutterApi) { - @Provides @Singleton fun provideContext() = applicationContext diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomIdentityProvider.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomIdentityProvider.kt index 86d4de31..015a1de8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomIdentityProvider.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomIdentityProvider.kt @@ -4,11 +4,11 @@ import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationA import com.onegini.mobile.sdk.android.model.OneginiCustomIdentityProvider class CustomIdentityProvider(private val action: CustomRegistrationAction) : OneginiCustomIdentityProvider { - override fun getRegistrationAction(): OneginiCustomRegistrationAction { - return action.getCustomRegistrationAction() - } + override fun getRegistrationAction(): OneginiCustomRegistrationAction { + return action.getCustomRegistrationAction() + } - override fun getId(): String { - return action.getIdProvider() - } + override fun getId(): String { + return action.getIdProvider() + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt index 22a690ef..71b71cb0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt @@ -1,7 +1,6 @@ package com.onegini.mobile.sdk.flutter.providers import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction -import io.flutter.plugin.common.MethodChannel interface CustomRegistrationAction { fun getCustomRegistrationAction(): OneginiCustomRegistrationAction diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 45aaf02e..7cdb2634 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -7,7 +7,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_I import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo class CustomRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 0310ac53..0caf21da 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -8,8 +8,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo -import javax.inject.Inject class CustomTwoStepRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 790eaee2..7a093356 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -9,7 +9,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt index f0bb261b..9d288e6a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt @@ -2,8 +2,6 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorDeregistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorDeregistrationError -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt index c1207bc5..05e78020 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterUserUseCase.kt @@ -13,7 +13,6 @@ class DeregisterUserUseCase @Inject constructor( private val getUserProfileUseCase: GetUserProfileUseCase ) { operator fun invoke(profileId: String, callback: (Result) -> Unit) { - val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt index 4d056f57..b178514b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/EnrollMobileAuthenticationUseCase.kt @@ -2,7 +2,6 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthEnrollmentHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -19,10 +18,14 @@ class EnrollMobileAuthenticationUseCase @Inject constructor( } override fun onError(enrollError: OneginiMobileAuthEnrollmentError) { - callback(Result.failure(SdkError( - code = enrollError.errorType, - message = enrollError.message - ).pigeonError())) + callback( + Result.failure( + SdkError( + code = enrollError.errorType, + message = enrollError.message + ).pigeonError() + ) + ) } }) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt index 49cfbcce..32a66563 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAppToWebSingleSignOnUseCase.kt @@ -12,33 +12,33 @@ import javax.inject.Singleton @Singleton class GetAppToWebSingleSignOnUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val uriFacade: UriFacade) { - operator fun invoke(url: String, callback: (Result) -> Unit) { - val targetUri = uriFacade.parse(url) - oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( - targetUri, - object : OneginiAppToWebSingleSignOnHandler { - override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { - callback( - Result.success( - OWAppToWebSingleSignOn( - oneginiAppToWebSingleSignOn.token, - oneginiAppToWebSingleSignOn.redirectUrl.toString() - ) - ) - ) - } + operator fun invoke(url: String, callback: (Result) -> Unit) { + val targetUri = uriFacade.parse(url) + oneginiSDK.oneginiClient.userClient.getAppToWebSingleSignOn( + targetUri, + object : OneginiAppToWebSingleSignOnHandler { + override fun onSuccess(oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn) { + callback( + Result.success( + OWAppToWebSingleSignOn( + oneginiAppToWebSingleSignOn.token, + oneginiAppToWebSingleSignOn.redirectUrl.toString() + ) + ) + ) + } - override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { - callback( - Result.failure( - SdkError( - code = oneginiSingleSignOnError.errorType, - message = oneginiSingleSignOnError.message - ).pigeonError() - ) - ) - } - } - ) - } + override fun onError(oneginiSingleSignOnError: OneginiAppToWebSingleSignOnError) { + callback( + Result.failure( + SdkError( + code = oneginiSingleSignOnError.errorType, + message = oneginiSingleSignOnError.message + ).pigeonError() + ) + ) + } + } + ) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt index b6819646..926eb9d1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/HandleRegisteredUrlUseCase.kt @@ -10,22 +10,23 @@ import javax.inject.Singleton @Singleton class HandleRegisteredUrlUseCase @Inject constructor(private val context: Context, private val oneginiSDK: OneginiSDK) { - operator fun invoke(url: String, signInType: Long): Result { - val intent = prepareIntentBasedOnType(signInType.toInt(), context, url) - context.startActivity(intent) + operator fun invoke(url: String, signInType: Long): Result { + val intent = prepareIntentBasedOnType(signInType.toInt(), context, url) + context.startActivity(intent) - return Result.success(Unit) - } + return Result.success(Unit) + } - private fun prepareIntentBasedOnType(type: Int?, context: Context, url: String): Intent { - val intent: Intent = if (type == null || type == 0) { - Intent(context, ActivityWebView::class.java).putExtra("url", url).putExtra("redirectUrl", oneginiSDK.oneginiClient.configModel.redirectUri) - } else { - val uri = Uri.parse(url) - Intent(Intent.ACTION_VIEW, uri) - } - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) - return intent + private fun prepareIntentBasedOnType(type: Int?, context: Context, url: String): Intent { + val intent: Intent = if (type == null || type == 0) { + Intent(context, ActivityWebView::class.java).putExtra("url", url) + .putExtra("redirectUrl", oneginiSDK.oneginiClient.configModel.redirectUri) + } else { + val uri = Uri.parse(url) + Intent(Intent.ACTION_VIEW, uri) } + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) + return intent + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt index b2f84901..35c5bbe1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestAcceptUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt index 229ef25a..1499e865 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinAuthenticationRequestDenyUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt index 9a71e2ef..af304835 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestAcceptUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt index 19839947..76040019 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/PinRegistrationRequestDenyUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.PinRequestHandler import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt index b9bd715a..9acd4401 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt @@ -2,9 +2,7 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index 4004ff85..b73a2753 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -9,7 +9,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile @@ -18,39 +17,45 @@ import javax.inject.Singleton @Singleton class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { - val identityProvider = oneginiSDK.oneginiClient.userClient.identityProviders.find { it.id == identityProviderId } + operator fun invoke(identityProviderId: String?, scopes: List?, callback: (Result) -> Unit) { + val identityProvider = oneginiSDK.oneginiClient.userClient.identityProviders.find { it.id == identityProviderId } - if (identityProviderId != null && identityProvider == null) { - callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) - } - - val registerScopes = scopes?.toTypedArray() - - register(identityProvider, registerScopes, callback) + if (identityProviderId != null && identityProvider == null) { + callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) } - private fun register(identityProvider: OneginiIdentityProvider?, scopes: Array?, callback: (Result) -> Unit) { - oneginiSDK.oneginiClient.userClient.registerUser(identityProvider, scopes, object : OneginiRegistrationHandler { - override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) { - val user = OWUserProfile(userProfile.profileId) - - when (customInfo) { - null -> callback(Result.success(OWRegistrationResponse(user))) - else -> { - callback(Result.success(OWRegistrationResponse(user, customInfo.mapToOwCustomInfo()))) - } - } - } - - override fun onError(oneginiRegistrationError: OneginiRegistrationError) { - callback(Result.failure( - SdkError( - code = oneginiRegistrationError.errorType, - message = oneginiRegistrationError.message - ).pigeonError()) - ) - } - }) - } + val registerScopes = scopes?.toTypedArray() + + register(identityProvider, registerScopes, callback) + } + + private fun register( + identityProvider: OneginiIdentityProvider?, + scopes: Array?, + callback: (Result) -> Unit + ) { + oneginiSDK.oneginiClient.userClient.registerUser(identityProvider, scopes, object : OneginiRegistrationHandler { + override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) { + val user = OWUserProfile(userProfile.profileId) + + when (customInfo) { + null -> callback(Result.success(OWRegistrationResponse(user))) + else -> { + callback(Result.success(OWRegistrationResponse(user, customInfo.mapToOwCustomInfo()))) + } + } + } + + override fun onError(oneginiRegistrationError: OneginiRegistrationError) { + callback( + Result.failure( + SdkError( + code = oneginiRegistrationError.errorType, + message = oneginiRegistrationError.message + ).pigeonError() + ) + ) + } + }) + } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index b0d46755..debd6eda 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -63,7 +63,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini // Pigeon 9.0.5 limits enforcing non null values in maps headers?.entries - ?.filter { it.key is String && it.value is String} + ?.filter { it.key is String && it.value is String } ?.forEach { headerBuilder.add(it.key as String, it.value as String) } return headerBuilder.build() diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt index 01353207..4e2abdcd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/StartAppUseCase.kt @@ -13,40 +13,42 @@ import javax.inject.Singleton @Singleton class StartAppUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(securityControllerClassName: String?, - configModelClassName: String?, - customIdentityProviderConfigs: List?, - connectionTimeout: Long?, - readTimeout: Long?, - callback: (Result) -> Unit) { - try { - oneginiSDK.buildSDK(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout) - start(oneginiSDK.oneginiClient, callback) - } catch (error: SdkError) { - callback(Result.failure(error.pigeonError())) - } + operator fun invoke( + securityControllerClassName: String?, + configModelClassName: String?, + customIdentityProviderConfigs: List?, + connectionTimeout: Long?, + readTimeout: Long?, + callback: (Result) -> Unit + ) { + try { + oneginiSDK.buildSDK(securityControllerClassName, configModelClassName, customIdentityProviderConfigs, connectionTimeout, readTimeout) + start(oneginiSDK.oneginiClient, callback) + } catch (error: SdkError) { + callback(Result.failure(error.pigeonError())) } + } - private fun start(oneginiClient: OneginiClient?, callback: (Result) -> Unit) { - if (oneginiClient == null) { - callback(Result.failure(SdkError(ONEWELCOME_SDK_NOT_INITIALIZED).pigeonError())) - } else { - oneginiSDK.oneginiClient.start(object : OneginiInitializationHandler { - override fun onSuccess(removedUserProfiles: Set) { - callback(Result.success(Unit)) - } + private fun start(oneginiClient: OneginiClient?, callback: (Result) -> Unit) { + if (oneginiClient == null) { + callback(Result.failure(SdkError(ONEWELCOME_SDK_NOT_INITIALIZED).pigeonError())) + } else { + oneginiSDK.oneginiClient.start(object : OneginiInitializationHandler { + override fun onSuccess(removedUserProfiles: Set) { + callback(Result.success(Unit)) + } - override fun onError(error: OneginiInitializationError) { - callback( - Result.failure( - SdkError( - code = error.errorType, - message = error.message - ).pigeonError() - ) - ) - } - }) + override fun onError(error: OneginiInitializationError) { + callback( + Result.failure( + SdkError( + code = error.errorType, + message = error.message + ).pigeonError() + ) + ) } + }) } + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index 8b54d8ae..9523b1b3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -21,7 +21,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class ChangePinUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt index 4fd72428..696003c5 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt @@ -24,7 +24,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class DeregisterAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt index e26cfeb8..df47f8c2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt @@ -24,7 +24,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class DeregisterUserUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt index 5eab6bc2..d284cdf6 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt @@ -3,10 +3,8 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.OneginiMobileAuthEnrollmentHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiMobileAuthEnrollmentError import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.useCases.EnrollMobileAuthenticationUseCase import org.junit.Assert diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index 456d72f2..377f6eff 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintAuthenticationRequestAcceptUseCaseTest { - @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index 6f5afe2b..08b67f9f 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintAuthenticationRequestDenyUseCaseTest { - @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback @@ -27,6 +26,7 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler + @Before fun attach() { fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 7882e769..5fe882c8 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class FingerprintFallbackToPinUseCaseTest { - @Mock lateinit var oneginiFingerprintCallbackMock: OneginiFingerprintCallback @@ -61,5 +60,4 @@ class FingerprintFallbackToPinUseCaseTest { fun WhenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } - } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index fb687681..299ac08f 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -15,7 +15,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetAccessTokenUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt index 55674431..84cce9f6 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt @@ -1,21 +1,15 @@ package com.onegini.mobile.sdk import android.net.Uri -import com.google.gson.Gson import com.onegini.mobile.sdk.android.handlers.OneginiAppToWebSingleSignOnHandler -import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAppToWebSingleSignOnError import com.onegini.mobile.sdk.android.model.OneginiAppToWebSingleSignOn -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.facade.UriFacade import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import junit.framework.TestCase.assertEquals import org.junit.Assert import org.junit.Before import org.junit.Test @@ -25,89 +19,87 @@ import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.eq import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetAppToWebSingleSignOnUseCaseTests { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock + lateinit var callbackMock: (Result) -> Unit - @Mock - lateinit var callbackMock: (Result) -> Unit + @Mock + private lateinit var uriFacade: UriFacade + // We need to deep stub here to mock a uri object's .toString() as we cant pass a uriFacade into the OneginiAppToWebSingleSignOn + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private lateinit var oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn - @Mock - private lateinit var uriFacade: UriFacade + @Mock + private lateinit var oneginiAppToWebSingleSignOnError: OneginiAppToWebSingleSignOnError - // We need to deep stub here to mock a uri object's .toString() as we cant pass a uriFacade into the OneginiAppToWebSingleSignOn - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - private lateinit var oneginiAppToWebSingleSignOn: OneginiAppToWebSingleSignOn + @Mock + private lateinit var parsedUri: Uri - @Mock - private lateinit var oneginiAppToWebSingleSignOnError: OneginiAppToWebSingleSignOnError + private val correctUri = "https://login-mobile.test.onegini.com/personal/dashboard" + private val mockedTokenString = "mockedToken" + private val mockedRedirectUrlString = "mockedRedirectUrl" - @Mock - private lateinit var parsedUri: Uri + lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase - private val correctUri = "https://login-mobile.test.onegini.com/personal/dashboard" - private val mockedTokenString = "mockedToken" - private val mockedRedirectUrlString = "mockedRedirectUrl" + @Before + fun setup() { + getAppToWebSingleSignOnUseCase = GetAppToWebSingleSignOnUseCase(oneginiSdk, uriFacade) + } - lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase - @Before - fun setup() { - getAppToWebSingleSignOnUseCase = GetAppToWebSingleSignOnUseCase(oneginiSdk, uriFacade) + @Test + fun `When oginini getAppToWebSingleSignOn calls onSuccess on the handler, Then promise should resolve with a OWAppToWebSingleSignOn with the token and url`() { + mockParseUri(correctUri) + mockSingleSignOnObject() + whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { + it.getArgument(1).onSuccess(oneginiAppToWebSingleSignOn) } - @Test - fun `When oginini getAppToWebSingleSignOn calls onSuccess on the handler, Then promise should resolve with a OWAppToWebSingleSignOn with the token and url`() { - mockParseUri(correctUri) - mockSingleSignOnObject() - whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { - it.getArgument(1).onSuccess(oneginiAppToWebSingleSignOn) - } - - getAppToWebSingleSignOnUseCase(correctUri, callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - Assert.assertEquals(firstValue.getOrNull()?.token, oneginiAppToWebSingleSignOn.token) - Assert.assertEquals(firstValue.getOrNull()?.redirectUrl, oneginiAppToWebSingleSignOn.redirectUrl.toString()) - } + getAppToWebSingleSignOnUseCase(correctUri, callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + Assert.assertEquals(firstValue.getOrNull()?.token, oneginiAppToWebSingleSignOn.token) + Assert.assertEquals(firstValue.getOrNull()?.redirectUrl, oneginiAppToWebSingleSignOn.redirectUrl.toString()) } + } - @Test - fun `When oginini getAppToWebSingleSignOn calls onError on the handler, Then result should fail with the error message and code`() { - mockParseUri(correctUri) - whenSSOReturnsError() + @Test + fun `When oginini getAppToWebSingleSignOn calls onError on the handler, Then result should fail with the error message and code`() { + mockParseUri(correctUri) + whenSSOReturnsError() - getAppToWebSingleSignOnUseCase(correctUri, callbackMock) + getAppToWebSingleSignOnUseCase(correctUri, callbackMock) - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - val expected = FlutterError(oneginiAppToWebSingleSignOnError.errorType.toString(), oneginiAppToWebSingleSignOnError.message) - SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) - } + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiAppToWebSingleSignOnError.errorType.toString(), oneginiAppToWebSingleSignOnError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } - - private fun mockSingleSignOnObject() { - whenever(oneginiAppToWebSingleSignOn.token).thenReturn(mockedTokenString) - whenever(oneginiAppToWebSingleSignOn.redirectUrl.toString()).thenReturn(mockedRedirectUrlString) + } + + private fun mockSingleSignOnObject() { + whenever(oneginiAppToWebSingleSignOn.token).thenReturn(mockedTokenString) + whenever(oneginiAppToWebSingleSignOn.redirectUrl.toString()).thenReturn(mockedRedirectUrlString) + } + + private fun whenSSOReturnsError() { + whenever(oneginiAppToWebSingleSignOnError.errorType).thenReturn(1000) + whenever(oneginiAppToWebSingleSignOnError.message).thenReturn("message") + whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { + it.getArgument(1).onError(oneginiAppToWebSingleSignOnError) } + } - private fun whenSSOReturnsError() { - whenever(oneginiAppToWebSingleSignOnError.errorType).thenReturn(1000) - whenever(oneginiAppToWebSingleSignOnError.message).thenReturn("message") - whenever(oneginiSdk.oneginiClient.userClient.getAppToWebSingleSignOn(any(), any())).thenAnswer { - it.getArgument(1).onError(oneginiAppToWebSingleSignOnError) - } - } - - private fun mockParseUri(uri: String) { - whenever(uriFacade.parse(uri)).thenReturn(parsedUri) - } + private fun mockParseUri(uri: String) { + whenever(uriFacade.parse(uri)).thenReturn(parsedUri) + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index 1bad4627..64464a50 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -16,7 +16,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetAuthenticatedUserProfileUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt index 77f3f9ce..854bf5a2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetIdentityProvidersUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt index d34e095b..1bad38a2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt @@ -15,7 +15,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetRedirectUrlUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index 86f3d73e..9e84a6ff 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -22,77 +22,82 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class GetRegisteredAuthenticatorsUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var clientMock: OneginiClient - - @Mock - lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator - - @Mock - lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - - lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - getRegisteredAuthenticatorsUseCase = GetRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) - } - - @Test - fun `should return empty list when sdk return empty set`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY") - - Assert.assertEquals(result.getOrNull(), mutableListOf>()) - } - - @Test - fun `When UserProfile is null, Then it should return an error`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) - } - - @Test - fun `When getRegisteredAuthenticators method returns not empty set, Then it should return list of registered authenticators `() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorFirstMock, oneginiAuthenticatorSecondMock)) - whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") - whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") - whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(true) - whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) - whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) - - whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") - whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") - whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(true) - whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) - whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY") - - when (val authenticators = result.getOrNull()) { - is List -> { - Assert.assertEquals(authenticators[0].id, "firstId") - Assert.assertEquals(authenticators[0].name, "firstName") - Assert.assertEquals(authenticators[0].isRegistered, true) - Assert.assertEquals(authenticators[0].isPreferred, true) - Assert.assertEquals(authenticators[0].authenticatorType, 5) - - Assert.assertEquals(authenticators[1].id, "secondId") - Assert.assertEquals(authenticators[1].name, "secondName") - Assert.assertEquals(authenticators[1].isRegistered, true) - Assert.assertEquals(authenticators[1].isPreferred, false) - Assert.assertEquals(authenticators[1].authenticatorType, 6) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var clientMock: OneginiClient + + @Mock + lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator + + @Mock + lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator + + lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase + + @Before + fun attach() { + val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) + getRegisteredAuthenticatorsUseCase = GetRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) + } + + @Test + fun `should return empty list when sdk return empty set`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + + val result = getRegisteredAuthenticatorsUseCase("QWERTY") + + Assert.assertEquals(result.getOrNull(), mutableListOf>()) + } + + @Test + fun `When UserProfile is null, Then it should return an error`() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) + + val result = getRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) + } + + @Test + fun `When getRegisteredAuthenticators method returns not empty set, Then it should return list of registered authenticators `() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorFirstMock, + oneginiAuthenticatorSecondMock + ) + ) + whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") + whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") + whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(true) + whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) + whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) + + whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") + whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") + whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(true) + whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) + whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) + + val result = getRegisteredAuthenticatorsUseCase("QWERTY") + + when (val authenticators = result.getOrNull()) { + is List -> { + Assert.assertEquals(authenticators[0].id, "firstId") + Assert.assertEquals(authenticators[0].name, "firstName") + Assert.assertEquals(authenticators[0].isRegistered, true) + Assert.assertEquals(authenticators[0].isPreferred, true) + Assert.assertEquals(authenticators[0].authenticatorType, 5) + + Assert.assertEquals(authenticators[1].id, "secondId") + Assert.assertEquals(authenticators[1].name, "secondName") + Assert.assertEquals(authenticators[1].isRegistered, true) + Assert.assertEquals(authenticators[1].isPreferred, false) + Assert.assertEquals(authenticators[1].authenticatorType, 6) + } + else -> fail(UNEXPECTED_ERROR_TYPE.message) } + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt index aa110d85..7ec77085 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -64,5 +64,4 @@ class OtpDenyAuthenticationRequestUseCaseTest { private fun WhenOTPAuthenticationHasStarted() { mobileAuthOtpRequestHandler.startAuthentication(oneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback) } - } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 445d2d72..4f34f69a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -18,7 +18,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinAuthenticationRequestAcceptUseCaseTest { - @Mock lateinit var oneginiPinCallbackMock: OneginiPinCallback diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index 24e3c494..7a843859 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -7,7 +7,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi -import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCase import org.junit.Assert import org.junit.Before @@ -19,7 +18,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinAuthenticationRequestDenyUseCaseTest { - @Mock lateinit var oneginiPinCallbackMock: OneginiPinCallback @@ -36,7 +34,6 @@ class PinAuthenticationRequestDenyUseCaseTest { lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler - @Before fun before() { pinAuthenticationRequestHandler = PinAuthenticationRequestHandler(nativeApi) diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index a0dbc18a..bfd0d1d3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestAcceptUseCaseTest { - @Mock lateinit var oneginiPinCallbackMock: OneginiPinCallback diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index a5c29496..d8c06611 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -17,7 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestDenyUseCaseTest { - @Mock lateinit var oneginiPinCallbackMock: OneginiPinCallback diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index 127db9fc..2301326d 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -26,7 +26,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class RegisterAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 3307fe02..69df1872 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -25,7 +25,6 @@ import org.mockito.kotlin.* @RunWith(MockitoJUnitRunner::class) class RegistrationUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index bdbf1db0..c3cee043 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -31,7 +31,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class ResourceRequestUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK @@ -70,7 +69,8 @@ class ResourceRequestUseCaseTests { whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) argumentCaptor { whenever( - okhttp3CallMock.enqueue(capture())).thenAnswer { + okhttp3CallMock.enqueue(capture()) + ).thenAnswer { firstValue.onResponse(okhttp3CallMock, responseMock) } } @@ -91,7 +91,8 @@ class ResourceRequestUseCaseTests { whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) argumentCaptor { whenever( - okhttp3CallMock.enqueue(capture())).thenAnswer { + okhttp3CallMock.enqueue(capture()) + ).thenAnswer { firstValue.onResponse(okhttp3CallMock, responseMock) } } @@ -101,7 +102,7 @@ class ResourceRequestUseCaseTests { argumentCaptor>().apply { verify(callbackMock, times(1)).invoke(capture()) - when(val error = firstValue.exceptionOrNull()) { + when (val error = firstValue.exceptionOrNull()) { is FlutterError -> { Assert.assertEquals(error.code.toInt(), ERROR_CODE_HTTP_REQUEST.code) Assert.assertEquals(error.message, ERROR_CODE_HTTP_REQUEST.message) @@ -125,4 +126,4 @@ class ResourceRequestUseCaseTests { val headers = Headers.Builder().add("headerKey", "headerValue").build() whenever(responseMock.headers).thenReturn(headers) } -} \ No newline at end of file +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index 71df687d..a100f5e5 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -19,7 +19,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class SetPreferredAuthenticatorUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt index 8a046344..0873576a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt @@ -20,109 +20,111 @@ import org.mockito.kotlin.* @RunWith(MockitoJUnitRunner::class) class StartAppUseCaseTests { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK + @Mock + lateinit var clientMock: OneginiClient - @Mock - lateinit var clientMock: OneginiClient + @Mock + lateinit var callbackMock: (Result) -> Unit - @Mock - lateinit var callbackMock: (Result) -> Unit + @Mock + lateinit var oneginiInitializationError: OneginiInitializationError - @Mock - lateinit var oneginiInitializationError: OneginiInitializationError + lateinit var startAppUseCase: StartAppUseCase - lateinit var startAppUseCase: StartAppUseCase + @Before + fun attach() { + startAppUseCase = StartAppUseCase(oneginiSdk) + } - @Before - fun attach() { - startAppUseCase = StartAppUseCase(oneginiSdk) - } - - val errorCode = OneginiInitializationError.GENERAL_ERROR - val errorMessage = "General error" + val errorCode = OneginiInitializationError.GENERAL_ERROR + val errorMessage = "General error" - @Test - fun `When onError gets called by oneginiClient, Then should call callback with Result_failure with that error`() { + @Test + fun `When onError gets called by oneginiClient, Then should call callback with Result_failure with that error`() { - whenCallsOnError() + whenCallsOnError() - startAppUseCase( - null, - null, - null, - null, - null, - callbackMock) + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock + ) - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - val expected = FlutterError(oneginiInitializationError.errorType.toString(), oneginiInitializationError.message) - SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) - } + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(oneginiInitializationError.errorType.toString(), oneginiInitializationError.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } + } - @Test - fun `When onSuccess gets called by oneginiClient, Then should call callback with Result_success`() { + @Test + fun `When onSuccess gets called by oneginiClient, Then should call callback with Result_success`() { - whenCallsOnSuccess() + whenCallsOnSuccess() - startAppUseCase( - null, - null, - null, - null, - null, - callbackMock) + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock + ) - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - assertEquals(firstValue.isSuccess, true) - } + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + assertEquals(firstValue.isSuccess, true) } - - @Test - fun `When OneginiSDK_buildSDK throws an exception Then we should reject with that error`() { - whenBuildSdkThrowsSdkError() - - startAppUseCase( - null, - null, - null, - null, - null, - callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - val expected = FlutterError(errorCode.toString(), errorMessage) - SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) - } + } + + @Test + fun `When OneginiSDK_buildSDK throws an exception Then we should reject with that error`() { + whenBuildSdkThrowsSdkError() + + startAppUseCase( + null, + null, + null, + null, + null, + callbackMock + ) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + val expected = FlutterError(errorCode.toString(), errorMessage) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } + } - private fun whenCallsOnError() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onError(oneginiInitializationError) - } - whenever(oneginiInitializationError.errorType).thenReturn(errorCode) - whenever(oneginiInitializationError.message).thenReturn(errorMessage) + private fun whenCallsOnError() { + whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { + it.getArgument(0).onError(oneginiInitializationError) } - - private fun whenBuildSdkThrowsSdkError() { - whenever(oneginiSdk.buildSDK(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())).thenAnswer { - throw SdkError( - code = errorCode, - message = errorMessage - ) - } + whenever(oneginiInitializationError.errorType).thenReturn(errorCode) + whenever(oneginiInitializationError.message).thenReturn(errorMessage) + } + + private fun whenBuildSdkThrowsSdkError() { + whenever(oneginiSdk.buildSDK(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())).thenAnswer { + throw SdkError( + code = errorCode, + message = errorMessage + ) } + } - private fun whenCallsOnSuccess() { - whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { - it.getArgument(0).onSuccess(emptySet()) - } + private fun whenCallsOnSuccess() { + whenever(oneginiSdk.oneginiClient.start(any())).thenAnswer { + it.getArgument(0).onSuccess(emptySet()) } + } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt index 8f8254ca..9fae908e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -22,7 +22,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class ValidatePinWithPolicyUseCaseTests { - @Mock lateinit var oneginiPinValidationErrorMock: OneginiPinValidationError From fe246d3f96282f8a5c7b90210e0e2af8c2aa9c71 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 4 Apr 2023 10:39:17 +0200 Subject: [PATCH 240/364] fp-30 process warnings from linters; removed unused classes; removed missed unused imports; fixt inconsistent newlines and privated vars --- .../sdk/flutter/errors/FlutterErrorExtension.kt | 8 -------- .../handlers/PinAuthenticationRequestHandler.kt | 3 +-- .../flutter/models/CustomIdentityProviderConfig.kt | 3 --- .../sdk/flutter/models/CustomRegistrationModel.kt | 3 --- .../com/onegini/mobile/sdk/flutter/models/Error.kt | 3 --- .../mobile/sdk/flutter/models/OneginiEvent.kt | 3 --- .../flutter/useCases/AuthenticateUserUseCase.kt | 2 +- .../mobile/sdk/AuthenticateDeviceUseCaseTests.kt | 2 +- .../sdk/AuthenticateUserImplicitlyUseCaseTests.kt | 2 +- .../mobile/sdk/AuthenticateUserUseCaseTests.kt | 2 +- .../sdk/CancelBrowserRegistrationUseCaseTest.kt | 2 +- .../onegini/mobile/sdk/ChangePinUseCaseTests.kt | 2 +- .../sdk/DeregisterAuthenticatorUseCaseTests.kt | 2 +- .../mobile/sdk/DeregisterUserUseCaseTests.kt | 2 +- .../sdk/EnrollMobileAuthenticationUseCaseTest.kt | 2 +- ...rprintAuthenticationRequestAcceptUseCaseTest.kt | 11 ++++++----- ...gerprintAuthenticationRequestDenyUseCaseTest.kt | 10 +++++----- .../sdk/FingerprintFallbackToPinUseCaseTest.kt | 11 ++++++----- .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 2 +- .../mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt | 2 +- .../sdk/GetAppToWebSingleSignOnUseCaseTests.kt | 2 +- .../sdk/GetAuthenticatedUserProfileUseCaseTests.kt | 2 +- .../mobile/sdk/GetIdentityProvidersUseCaseTests.kt | 2 +- .../GetNotRegisteredAuthenticatorsUseCaseTests.kt | 2 +- .../mobile/sdk/GetRedirectUrlUseCaseTests.kt | 2 +- .../sdk/GetRegisteredAuthenticatorsUseCaseTests.kt | 2 +- .../mobile/sdk/GetUserProfilesUseCaseTests.kt | 2 +- .../sdk/HandleMobileAuthWithOtpUseCaseTest.kt | 2 +- .../com/onegini/mobile/sdk/LogoutUseCaseTests.kt | 1 - .../OtpAcceptAuthenticationRequestUseCaseTest.kt | 11 ++++++----- .../sdk/OtpDenyAuthenticationRequestUseCaseTest.kt | 10 +++++----- .../PinAuthenticationRequestAcceptUseCaseTest.kt | 11 ++++++----- .../sdk/PinAuthenticationRequestDenyUseCaseTest.kt | 10 +++++----- .../sdk/PinRegistrationRequestAcceptUseCaseTest.kt | 14 +++++--------- .../sdk/PinRegistrationRequestDenyUseCaseTest.kt | 14 +++++--------- .../sdk/RegisterAuthenticatorUseCaseTests.kt | 2 +- .../onegini/mobile/sdk/RegistrationUseCaseTests.kt | 2 +- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 2 +- .../sdk/SetPreferredAuthenticatorUseCaseTests.kt | 2 +- .../com/onegini/mobile/sdk/StartAppUseCaseTests.kt | 11 +++-------- .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 3 +-- 41 files changed, 77 insertions(+), 109 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomIdentityProviderConfig.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomRegistrationModel.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Error.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/OneginiEvent.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt deleted file mode 100644 index 8c602dd4..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/errors/FlutterErrorExtension.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.onegini.mobile.sdk.flutter.errors - -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors -import io.flutter.plugin.common.MethodChannel - -fun MethodChannel.Result.wrapperError(error: OneWelcomeWrapperErrors) { - this.error(error.code.toString(), error.message, null) -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index 35a0c6bd..838bb72a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -5,7 +5,6 @@ import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallba import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticationAttempt @@ -31,7 +30,7 @@ class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: attemptCounter.failedAttempts.toLong(), attemptCounter.maxAttempts.toLong(), attemptCounter.remainingAttempts.toLong() - ); + ) nativeApi.n2fNextAuthenticationAttempt(authenticationAttempt) {} } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomIdentityProviderConfig.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomIdentityProviderConfig.kt deleted file mode 100644 index 49947db4..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomIdentityProviderConfig.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.onegini.mobile.sdk.flutter.models - -data class CustomIdentityProviderConfig(val providerId: String, val isTwoStep: Boolean) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomRegistrationModel.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomRegistrationModel.kt deleted file mode 100644 index 94045cd1..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/CustomRegistrationModel.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.onegini.mobile.sdk.flutter.models - -data class CustomRegistrationModel(val data: String, val status: Int?, val providerId: String) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Error.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Error.kt deleted file mode 100644 index 7ea8c620..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/Error.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.onegini.mobile.sdk.flutter.models - -data class Error(val code: String, val message: String) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/OneginiEvent.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/OneginiEvent.kt deleted file mode 100644 index bdd67f85..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/models/OneginiEvent.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.onegini.mobile.sdk.flutter.models - -data class OneginiEvent(val eventName: String, val eventValue: String) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 7a093356..228bf538 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -55,7 +55,7 @@ class AuthenticateUserUseCase @Inject constructor( when (customInfo) { null -> callback(Result.success(OWRegistrationResponse(owProfile))) else -> { - callback(Result.success(OWRegistrationResponse(owProfile, customInfo?.mapToOwCustomInfo()))) + callback(Result.success(OWRegistrationResponse(owProfile, customInfo.mapToOwCustomInfo()))) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt index 128243f2..b5939938 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateDeviceUseCaseTests.kt @@ -34,7 +34,7 @@ class AuthenticateDeviceUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase + private lateinit var authenticateDeviceUseCase: AuthenticateDeviceUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt index 7a4f3be7..fbea055f 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt @@ -37,7 +37,7 @@ class AuthenticateUserImplicitlyUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase + private lateinit var authenticateUserImplicitlyUseCase: AuthenticateUserImplicitlyUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index bbab88fb..4ae7f0a8 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -41,7 +41,7 @@ class AuthenticateUserUseCaseTests { @Mock lateinit var oneginiAuthenticationErrorMock: OneginiAuthenticationError - lateinit var authenticateUserUseCase: AuthenticateUserUseCase + private lateinit var authenticateUserUseCase: AuthenticateUserUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt index 6ab75bf9..2359fe7b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt @@ -17,7 +17,7 @@ class CancelBrowserRegistrationUseCaseTest { @Mock lateinit var oneginiBrowserCallbackMock: OneginiBrowserRegistrationCallback - lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase + private lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index 9523b1b3..545bfbf1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -33,7 +33,7 @@ class ChangePinUseCaseTests { @Mock lateinit var oneginiChangePinError: OneginiChangePinError - lateinit var changePinUseCase: ChangePinUseCase + private lateinit var changePinUseCase: ChangePinUseCase @Before fun setup() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt index 696003c5..e6fe8e32 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt @@ -36,7 +36,7 @@ class DeregisterAuthenticatorUseCaseTests { @Mock lateinit var oneginiAuthenticatorDeregistrationErrorMock: OneginiAuthenticatorDeregistrationError - lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase + private lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt index df47f8c2..4ce84d90 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt @@ -33,7 +33,7 @@ class DeregisterUserUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var deregisterUserUseCase: DeregisterUserUseCase + private lateinit var deregisterUserUseCase: DeregisterUserUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt index d284cdf6..4867d580 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/EnrollMobileAuthenticationUseCaseTest.kt @@ -30,7 +30,7 @@ class EnrollMobileAuthenticationUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var enrollMobileAuthenticationUseCase: EnrollMobileAuthenticationUseCase + private lateinit var enrollMobileAuthenticationUseCase: EnrollMobileAuthenticationUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index 377f6eff..f5b8d43a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -23,9 +23,10 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { @Mock lateinit var nativeApi: NativeCallFlutterApi - lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + private lateinit var fingerprintAuthenticationRequestAcceptUseCase: FingerprintAuthenticationRequestAcceptUseCase + + private lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler - lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) @@ -41,7 +42,7 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() val result = fingerprintAuthenticationRequestAcceptUseCase().getOrNull() @@ -50,14 +51,14 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should call accept on the sdk callback`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() fingerprintAuthenticationRequestAcceptUseCase() verify(oneginiFingerprintCallbackMock).acceptAuthenticationRequest() } - fun WhenFingerPrintHasStarted() { + private fun whenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index 08b67f9f..fe6cef0b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -23,9 +23,9 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { @Mock lateinit var nativeApi: NativeCallFlutterApi - lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase + private lateinit var fingerprintAuthenticationRequestDenyUseCase: FingerprintAuthenticationRequestDenyUseCase - lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler + private lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { @@ -42,7 +42,7 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() val result = fingerprintAuthenticationRequestDenyUseCase().getOrNull() @@ -51,14 +51,14 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should call deny on the sdk callback`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() fingerprintAuthenticationRequestDenyUseCase() verify(oneginiFingerprintCallbackMock).denyAuthenticationRequest() } - fun WhenFingerPrintHasStarted() { + private fun whenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 5fe882c8..8f5b5ff3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -23,9 +23,10 @@ class FingerprintFallbackToPinUseCaseTest { @Mock lateinit var nativeApi: NativeCallFlutterApi - lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + private lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + + private lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler - lateinit var fingerprintAuthenticationRequestHandler: FingerprintAuthenticationRequestHandler @Before fun attach() { fingerprintAuthenticationRequestHandler = FingerprintAuthenticationRequestHandler(nativeApi) @@ -41,7 +42,7 @@ class FingerprintFallbackToPinUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should resolve successfully`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() val result = fingerprintFallbackToPinUseCase().getOrNull() @@ -50,14 +51,14 @@ class FingerprintFallbackToPinUseCaseTest { @Test fun `When a pin authentication callback is set, Then it should call fallbackToPin on the sdk callback`() { - WhenFingerPrintHasStarted() + whenFingerPrintHasStarted() fingerprintFallbackToPinUseCase() verify(oneginiFingerprintCallbackMock).fallbackToPin() } - fun WhenFingerPrintHasStarted() { + private fun whenFingerPrintHasStarted() { fingerprintAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiFingerprintCallbackMock) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index 299ac08f..e55e1409 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -18,7 +18,7 @@ class GetAccessTokenUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - lateinit var getAccessTokenUseCase: GetAccessTokenUseCase + private lateinit var getAccessTokenUseCase: GetAccessTokenUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index 1ae20ff2..b7013c23 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -27,7 +27,7 @@ class GetAllAuthenticatorsUseCaseTests { lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase + private lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt index 84cce9f6..3ddfaff4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAppToWebSingleSignOnUseCaseTests.kt @@ -47,7 +47,7 @@ class GetAppToWebSingleSignOnUseCaseTests { private val mockedTokenString = "mockedToken" private val mockedRedirectUrlString = "mockedRedirectUrl" - lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase + private lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase @Before fun setup() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index 64464a50..222a67d1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -19,7 +19,7 @@ class GetAuthenticatedUserProfileUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase + private lateinit var getAuthenticatedUserProfileUseCase: GetAuthenticatedUserProfileUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt index 854bf5a2..2e44afa8 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt @@ -26,7 +26,7 @@ class GetIdentityProvidersUseCaseTests { @Mock lateinit var oneginiIdentityProviderSecondMock: OneginiIdentityProvider - lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase + private lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 105c3131..89fbb23e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -31,7 +31,7 @@ class GetNotRegisteredAuthenticatorsUseCaseTests { @Mock lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase + private lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt index 1bad38a2..0465bae5 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt @@ -24,7 +24,7 @@ class GetRedirectUrlUseCaseTests { @Mock lateinit var oneginiClientConfigModelMock: OneginiClientConfigModel - lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase + private lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index 9e84a6ff..1ff58766 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -34,7 +34,7 @@ class GetRegisteredAuthenticatorsUseCaseTests { @Mock lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase + private lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt index 7d7548cd..0cca897b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt @@ -23,7 +23,7 @@ class GetUserProfilesUseCaseTests { @Mock lateinit var clientMock: OneginiClient - lateinit var getUserProfilesUseCase: GetUserProfilesUseCase + private lateinit var getUserProfilesUseCase: GetUserProfilesUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt index ca37a5a4..dba81757 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/HandleMobileAuthWithOtpUseCaseTest.kt @@ -31,7 +31,7 @@ class HandleMobileAuthWithOtpUseCaseTest { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var handleMobileAuthWithOtpUseCase: HandleMobileAuthWithOtpUseCase + private lateinit var handleMobileAuthWithOtpUseCase: HandleMobileAuthWithOtpUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt index 8b85b210..421dcf3e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt @@ -21,7 +21,6 @@ import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) class LogoutUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt index 01e2a4b1..28a1b0db 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt @@ -26,9 +26,10 @@ class OtpAcceptAuthenticationRequestUseCaseTest { @Mock lateinit var nativeApi: NativeCallFlutterApi - lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + private lateinit var otpAcceptAuthenticationRequestUseCase: OtpAcceptAuthenticationRequestUseCase + + private lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler - lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler @Before fun attach() { mobileAuthOtpRequestHandler = MobileAuthOtpRequestHandler(nativeApi) @@ -44,7 +45,7 @@ class OtpAcceptAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - WhenOTPAuthenticationHasStarted() + whenOTPAuthenticationHasStarted() val result = otpAcceptAuthenticationRequestUseCase().getOrNull() @@ -53,14 +54,14 @@ class OtpAcceptAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should call the accept on the sdk callback`() { - WhenOTPAuthenticationHasStarted() + whenOTPAuthenticationHasStarted() otpAcceptAuthenticationRequestUseCase().getOrNull() verify(oneginiAcceptDenyCallback).acceptAuthenticationRequest() } - private fun WhenOTPAuthenticationHasStarted() { + private fun whenOTPAuthenticationHasStarted() { mobileAuthOtpRequestHandler.startAuthentication(oneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt index 7ec77085..81fc552a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -26,9 +26,9 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Mock lateinit var nativeApi: NativeCallFlutterApi - lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase + private lateinit var otpDenyAuthenticationRequestUseCase: OtpDenyAuthenticationRequestUseCase - lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler + private lateinit var mobileAuthOtpRequestHandler: MobileAuthOtpRequestHandler @Before fun attach() { @@ -45,7 +45,7 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should resolve successfully`() { - WhenOTPAuthenticationHasStarted() + whenOTPAuthenticationHasStarted() val result = otpDenyAuthenticationRequestUseCase().getOrNull() @@ -54,14 +54,14 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Test fun `When a otp authentication callback is set, Then it should call the deny on the sdk callback`() { - WhenOTPAuthenticationHasStarted() + whenOTPAuthenticationHasStarted() otpDenyAuthenticationRequestUseCase().getOrNull() verify(oneginiAcceptDenyCallback).denyAuthenticationRequest() } - private fun WhenOTPAuthenticationHasStarted() { + private fun whenOTPAuthenticationHasStarted() { mobileAuthOtpRequestHandler.startAuthentication(oneginiMobileAuthenticationRequest, oneginiAcceptDenyCallback) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 4f34f69a..761f65d2 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -30,9 +30,10 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Mock lateinit var authenticationAttemptCounter: AuthenticationAttemptCounter - lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase + private lateinit var pinAuthenticationRequestAcceptUseCase: PinAuthenticationRequestAcceptUseCase + + private lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler - lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler @Before fun before() { pinAuthenticationRequestHandler = PinAuthenticationRequestHandler(nativeApi) @@ -48,7 +49,7 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - WhenPinAuthenticationStarted() + whenPinAuthenticationStarted() val result = pinAuthenticationRequestAcceptUseCase("12345").getOrNull() @@ -57,14 +58,14 @@ class PinAuthenticationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should call accept on the sdk callback`() { - WhenPinAuthenticationStarted() + whenPinAuthenticationStarted() pinAuthenticationRequestAcceptUseCase("12345") verify(oneginiPinCallbackMock).acceptAuthenticationRequest("12345".toCharArray()) } - private fun WhenPinAuthenticationStarted() { + private fun whenPinAuthenticationStarted() { // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index 7a843859..3f3412d4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -30,9 +30,9 @@ class PinAuthenticationRequestDenyUseCaseTest { @Mock lateinit var authenticationAttemptCounter: AuthenticationAttemptCounter - lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase + private lateinit var pinAuthenticationRequestDenyUseCase: PinAuthenticationRequestDenyUseCase - lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler + private lateinit var pinAuthenticationRequestHandler: PinAuthenticationRequestHandler @Before fun before() { @@ -49,7 +49,7 @@ class PinAuthenticationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - WhenPinAuthenticationStarted() + whenPinAuthenticationStarted() val result = pinAuthenticationRequestDenyUseCase().getOrNull() @@ -58,14 +58,14 @@ class PinAuthenticationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should call deny on the sdk callback`() { - WhenPinAuthenticationStarted() + whenPinAuthenticationStarted() pinAuthenticationRequestDenyUseCase() verify(oneginiPinCallbackMock).denyAuthenticationRequest() } - private fun WhenPinAuthenticationStarted() { + private fun whenPinAuthenticationStarted() { // Since we Mock the SDK we need to call the startAuthentication ourselves on the pinAuthenticationRequestHandler pinAuthenticationRequestHandler.startAuthentication(UserProfile("123456"), oneginiPinCallbackMock, authenticationAttemptCounter) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index bfd0d1d3..60468690 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -17,9 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestAcceptUseCaseTest { - @Mock - lateinit var oneginiPinCallbackMock: OneginiPinCallback - @Mock lateinit var callbackMock: (Result) -> Unit @@ -29,9 +26,9 @@ class PinRegistrationRequestAcceptUseCaseTest { @Mock lateinit var oneginiPinCallback: OneginiPinCallback - lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase + private lateinit var pinRegistrationRequestAcceptUseCase: PinRegistrationRequestAcceptUseCase - lateinit var pinRequestHandler: PinRequestHandler + private lateinit var pinRequestHandler: PinRequestHandler @Before fun setup() { @@ -48,7 +45,7 @@ class PinRegistrationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - WhenPinCreationStarted() + whenPinCreationStarted() val result = pinRegistrationRequestAcceptUseCase("12345").getOrNull() @@ -57,15 +54,14 @@ class PinRegistrationRequestAcceptUseCaseTest { @Test fun `When a pin registration callback is set, Then it should call accept on the sdk callback`() { - WhenPinCreationStarted() + whenPinCreationStarted() pinRegistrationRequestAcceptUseCase("12345") verify(oneginiPinCallback).acceptAuthenticationRequest("12345".toCharArray()) } - - private fun WhenPinCreationStarted() { + private fun whenPinCreationStarted() { // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler pinRequestHandler.startPinCreation(UserProfile("123456"), oneginiPinCallback, 5) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index d8c06611..d494c367 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -17,9 +17,6 @@ import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class PinRegistrationRequestDenyUseCaseTest { - @Mock - lateinit var oneginiPinCallbackMock: OneginiPinCallback - @Mock lateinit var callbackMock: (Result) -> Unit @@ -29,9 +26,9 @@ class PinRegistrationRequestDenyUseCaseTest { @Mock lateinit var oneginiPinCallback: OneginiPinCallback - lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase + private lateinit var pinRegistrationRequestDenyUseCase: PinRegistrationRequestDenyUseCase - lateinit var pinRequestHandler: PinRequestHandler + private lateinit var pinRequestHandler: PinRequestHandler @Before fun attach() { @@ -47,7 +44,7 @@ class PinRegistrationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should resolve successfully`() { - WhenPinCreationStarted() + whenPinCreationStarted() val result = pinRegistrationRequestDenyUseCase().getOrNull() Assert.assertEquals(Unit, result) @@ -55,15 +52,14 @@ class PinRegistrationRequestDenyUseCaseTest { @Test fun `When a pin registration callback is set, Then it should call deny on the sdk callback`() { - WhenPinCreationStarted() + whenPinCreationStarted() pinRegistrationRequestDenyUseCase() verify(oneginiPinCallback).denyAuthenticationRequest() } - - private fun WhenPinCreationStarted() { + private fun whenPinCreationStarted() { // Since we Mock the SDK we need to call the startPinCreation ourselves on the CreatePinRequestHandler pinRequestHandler.startPinCreation(UserProfile("123456"), oneginiPinCallback, 5) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index 2301326d..fc85e9ad 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -41,7 +41,7 @@ class RegisterAuthenticatorUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase + private lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 69df1872..64844297 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -37,7 +37,7 @@ class RegistrationUseCaseTests { @Mock lateinit var oneginiIdentityProviderMock: OneginiIdentityProvider - lateinit var registrationUseCase: RegistrationUseCase + private lateinit var registrationUseCase: RegistrationUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index c3cee043..426be311 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -49,7 +49,7 @@ class ResourceRequestUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var resourceRequestUseCase: ResourceRequestUseCase + private lateinit var resourceRequestUseCase: ResourceRequestUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index a100f5e5..fab4e90a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -28,7 +28,7 @@ class SetPreferredAuthenticatorUseCaseTests { @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase + private lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase @Before fun attach() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt index 0873576a..d6e817ab 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt @@ -3,7 +3,6 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiInitializationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiInitializationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -32,22 +31,20 @@ class StartAppUseCaseTests { @Mock lateinit var oneginiInitializationError: OneginiInitializationError - lateinit var startAppUseCase: StartAppUseCase + private lateinit var startAppUseCase: StartAppUseCase @Before fun attach() { startAppUseCase = StartAppUseCase(oneginiSdk) } - val errorCode = OneginiInitializationError.GENERAL_ERROR - val errorMessage = "General error" + private val errorCode = OneginiInitializationError.GENERAL_ERROR + private val errorMessage = "General error" @Test fun `When onError gets called by oneginiClient, Then should call callback with Result_failure with that error`() { - whenCallsOnError() - startAppUseCase( null, null, @@ -66,10 +63,8 @@ class StartAppUseCaseTests { @Test fun `When onSuccess gets called by oneginiClient, Then should call callback with Result_success`() { - whenCallsOnSuccess() - startAppUseCase( null, null, diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt index 9fae908e..19d5dfad 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -34,14 +34,13 @@ class ValidatePinWithPolicyUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase + private lateinit var validatePinWithPolicyUseCase: ValidatePinWithPolicyUseCase @Before fun attach() { validatePinWithPolicyUseCase = ValidatePinWithPolicyUseCase(oneginiSdk) } - @Test fun `When pin is not null, Then it should call validatePinWithPolicy on the onegini sdk`() { validatePinWithPolicyUseCase("14789", callbackMock) From 65b15b49dcee424ae2fa04a9e6e9aca83f221ff8 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 4 Apr 2023 12:08:02 +0200 Subject: [PATCH 241/364] FP-77 Removed unused event --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 7 ------- ios/Classes/Pigeon.swift | 7 ------- lib/onegini_event_listener.dart | 8 -------- lib/pigeon.dart | 17 ----------------- pigeons/onewelcome_pigeon_interface.dart | 3 --- 5 files changed, 42 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index d8c1cf88..414c84a3 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1305,13 +1305,6 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - /** Called to open pin authentication screen. */ - fun n2fOpenPinAuthenticator(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator", codec) - channel.send(null) { - callback() - } - } /** Called to attempt next authentication. */ fun n2fNextAuthenticationAttempt(authenticationAttemptArg: OWAuthenticationAttempt, callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", codec) diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 8ee4b9ca..3c23af32 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1202,13 +1202,6 @@ class NativeCallFlutterApi { completion() } } - /// Called to open pin authentication screen. - func n2fOpenPinAuthenticator(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage(nil) { _ in - completion() - } - } /// Called to attempt next authentication. func n2fNextAuthenticationAttempt(authenticationAttempt authenticationAttemptArg: OWAuthenticationAttempt, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 6acfd940..64655287 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -28,9 +28,6 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { /// Called to open pin authentication screen. void openPinScreenAuth(BuildContext? buildContext); - /// Called to open pin authentication screen. - void openPinAuthenticator(BuildContext? buildContext); - /// Called to attempt next authentication. void nextAuthenticationAttempt( BuildContext? buildContext, AuthenticationAttempt authenticationAttempt); @@ -128,11 +125,6 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { openFingerprintScreen(_context); } - @override - void n2fOpenPinAuthenticator() { - openPinAuthenticator(_context); - } - @override void n2fOpenPinRequestScreen() { openPinRequestScreen(_context); diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dda3df5f..02b5fb41 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1382,9 +1382,6 @@ abstract class NativeCallFlutterApi { /// Called to open pin authentication screen. void n2fOpenPinScreenAuth(); - /// Called to open pin authentication screen. - void n2fOpenPinAuthenticator(); - /// Called to attempt next authentication. void n2fNextAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); @@ -1493,20 +1490,6 @@ abstract class NativeCallFlutterApi { }); } } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthenticator', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); - } else { - channel.setMessageHandler((Object? message) async { - // ignore message - api.n2fOpenPinAuthenticator(); - return; - }); - } - } { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt', codec, diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index a081f3f4..b00b1345 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -274,9 +274,6 @@ abstract class NativeCallFlutterApi { /// Called to open pin authentication screen. void n2fOpenPinScreenAuth(); - /// Called to open pin authentication screen. - void n2fOpenPinAuthenticator(); - /// Called to attempt next authentication. void n2fNextAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt); From d4ea5697a6c23d18f716abcc6893da35db423af5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 4 Apr 2023 13:14:55 +0200 Subject: [PATCH 242/364] FP-81: Move all completions to end of init in delegate init --- .../NativeBridge/Handlers/AuthenticatorsHandler.swift | 8 ++++---- ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift | 4 ++-- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 4 ++-- .../NativeBridge/Handlers/RegistrationHandler.swift | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index c2b5cb8d..4ef3bf8b 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -25,7 +25,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotFound))) return } - let delegate = AuthenticatorRegistrationDelegateImpl(completion, loginHandler) + let delegate = AuthenticatorRegistrationDelegateImpl(loginHandler: loginHandler, completion: completion) SharedUserClient.instance.register(authenticator: authenticator, delegate: delegate) } @@ -39,7 +39,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { completion(.failure(FlutterError(.authenticatorNotRegistered))) return } - let delegate = AuthenticatorDeregistrationDelegateImpl(completion) + let delegate = AuthenticatorDeregistrationDelegateImpl(completion: completion) SharedUserClient.instance.deregister(authenticator: authenticator, delegate: delegate) } @@ -63,7 +63,7 @@ class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { private let completion: ((Result) -> Void) private let loginHandler: LoginHandler - init(_ completion: (@escaping (Result) -> Void), _ loginHandler: LoginHandler) { + init(loginHandler: LoginHandler, completion: (@escaping (Result) -> Void)) { self.completion = completion self.loginHandler = loginHandler } @@ -101,7 +101,7 @@ class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { class AuthenticatorDeregistrationDelegateImpl: AuthenticatorDeregistrationDelegate { private let completion: ((Result) -> Void) - init(_ completion: @escaping (Result) -> Void) { + init(completion: @escaping (Result) -> Void) { self.completion = completion } diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 35e5d689..0e007b0d 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -9,7 +9,7 @@ class ChangePinHandler { self.registrationHandler = registrationHandler } func changePin(completion: @escaping (Result) -> Void) { - let delegate = ChangePinDelegateImpl(completion: completion, loginHandler, registrationHandler) + let delegate = ChangePinDelegateImpl(loginHandler: loginHandler, registrationHandler: registrationHandler, completion: completion) SharedUserClient.instance.changePin(delegate: delegate) } } @@ -19,7 +19,7 @@ class ChangePinDelegateImpl: ChangePinDelegate { private let loginHandler: LoginHandler private let registrationHandler: RegistrationHandler - init(completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler, _ registrationHandler: RegistrationHandler) { + init(loginHandler: LoginHandler, registrationHandler: RegistrationHandler, completion: @escaping (Result) -> Void) { self.completion = completion self.loginHandler = loginHandler self.registrationHandler = registrationHandler diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index d1ef9da9..48c04787 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -56,7 +56,7 @@ class LoginHandler { } func authenticateUser(_ profile: UserProfile, authenticator: Authenticator?, completion: @escaping (Result) -> Void) { - let delegate = AuthenticationDelegateImpl(completion, self) + let delegate = AuthenticationDelegateImpl(loginHandler: self, completion: completion) SharedUserClient.instance.authenticateUserWith(profile: profile, authenticator: authenticator, delegate: delegate) } } @@ -65,7 +65,7 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { private let completion: (Result) -> Void private let loginHandler: LoginHandler - init(_ completion: @escaping (Result) -> Void, _ loginHandler: LoginHandler) { + init(loginHandler: LoginHandler, completion: @escaping (Result) -> Void) { self.completion = completion self.loginHandler = loginHandler } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index fc97965c..82f7ac54 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -93,7 +93,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) - let delegate = RegistrationDelegateImpl(completion, self) + let delegate = RegistrationDelegateImpl(registrationHandler: self, completion: completion) SharedUserClient.instance.registerUserWith(identityProvider: identityProvider, scopes: scopes, delegate: delegate) } @@ -142,7 +142,7 @@ class RegistrationDelegateImpl: RegistrationDelegate { private let completion: ((Result) -> Void) private let registrationHandler: RegistrationHandler - init(_ completion: @escaping (Result) -> Void, _ registrationHandler: RegistrationHandler) { + init(registrationHandler: RegistrationHandler, completion: @escaping (Result) -> Void) { self.completion = completion self.registrationHandler = registrationHandler } From dd3a61c378df63cc531a4fa15ada3a76ba4f71e3 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 4 Apr 2023 14:07:31 +0200 Subject: [PATCH 243/364] FP-81: Update init's to named arguments --- ios/Classes/NativeBridge/Connectors/BridgeConnector.swift | 4 ++-- ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift | 2 +- ios/Classes/NativeBridge/Handlers/BrowserHandler.swift | 4 ++-- ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift | 2 +- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift index df83fa85..0881d9e4 100644 --- a/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift +++ b/ios/Classes/NativeBridge/Connectors/BridgeConnector.swift @@ -11,8 +11,8 @@ class BridgeConnector { public static var shared: BridgeConnector? init() { - toChangePinHandler = ChangePinHandler(toLoginHandler, toRegistrationHandler) - toAuthenticatorsHandler = AuthenticatorsHandler(toLoginHandler) + toChangePinHandler = ChangePinHandler(loginHandler: toLoginHandler, registrationHandler: toRegistrationHandler) + toAuthenticatorsHandler = AuthenticatorsHandler(loginHandler: toLoginHandler) BridgeConnector.shared = self } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 4ef3bf8b..259e4ae1 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -10,7 +10,7 @@ protocol BridgeToAuthenticatorsHandlerProtocol { class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { private let loginHandler: LoginHandler - init(_ loginHandler: LoginHandler) { + init(loginHandler: LoginHandler) { self.loginHandler = loginHandler } func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift index b8dba09b..624d2152 100644 --- a/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/BrowserHandler.swift @@ -2,7 +2,7 @@ import AuthenticationServices import OneginiSDKiOS protocol BrowserHandlerProtocol { - func handleUrl(url: URL, webSignInType: WebSignInType) + func handleUrl(_ url: URL, webSignInType: WebSignInType) } protocol BrowserHandlerToRegisterHandlerProtocol { @@ -21,7 +21,7 @@ class BrowserViewController: NSObject, BrowserHandlerProtocol { self.registerHandler = registerHandlerProtocol } - func handleUrl(url: URL, webSignInType: WebSignInType) { + func handleUrl(_ url: URL, webSignInType: WebSignInType) { Logger.log("handleUrl url: \(url.absoluteString)", sender: self) switch webSignInType { case .safari: diff --git a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift index 0e007b0d..03ca50a3 100644 --- a/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ChangePinHandler.swift @@ -4,7 +4,7 @@ import Flutter class ChangePinHandler { private let loginHandler: LoginHandler private let registrationHandler: RegistrationHandler - init(_ loginHandler: LoginHandler, _ registrationHandler: RegistrationHandler) { + init(loginHandler: LoginHandler, registrationHandler: RegistrationHandler) { self.loginHandler = loginHandler self.registrationHandler = registrationHandler } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 82f7ac54..07b2af0c 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -22,11 +22,11 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func presentBrowserUserRegistrationView(registrationUserURL: URL, webSignInType: WebSignInType) { guard let browserController = browserConntroller else { browserConntroller = BrowserViewController(registerHandlerProtocol: self) - browserConntroller?.handleUrl(url: registrationUserURL, webSignInType: webSignInType) + browserConntroller?.handleUrl(registrationUserURL, webSignInType: webSignInType) return } - browserController.handleUrl(url: registrationUserURL, webSignInType: webSignInType) + browserController.handleUrl(registrationUserURL, webSignInType: webSignInType) } func handleRedirectURL(url: URL) { From 2bc34bdf3b708854461533572c2e977295e32c75 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 5 Apr 2023 10:34:39 +0200 Subject: [PATCH 244/364] FP-85: Update Flutter pigeon version --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 2 +- ios/Classes/Pigeon.swift | 55 ++++++++++--------- lib/pigeon.dart | 2 +- pubspec.yaml | 2 +- 4 files changed, 32 insertions(+), 29 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index d8c1cf88..a368496d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.1.1), do not edit directly. +// Autogenerated from Pigeon (v9.2.2), do not edit directly. // See also: https://pub.dev/packages/pigeon package com.onegini.mobile.sdk.flutter.pigeonPlugin diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 8ee4b9ca..74c343b3 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.1.1), do not edit directly. +// Autogenerated from Pigeon (v9.2.2), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -10,8 +10,6 @@ import FlutterMacOS #error("Unsupported platform.") #endif - - private func wrapResult(_ result: Any?) -> [Any?] { return [result] } @@ -31,6 +29,11 @@ private func wrapError(_ error: Any) -> [Any?] { ] } +private func nilOrValue(_ value: Any?) -> T? { + if value is NSNull { return nil } + return (value as Any) as! T? +} + enum HttpRequestMethod: Int { case get = 0 case post = 1 @@ -71,8 +74,8 @@ struct OWCustomInfo { var data: String? = nil static func fromList(_ list: [Any]) -> OWCustomInfo? { - let status = list[0] as! Int64 - let data = list[1] as! String? + let status = list[0] is Int64 ? list[0] as! Int64 : Int64(list[0] as! Int32) + let data: String? = nilOrValue(list[1]) return OWCustomInfo( status: status, @@ -122,7 +125,7 @@ struct OWAuthenticator { let name = list[1] as! String let isRegistered = list[2] as! Bool let isPreferred = list[3] as! Bool - let authenticatorType = list[4] as! Int64 + let authenticatorType = list[4] is Int64 ? list[4] as! Int64 : Int64(list[4] as! Int32) return OWAuthenticator( id: id, @@ -174,7 +177,7 @@ struct OWRegistrationResponse { let userProfile = OWUserProfile.fromList(list[0] as! [Any])! var customInfo: OWCustomInfo? = nil if let customInfoList = list[1] as! [Any]? { - customInfo = OWCustomInfo.fromList(customInfoList as [Any]) + customInfo = OWCustomInfo.fromList(customInfoList) } return OWRegistrationResponse( @@ -200,8 +203,8 @@ struct OWRequestDetails { static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String let method = HttpRequestMethod(rawValue: list[1] as! Int)! - let headers = list[2] as! [String?: String?]? - let body = list[3] as! String? + let headers: [String?: String?]? = nilOrValue(list[2]) + let body: String? = nilOrValue(list[3]) return OWRequestDetails( path: path, @@ -231,7 +234,7 @@ struct OWRequestResponse { let headers = list[0] as! [String?: String?] let body = list[1] as! String let ok = list[2] as! Bool - let status = list[3] as! Int64 + let status = list[3] is Int64 ? list[3] as! Int64 : Int64(list[3] as! Int32) return OWRequestResponse( headers: headers, @@ -257,9 +260,9 @@ struct OWAuthenticationAttempt { var remainingAttempts: Int64 static func fromList(_ list: [Any]) -> OWAuthenticationAttempt? { - let failedAttempts = list[0] as! Int64 - let maxAttempts = list[1] as! Int64 - let remainingAttempts = list[2] as! Int64 + let failedAttempts = list[0] is Int64 ? list[0] as! Int64 : Int64(list[0] as! Int32) + let maxAttempts = list[1] is Int64 ? list[1] as! Int64 : Int64(list[1] as! Int32) + let remainingAttempts = list[2] is Int64 ? list[2] as! Int64 : Int64(list[2] as! Int32) return OWAuthenticationAttempt( failedAttempts: failedAttempts, @@ -282,7 +285,7 @@ struct OWOneginiError { var message: String static func fromList(_ list: [Any]) -> OWOneginiError? { - let code = list[0] as! Int64 + let code = list[0] is Int64 ? list[0] as! Int64 : Int64(list[0] as! Int32) let message = list[1] as! String return OWOneginiError( @@ -444,11 +447,11 @@ class UserClientApiSetup { if let api = api { startApplicationChannel.setMessageHandler { message, reply in let args = message as! [Any] - let securityControllerClassNameArg = args[0] as! String? - let configModelClassNameArg = args[1] as! String? - let customIdentityProviderConfigsArg = args[2] as! [OWCustomIdentityProvider]? - let connectionTimeoutArg = (args[3] is Int) ? Int64(args[3] as! Int) : args[3] as! Int64? - let readTimeoutArg = (args[4] is Int) ? Int64(args[4] as! Int) : args[4] as! Int64? + let securityControllerClassNameArg: String? = nilOrValue(args[0]) + let configModelClassNameArg: String? = nilOrValue(args[1]) + let customIdentityProviderConfigsArg: [OWCustomIdentityProvider]? = nilOrValue(args[2]) + let connectionTimeoutArg: Int64? = args[3] is NSNull ? nil : (args[3] is Int64? ? args[3] as! Int64? : Int64(args[3] as! Int32)) + let readTimeoutArg: Int64? = args[4] is NSNull ? nil : (args[4] is Int64? ? args[4] as! Int64? : Int64(args[4] as! Int32)) api.startApplication(securityControllerClassName: securityControllerClassNameArg, configModelClassName: configModelClassNameArg, customIdentityProviderConfigs: customIdentityProviderConfigsArg, connectionTimeout: connectionTimeoutArg, readTimeout: readTimeoutArg) { result in switch result { case .success: @@ -465,8 +468,8 @@ class UserClientApiSetup { if let api = api { registerUserChannel.setMessageHandler { message, reply in let args = message as! [Any] - let identityProviderIdArg = args[0] as! String? - let scopesArg = args[1] as! [String]? + let identityProviderIdArg: String? = nilOrValue(args[0]) + let scopesArg: [String]? = nilOrValue(args[1]) api.registerUser(identityProviderId: identityProviderIdArg, scopes: scopesArg) { result in switch result { case .success(let res): @@ -484,7 +487,7 @@ class UserClientApiSetup { handleRegisteredUserUrlChannel.setMessageHandler { message, reply in let args = message as! [Any] let urlArg = args[0] as! String - let signInTypeArg = (args[1] is Int) ? Int64(args[1] as! Int) : args[1] as! Int64 + let signInTypeArg = args[1] is Int64 ? args[1] as! Int64 : Int64(args[1] as! Int32) api.handleRegisteredUserUrl(url: urlArg, signInType: signInTypeArg) { result in switch result { case .success: @@ -583,7 +586,7 @@ class UserClientApiSetup { authenticateUserChannel.setMessageHandler { message, reply in let args = message as! [Any] let profileIdArg = args[0] as! String - let registeredAuthenticatorIdArg = args[1] as! String? + let registeredAuthenticatorIdArg: String? = nilOrValue(args[1]) api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in switch result { case .success(let res): @@ -809,7 +812,7 @@ class UserClientApiSetup { if let api = api { authenticateDeviceChannel.setMessageHandler { message, reply in let args = message as! [Any] - let scopesArg = args[0] as! [String]? + let scopesArg: [String]? = nilOrValue(args[0]) api.authenticateDevice(scopes: scopesArg) { result in switch result { case .success: @@ -827,7 +830,7 @@ class UserClientApiSetup { authenticateUserImplicitlyChannel.setMessageHandler { message, reply in let args = message as! [Any] let profileIdArg = args[0] as! String - let scopesArg = args[1] as! [String]? + let scopesArg: [String]? = nilOrValue(args[1]) api.authenticateUserImplicitly(profileId: profileIdArg, scopes: scopesArg) { result in switch result { case .success: @@ -846,7 +849,7 @@ class UserClientApiSetup { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in let args = message as! [Any] let identityProviderIdArg = args[0] as! String - let dataArg = args[1] as! String? + let dataArg: String? = nilOrValue(args[1]) api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in switch result { case .success: diff --git a/lib/pigeon.dart b/lib/pigeon.dart index dda3df5f..de0506dd 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1,4 +1,4 @@ -// Autogenerated from Pigeon (v9.1.1), do not edit directly. +// Autogenerated from Pigeon (v9.2.2), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import diff --git a/pubspec.yaml b/pubspec.yaml index 081d31b5..9357c204 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ dev_dependencies: flutter_lints: ^2.0.1 flutter_test: sdk: flutter - pigeon: 9.1.1 + pigeon: 9.2.2 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec From 24c860ba309264ae19cfe6fc2ad390733f425225 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 5 Apr 2023 13:58:17 +0200 Subject: [PATCH 245/364] FP-77 Setup broadcast events wip --- lib/constants/constants.dart | 3 - lib/events/browser_event.dart | 7 ++ lib/events/custom_registration_event.dart | 15 +++++ lib/events/fingerprint_event.dart | 18 ++++++ lib/events/generic_event.dart | 8 +++ lib/events/onewelcome_events.dart | 78 +++++++++++++++++++++++ lib/events/otp_event.dart | 11 ++++ lib/events/pin_event.dart | 24 +++++++ lib/onegini_event_listener.dart | 65 ++++++++++++++++--- lib/user_client.dart | 6 ++ 10 files changed, 224 insertions(+), 11 deletions(-) create mode 100644 lib/events/browser_event.dart create mode 100644 lib/events/custom_registration_event.dart create mode 100644 lib/events/fingerprint_event.dart create mode 100644 lib/events/generic_event.dart create mode 100644 lib/events/onewelcome_events.dart create mode 100644 lib/events/otp_event.dart create mode 100644 lib/events/pin_event.dart diff --git a/lib/constants/constants.dart b/lib/constants/constants.dart index e1f00b94..341ea317 100644 --- a/lib/constants/constants.dart +++ b/lib/constants/constants.dart @@ -193,9 +193,6 @@ class Constants { /// Event triggered by the finishRegistration needs to be responded static const String eventFinishCustomRegistration = "eventFinishCustomRegistration"; - /// Error event name - static const String eventError = "eventError"; - // Error codes //When the native type does not correspond with the expected dart type diff --git a/lib/events/browser_event.dart b/lib/events/browser_event.dart new file mode 100644 index 00000000..bb562a05 --- /dev/null +++ b/lib/events/browser_event.dart @@ -0,0 +1,7 @@ +// Wrapper for Browser Events +import 'package:onegini/events/onewelcome_events.dart'; + +class HandleRegisteredUrlEvent extends OWEvent { + String url; + HandleRegisteredUrlEvent(this.url) : super(OWAction.handleRegisteredUrl); +} diff --git a/lib/events/custom_registration_event.dart b/lib/events/custom_registration_event.dart new file mode 100644 index 00000000..9316ca82 --- /dev/null +++ b/lib/events/custom_registration_event.dart @@ -0,0 +1,15 @@ +// Wrapper for Custom Registration Events +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/pigeon.dart'; + +class InitCustomRegistrationEvent extends OWEvent { + OWCustomInfo? customInfo; + String providerId; + InitCustomRegistrationEvent(this.customInfo, this.providerId) : super(OWAction.initCustomRegistration); +} + +class FinishCustomRegistrationEvent extends OWEvent { + OWCustomInfo? customInfo; + String providerId; + FinishCustomRegistrationEvent(this.customInfo, this.providerId) : super(OWAction.finishCustomRegistration); +} diff --git a/lib/events/fingerprint_event.dart b/lib/events/fingerprint_event.dart new file mode 100644 index 00000000..3ed6778b --- /dev/null +++ b/lib/events/fingerprint_event.dart @@ -0,0 +1,18 @@ +// Wrapper for Fingerprint Events +import 'package:onegini/events/onewelcome_events.dart'; + +class OpenFingerprintEvent extends OWEvent { + OpenFingerprintEvent() : super(OWAction.openFingerprint); +} + +class CloseFingerprintEvent extends OWEvent { + CloseFingerprintEvent() : super(OWAction.closeFingerprint); +} + +class ShowScanningFingerprintEvent extends OWEvent { + ShowScanningFingerprintEvent() : super(OWAction.showScanningFingerprint); +} + +class ReceivedFingerprintEvent extends OWEvent { + ReceivedFingerprintEvent() : super(OWAction.receivedFingerprint); +} diff --git a/lib/events/generic_event.dart b/lib/events/generic_event.dart new file mode 100644 index 00000000..7e559cbb --- /dev/null +++ b/lib/events/generic_event.dart @@ -0,0 +1,8 @@ +// Wrapper for Generic Events +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/pigeon.dart'; + +class NextAuthenticationAttemptEvent extends OWEvent { + OWAuthenticationAttempt authenticationAttempt; + NextAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextAuthenticationAttempt); +} diff --git a/lib/events/onewelcome_events.dart b/lib/events/onewelcome_events.dart new file mode 100644 index 00000000..2386d7f1 --- /dev/null +++ b/lib/events/onewelcome_events.dart @@ -0,0 +1,78 @@ +// Wrapper for OneWelcome Events +abstract class OWEvent { + OWAction action; + OWEvent(this.action); +} + +enum OWAction { + // Browser + handleRegisteredUrl, // Called to handle registration URL + + // Otp + openAuthOtp, // Called to open OTP authentication screen + closeAuthOtp, // Called to close OTP authentication screen + + // Pin + openPinRegistration, // previously openPinRequestScreen; Called to open pin registration screen. + closePinRegistration, // previously closePin; Called to open pin registration screen. + openPinAuthentication, // previously openPinScreenAuth; Called to open pin authentication screen + closePinAuthentication, // previously closePinAuth; Called to close pin authentication screen + pinNotAllowed, // Called when the supplied pin is not allowed + + // Fingerprint + openFingerprint, // previously openFingerprintScreen; Called to open fingerprint screen. + closeFingerprint, // previously closeFingerprintScreen; Called to close fingerprint screen. + showScanningFingerprint, // Called to scan fingerprint. + receivedFingerprint, // Called when fingerprint was received. + + // CustomRegistration + initCustomRegistration, // previously eventInitCustomRegistration; Called when customRegistration is initialized and a response should be given (only for two-step) + finishCustomRegistration, // previously eventFinishCustomRegistration; Called when customRegistration finishes and a final response should be given + + // Authentication + nextAuthenticationAttempt, // Called to attempt next authentication. + + /* + Deleted events: + - eventOther + - openPinAuthenticator + - eventError + */ +} + +extension OWActionExtension on OWAction { + String get value { + switch (this) { + case OWAction.handleRegisteredUrl: + return "handleRegisteredUrl"; + case OWAction.openAuthOtp: + return "openAuthOtp"; + case OWAction.openPinRegistration: + return "openPinRegistration"; + case OWAction.openPinAuthentication: + return "openPinAuthentication"; + case OWAction.openFingerprint: + return "openFingerprint"; + case OWAction.closeAuthOtp: + return "closeAuthOtp"; + case OWAction.closePinRegistration: + return "closePinRegistration"; + case OWAction.closePinAuthentication: + return "closePinAuthentication"; + case OWAction.closeFingerprint: + return "closeFingerprint"; + case OWAction.pinNotAllowed: + return "pinNotAllowed"; + case OWAction.showScanningFingerprint: + return "showScanningFingerprint"; + case OWAction.receivedFingerprint: + return "receivedFingerprint"; + case OWAction.initCustomRegistration: + return "initCustomRegistration"; + case OWAction.finishCustomRegistration: + return "finishCustomRegistration"; + case OWAction.nextAuthenticationAttempt: + return "nextAuthenticationAttempt"; + } + } +} diff --git a/lib/events/otp_event.dart b/lib/events/otp_event.dart new file mode 100644 index 00000000..aeeeb51c --- /dev/null +++ b/lib/events/otp_event.dart @@ -0,0 +1,11 @@ +// Wrapper for OTP Events +import 'package:onegini/events/onewelcome_events.dart'; + +class OpenAuthOtpEvent extends OWEvent { + String message; + OpenAuthOtpEvent(this.message) : super(OWAction.openAuthOtp); +} + +class CloseAuthOtpEvent extends OWEvent { + CloseAuthOtpEvent() : super(OWAction.closeAuthOtp); +} diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart new file mode 100644 index 00000000..94ea7975 --- /dev/null +++ b/lib/events/pin_event.dart @@ -0,0 +1,24 @@ +// Wrapper for Pin Events +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/pigeon.dart'; + +class OpenPinRegistrationEvent extends OWEvent { + OpenPinRegistrationEvent() : super(OWAction.openPinRegistration); +} + +class ClosePinRegistrationEvent extends OWEvent { + ClosePinRegistrationEvent() : super(OWAction.closePinRegistration); +} + +class OpenPinAuthenticationEvent extends OWEvent { + OpenPinAuthenticationEvent() : super(OWAction.openPinAuthentication); +} + +class ClosePinAuthenticationEvent extends OWEvent { + ClosePinAuthenticationEvent() : super(OWAction.closePinAuthentication); +} + +class PinNotAllowedEventEvent extends OWEvent { + OWOneginiError error; + PinNotAllowedEventEvent(this.error) : super(OWAction.pinNotAllowed); +} diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 64655287..8ce06633 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,5 +1,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/events/browser_event.dart'; +import 'package:onegini/events/custom_registration_event.dart'; +import 'package:onegini/events/fingerprint_event.dart'; +import 'package:onegini/events/generic_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/otp_event.dart'; +import 'package:onegini/events/pin_event.dart'; +import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'model/authentication_attempt.dart'; import 'model/onegini_event.dart'; @@ -13,100 +21,123 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { _context = context; } + // done ///Called to handle registration URL void handleRegisteredUrl(BuildContext? buildContext, String url); + // done /// Called to open OTP authentication. void openAuthOtp(BuildContext? buildContext, String message); + // done /// Called to close OTP authentication. void closeAuthOtp(BuildContext? buildContext); + // done /// Called to open pin registration screen. void openPinRequestScreen(BuildContext? buildContext); + // done /// Called to open pin authentication screen. void openPinScreenAuth(BuildContext? buildContext); + // done /// Called to attempt next authentication. void nextAuthenticationAttempt( BuildContext? buildContext, AuthenticationAttempt authenticationAttempt); + // done /// Called to close pin registration screen. void closePin(BuildContext? buildContext); + // done /// Called to close pin authentication screen. void closePinAuth(BuildContext? buildContext); + // done /// Called to open fingerprint screen. void openFingerprintScreen(BuildContext? buildContext); + // done /// Called to scan fingerprint. void showScanningFingerprint(BuildContext? buildContext); + // done /// Called when fingerprint was received. void receivedFingerprint(BuildContext? buildContext); + // done /// Called to close fingerprint screen. void closeFingerprintScreen(BuildContext? buildContext); + // done /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) void eventInitCustomRegistration( BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); + // done /// Called when the FinishCustomRegistration event occurs and a response should be given void eventFinishCustomRegistration( BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); - /// Called when error event was received. - void eventError(BuildContext? buildContext, PlatformException error); - - /// Called when custom event was received. - void eventOther(BuildContext? buildContext, Event event); - void pinNotAllowed(OWOneginiError error); @override void n2fCloseAuthOtp() { + broadcastEvent(CloseAuthOtpEvent()); + closeAuthOtp(_context); } @override void n2fCloseFingerprintScreen() { + broadcastEvent(CloseFingerprintEvent()); + closeFingerprintScreen(_context); } @override void n2fClosePin() { + broadcastEvent(ClosePinRegistrationEvent()); + closePin(_context); } @override void n2fClosePinAuth() { + broadcastEvent(ClosePinAuthenticationEvent()); + closePinAuth(_context); } @override void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId) { + broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); + eventFinishCustomRegistration(_context, customInfo, providerId); } @override void n2fEventInitCustomRegistration( OWCustomInfo? customInfo, String providerId) { + broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); + eventInitCustomRegistration(_context, customInfo, providerId); } @override void n2fHandleRegisteredUrl(String url) { - print("hello from handleRegisteredUrl"); + broadcastEvent(HandleRegisteredUrlEvent(url)); + handleRegisteredUrl(_context, url); } @override void n2fNextAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt) { + broadcastEvent(NextAuthenticationAttemptEvent(authenticationAttempt)); + nextAuthenticationAttempt( _context, AuthenticationAttempt( @@ -117,36 +148,54 @@ abstract class OneginiEventListener implements NativeCallFlutterApi { @override void n2fOpenAuthOtp(String? message) { - openAuthOtp(_context, message != null ? message : ""); + broadcastEvent(OpenAuthOtpEvent(message ?? "")); + + openAuthOtp(_context, message ?? ""); } @override void n2fOpenFingerprintScreen() { + broadcastEvent(OpenFingerprintEvent()); + openFingerprintScreen(_context); } @override void n2fOpenPinRequestScreen() { + broadcastEvent(OpenPinRegistrationEvent()); + openPinRequestScreen(_context); } @override void n2fOpenPinScreenAuth() { + broadcastEvent(OpenPinAuthenticationEvent()); + openPinScreenAuth(_context); } @override void n2fReceivedFingerprint() { + broadcastEvent(ReceivedFingerprintEvent()); + receivedFingerprint(_context); } @override void n2fShowScanningFingerprint() { + broadcastEvent(ShowScanningFingerprintEvent()); + showScanningFingerprint(_context); } @override void n2fEventPinNotAllowed(OWOneginiError error) { + broadcastEvent(PinNotAllowedEventEvent(error)); + pinNotAllowed(error); } + + void broadcastEvent(OWEvent event) { + Onegini.instance.userClient.owEventStreamController.sink.add(event); + } } diff --git a/lib/user_client.dart b/lib/user_client.dart index b363e7b4..7a930af3 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,5 +1,8 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/pigeon.dart'; @@ -11,6 +14,9 @@ class UserClient { final UserClientApi api; UserClient(this.api); + // ignore: close_sinks + final owEventStreamController = StreamController.broadcast(); + ///Start registration flow. /// /// If [identityProviderId] is null, starts standard browser registration. From a40d7c826e565f82b172c14b3eb993799e49bfbb Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 5 Apr 2023 14:24:40 +0200 Subject: [PATCH 246/364] fp-77 update podlock --- example/ios/Podfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 1ccd1fcb..98a96983 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -82,7 +82,7 @@ SPEC CHECKSUMS: SwiftLint: 77f7cb2b9bb81ab4a12fcc86448ba3f11afa50c6 Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 - url_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4 + url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de PODFILE CHECKSUM: e49c186fd5db1b7547d2a80e7096f4e0713e90f9 From 3e62854f654a9a623f63bcb735a918eada193d1d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 7 Apr 2023 16:08:14 +0200 Subject: [PATCH 247/364] FP-65: Update AuthenticateUser api's Simplify the authenticate api's to use pin/biometric as a type and remove the need to pass the actual id of an authenticator. --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 104 +++++++--------- ios/Classes/Pigeon.swift | 117 +++++++----------- lib/pigeon.dart | 92 ++++++-------- pigeons/onewelcome_pigeon_interface.dart | 28 +++-- 4 files changed, 141 insertions(+), 200 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index a368496d..969da76a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -56,6 +56,17 @@ enum class HttpRequestMethod(val raw: Int) { } } +enum class OWAuthenticatorType(val raw: Int) { + PIN(0), + BIOMETRIC(1); + + companion object { + fun ofRaw(raw: Int): OWAuthenticatorType? { + return values().firstOrNull { it.raw == raw } + } + } +} + enum class ResourceRequestType(val raw: Int) { AUTHENTICATED(0), IMPLICIT(1), @@ -142,7 +153,7 @@ data class OWAuthenticator ( val name: String, val isRegistered: Boolean, val isPreferred: Boolean, - val authenticatorType: Long + val authenticatorType: OWAuthenticatorType ) { companion object { @@ -152,7 +163,7 @@ data class OWAuthenticator ( val name = list[1] as String val isRegistered = list[2] as Boolean val isPreferred = list[3] as Boolean - val authenticatorType = list[4].let { if (it is Int) it.toLong() else it as Long } + val authenticatorType = OWAuthenticatorType.ofRaw(list[4] as Int)!! return OWAuthenticator(id, name, isRegistered, isPreferred, authenticatorType) } } @@ -162,7 +173,7 @@ data class OWAuthenticator ( name, isRegistered, isPreferred, - authenticatorType, + authenticatorType.raw, ) } } @@ -426,15 +437,14 @@ interface UserClientApi { fun handleRegisteredUserUrl(url: String, signInType: Long, callback: (Result) -> Unit) fun getIdentityProviders(callback: (Result>) -> Unit) fun deregisterUser(profileId: String, callback: (Result) -> Unit) - fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) - fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) fun getAuthenticatedUserProfile(callback: (Result) -> Unit) - fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) - fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) + fun authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) + fun isBiometricAuthenticatorRegistered(callback: (Result) -> Unit) + fun getPreferredAuthenticator(callback: (Result) -> Unit) + fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) + fun deregisterBiometricAuthenticator(callback: (Result) -> Unit) + fun registerBiometricAuthenticator(callback: (Result) -> Unit) fun changePin(callback: (Result) -> Unit) - fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) - fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) - fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) fun logout(callback: (Result) -> Unit) fun enrollMobileAuthentication(callback: (Result) -> Unit) fun handleMobileAuthWithOtp(data: String, callback: (Result) -> Unit) @@ -574,12 +584,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val profileIdArg = args[0] as String - api.getRegisteredAuthenticators(profileIdArg) { result: Result> -> + channel.setMessageHandler { _, reply -> + api.getAuthenticatedUserProfile() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -594,12 +602,13 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List val profileIdArg = args[0] as String - api.getAllAuthenticators(profileIdArg) { result: Result> -> + val authenticatorTypeArg = OWAuthenticatorType.ofRaw(args[1] as Int)!! + api.authenticateUser(profileIdArg, authenticatorTypeArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -614,10 +623,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", codec) if (api != null) { channel.setMessageHandler { _, reply -> - api.getAuthenticatedUserProfile() { result: Result -> + api.isBiometricAuthenticatorRegistered() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -632,13 +641,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUser", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator", codec) if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val profileIdArg = args[0] as String - val registeredAuthenticatorIdArg = args[1] as String? - api.authenticateUser(profileIdArg, registeredAuthenticatorIdArg) { result: Result -> + channel.setMessageHandler { _, reply -> + api.getPreferredAuthenticator() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -653,30 +659,12 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val profileIdArg = args[0] as String - api.getNotRegisteredAuthenticators(profileIdArg) { result: Result> -> - val error = result.exceptionOrNull() - if (error != null) { - reply.reply(wrapError(error)) - } else { - val data = result.getOrNull() - reply.reply(wrapResult(data)) - } - } - } - } else { - channel.setMessageHandler(null) - } - } - run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) - if (api != null) { - channel.setMessageHandler { _, reply -> - api.changePin() { result: Result -> + val authenticatorTypeArg = OWAuthenticatorType.ofRaw(args[0] as Int)!! + api.setPreferredAuthenticator(authenticatorTypeArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -690,12 +678,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator", codec) if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val authenticatorIdArg = args[0] as String - api.setPreferredAuthenticator(authenticatorIdArg) { result: Result -> + channel.setMessageHandler { _, reply -> + api.deregisterBiometricAuthenticator() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -709,12 +695,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator", codec) if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val authenticatorIdArg = args[0] as String - api.deregisterAuthenticator(authenticatorIdArg) { result: Result -> + channel.setMessageHandler { _, reply -> + api.registerBiometricAuthenticator() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -728,12 +712,10 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.registerAuthenticator", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.changePin", codec) if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val authenticatorIdArg = args[0] as String - api.registerAuthenticator(authenticatorIdArg) { result: Result -> + channel.setMessageHandler { _, reply -> + api.changePin() { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 74c343b3..22321a67 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -41,6 +41,11 @@ enum HttpRequestMethod: Int { case delete = 3 } +enum OWAuthenticatorType: Int { + case pin = 0 + case biometric = 1 +} + enum ResourceRequestType: Int { case authenticated = 0 case implicit = 1 @@ -118,14 +123,14 @@ struct OWAuthenticator { var name: String var isRegistered: Bool var isPreferred: Bool - var authenticatorType: Int64 + var authenticatorType: OWAuthenticatorType static func fromList(_ list: [Any]) -> OWAuthenticator? { let id = list[0] as! String let name = list[1] as! String let isRegistered = list[2] as! Bool let isPreferred = list[3] as! Bool - let authenticatorType = list[4] is Int64 ? list[4] as! Int64 : Int64(list[4] as! Int32) + let authenticatorType = OWAuthenticatorType(rawValue: list[4] as! Int)! return OWAuthenticator( id: id, @@ -141,7 +146,7 @@ struct OWAuthenticator { name, isRegistered, isPreferred, - authenticatorType, + authenticatorType.rawValue, ] } } @@ -398,15 +403,14 @@ protocol UserClientApi { func handleRegisteredUserUrl(url: String, signInType: Int64, completion: @escaping (Result) -> Void) func getIdentityProviders(completion: @escaping (Result<[OWIdentityProvider], Error>) -> Void) func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) - func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) - func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) - func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) - func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) + func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) + func isBiometricAuthenticatorRegistered(completion: @escaping (Result) -> Void) + func getPreferredAuthenticator(completion: @escaping (Result) -> Void) + func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) + func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) + func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) func changePin(completion: @escaping (Result) -> Void) - func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) - func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) - func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) func logout(completion: @escaping (Result) -> Void) func enrollMobileAuthentication(completion: @escaping (Result) -> Void) func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) @@ -532,12 +536,10 @@ class UserClientApiSetup { } else { deregisterUserChannel.setMessageHandler(nil) } - let getRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + let getAuthenticatedUserProfileChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - getRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in - let args = message as! [Any] - let profileIdArg = args[0] as! String - api.getRegisteredAuthenticators(profileId: profileIdArg) { result in + getAuthenticatedUserProfileChannel.setMessageHandler { _, reply in + api.getAuthenticatedUserProfile() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -547,14 +549,15 @@ class UserClientApiSetup { } } } else { - getRegisteredAuthenticatorsChannel.setMessageHandler(nil) + getAuthenticatedUserProfileChannel.setMessageHandler(nil) } - let getAllAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAllAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - getAllAuthenticatorsChannel.setMessageHandler { message, reply in + authenticateUserChannel.setMessageHandler { message, reply in let args = message as! [Any] let profileIdArg = args[0] as! String - api.getAllAuthenticators(profileId: profileIdArg) { result in + let authenticatorTypeArg = OWAuthenticatorType(rawValue: args[1] as! Int)! + api.authenticateUser(profileId: profileIdArg, authenticatorType: authenticatorTypeArg) { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -564,12 +567,12 @@ class UserClientApiSetup { } } } else { - getAllAuthenticatorsChannel.setMessageHandler(nil) + authenticateUserChannel.setMessageHandler(nil) } - let getAuthenticatedUserProfileChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", binaryMessenger: binaryMessenger, codec: codec) + let isBiometricAuthenticatorRegisteredChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - getAuthenticatedUserProfileChannel.setMessageHandler { _, reply in - api.getAuthenticatedUserProfile() { result in + isBiometricAuthenticatorRegisteredChannel.setMessageHandler { _, reply in + api.isBiometricAuthenticatorRegistered() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -579,15 +582,12 @@ class UserClientApiSetup { } } } else { - getAuthenticatedUserProfileChannel.setMessageHandler(nil) + isBiometricAuthenticatorRegisteredChannel.setMessageHandler(nil) } - let authenticateUserChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUser", binaryMessenger: binaryMessenger, codec: codec) + let getPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - authenticateUserChannel.setMessageHandler { message, reply in - let args = message as! [Any] - let profileIdArg = args[0] as! String - let registeredAuthenticatorIdArg: String? = nilOrValue(args[1]) - api.authenticateUser(profileId: profileIdArg, registeredAuthenticatorId: registeredAuthenticatorIdArg) { result in + getPreferredAuthenticatorChannel.setMessageHandler { _, reply in + api.getPreferredAuthenticator() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -597,29 +597,14 @@ class UserClientApiSetup { } } } else { - authenticateUserChannel.setMessageHandler(nil) + getPreferredAuthenticatorChannel.setMessageHandler(nil) } - let getNotRegisteredAuthenticatorsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators", binaryMessenger: binaryMessenger, codec: codec) + let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - getNotRegisteredAuthenticatorsChannel.setMessageHandler { message, reply in + setPreferredAuthenticatorChannel.setMessageHandler { message, reply in let args = message as! [Any] - let profileIdArg = args[0] as! String - api.getNotRegisteredAuthenticators(profileId: profileIdArg) { result in - switch result { - case .success(let res): - reply(wrapResult(res)) - case .failure(let error): - reply(wrapError(error)) - } - } - } - } else { - getNotRegisteredAuthenticatorsChannel.setMessageHandler(nil) - } - let changePinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.changePin", binaryMessenger: binaryMessenger, codec: codec) - if let api = api { - changePinChannel.setMessageHandler { _, reply in - api.changePin() { result in + let authenticatorTypeArg = OWAuthenticatorType(rawValue: args[0] as! Int)! + api.setPreferredAuthenticator(authenticatorType: authenticatorTypeArg) { result in switch result { case .success: reply(wrapResult(nil)) @@ -629,14 +614,12 @@ class UserClientApiSetup { } } } else { - changePinChannel.setMessageHandler(nil) + setPreferredAuthenticatorChannel.setMessageHandler(nil) } - let setPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + let deregisterBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - setPreferredAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any] - let authenticatorIdArg = args[0] as! String - api.setPreferredAuthenticator(authenticatorId: authenticatorIdArg) { result in + deregisterBiometricAuthenticatorChannel.setMessageHandler { _, reply in + api.deregisterBiometricAuthenticator() { result in switch result { case .success: reply(wrapResult(nil)) @@ -646,14 +629,12 @@ class UserClientApiSetup { } } } else { - setPreferredAuthenticatorChannel.setMessageHandler(nil) + deregisterBiometricAuthenticatorChannel.setMessageHandler(nil) } - let deregisterAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + let registerBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - deregisterAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any] - let authenticatorIdArg = args[0] as! String - api.deregisterAuthenticator(authenticatorId: authenticatorIdArg) { result in + registerBiometricAuthenticatorChannel.setMessageHandler { _, reply in + api.registerBiometricAuthenticator() { result in switch result { case .success: reply(wrapResult(nil)) @@ -663,14 +644,12 @@ class UserClientApiSetup { } } } else { - deregisterAuthenticatorChannel.setMessageHandler(nil) + registerBiometricAuthenticatorChannel.setMessageHandler(nil) } - let registerAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerAuthenticator", binaryMessenger: binaryMessenger, codec: codec) + let changePinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.changePin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - registerAuthenticatorChannel.setMessageHandler { message, reply in - let args = message as! [Any] - let authenticatorIdArg = args[0] as! String - api.registerAuthenticator(authenticatorId: authenticatorIdArg) { result in + changePinChannel.setMessageHandler { _, reply in + api.changePin() { result in switch result { case .success: reply(wrapResult(nil)) @@ -680,7 +659,7 @@ class UserClientApiSetup { } } } else { - registerAuthenticatorChannel.setMessageHandler(nil) + changePinChannel.setMessageHandler(nil) } let logoutChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.logout", binaryMessenger: binaryMessenger, codec: codec) if let api = api { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index de0506dd..3bbd735e 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -15,6 +15,11 @@ enum HttpRequestMethod { delete, } +enum OWAuthenticatorType { + pin, + biometric, +} + enum ResourceRequestType { authenticated, implicit, @@ -113,7 +118,7 @@ class OWAuthenticator { bool isPreferred; - int authenticatorType; + OWAuthenticatorType authenticatorType; Object encode() { return [ @@ -121,7 +126,7 @@ class OWAuthenticator { name, isRegistered, isPreferred, - authenticatorType, + authenticatorType.index, ]; } @@ -132,7 +137,7 @@ class OWAuthenticator { name: result[1]! as String, isRegistered: result[2]! as bool, isPreferred: result[3]! as bool, - authenticatorType: result[4]! as int, + authenticatorType: OWAuthenticatorType.values[result[4]! as int], ); } } @@ -530,12 +535,12 @@ class UserClientApi { } } - Future> getRegisteredAuthenticators(String arg_profileId) async { + Future getAuthenticatedUserProfile() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.getRegisteredAuthenticators', codec, + 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_profileId]) as List?; + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -553,16 +558,16 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as OWUserProfile?)!; } } - Future> getAllAuthenticators(String arg_profileId) async { + Future authenticateUser(String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.getAllAuthenticators', codec, + 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_profileId]) as List?; + await channel.send([arg_profileId, arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -580,13 +585,13 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as OWRegistrationResponse?)!; } } - Future getAuthenticatedUserProfile() async { + Future isBiometricAuthenticatorRegistered() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, + 'dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send(null) as List?; @@ -607,43 +612,16 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as OWUserProfile?)!; - } - } - - Future authenticateUser(String arg_profileId, String? arg_registeredAuthenticatorId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_registeredAuthenticatorId]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as OWRegistrationResponse?)!; + return (replyList[0] as bool?)!; } } - Future> getNotRegisteredAuthenticators(String arg_profileId) async { + Future getPreferredAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.getNotRegisteredAuthenticators', codec, + 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_profileId]) as List?; + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -661,16 +639,16 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as OWAuthenticator?)!; } } - Future changePin() async { + Future setPreferredAuthenticator(OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.changePin', codec, + 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send(null) as List?; + await channel.send([arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -687,12 +665,12 @@ class UserClientApi { } } - Future setPreferredAuthenticator(String arg_authenticatorId) async { + Future deregisterBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_authenticatorId]) as List?; + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -709,12 +687,12 @@ class UserClientApi { } } - Future deregisterAuthenticator(String arg_authenticatorId) async { + Future registerBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.deregisterAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_authenticatorId]) as List?; + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -731,12 +709,12 @@ class UserClientApi { } } - Future registerAuthenticator(String arg_authenticatorId) async { + Future changePin() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.registerAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_authenticatorId]) as List?; + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index a081f3f4..d4e0d17f 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -46,7 +46,7 @@ class OWAuthenticator { String name; bool isRegistered; bool isPreferred; - int authenticatorType; + OWAuthenticatorType authenticatorType; OWAuthenticator( {required this.id, @@ -77,6 +77,11 @@ enum HttpRequestMethod { delete, } +enum OWAuthenticatorType { + pin, + biometric, +} + enum ResourceRequestType { authenticated, implicit, anonymous, unauthenticated } class OWRequestDetails { @@ -148,33 +153,30 @@ abstract class UserClientApi { @async void deregisterUser(String profileId); - @async - List getRegisteredAuthenticators(String profileId); - - @async - List getAllAuthenticators(String profileId); - @async OWUserProfile getAuthenticatedUserProfile(); @async OWRegistrationResponse authenticateUser( - String profileId, String? registeredAuthenticatorId); + String profileId, OWAuthenticatorType authenticatorType); @async - List getNotRegisteredAuthenticators(String profileId); + bool isBiometricAuthenticatorRegistered(); @async - void changePin(); + OWAuthenticator getPreferredAuthenticator(); @async - void setPreferredAuthenticator(String authenticatorId); + void setPreferredAuthenticator(OWAuthenticatorType authenticatorType); @async - void deregisterAuthenticator(String authenticatorId); + void deregisterBiometricAuthenticator(); @async - void registerAuthenticator(String authenticatorId); + void registerBiometricAuthenticator(); + + @async + void changePin(); @async void logout(); From 48a666e4d6cfcc329271386b85beefd6f608b7d5 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 11 Apr 2023 12:02:34 +0200 Subject: [PATCH 248/364] FP-77 Setup working structure example app to handle the new broadcast listener structure --- example/lib/main.dart | 4 - example/lib/onegini_listener.dart | 190 +++++++++++++------------- example/lib/ow_broadcast_helper.dart | 175 ++++++++++++++++++++++++ example/lib/screens/login_screen.dart | 22 +++ example/lib/screens/user_screen.dart | 26 +++- lib/events/onewelcome_events.dart | 2 +- lib/onegini.dart | 5 +- 7 files changed, 315 insertions(+), 109 deletions(-) create mode 100644 example/lib/ow_broadcast_helper.dart diff --git a/example/lib/main.dart b/example/lib/main.dart index 834fd15c..923a0711 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,6 +1,5 @@ // @dart = 2.10 import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; @@ -46,9 +45,6 @@ class BodyWidget extends StatefulWidget { } class _BodyWidgetState extends State { - var _appStarted = false; - var appError; - @override void initState() { _startApplication(); diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart index a217ef02..201cb042 100644 --- a/example/lib/onegini_listener.dart +++ b/example/lib/onegini_listener.dart @@ -20,163 +20,157 @@ import 'screens/otp_screen.dart'; class OneginiListener extends OneginiEventListener { final PinScreenController pinScreenController = PinScreenController(); + // done @override void closePin(BuildContext buildContext) { - if (Navigator.of(buildContext).canPop()) { - Navigator.of(buildContext).pop(); - } + // if (Navigator.of(buildContext).canPop()) { + // Navigator.of(buildContext).pop(); + // } } + // done @override void openPinRequestScreen(BuildContext buildContext) { - Navigator.push( - buildContext, - MaterialPageRoute(builder: (context) => PinRequestScreen()), - ); - } - - @override - void eventOther(BuildContext buildContext, Event event) { - print(event.eventValue); - } - - @override - void eventError(BuildContext buildContext, PlatformException error) { - showFlutterToast("${error.message} Code: ${error.code} "); + // Navigator.push( + // buildContext, + // MaterialPageRoute(builder: (context) => PinRequestScreen()), + // ); } + // done @override void openPinScreenAuth(BuildContext buildContext) { - Navigator.push( - buildContext, - MaterialPageRoute( - builder: (context) => PinScreen(controller: pinScreenController)), - ); + // Navigator.push( + // buildContext, + // MaterialPageRoute( + // builder: (context) => PinScreen(controller: pinScreenController)), + // ); } - - @override - void openPinAuthenticator(BuildContext buildContext) { - Navigator.push( - buildContext, - MaterialPageRoute( - builder: (context) => PinRequestScreen( - customAuthenticator: true, - )), - ); - } - + + // done @override void nextAuthenticationAttempt( BuildContext buildContext, AuthenticationAttempt authenticationAttempt) { - pinScreenController.clearState(); - showFlutterToast( - "failed attempts ${authenticationAttempt.failedAttempts} from ${authenticationAttempt.maxAttempts}"); + // pinScreenController.clearState(); + // showFlutterToast( + // "failed attempts ${authenticationAttempt.failedAttempts} from ${authenticationAttempt.maxAttempts}"); } + // done @override void closeFingerprintScreen(BuildContext buildContext) { - print("close fingerprint"); - overlayEntry?.remove(); - if (Navigator.of(buildContext).canPop()) { - Navigator.of(buildContext).pop(); - } + // print("close fingerprint"); + // overlayEntry?.remove(); + // if (Navigator.of(buildContext).canPop()) { + // Navigator.of(buildContext).pop(); + // } } + // done @override void openFingerprintScreen(BuildContext buildContext) { - print("open fingerprint"); - Navigator.push( - buildContext, - MaterialPageRoute(builder: (context) => FingerprintScreen()), - ); + // print("open fingerprint"); + // Navigator.push( + // buildContext, + // MaterialPageRoute(builder: (context) => FingerprintScreen()), + // ); } + // done @override void receivedFingerprint(BuildContext buildContext) { - overlayEntry?.remove(); + // overlayEntry?.remove(); } + // done @override void showScanningFingerprint(BuildContext buildContext) { - overlayEntry = OverlayEntry(builder: (context) { - return Container( - color: Colors.black12.withOpacity(0.5), - child: Center( - child: CircularProgressIndicator(), - )); - }); - Overlay.of(buildContext)?.insert(overlayEntry); + // overlayEntry = OverlayEntry(builder: (context) { + // return Container( + // color: Colors.black12.withOpacity(0.5), + // child: Center( + // child: CircularProgressIndicator(), + // )); + // }); + // Overlay.of(buildContext)?.insert(overlayEntry); } OverlayEntry overlayEntry; + // done @override void openAuthOtp(BuildContext buildContext, String message) { - Navigator.push( - buildContext, - MaterialPageRoute( - builder: (context) => AuthOtpScreen( - message: message, - )), - ); + // Navigator.push( + // buildContext, + // MaterialPageRoute( + // builder: (context) => AuthOtpScreen( + // message: message, + // )), + // ); } + // done @override void closeAuthOtp(BuildContext buildContext) { - Navigator.of(buildContext).pop(); + // Navigator.of(buildContext).pop(); } + // done @override void closePinAuth(BuildContext buildContext) { - if (Navigator.of(buildContext).canPop()) { - Navigator.of(buildContext).pop(); - } + // if (Navigator.of(buildContext).canPop()) { + // Navigator.of(buildContext).pop(); + // } } + // done @override void eventInitCustomRegistration( BuildContext buildContext, OWCustomInfo customInfo, String providerId) { - try { - if (providerId == "2-way-otp-api") { - // a 2-way-otp does not require data for the initialization request - OneginiCustomRegistrationCallback() - .submitSuccessAction(providerId, null) - .catchError((error) => { - if (error is PlatformException) - {showFlutterToast(error.message)} - }); - } - } on FormatException catch (error) { - showFlutterToast(error.message); - return; - } - } - + // try { + // if (providerId == "2-way-otp-api") { + // // a 2-way-otp does not require data for the initialization request + // OneginiCustomRegistrationCallback() + // .submitSuccessAction(providerId, null) + // .catchError((error) => { + // if (error is PlatformException) + // {showFlutterToast(error.message)} + // }); + // } + // } on FormatException catch (error) { + // showFlutterToast(error.message); + // return; + // } + } + + // done @override void eventFinishCustomRegistration( BuildContext buildContext, OWCustomInfo customInfo, String providerId) { - try { - if (providerId == "2-way-otp-api") - Navigator.push( - buildContext, - MaterialPageRoute( - builder: (context) => OtpScreen( - password: customInfo?.data, providerId: providerId)), - ); - } on FormatException catch (error) { - showFlutterToast(error.message); - return; - } + // try { + // if (providerId == "2-way-otp-api") + // Navigator.push( + // buildContext, + // MaterialPageRoute( + // builder: (context) => OtpScreen( + // password: customInfo?.data, providerId: providerId)), + // ); + // } on FormatException catch (error) { + // showFlutterToast(error.message); + // return; + // } } + @override void handleRegisteredUrl(BuildContext buildContext, String url) async { - await Onegini.instance.userClient.handleRegisteredUserUrl(buildContext, url, - signInType: WebSignInType.insideApp); + // await Onegini.instance.userClient.handleRegisteredUserUrl(buildContext, url, + // signInType: WebSignInType.insideApp); } + // done @override void pinNotAllowed(OWOneginiError error) { - showFlutterToast("${error.message} Code: ${error.code}"); + // showFlutterToast("${error.message} Code: ${error.code}"); } } diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart new file mode 100644 index 00000000..e9f643c6 --- /dev/null +++ b/example/lib/ow_broadcast_helper.dart @@ -0,0 +1,175 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; +import 'package:onegini/events/browser_event.dart'; +import 'package:onegini/events/custom_registration_event.dart'; +import 'package:onegini/events/fingerprint_event.dart'; +import 'package:onegini/events/generic_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/otp_event.dart'; +import 'package:onegini/events/pin_event.dart'; +import 'package:onegini/onegini.dart'; +import 'package:onegini/user_client.dart'; +import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/screens/auth_otp_screen.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/fingerprint_screen.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/otp_screen.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/pin_request_screen.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/pin_screen.dart'; + +class OWBroadcastHelper { + static List> initRegistrationListeners(BuildContext context) { + var broadCastController = Onegini.instance.userClient.owEventStreamController; + + // Url Registration Related Events + StreamSubscription handleRegisteredUrlSub = broadCastController.stream.where((event) => event is HandleRegisteredUrlEvent).listen((event) { + if (event is HandleRegisteredUrlEvent) { + Onegini.instance.userClient.handleRegisteredUserUrl(context, event.url, + signInType: WebSignInType.insideApp); + } + }); + + // Pin Registration Related Events + StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinRegistrationEvent).listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => PinRequestScreen()), + ); + }); + + StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinRegistrationEvent).listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + + StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEventEvent).listen((event) { + if (event is PinNotAllowedEventEvent) { + showFlutterToast("${event.error.message} Code: ${event.error.code}"); + } + }); + + // Custom Registration related events + StreamSubscription initCustomSub = broadCastController.stream.where((event) => event is InitCustomRegistrationEvent).listen((event) { + if (event is InitCustomRegistrationEvent && event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + OneginiCustomRegistrationCallback() + .submitSuccessAction(event.providerId, null) + .catchError((error) => { + if (error is PlatformException) + {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} + }); + } + }); + + StreamSubscription finishCustomSub = broadCastController.stream.where((event) => event is FinishCustomRegistrationEvent).listen((event) { + if (event is FinishCustomRegistrationEvent && event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => OtpScreen( + password: event.customInfo?.data, providerId: event.providerId)), + ); + } + }); + + return [handleRegisteredUrlSub, openPinSub, closePinSub, pinNotAllowedSub, initCustomSub, finishCustomSub]; + } + + static List> initAuthenticationListeners(BuildContext context) { + var broadCastController = Onegini.instance.userClient.owEventStreamController; + var pinScreenController = PinScreenController(); + var fingerprintOverlay = OverlayEntry(builder: (context) { + return Container( + color: Colors.black12.withOpacity(0.5), + child: Center( + child: CircularProgressIndicator(), + )); + }); + + // Pin Authentication related events + StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinAuthenticationEvent).listen((event) { + print("open pin auth:"); + print(context); + print(pinScreenController); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PinScreen(controller: pinScreenController)), + ); + }); + + StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinAuthenticationEvent).listen((event) { + print("close pin auth"); + print(context); + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + + // Fingerprint Authentication related events + StreamSubscription openFingerprintSub = broadCastController.stream.where((event) => event is OpenFingerprintEvent).listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => FingerprintScreen()), + ); + }); + + StreamSubscription closeFingerprintSub = broadCastController.stream.where((event) => event is CloseFingerprintEvent).listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + + StreamSubscription showScanningFingerprintSub = broadCastController.stream.where((event) => event is ShowScanningFingerprintEvent).listen((event) { + Overlay.of(context).insert(fingerprintOverlay); + }); + + StreamSubscription receivedFingerprintSub = broadCastController.stream.where((event) => event is ReceivedFingerprintEvent).listen((event) { + fingerprintOverlay.remove(); + }); + + // Generic Authentication related events + StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextAuthenticationAttemptEvent).listen((event) { + if (event is NextAuthenticationAttemptEvent) { + pinScreenController.clearState(); + showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); + } + }); + + return [openPinSub, closePinSub, openFingerprintSub, closeFingerprintSub, showScanningFingerprintSub, receivedFingerprintSub, nextAuthenticationAttempt]; + } + + static List> initOTPListeners(BuildContext context) { + var broadCastController = Onegini.instance.userClient.owEventStreamController; + + StreamSubscription openAuthOtpSub = broadCastController.stream.where((event) => event is OpenAuthOtpEvent).listen((event) { + if (event is OpenAuthOtpEvent) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => AuthOtpScreen( + message: event.message, + )), + ); + } + }); + + StreamSubscription closeAuthOtpSub = broadCastController.stream.where((event) => event is CloseAuthOtpEvent).listen((event) { + Navigator.of(context).pop(); + }); + + return [openAuthOtpSub, closeAuthOtpSub]; + } + + static void stopListening(List> subscriptions) { + subscriptions.forEach((element) { element.cancel(); }); + } +} \ No newline at end of file diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 854b6203..e5ab85da 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -1,12 +1,16 @@ // @dart = 2.10 +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_registration_callback.dart'; +import 'package:onegini/events/custom_registration_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/user_screen.dart'; import '../components/display_toast.dart'; @@ -18,15 +22,32 @@ class LoginScreen extends StatefulWidget { class _LoginScreenState extends State { bool isLoading = false; + OWBroadcastHelper broadcastHelper; + List> registrationSubscriptions; + List> authenticationSubscriptions; @override initState() { + // this.broadcastHelper = OWBroadcastHelper(context: context, temp: "1"); + this.registrationSubscriptions = OWBroadcastHelper.initRegistrationListeners(context); + this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationListeners(context); + super.initState(); } + @override + void dispose() { + print("disposing listeners"); + OWBroadcastHelper.stopListening(registrationSubscriptions); + OWBroadcastHelper.stopListening(authenticationSubscriptions); + + super.dispose(); + } + openWeb() async { /// Start registration setState(() => {isLoading = true}); + try { var registrationResponse = await Onegini.instance.userClient.registerUser( context, @@ -58,6 +79,7 @@ class _LoginScreenState extends State { identityProviderId, ["read"], ); + if (registrationResponse.userProfile.profileId != null) Navigator.pushAndRemoveUntil( context, diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6c5b1bc3..2d15827a 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -1,14 +1,17 @@ // @dart = 2.10 +import 'dart:async'; import 'dart:convert'; import "package:collection/collection.dart"; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/models/application_details.dart'; import 'package:onegini_example/models/client_resource.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:onegini/pigeon.dart'; @@ -32,6 +35,11 @@ class _UserScreenState extends State with RouteAware { List registeredAuthenticators = []; List notRegisteredAuthenticators = []; String profileId = ""; + OWBroadcastHelper broadcastHelper; + List> registrationSubscriptions; + List> authenticationSubscriptions; + List> otpSubscriptions; + void onTabTapped(int index) { setState(() { @@ -49,6 +57,11 @@ class _UserScreenState extends State with RouteAware { ]; super.initState(); this.profileId = widget.userProfileId; + + // Init listeners for changePin, setPreferredAuthenticators + this.registrationSubscriptions = OWBroadcastHelper.initRegistrationListeners(context); + this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationListeners(context); + getAuthenticators(); } @@ -61,6 +74,10 @@ class _UserScreenState extends State with RouteAware { @override void dispose() { routeObserver.unsubscribe(this); + + OWBroadcastHelper.stopListening(authenticationSubscriptions); + OWBroadcastHelper.stopListening(registrationSubscriptions); + super.dispose(); } @@ -170,6 +187,7 @@ class _UserScreenState extends State with RouteAware { changePin(BuildContext context) { Navigator.pop(context); + Onegini.instance.userClient.changePin(context).catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); @@ -304,7 +322,8 @@ class Home extends StatelessWidget { } authWithOpt(BuildContext context) async { - Onegini.instance.setEventContext(context); + List otpSubscriptions = OWBroadcastHelper.initOTPListeners(context); + var data = await Navigator.push( context, MaterialPageRoute(builder: (_) => QrScanScreen()), @@ -313,14 +332,15 @@ class Home extends StatelessWidget { if (data != null) { await Onegini.instance.userClient .handleMobileAuthWithOtp(data) - .then((value) => showFlutterToast("OTP1 Authentication is successfull")) + .then((value) => showFlutterToast("OTP Authentication is successfull")) .catchError((error) { if (error is PlatformException) { - print("otp1"); print(error.message); } }); } + + OWBroadcastHelper.stopListening(otpSubscriptions); } getAppToWebSingleSignOn(BuildContext context) async { diff --git a/lib/events/onewelcome_events.dart b/lib/events/onewelcome_events.dart index 2386d7f1..7cdb71b4 100644 --- a/lib/events/onewelcome_events.dart +++ b/lib/events/onewelcome_events.dart @@ -17,7 +17,7 @@ enum OWAction { closePinRegistration, // previously closePin; Called to open pin registration screen. openPinAuthentication, // previously openPinScreenAuth; Called to open pin authentication screen closePinAuthentication, // previously closePinAuth; Called to close pin authentication screen - pinNotAllowed, // Called when the supplied pin is not allowed + pinNotAllowed, // Called when the supplied pin for registration is not allowed // Fingerprint openFingerprint, // previously openFingerprintScreen; Called to open fingerprint screen. diff --git a/lib/onegini.dart b/lib/onegini.dart index 3ec6e094..b420c998 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -13,6 +13,8 @@ import 'model/onegini_removed_user_profile.dart'; /// The main class used to call methods. class Onegini { + // UserClientApi is the flutter to native api created by the Pigeon package, see /pigeons/README.md + /// User client methods. final UserClientApi api = UserClientApi(); late final UserClient userClient; @@ -33,9 +35,6 @@ class Onegini { /// Resource methods. ResourcesMethods resourcesMethods = ResourcesMethods(); - // UserClientApi is the flutter to native api created by the Pigeon package, see /pigeons/README.md - /// User client methods. - /// Use this method when you want change [BuildContext] in your [OneginiEventListener] setEventContext(BuildContext? context) { _eventListener?.context = context; From f1745414bb105ca9ff4d5f5514734df2218680aa Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 11 Apr 2023 15:33:55 +0200 Subject: [PATCH 249/364] FP-77 Clean up of the oneginilistener cleaner, buildcontext and code leftovers --- example/lib/main.dart | 7 +- example/lib/onegini_listener.dart | 176 ------------------ example/lib/ow_broadcast_helper.dart | 5 +- example/lib/screens/auth_otp_screen.dart | 4 +- example/lib/screens/fingerprint_screen.dart | 2 +- example/lib/screens/login_screen.dart | 10 +- example/lib/screens/pin_request_screen.dart | 2 +- example/lib/screens/pin_screen.dart | 2 +- example/lib/screens/user_screen.dart | 18 +- .../onegini_fingerprint_callback.dart | 7 +- .../onegini_otp_accept_deny_callback.dart | 7 +- .../onegini_pin_authentication_callback.dart | 7 +- .../onegini_pin_registration_callback.dart | 8 +- .../onegini_registration_callback.dart | 1 - lib/events/onewelcome_events.dart | 23 +-- lib/onegini.dart | 14 +- lib/onegini_event_listener.dart | 110 +---------- lib/user_client.dart | 56 ++---- 18 files changed, 52 insertions(+), 407 deletions(-) delete mode 100644 example/lib/onegini_listener.dart diff --git a/example/lib/main.dart b/example/lib/main.dart index 923a0711..71fadc09 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -3,10 +3,9 @@ import 'package:flutter/material.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/login_screen.dart'; -import 'onegini_listener.dart'; - final RouteObserver routeObserver = RouteObserver(); void main() { @@ -45,6 +44,8 @@ class BodyWidget extends StatefulWidget { } class _BodyWidgetState extends State { + OWBroadcastHelper derp; + @override void initState() { _startApplication(); @@ -54,7 +55,7 @@ class _BodyWidgetState extends State { void _startApplication() async { /// init Onegini sdk on native side try { - await Onegini.instance.startApplication(OneginiListener(), + await Onegini.instance.startApplication( securityControllerClassName: "com.onegini.mobile.onegini_example.SecurityController", configModelClassName: diff --git a/example/lib/onegini_listener.dart b/example/lib/onegini_listener.dart deleted file mode 100644 index 201cb042..00000000 --- a/example/lib/onegini_listener.dart +++ /dev/null @@ -1,176 +0,0 @@ -// @dart = 2.10 - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:onegini/model/authentication_attempt.dart'; -import 'package:onegini/model/onegini_event.dart'; -import 'package:onegini/onegini.dart'; -import 'package:onegini/onegini_event_listener.dart'; -import 'package:onegini/pigeon.dart'; -import 'package:onegini/user_client.dart'; -import 'package:onegini_example/screens/auth_otp_screen.dart'; -import 'package:onegini_example/screens/fingerprint_screen.dart'; -import 'package:onegini_example/screens/pin_request_screen.dart'; -import 'package:onegini_example/screens/pin_screen.dart'; -import 'package:onegini_example/components/display_toast.dart'; -import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; - -import 'screens/otp_screen.dart'; - -class OneginiListener extends OneginiEventListener { - final PinScreenController pinScreenController = PinScreenController(); - - // done - @override - void closePin(BuildContext buildContext) { - // if (Navigator.of(buildContext).canPop()) { - // Navigator.of(buildContext).pop(); - // } - } - - // done - @override - void openPinRequestScreen(BuildContext buildContext) { - // Navigator.push( - // buildContext, - // MaterialPageRoute(builder: (context) => PinRequestScreen()), - // ); - } - - // done - @override - void openPinScreenAuth(BuildContext buildContext) { - // Navigator.push( - // buildContext, - // MaterialPageRoute( - // builder: (context) => PinScreen(controller: pinScreenController)), - // ); - } - - // done - @override - void nextAuthenticationAttempt( - BuildContext buildContext, AuthenticationAttempt authenticationAttempt) { - // pinScreenController.clearState(); - // showFlutterToast( - // "failed attempts ${authenticationAttempt.failedAttempts} from ${authenticationAttempt.maxAttempts}"); - } - - // done - @override - void closeFingerprintScreen(BuildContext buildContext) { - // print("close fingerprint"); - // overlayEntry?.remove(); - // if (Navigator.of(buildContext).canPop()) { - // Navigator.of(buildContext).pop(); - // } - } - - // done - @override - void openFingerprintScreen(BuildContext buildContext) { - // print("open fingerprint"); - // Navigator.push( - // buildContext, - // MaterialPageRoute(builder: (context) => FingerprintScreen()), - // ); - } - - // done - @override - void receivedFingerprint(BuildContext buildContext) { - // overlayEntry?.remove(); - } - - // done - @override - void showScanningFingerprint(BuildContext buildContext) { - // overlayEntry = OverlayEntry(builder: (context) { - // return Container( - // color: Colors.black12.withOpacity(0.5), - // child: Center( - // child: CircularProgressIndicator(), - // )); - // }); - // Overlay.of(buildContext)?.insert(overlayEntry); - } - - OverlayEntry overlayEntry; - - // done - @override - void openAuthOtp(BuildContext buildContext, String message) { - // Navigator.push( - // buildContext, - // MaterialPageRoute( - // builder: (context) => AuthOtpScreen( - // message: message, - // )), - // ); - } - - // done - @override - void closeAuthOtp(BuildContext buildContext) { - // Navigator.of(buildContext).pop(); - } - - // done - @override - void closePinAuth(BuildContext buildContext) { - // if (Navigator.of(buildContext).canPop()) { - // Navigator.of(buildContext).pop(); - // } - } - - // done - @override - void eventInitCustomRegistration( - BuildContext buildContext, OWCustomInfo customInfo, String providerId) { - // try { - // if (providerId == "2-way-otp-api") { - // // a 2-way-otp does not require data for the initialization request - // OneginiCustomRegistrationCallback() - // .submitSuccessAction(providerId, null) - // .catchError((error) => { - // if (error is PlatformException) - // {showFlutterToast(error.message)} - // }); - // } - // } on FormatException catch (error) { - // showFlutterToast(error.message); - // return; - // } - } - - // done - @override - void eventFinishCustomRegistration( - BuildContext buildContext, OWCustomInfo customInfo, String providerId) { - // try { - // if (providerId == "2-way-otp-api") - // Navigator.push( - // buildContext, - // MaterialPageRoute( - // builder: (context) => OtpScreen( - // password: customInfo?.data, providerId: providerId)), - // ); - // } on FormatException catch (error) { - // showFlutterToast(error.message); - // return; - // } - } - - - @override - void handleRegisteredUrl(BuildContext buildContext, String url) async { - // await Onegini.instance.userClient.handleRegisteredUserUrl(buildContext, url, - // signInType: WebSignInType.insideApp); - } - - // done - @override - void pinNotAllowed(OWOneginiError error) { - // showFlutterToast("${error.message} Code: ${error.code}"); - } -} diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index e9f643c6..902880cd 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -13,6 +13,7 @@ import 'package:onegini/events/pin_event.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/user_client.dart'; import 'package:onegini_example/components/display_toast.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'package:onegini_example/screens/auth_otp_screen.dart'; // ignore: import_of_legacy_library_into_null_safe import 'package:onegini_example/screens/fingerprint_screen.dart'; @@ -30,7 +31,7 @@ class OWBroadcastHelper { // Url Registration Related Events StreamSubscription handleRegisteredUrlSub = broadCastController.stream.where((event) => event is HandleRegisteredUrlEvent).listen((event) { if (event is HandleRegisteredUrlEvent) { - Onegini.instance.userClient.handleRegisteredUserUrl(context, event.url, + Onegini.instance.userClient.handleRegisteredUserUrl(event.url, signInType: WebSignInType.insideApp); } }); @@ -172,4 +173,4 @@ class OWBroadcastHelper { static void stopListening(List> subscriptions) { subscriptions.forEach((element) { element.cancel(); }); } -} \ No newline at end of file +} diff --git a/example/lib/screens/auth_otp_screen.dart b/example/lib/screens/auth_otp_screen.dart index b27cd149..17a4af33 100644 --- a/example/lib/screens/auth_otp_screen.dart +++ b/example/lib/screens/auth_otp_screen.dart @@ -2,7 +2,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_otp_accept_deny_callback.dart'; -import 'package:onegini/onegini.dart'; import '../components/display_toast.dart'; class AuthOtpScreen extends StatefulWidget { @@ -16,9 +15,8 @@ class AuthOtpScreen extends StatefulWidget { class _AuthOtpScreenState extends State { accept(BuildContext context) async { - Onegini.instance.setEventContext(context); OneginiOtpAcceptDenyCallback() - .acceptAuthenticationRequest(context) + .acceptAuthenticationRequest() .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); diff --git a/example/lib/screens/fingerprint_screen.dart b/example/lib/screens/fingerprint_screen.dart index 29e53a53..29b09ae7 100644 --- a/example/lib/screens/fingerprint_screen.dart +++ b/example/lib/screens/fingerprint_screen.dart @@ -18,7 +18,7 @@ class _FingerprintScreenState extends State { activateFingerprint() async { await OneginiFingerprintCallback() - .acceptAuthenticationRequest(context) + .acceptAuthenticationRequest() .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index e5ab85da..0fa5e85a 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -5,7 +5,6 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_registration_callback.dart'; -import 'package:onegini/events/custom_registration_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; @@ -50,7 +49,6 @@ class _LoginScreenState extends State { try { var registrationResponse = await Onegini.instance.userClient.registerUser( - context, null, ["read"], ); @@ -75,7 +73,6 @@ class _LoginScreenState extends State { setState(() => {isLoading = true}); try { var registrationResponse = await Onegini.instance.userClient.registerUser( - context, identityProviderId, ["read"], ); @@ -99,7 +96,7 @@ class _LoginScreenState extends State { authenticateWithPreferredAuthenticator(String profileId) async { setState(() => {isLoading = true}); var registrationResponse = await Onegini.instance.userClient - .authenticateUser(context, profileId, null) + .authenticateUser(profileId, null) .catchError((error) { setState(() => isLoading = false); if (error is PlatformException) { @@ -123,7 +120,7 @@ class _LoginScreenState extends State { // print(result); var registrationResponse = await Onegini.instance.userClient - .authenticateUser(context, profileId, registeredAuthenticatorId) + .authenticateUser(profileId, registeredAuthenticatorId) .catchError((error) { setState(() => isLoading = false); if (error is PlatformException) { @@ -283,7 +280,6 @@ class _LoginScreenState extends State { future: Onegini .instance.userClient .getRegisteredAuthenticators( - context, userProfiles .data .first @@ -364,7 +360,7 @@ class _LoginScreenState extends State { ), FutureBuilder>( future: Onegini.instance.userClient - .getIdentityProviders(context), + .getIdentityProviders(), builder: (BuildContext context, identityProviders) { return identityProviders.hasData ? PopupMenuButton( diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index 021fbfc2..f19fa75c 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -65,7 +65,7 @@ class _PinRequestScreenState extends State { if (widget.confirmation) { if (pin == widget.previousCode) { OneginiPinRegistrationCallback() - .acceptAuthenticationRequest(context, pin) + .acceptAuthenticationRequest(pin) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); diff --git a/example/lib/screens/pin_screen.dart b/example/lib/screens/pin_screen.dart index f557a828..3777ecb1 100644 --- a/example/lib/screens/pin_screen.dart +++ b/example/lib/screens/pin_screen.dart @@ -66,7 +66,7 @@ class _PinScreenState extends State { pin += element; }); OneginiPinAuthenticationCallback() - .acceptAuthenticationRequest(context, pin) + .acceptAuthenticationRequest(pin) .catchError((error) { if (error is PlatformException) { setState(() => {isLoading = false}); diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 2d15827a..dc0e1f3b 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -101,15 +101,15 @@ class _UserScreenState extends State with RouteAware { Future getAuthenticators() async { notRegisteredAuthenticators = await Onegini.instance.userClient - .getNotRegisteredAuthenticators(context, this.profileId); + .getNotRegisteredAuthenticators(this.profileId); registeredAuthenticators = await Onegini.instance.userClient - .getRegisteredAuthenticators(context, this.profileId); + .getRegisteredAuthenticators(this.profileId); } Future> getAllSortAuthenticators() async { var allAuthenticators = await Onegini.instance.userClient - .getAllAuthenticators(context, this.profileId); + .getAllAuthenticators(this.profileId); allAuthenticators.sort((a, b) { return compareAsciiUpperCase(a.name, b.name); }); @@ -118,13 +118,13 @@ class _UserScreenState extends State with RouteAware { Future> getNotRegisteredAuthenticators() async { var authenticators = await Onegini.instance.userClient - .getNotRegisteredAuthenticators(context, this.profileId); + .getNotRegisteredAuthenticators(this.profileId); return authenticators; } registerAuthenticator(String authenticatorId) async { await Onegini.instance.userClient - .registerAuthenticator(context, authenticatorId) + .registerAuthenticator(authenticatorId) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); @@ -143,7 +143,7 @@ class _UserScreenState extends State with RouteAware { deregisterAuthenticator(String authenticatorId) async { await Onegini.instance.userClient - .deregisterAuthenticator(context, authenticatorId) + .deregisterAuthenticator(authenticatorId) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); @@ -155,7 +155,7 @@ class _UserScreenState extends State with RouteAware { setPreferredAuthenticator(String authenticatorId) async { await Onegini.instance.userClient - .setPreferredAuthenticator(context, authenticatorId) + .setPreferredAuthenticator(authenticatorId) .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); @@ -188,7 +188,7 @@ class _UserScreenState extends State with RouteAware { changePin(BuildContext context) { Navigator.pop(context); - Onegini.instance.userClient.changePin(context).catchError((error) { + Onegini.instance.userClient.changePin().catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); // FIXME: this should be extracted into a seperate method and should also use constants (dont exist yet) @@ -259,7 +259,7 @@ class _UserScreenState extends State with RouteAware { ), FutureBuilder>( future: Onegini.instance.userClient - .getRegisteredAuthenticators(context, this.profileId), + .getRegisteredAuthenticators(this.profileId), builder: (BuildContext context, snapshot) { return PopupMenuButton( child: ListTile( diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index 2368be51..2168f702 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -1,10 +1,6 @@ import 'dart:async'; - -import 'package:flutter/cupertino.dart'; import 'package:onegini/pigeon.dart'; -import '../onegini.dart'; - /// A callback of fingerprint authentication. /// /// Use this callback when user want authenticate by fingerprint. @@ -25,8 +21,7 @@ class OneginiFingerprintCallback { /// Accept fingerprint request. /// /// Use this method when you want start scanning fingerprint. - Future acceptAuthenticationRequest(BuildContext? context) async { - Onegini.instance.setEventContext(context); + Future acceptAuthenticationRequest() async { await api.fingerprintAcceptAuthenticationRequest(); } } diff --git a/lib/callbacks/onegini_otp_accept_deny_callback.dart b/lib/callbacks/onegini_otp_accept_deny_callback.dart index 3ced9b01..938a1ba2 100644 --- a/lib/callbacks/onegini_otp_accept_deny_callback.dart +++ b/lib/callbacks/onegini_otp_accept_deny_callback.dart @@ -1,8 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:onegini/pigeon.dart'; -import '../onegini.dart'; - /// A callback for mobile authentication with OTP class OneginiOtpAcceptDenyCallback { final api = UserClientApi(); @@ -13,9 +10,7 @@ class OneginiOtpAcceptDenyCallback { } /// Accepts OTP authentication. - Future acceptAuthenticationRequest(BuildContext? context) async { - Onegini.instance.setEventContext(context); - + Future acceptAuthenticationRequest() async { await api.otpAcceptAuthenticationRequest(); } } diff --git a/lib/callbacks/onegini_pin_authentication_callback.dart b/lib/callbacks/onegini_pin_authentication_callback.dart index d4ae17f9..fbaae4c5 100644 --- a/lib/callbacks/onegini_pin_authentication_callback.dart +++ b/lib/callbacks/onegini_pin_authentication_callback.dart @@ -1,8 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:onegini/pigeon.dart'; -import '../onegini.dart'; - /// A callback for pin AUTHENTICATION. class OneginiPinAuthenticationCallback { final api = UserClientApi(); @@ -13,9 +10,7 @@ class OneginiPinAuthenticationCallback { } /// Accepts pin authentication and sent [pin] to the OneginiSdk. - Future acceptAuthenticationRequest(BuildContext? context, String pin) async { - Onegini.instance.setEventContext(context); - + Future acceptAuthenticationRequest(String pin) async { await api.pinAcceptAuthenticationRequest(pin); } } diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index 146edae8..e9a79dd4 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -1,8 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:onegini/pigeon.dart'; -import '../onegini.dart'; - /// A callback for pin REGISTRATION. class OneginiPinRegistrationCallback { final api = UserClientApi(); @@ -13,10 +10,7 @@ class OneginiPinRegistrationCallback { } /// Accepts pin registration and sent [pin] to the OneginiSdk. - Future acceptAuthenticationRequest( - BuildContext? context, String pin) async { - Onegini.instance.setEventContext(context); - + Future acceptAuthenticationRequest(String pin) async { await api.pinAcceptRegistrationRequest(pin); } } diff --git a/lib/callbacks/onegini_registration_callback.dart b/lib/callbacks/onegini_registration_callback.dart index cd043b5c..75697b75 100644 --- a/lib/callbacks/onegini_registration_callback.dart +++ b/lib/callbacks/onegini_registration_callback.dart @@ -1,6 +1,5 @@ import 'package:onegini/pigeon.dart'; - /// A callback for registration. class OneginiRegistrationCallback { final api = UserClientApi(); diff --git a/lib/events/onewelcome_events.dart b/lib/events/onewelcome_events.dart index 7cdb71b4..9c447e1c 100644 --- a/lib/events/onewelcome_events.dart +++ b/lib/events/onewelcome_events.dart @@ -13,31 +13,24 @@ enum OWAction { closeAuthOtp, // Called to close OTP authentication screen // Pin - openPinRegistration, // previously openPinRequestScreen; Called to open pin registration screen. - closePinRegistration, // previously closePin; Called to open pin registration screen. - openPinAuthentication, // previously openPinScreenAuth; Called to open pin authentication screen - closePinAuthentication, // previously closePinAuth; Called to close pin authentication screen + openPinRegistration, // Called to open pin registration screen. + closePinRegistration, // Called to open pin registration screen. + openPinAuthentication, // Called to open pin authentication screen + closePinAuthentication, // Called to close pin authentication screen pinNotAllowed, // Called when the supplied pin for registration is not allowed // Fingerprint - openFingerprint, // previously openFingerprintScreen; Called to open fingerprint screen. - closeFingerprint, // previously closeFingerprintScreen; Called to close fingerprint screen. + openFingerprint, // Called to open fingerprint screen. + closeFingerprint, // Called to close fingerprint screen. showScanningFingerprint, // Called to scan fingerprint. receivedFingerprint, // Called when fingerprint was received. // CustomRegistration - initCustomRegistration, // previously eventInitCustomRegistration; Called when customRegistration is initialized and a response should be given (only for two-step) - finishCustomRegistration, // previously eventFinishCustomRegistration; Called when customRegistration finishes and a final response should be given + initCustomRegistration, // Called when customRegistration is initialized and a response should be given (only for two-step) + finishCustomRegistration, // Called when customRegistration finishes and a final response should be given // Authentication nextAuthenticationAttempt, // Called to attempt next authentication. - - /* - Deleted events: - - eventOther - - openPinAuthenticator - - eventError - */ } extension OWActionExtension on OWAction { diff --git a/lib/onegini.dart b/lib/onegini.dart index b420c998..707567bc 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -29,28 +29,18 @@ class Onegini { /// Communication channel between flutter and native side. final MethodChannel channel = const MethodChannel('onegini'); - /// Reference to the event listener. - OneginiEventListener? _eventListener; - /// Resource methods. ResourcesMethods resourcesMethods = ResourcesMethods(); - /// Use this method when you want change [BuildContext] in your [OneginiEventListener] - setEventContext(BuildContext? context) { - _eventListener?.context = context; - } - /// Initialize SDK and establish communication on [eventListener]. - Future startApplication( - OneginiEventListener eventListener, { + Future startApplication({ String? securityControllerClassName, String? configModelClassName, List? customIdentityProviderConfigs, int? connectionTimeout, int? readTimeout, }) async { - _eventListener = eventListener; - NativeCallFlutterApi.setup(_eventListener); + NativeCallFlutterApi.setup(OneginiEventListener()); await api.startApplication( securityControllerClassName, configModelClassName, diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 8ce06633..14743d3c 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,5 +1,3 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/services.dart'; import 'package:onegini/events/browser_event.dart'; import 'package:onegini/events/custom_registration_event.dart'; import 'package:onegini/events/fingerprint_event.dart'; @@ -9,190 +7,84 @@ import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; -import 'model/authentication_attempt.dart'; -import 'model/onegini_event.dart'; - -/// Extend from this class to describe the events that will take place inside OneginiSDK -abstract class OneginiEventListener implements NativeCallFlutterApi { - BuildContext? _context; - - /// Saves the build context - set context(BuildContext? context) { - _context = context; - } - - // done - ///Called to handle registration URL - void handleRegisteredUrl(BuildContext? buildContext, String url); - - // done - /// Called to open OTP authentication. - void openAuthOtp(BuildContext? buildContext, String message); - - // done - /// Called to close OTP authentication. - void closeAuthOtp(BuildContext? buildContext); - - // done - /// Called to open pin registration screen. - void openPinRequestScreen(BuildContext? buildContext); - - // done - /// Called to open pin authentication screen. - void openPinScreenAuth(BuildContext? buildContext); - - // done - /// Called to attempt next authentication. - void nextAuthenticationAttempt( - BuildContext? buildContext, AuthenticationAttempt authenticationAttempt); - - // done - /// Called to close pin registration screen. - void closePin(BuildContext? buildContext); - - // done - /// Called to close pin authentication screen. - void closePinAuth(BuildContext? buildContext); - - // done - /// Called to open fingerprint screen. - void openFingerprintScreen(BuildContext? buildContext); - - // done - /// Called to scan fingerprint. - void showScanningFingerprint(BuildContext? buildContext); - - // done - /// Called when fingerprint was received. - void receivedFingerprint(BuildContext? buildContext); - - // done - /// Called to close fingerprint screen. - void closeFingerprintScreen(BuildContext? buildContext); - - // done - /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) - void eventInitCustomRegistration( - BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); - - // done - /// Called when the FinishCustomRegistration event occurs and a response should be given - void eventFinishCustomRegistration( - BuildContext? buildContext, OWCustomInfo? customInfo, String providerId); - - void pinNotAllowed(OWOneginiError error); +class OneginiEventListener implements NativeCallFlutterApi { @override void n2fCloseAuthOtp() { broadcastEvent(CloseAuthOtpEvent()); - - closeAuthOtp(_context); } @override void n2fCloseFingerprintScreen() { broadcastEvent(CloseFingerprintEvent()); - - closeFingerprintScreen(_context); } @override void n2fClosePin() { broadcastEvent(ClosePinRegistrationEvent()); - - closePin(_context); } @override void n2fClosePinAuth() { broadcastEvent(ClosePinAuthenticationEvent()); - - closePinAuth(_context); } @override void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId) { broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); - - eventFinishCustomRegistration(_context, customInfo, providerId); } @override void n2fEventInitCustomRegistration( OWCustomInfo? customInfo, String providerId) { broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); - - eventInitCustomRegistration(_context, customInfo, providerId); } @override void n2fHandleRegisteredUrl(String url) { broadcastEvent(HandleRegisteredUrlEvent(url)); - - handleRegisteredUrl(_context, url); } @override void n2fNextAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt) { broadcastEvent(NextAuthenticationAttemptEvent(authenticationAttempt)); - - nextAuthenticationAttempt( - _context, - AuthenticationAttempt( - failedAttempts: authenticationAttempt.failedAttempts, - maxAttempts: authenticationAttempt.maxAttempts, - remainingAttempts: authenticationAttempt.remainingAttempts)); } @override void n2fOpenAuthOtp(String? message) { broadcastEvent(OpenAuthOtpEvent(message ?? "")); - - openAuthOtp(_context, message ?? ""); } @override void n2fOpenFingerprintScreen() { broadcastEvent(OpenFingerprintEvent()); - - openFingerprintScreen(_context); } @override void n2fOpenPinRequestScreen() { broadcastEvent(OpenPinRegistrationEvent()); - - openPinRequestScreen(_context); } @override void n2fOpenPinScreenAuth() { broadcastEvent(OpenPinAuthenticationEvent()); - - openPinScreenAuth(_context); } @override void n2fReceivedFingerprint() { broadcastEvent(ReceivedFingerprintEvent()); - - receivedFingerprint(_context); } @override void n2fShowScanningFingerprint() { broadcastEvent(ShowScanningFingerprintEvent()); - - showScanningFingerprint(_context); } @override void n2fEventPinNotAllowed(OWOneginiError error) { broadcastEvent(PinNotAllowedEventEvent(error)); - - pinNotAllowed(error); } void broadcastEvent(OWEvent event) { diff --git a/lib/user_client.dart b/lib/user_client.dart index 7a930af3..9b28d1cb 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -22,26 +22,20 @@ class UserClient { /// If [identityProviderId] is null, starts standard browser registration. /// Use your [scopes] for registration. By default it is "read". Future registerUser( - BuildContext? context, String? identityProviderId, List? scopes, ) async { - Onegini.instance.setEventContext(context); return await api.registerUser(identityProviderId, scopes); } /// Start browser Registration logic - Future handleRegisteredUserUrl(BuildContext? context, String url, + Future handleRegisteredUserUrl(String url, {WebSignInType signInType = WebSignInType.insideApp}) async { - Onegini.instance.setEventContext(context); await api.handleRegisteredUserUrl(url, signInType.value); } /// Returns a list of available identity providers. - Future> getIdentityProviders( - BuildContext? context) async { - Onegini.instance.setEventContext(context); - + Future> getIdentityProviders() async { final providers = await api.getIdentityProviders(); return providers.whereType().toList(); } @@ -52,18 +46,13 @@ class UserClient { } /// Returns a list of authenticators registered and available to the user. - Future> getRegisteredAuthenticators( - BuildContext? context, String profileId) async { - Onegini.instance.setEventContext(context); - + Future> getRegisteredAuthenticators(String profileId) async { final registeredAuthenticators = await api.getRegisteredAuthenticators(profileId); return registeredAuthenticators.whereType().toList(); } - Future> getAllAuthenticators( - BuildContext? context, String profileId) async { - Onegini.instance.setEventContext(context); + Future> getAllAuthenticators(String profileId) async { final allAuthenticators = await api.getAllAuthenticators(profileId); return allAuthenticators.whereType().toList(); @@ -78,68 +67,51 @@ class UserClient { /// If [registeredAuthenticatorId] is null, starts authentication by default authenticator. /// Usually it is Pin authenticator. Future authenticateUser( - BuildContext? context, String profileId, String? registeredAuthenticatorId, ) async { - Onegini.instance.setEventContext(context); - return await api.authenticateUser(profileId, registeredAuthenticatorId); } /// Returns a list of authenticators available to the user, but not yet registered. Future> getNotRegisteredAuthenticators( - BuildContext? context, String profileId) async { + String profileId) async { final notRegisteredAuthenticators = await api.getNotRegisteredAuthenticators(profileId); return notRegisteredAuthenticators.whereType().toList(); } /// Starts change pin flow. - Future changePin( - BuildContext? context, - ) async { - Onegini.instance.setEventContext(context); + Future changePin() async { await api.changePin(); } /// Registers authenticator from [getNotRegisteredAuthenticators] list. - Future registerAuthenticator( - BuildContext? context, String authenticatorId) async { - Onegini.instance.setEventContext(context); - + Future registerAuthenticator(String authenticatorId) async { await api.registerAuthenticator(authenticatorId); } - ///Set preferred authenticator - /// todo removed boolean return update docu - Future setPreferredAuthenticator( - BuildContext? context, String authenticatorId) async { - Onegini.instance.setEventContext(context); - + /// Set preferred authenticator + Future setPreferredAuthenticator(String authenticatorId) async { await api.setPreferredAuthenticator(authenticatorId); } - /// todo removed boolean return update docu - Future deregisterAuthenticator( - BuildContext? context, String authenticatorId) async { - Onegini.instance.setEventContext(context); - + /// Deregister Authenticator + Future deregisterAuthenticator(String authenticatorId) async { await api.deregisterAuthenticator(authenticatorId); } - ///Method for log out - /// todo removed boolean return update docu + /// Method for log out Future logout() async { await api.logout(); } - // TODO Implement these functions within example app after. - // https://onewelcome.atlassian.net/browse/FP-69 + /// Enroll for MobileAuthentication (enable OTP) Future enrollMobileAuthentication() async { await api.enrollMobileAuthentication(); } + /// Respond to mobile authentication with OTP Future handleMobileAuthWithOtp(String data) async { await api.handleMobileAuthWithOtp(data); } From 474bf127859123c52a30048eced8d65464f504ad Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 11 Apr 2023 15:35:40 +0200 Subject: [PATCH 250/364] fp-77 removed unused code --- example/lib/main.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 71fadc09..38de7d87 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -44,8 +44,6 @@ class BodyWidget extends StatefulWidget { } class _BodyWidgetState extends State { - OWBroadcastHelper derp; - @override void initState() { _startApplication(); From 2324cdc9efe2f52d180505d39903dcae4ec37303 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 11 Apr 2023 16:16:04 +0200 Subject: [PATCH 251/364] FP-65: Android: Add extension for authenticator and use new authType Previously we were using an authenticatorId, we are now changing this to a authenticatorType. --- .../mobile/sdk/flutter/PigeonInterface.kt | 41 ++++++++++--------- .../OWAuthenticatorTypeExtension.kt | 11 +++++ .../useCases/AuthenticateUserUseCase.kt | 11 +++-- 3 files changed, 38 insertions(+), 25 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 21c769a6..6b49af9c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -3,6 +3,7 @@ package com.onegini.mobile.sdk.flutter import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAppToWebSingleSignOn import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomIdentityProvider import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider @@ -200,42 +201,44 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { deregisterUserUseCase(profileId, callback) } - override fun getRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - callback(getRegisteredAuthenticatorsUseCase(profileId)) + override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { + callback(getAuthenticatedUserProfileUseCase()) } - override fun getAllAuthenticators(profileId: String, callback: (Result>) -> Unit) { - callback(getAllAuthenticatorsUseCase(profileId)) + override fun authenticateUser( + profileId: String, + authenticatorType: OWAuthenticatorType, + callback: (Result) -> Unit + ) { + authenticateUserUseCase(profileId, authenticatorType, callback) } - override fun getAuthenticatedUserProfile(callback: (Result) -> Unit) { - callback(getAuthenticatedUserProfileUseCase()) - } - override fun authenticateUser(profileId: String, registeredAuthenticatorId: String?, callback: (Result) -> Unit) { - authenticateUserUseCase(profileId, registeredAuthenticatorId, callback) + override fun isBiometricAuthenticatorRegistered(callback: (Result) -> Unit) { + TODO("Not yet implemented") } - override fun getNotRegisteredAuthenticators(profileId: String, callback: (Result>) -> Unit) { - callback(getNotRegisteredAuthenticatorsUseCase(profileId)) + override fun getPreferredAuthenticator(callback: (Result) -> Unit) { + TODO("Not yet implemented") } - override fun changePin(callback: (Result) -> Unit) { - changePinUseCase(callback) + override fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { + TODO("Not yet implemented") } - override fun setPreferredAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - callback(setPreferredAuthenticatorUseCase(authenticatorId)) + override fun deregisterBiometricAuthenticator(callback: (Result) -> Unit) { + TODO("Not yet implemented") } - override fun deregisterAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - deregisterAuthenticatorUseCase(authenticatorId, callback) + override fun registerBiometricAuthenticator(callback: (Result) -> Unit) { + TODO("Not yet implemented") } - override fun registerAuthenticator(authenticatorId: String, callback: (Result) -> Unit) { - registerAuthenticatorUseCase(authenticatorId, callback) + override fun changePin(callback: (Result) -> Unit) { + changePinUseCase(callback) } + override fun logout(callback: (Result) -> Unit) { logoutUseCase(callback) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt new file mode 100644 index 00000000..a8d76fdf --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt @@ -0,0 +1,11 @@ +package com.onegini.mobile.sdk.flutter.extensions + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType + +fun OWAuthenticatorType.toOneginiInt(): Int { + return when (this) { + OWAuthenticatorType.PIN -> OneginiAuthenticator.PIN + OWAuthenticatorType.BIOMETRIC -> OneginiAuthenticator.FINGERPRINT + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 228bf538..a16de134 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -7,8 +7,10 @@ import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile import javax.inject.Inject @@ -19,7 +21,7 @@ class AuthenticateUserUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(profileId: String, authenticatorId: String?, callback: (Result) -> Unit) { + operator fun invoke(profileId: String, authenticatorType: OWAuthenticatorType?, callback: (Result) -> Unit) { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { @@ -27,12 +29,9 @@ class AuthenticateUserUseCase @Inject constructor( } val authenticator = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - .find { it.id == authenticatorId } + .find { it.type == authenticatorType?.toOneginiInt() } - when { - authenticatorId != null && authenticator == null -> callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) - else -> authenticate(userProfile, authenticator, callback) - } + authenticate(userProfile, authenticator, callback) } private fun authenticate( From 365f5962e22fd637c034d6ce0e98669c45ee9b85 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 12 Apr 2023 09:12:53 +0200 Subject: [PATCH 252/364] fp-77 update event name --- example/lib/ow_broadcast_helper.dart | 4 ++-- lib/events/pin_event.dart | 4 ++-- lib/onegini_event_listener.dart | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 902880cd..42468454 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -50,8 +50,8 @@ class OWBroadcastHelper { } }); - StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEventEvent).listen((event) { - if (event is PinNotAllowedEventEvent) { + StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEvent).listen((event) { + if (event is PinNotAllowedEvent) { showFlutterToast("${event.error.message} Code: ${event.error.code}"); } }); diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index 94ea7975..c3864c19 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -18,7 +18,7 @@ class ClosePinAuthenticationEvent extends OWEvent { ClosePinAuthenticationEvent() : super(OWAction.closePinAuthentication); } -class PinNotAllowedEventEvent extends OWEvent { +class PinNotAllowedEvent extends OWEvent { OWOneginiError error; - PinNotAllowedEventEvent(this.error) : super(OWAction.pinNotAllowed); + PinNotAllowedEvent(this.error) : super(OWAction.pinNotAllowed); } diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 14743d3c..300cd4f2 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -84,7 +84,7 @@ class OneginiEventListener implements NativeCallFlutterApi { @override void n2fEventPinNotAllowed(OWOneginiError error) { - broadcastEvent(PinNotAllowedEventEvent(error)); + broadcastEvent(PinNotAllowedEvent(error)); } void broadcastEvent(OWEvent event) { From 09e3964d7e53d043d9f0d9e5c2e74d7fbbcec064 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 12 Apr 2023 11:35:00 +0200 Subject: [PATCH 253/364] FP-65: Update api --- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 37 ++++++++++++++++--- ios/Classes/Pigeon.swift | 34 ++++++++++++++--- ios/Classes/SwiftOneginiPlugin.swift | 29 ++++++++++++++- lib/pigeon.dart | 35 ++++++++++++++++-- pigeons/onewelcome_pigeon_interface.dart | 7 +++- 5 files changed, 123 insertions(+), 19 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 969da76a..205ca546 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -439,8 +439,9 @@ interface UserClientApi { fun deregisterUser(profileId: String, callback: (Result) -> Unit) fun getAuthenticatedUserProfile(callback: (Result) -> Unit) fun authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) - fun isBiometricAuthenticatorRegistered(callback: (Result) -> Unit) - fun getPreferredAuthenticator(callback: (Result) -> Unit) + fun isBiometricAuthenticatorRegistered(profileId: String, callback: (Result) -> Unit) + fun isBiometricAuthenticatorAvailable(profileId: String, callback: (Result) -> Unit) + fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) fun deregisterBiometricAuthenticator(callback: (Result) -> Unit) fun registerBiometricAuthenticator(callback: (Result) -> Unit) @@ -625,8 +626,30 @@ interface UserClientApi { run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", codec) if (api != null) { - channel.setMessageHandler { _, reply -> - api.isBiometricAuthenticatorRegistered() { result: Result -> + channel.setMessageHandler { message, reply -> + val args = message as List + val profileIdArg = args[0] as String + api.isBiometricAuthenticatorRegistered(profileIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val profileIdArg = args[0] as String + api.isBiometricAuthenticatorAvailable(profileIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -643,8 +666,10 @@ interface UserClientApi { run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator", codec) if (api != null) { - channel.setMessageHandler { _, reply -> - api.getPreferredAuthenticator() { result: Result -> + channel.setMessageHandler { message, reply -> + val args = message as List + val profileIdArg = args[0] as String + api.getPreferredAuthenticator(profileIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 22321a67..e83860c4 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -405,8 +405,9 @@ protocol UserClientApi { func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) - func isBiometricAuthenticatorRegistered(completion: @escaping (Result) -> Void) - func getPreferredAuthenticator(completion: @escaping (Result) -> Void) + func isBiometricAuthenticatorRegistered(profileId: String, completion: @escaping (Result) -> Void) + func isBiometricAuthenticatorAvailable(profileId: String, completion: @escaping (Result) -> Void) + func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) @@ -571,8 +572,10 @@ class UserClientApiSetup { } let isBiometricAuthenticatorRegisteredChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - isBiometricAuthenticatorRegisteredChannel.setMessageHandler { _, reply in - api.isBiometricAuthenticatorRegistered() { result in + isBiometricAuthenticatorRegisteredChannel.setMessageHandler { message, reply in + let args = message as! [Any] + let profileIdArg = args[0] as! String + api.isBiometricAuthenticatorRegistered(profileId: profileIdArg) { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -584,10 +587,29 @@ class UserClientApiSetup { } else { isBiometricAuthenticatorRegisteredChannel.setMessageHandler(nil) } + let isBiometricAuthenticatorAvailableChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + isBiometricAuthenticatorAvailableChannel.setMessageHandler { message, reply in + let args = message as! [Any] + let profileIdArg = args[0] as! String + api.isBiometricAuthenticatorAvailable(profileId: profileIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + isBiometricAuthenticatorAvailableChannel.setMessageHandler(nil) + } let getPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - getPreferredAuthenticatorChannel.setMessageHandler { _, reply in - api.getPreferredAuthenticator() { result in + getPreferredAuthenticatorChannel.setMessageHandler { message, reply in + let args = message as! [Any] + let profileIdArg = args[0] as! String + api.getPreferredAuthenticator(profileId: profileIdArg) { result in switch result { case .success(let res): reply(wrapResult(res)) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 07b23f94..d70f8aca 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -2,7 +2,6 @@ import Flutter import UIKit import OneginiSDKiOS -extension FlutterError: Error {} extension FlutterError { convenience init(_ error: OneWelcomeWrapperError) { @@ -80,6 +79,34 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { } public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { + func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { + <#code#> + } + + func isBiometricAuthenticatorRegistered(completion: @escaping (Result) -> Void) { + <#code#> + } + + func isBiometricAuthenticatorAvailable(completion: @escaping (Result) -> Void) { + <#code#> + } + + func getPreferredAuthenticator(completion: @escaping (Result) -> Void) { + <#code#> + } + + func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { + <#code#> + } + + func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) { + <#code#> + } + + func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) { + <#code#> + } + func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 3bbd735e..ad8bb009 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -589,12 +589,12 @@ class UserClientApi { } } - Future isBiometricAuthenticatorRegistered() async { + Future isBiometricAuthenticatorRegistered(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send(null) as List?; + await channel.send([arg_profileId]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -616,12 +616,39 @@ class UserClientApi { } } - Future getPreferredAuthenticator() async { + Future isBiometricAuthenticatorAvailable(String arg_profileId) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_profileId]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as bool?)!; + } + } + + Future getPreferredAuthenticator(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send(null) as List?; + await channel.send([arg_profileId]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index d4e0d17f..a996be1d 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -161,10 +161,13 @@ abstract class UserClientApi { String profileId, OWAuthenticatorType authenticatorType); @async - bool isBiometricAuthenticatorRegistered(); + bool isBiometricAuthenticatorRegistered(String profileId); @async - OWAuthenticator getPreferredAuthenticator(); + bool isBiometricAuthenticatorAvailable(String profileId); + + @async + OWAuthenticator getPreferredAuthenticator(String profileId); @async void setPreferredAuthenticator(OWAuthenticatorType authenticatorType); From cc0b750496a3d4b7306cfc7edf2986fc3aca83c8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 12 Apr 2023 11:35:09 +0200 Subject: [PATCH 254/364] FP-65: Implement authenticator api's --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../mobile/sdk/flutter/PigeonInterface.kt | 46 ++++++++++++------- .../OWAuthenticatorTypeExtension.kt | 2 +- .../mobile/sdk/flutter/helpers/SdkError.kt | 1 + ...DeregisterBiometricAuthenticatorUseCase.kt | 37 +++++++++++++++ .../useCases/GetAllAuthenticatorsUseCase.kt | 25 ---------- .../GetNotRegisteredAuthenticatorsUseCase.kt | 25 ---------- .../GetPreferredAuthenticatorUseCase.kt | 26 +++++++++++ .../GetRegisteredAuthenticatorsUseCase.kt | 25 ---------- ...sBiometricAuthenticatorAvailableUseCase.kt | 20 ++++++++ ...BiometricAuthenticatorRegisteredUseCase.kt | 20 ++++++++ .../RegisterBiometricAuthenticatorUseCase.kt | 38 +++++++++++++++ .../SetPreferredAuthenticatorUseCase.kt | 6 ++- 13 files changed, 177 insertions(+), 95 deletions(-) create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt create mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 3ae938b9..8bf59265 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -7,6 +7,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8043, "Biometric authentication is supported on this device"), REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 6b49af9c..28e75142 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -21,22 +21,23 @@ import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUseCase import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.DeregisterBiometricAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase import com.onegini.mobile.sdk.flutter.useCases.EnrollMobileAuthenticationUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintAuthenticationRequestDenyUseCase import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase +import com.onegini.mobile.sdk.flutter.useCases.IsBiometricAuthenticatorAvailableUseCase +import com.onegini.mobile.sdk.flutter.useCases.IsBiometricAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase @@ -45,6 +46,7 @@ import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCa import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestDenyUseCase import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.RegisterBiometricAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase @@ -69,6 +71,9 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase + @Inject + lateinit var deregisterBiometricAuthenticatorUseCase: DeregisterBiometricAuthenticatorUseCase + @Inject lateinit var deregisterUserUseCase: DeregisterUserUseCase @@ -78,9 +83,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var cancelBrowserRegistrationUseCase: CancelBrowserRegistrationUseCase - @Inject - lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase - @Inject lateinit var getAppToWebSingleSignOnUseCase: GetAppToWebSingleSignOnUseCase @@ -91,26 +93,33 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { lateinit var getIdentityProvidersUseCase: GetIdentityProvidersUseCase @Inject - lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase + lateinit var getPreferredAuthenticatorUseCase: GetPreferredAuthenticatorUseCase @Inject lateinit var getRedirectUrlUseCase: GetRedirectUrlUseCase - @Inject - lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase - @Inject lateinit var getUserProfilesUseCase: GetUserProfilesUseCase + @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase + @Inject + lateinit var isBiometricAuthenticatorRegisteredUseCase: IsBiometricAuthenticatorRegisteredUseCase + + @Inject + lateinit var isBiometricAuthenticatorAvailableUseCase: IsBiometricAuthenticatorAvailableUseCase + @Inject lateinit var logoutUseCase: LogoutUseCase @Inject lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase + @Inject + lateinit var registerBiometricAuthenticatorUseCase: RegisterBiometricAuthenticatorUseCase + @Inject lateinit var registrationUseCase: RegistrationUseCase @@ -213,25 +222,28 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { authenticateUserUseCase(profileId, authenticatorType, callback) } + override fun isBiometricAuthenticatorRegistered(profileId: String, callback: (Result) -> Unit) { + isBiometricAuthenticatorRegisteredUseCase(profileId, callback) + } - override fun isBiometricAuthenticatorRegistered(callback: (Result) -> Unit) { - TODO("Not yet implemented") + override fun isBiometricAuthenticatorAvailable(profileId: String, callback: (Result) -> Unit) { + isBiometricAuthenticatorAvailableUseCase(profileId, callback) } - override fun getPreferredAuthenticator(callback: (Result) -> Unit) { - TODO("Not yet implemented") + override fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) { + getPreferredAuthenticatorUseCase(callback) } override fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { - TODO("Not yet implemented") + callback(setPreferredAuthenticatorUseCase(authenticatorType)) } override fun deregisterBiometricAuthenticator(callback: (Result) -> Unit) { - TODO("Not yet implemented") + deregisterBiometricAuthenticatorUseCase(callback) } override fun registerBiometricAuthenticator(callback: (Result) -> Unit) { - TODO("Not yet implemented") + registerBiometricAuthenticatorUseCase(callback) } override fun changePin(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt index a8d76fdf..704a2f79 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt @@ -8,4 +8,4 @@ fun OWAuthenticatorType.toOneginiInt(): Int { OWAuthenticatorType.PIN -> OneginiAuthenticator.PIN OWAuthenticatorType.BIOMETRIC -> OneginiAuthenticator.FINGERPRINT } -} \ No newline at end of file +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index f95b7dc2..b193e691 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -1,5 +1,6 @@ package com.onegini.mobile.sdk.flutter.helpers +import com.onegini.mobile.sdk.android.handlers.error.OneginiError import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_BODY diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt new file mode 100644 index 00000000..c421073c --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt @@ -0,0 +1,37 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorDeregistrationHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorDeregistrationError +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject + +class DeregisterBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(callback: (Result) -> Unit) { + val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) + val biometricAuthenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) + + oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(biometricAuthenticator, object : OneginiAuthenticatorDeregistrationHandler { + override fun onSuccess() { + callback(Result.success(Unit)) + } + + override fun onError(oneginiAuthenticatorDeregistrationError: OneginiAuthenticatorDeregistrationError) { + callback( + Result.failure( + SdkError( + code = oneginiAuthenticatorDeregistrationError.errorType, + message = oneginiAuthenticatorDeregistrationError.message + ).pigeonError() + ) + ) + } + }) + } +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt deleted file mode 100644 index b4e3e574..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAllAuthenticatorsUseCase.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetAllAuthenticatorsUseCase @Inject constructor( - private val oneginiSDK: OneginiSDK, - private val getUserProfileUseCase: GetUserProfileUseCase -) { - operator fun invoke(profileId: String): Result> { - val userProfile = try { - getUserProfileUseCase(profileId) - } catch (error: SdkError) { - return Result.failure(error.pigeonError()) - } - - return oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } - .let { Result.success(it) } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt deleted file mode 100644 index 38bfa64a..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetNotRegisteredAuthenticatorsUseCase.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetNotRegisteredAuthenticatorsUseCase @Inject constructor( - private val oneginiSDK: OneginiSDK, - private val getUserProfileUseCase: GetUserProfileUseCase -) { - operator fun invoke(profileId: String): Result> { - val userProfile = try { - getUserProfileUseCase(profileId) - } catch (error: SdkError) { - return Result.failure(error.pigeonError()) - } - - return oneginiSDK.oneginiClient.userClient.getNotRegisteredAuthenticators(userProfile) - .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } - .let { Result.success(it) } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt new file mode 100644 index 00000000..ca582e6a --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -0,0 +1,26 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType +import javax.inject.Inject + +class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(callback: (Result) -> Unit) { + val authenticator = oneginiSDK.oneginiClient.userClient.preferredAuthenticator + ?: return callback(Result.failure(SdkError(OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED))) + + if (authenticator.type == OWAuthenticatorType.PIN.toOneginiInt()) { + return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.PIN))) + } + if (authenticator.type == OWAuthenticatorType.BIOMETRIC.toOneginiInt()) { + return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC))) + } + // This should never happen because we don't support CUSTOM/FIDO authenticators + return callback(Result.failure(SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR).pigeonError())) + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt deleted file mode 100644 index 5364408f..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetRegisteredAuthenticatorsUseCase.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class GetRegisteredAuthenticatorsUseCase @Inject constructor( - private val oneginiSDK: OneginiSDK, - private val getUserProfileUseCase: GetUserProfileUseCase -) { - operator fun invoke(profileId: String): Result> { - val userProfile = try { - getUserProfileUseCase(profileId) - } catch (error: SdkError) { - return Result.failure(error.pigeonError()) - } - - return oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - .map { OWAuthenticator(it.id, it.name, it.isRegistered, it.isPreferred, it.type.toLong()) } - .let { Result.success(it) } - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt new file mode 100644 index 00000000..70b708d5 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject + +class IsBiometricAuthenticatorAvailableUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(profileId: String, callback: (Result) -> Unit) { + val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } + ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) + val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) + authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) + + callback(Result.success(true)) + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt new file mode 100644 index 00000000..dedd60db --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt @@ -0,0 +1,20 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject + +class IsBiometricAuthenticatorRegisteredUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(profileId: String, callback: (Result) -> Unit) { + val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } + ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) + val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) + val biometricAuthenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) + + callback(Result.success(biometricAuthenticator.isRegistered)) + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt new file mode 100644 index 00000000..c4608284 --- /dev/null +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt @@ -0,0 +1,38 @@ +package com.onegini.mobile.sdk.flutter.useCases + +import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler +import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.android.model.entity.CustomInfo +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.helpers.SdkError +import javax.inject.Inject + +class RegisterBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(callback: (Result) -> Unit) { + val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + + val biometricAuthenticator = oneginiSDK.oneginiClient.userClient + .getAllAuthenticators(authenticatedUserProfile).find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) + + oneginiSDK.oneginiClient.userClient.registerAuthenticator(biometricAuthenticator, object : OneginiAuthenticatorRegistrationHandler { + override fun onSuccess(customInfo: CustomInfo?) { + callback(Result.success(Unit)) + } + + override fun onError(oneginiAuthenticatorRegistrationError: OneginiAuthenticatorRegistrationError) { + callback( + Result.failure( + SdkError( + code = oneginiAuthenticatorRegistrationError.errorType, + message = oneginiAuthenticatorRegistrationError.message + ).pigeonError() + ) + ) + } + }) + } +} \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 62a1f92c..63e021cc 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -2,19 +2,21 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject import javax.inject.Singleton @Singleton class SetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(authenticatorId: String): Result { + operator fun invoke(authenticatorType: OWAuthenticatorType): Result { val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) val authenticator = oneginiSDK.oneginiClient.userClient - .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } + .getRegisteredAuthenticators(userProfile).find { it.type == authenticatorType.toOneginiInt() } ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError()) oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) From c01ee5b7d3a4e43ddd5bdf6e006680d32f2ce725 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 12 Apr 2023 14:25:31 +0200 Subject: [PATCH 255/364] FP-65: Update api again to make authenticator type non nullable. We can't make the authenticatorType nullable because pigeon does not yet allow this. To fix this, we add an extra value to the enum to indicate we're dealing with a preferred authenticatorType. --- .../com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 3 ++- ios/Classes/Pigeon.swift | 1 + lib/pigeon.dart | 1 + pigeons/onewelcome_pigeon_interface.dart | 1 + 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 205ca546..d337ef83 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -58,7 +58,8 @@ enum class HttpRequestMethod(val raw: Int) { enum class OWAuthenticatorType(val raw: Int) { PIN(0), - BIOMETRIC(1); + BIOMETRIC(1), + PREFERRED(2); companion object { fun ofRaw(raw: Int): OWAuthenticatorType? { diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index e83860c4..83f330c7 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -44,6 +44,7 @@ enum HttpRequestMethod: Int { enum OWAuthenticatorType: Int { case pin = 0 case biometric = 1 + case preferred = 2 } enum ResourceRequestType: Int { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ad8bb009..64d7f9de 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -18,6 +18,7 @@ enum HttpRequestMethod { enum OWAuthenticatorType { pin, biometric, + preferred, } enum ResourceRequestType { diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index a996be1d..8ee0c2f4 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -80,6 +80,7 @@ enum HttpRequestMethod { enum OWAuthenticatorType { pin, biometric, + preferred, } enum ResourceRequestType { authenticated, implicit, anonymous, unauthenticated } From fa5f46287de759dc67b5f6c5c720913fbba08961 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 12 Apr 2023 16:02:19 +0200 Subject: [PATCH 256/364] fp-77 renamed ReceivedFingerprintEvent to NextFingerprintAuthenticationAttempt better reflect functionality --- .../handlers/FingerprintAuthenticationRequestHandler.kt | 2 +- .../com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 4 ++-- example/lib/ow_broadcast_helper.dart | 2 +- ios/Classes/Pigeon.swift | 4 ++-- lib/events/fingerprint_event.dart | 4 ++-- lib/events/onewelcome_events.dart | 4 ++-- lib/onegini_event_listener.dart | 4 ++-- lib/pigeon.dart | 6 +++--- pigeons/onewelcome_pigeon_interface.dart | 2 +- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt index e066feb3..823bf2e8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt @@ -20,7 +20,7 @@ class FingerprintAuthenticationRequestHandler @Inject constructor(private val na } override fun onNextAuthenticationAttempt() { - nativeApi.n2fReceivedFingerprint { } + nativeApi.n2fNextFingerprintAuthenticationAttempt { } } override fun onFingerprintCaptured() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 14e12e03..341d391f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1341,8 +1341,8 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { } } /** Called when fingerprint was received. */ - fun n2fReceivedFingerprint(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint", codec) + fun n2fNextFingerprintAuthenticationAttempt(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt", codec) channel.send(null) { callback() } diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 42468454..77488409 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -133,7 +133,7 @@ class OWBroadcastHelper { Overlay.of(context).insert(fingerprintOverlay); }); - StreamSubscription receivedFingerprintSub = broadCastController.stream.where((event) => event is ReceivedFingerprintEvent).listen((event) { + StreamSubscription receivedFingerprintSub = broadCastController.stream.where((event) => event is NextFingerprintAuthenticationAttempt).listen((event) { fingerprintOverlay.remove(); }); diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 9f56d81a..1d00e25f 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1241,8 +1241,8 @@ class NativeCallFlutterApi { } } /// Called when fingerprint was received. - func n2fReceivedFingerprint(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint", binaryMessenger: binaryMessenger, codec: codec) + func n2fNextFingerprintAuthenticationAttempt(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in completion() } diff --git a/lib/events/fingerprint_event.dart b/lib/events/fingerprint_event.dart index 3ed6778b..8103185e 100644 --- a/lib/events/fingerprint_event.dart +++ b/lib/events/fingerprint_event.dart @@ -13,6 +13,6 @@ class ShowScanningFingerprintEvent extends OWEvent { ShowScanningFingerprintEvent() : super(OWAction.showScanningFingerprint); } -class ReceivedFingerprintEvent extends OWEvent { - ReceivedFingerprintEvent() : super(OWAction.receivedFingerprint); +class NextFingerprintAuthenticationAttempt extends OWEvent { + NextFingerprintAuthenticationAttempt() : super(OWAction.nextFingerprintAuthenticationAttempt); } diff --git a/lib/events/onewelcome_events.dart b/lib/events/onewelcome_events.dart index 9c447e1c..d87de04b 100644 --- a/lib/events/onewelcome_events.dart +++ b/lib/events/onewelcome_events.dart @@ -23,7 +23,7 @@ enum OWAction { openFingerprint, // Called to open fingerprint screen. closeFingerprint, // Called to close fingerprint screen. showScanningFingerprint, // Called to scan fingerprint. - receivedFingerprint, // Called when fingerprint was received. + nextFingerprintAuthenticationAttempt, // Called when fingerprint was received but was incorrect. // CustomRegistration initCustomRegistration, // Called when customRegistration is initialized and a response should be given (only for two-step) @@ -58,7 +58,7 @@ extension OWActionExtension on OWAction { return "pinNotAllowed"; case OWAction.showScanningFingerprint: return "showScanningFingerprint"; - case OWAction.receivedFingerprint: + case OWAction.nextFingerprintAuthenticationAttempt: return "receivedFingerprint"; case OWAction.initCustomRegistration: return "initCustomRegistration"; diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 300cd4f2..6a2a867d 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -73,8 +73,8 @@ class OneginiEventListener implements NativeCallFlutterApi { } @override - void n2fReceivedFingerprint() { - broadcastEvent(ReceivedFingerprintEvent()); + void n2fNextFingerprintAuthenticationAttempt() { + broadcastEvent(NextFingerprintAuthenticationAttempt()); } @override diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 6f858d20..3c707a62 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1398,7 +1398,7 @@ abstract class NativeCallFlutterApi { void n2fShowScanningFingerprint(); /// Called when fingerprint was received. - void n2fReceivedFingerprint(); + void n2fNextFingerprintAuthenticationAttempt(); /// Called to close fingerprint screen. void n2fCloseFingerprintScreen(); @@ -1567,14 +1567,14 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fReceivedFingerprint', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fReceivedFingerprint(); + api.n2fNextFingerprintAuthenticationAttempt(); return; }); } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index b00b1345..e25903fd 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -291,7 +291,7 @@ abstract class NativeCallFlutterApi { void n2fShowScanningFingerprint(); /// Called when fingerprint was received. - void n2fReceivedFingerprint(); + void n2fNextFingerprintAuthenticationAttempt(); /// Called to close fingerprint screen. void n2fCloseFingerprintScreen(); From 7ea50f584d6ff2b93ccc9d9aeeb5381aa7226579 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 13 Apr 2023 10:54:13 +0200 Subject: [PATCH 257/364] fp-77 added casts to subscriptions that used the event objects to remove the if statements, re-arranged the oneginilistener class to group the events together, removed prints --- example/lib/ow_broadcast_helper.dart | 49 +++++++++++-------------- lib/events/pin_event.dart | 13 +++++-- lib/onegini_event_listener.dart | 53 ++++++++++++++++------------ 3 files changed, 61 insertions(+), 54 deletions(-) diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 77488409..e9f1d771 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -6,7 +6,6 @@ import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; import 'package:onegini/events/browser_event.dart'; import 'package:onegini/events/custom_registration_event.dart'; import 'package:onegini/events/fingerprint_event.dart'; -import 'package:onegini/events/generic_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; @@ -29,11 +28,9 @@ class OWBroadcastHelper { var broadCastController = Onegini.instance.userClient.owEventStreamController; // Url Registration Related Events - StreamSubscription handleRegisteredUrlSub = broadCastController.stream.where((event) => event is HandleRegisteredUrlEvent).listen((event) { - if (event is HandleRegisteredUrlEvent) { - Onegini.instance.userClient.handleRegisteredUserUrl(event.url, - signInType: WebSignInType.insideApp); - } + StreamSubscription handleRegisteredUrlSub = broadCastController.stream.where((event) => event is HandleRegisteredUrlEvent).cast().listen((event) { + Onegini.instance.userClient.handleRegisteredUserUrl(event.url, + signInType: WebSignInType.insideApp); }); // Pin Registration Related Events @@ -50,15 +47,13 @@ class OWBroadcastHelper { } }); - StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEvent).listen((event) { - if (event is PinNotAllowedEvent) { - showFlutterToast("${event.error.message} Code: ${event.error.code}"); - } + StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEvent).cast().listen((event) { + showFlutterToast("${event.error.message} Code: ${event.error.code}"); }); // Custom Registration related events - StreamSubscription initCustomSub = broadCastController.stream.where((event) => event is InitCustomRegistrationEvent).listen((event) { - if (event is InitCustomRegistrationEvent && event.providerId == "2-way-otp-api") { + StreamSubscription initCustomSub = broadCastController.stream.where((event) => event is InitCustomRegistrationEvent).cast().listen((event) { + if (event.providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request OneginiCustomRegistrationCallback() .submitSuccessAction(event.providerId, null) @@ -69,8 +64,8 @@ class OWBroadcastHelper { } }); - StreamSubscription finishCustomSub = broadCastController.stream.where((event) => event is FinishCustomRegistrationEvent).listen((event) { - if (event is FinishCustomRegistrationEvent && event.providerId == "2-way-otp-api") { + StreamSubscription finishCustomSub = broadCastController.stream.where((event) => event is FinishCustomRegistrationEvent).cast().listen((event) { + if (event.providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request Navigator.push( context, @@ -138,11 +133,9 @@ class OWBroadcastHelper { }); // Generic Authentication related events - StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextAuthenticationAttemptEvent).listen((event) { - if (event is NextAuthenticationAttemptEvent) { - pinScreenController.clearState(); - showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); - } + StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextAuthenticationAttemptEvent).cast().listen((event) { + pinScreenController.clearState(); + showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); }); return [openPinSub, closePinSub, openFingerprintSub, closeFingerprintSub, showScanningFingerprintSub, receivedFingerprintSub, nextAuthenticationAttempt]; @@ -151,16 +144,14 @@ class OWBroadcastHelper { static List> initOTPListeners(BuildContext context) { var broadCastController = Onegini.instance.userClient.owEventStreamController; - StreamSubscription openAuthOtpSub = broadCastController.stream.where((event) => event is OpenAuthOtpEvent).listen((event) { - if (event is OpenAuthOtpEvent) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AuthOtpScreen( - message: event.message, - )), - ); - } + StreamSubscription openAuthOtpSub = broadCastController.stream.where((event) => event is OpenAuthOtpEvent).cast().listen((event) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => AuthOtpScreen( + message: event.message, + )), + ); }); StreamSubscription closeAuthOtpSub = broadCastController.stream.where((event) => event is CloseAuthOtpEvent).listen((event) { diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index c3864c19..1272a573 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -2,6 +2,7 @@ import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/pigeon.dart'; +// For Pin Creation class OpenPinRegistrationEvent extends OWEvent { OpenPinRegistrationEvent() : super(OWAction.openPinRegistration); } @@ -10,6 +11,12 @@ class ClosePinRegistrationEvent extends OWEvent { ClosePinRegistrationEvent() : super(OWAction.closePinRegistration); } +class PinNotAllowedEvent extends OWEvent { + OWOneginiError error; + PinNotAllowedEvent(this.error) : super(OWAction.pinNotAllowed); +} + +// For Pin Authentication class OpenPinAuthenticationEvent extends OWEvent { OpenPinAuthenticationEvent() : super(OWAction.openPinAuthentication); } @@ -18,7 +25,7 @@ class ClosePinAuthenticationEvent extends OWEvent { ClosePinAuthenticationEvent() : super(OWAction.closePinAuthentication); } -class PinNotAllowedEvent extends OWEvent { - OWOneginiError error; - PinNotAllowedEvent(this.error) : super(OWAction.pinNotAllowed); +class NextAuthenticationAttemptEvent extends OWEvent { + OWAuthenticationAttempt authenticationAttempt; + NextAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextAuthenticationAttempt); } diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 6a2a867d..9979cfea 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,7 +1,6 @@ import 'package:onegini/events/browser_event.dart'; import 'package:onegini/events/custom_registration_event.dart'; import 'package:onegini/events/fingerprint_event.dart'; -import 'package:onegini/events/generic_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; @@ -9,26 +8,31 @@ import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; class OneginiEventListener implements NativeCallFlutterApi { + /// Browser Registration related events @override - void n2fCloseAuthOtp() { - broadcastEvent(CloseAuthOtpEvent()); + void n2fHandleRegisteredUrl(String url) { + broadcastEvent(HandleRegisteredUrlEvent(url)); } + /// Pin Creation related events @override - void n2fCloseFingerprintScreen() { - broadcastEvent(CloseFingerprintEvent()); + void n2fOpenPinRequestScreen() { + // renamed OpenPinRegistrationEvent to OpenPinCreationEvent + broadcastEvent(OpenPinRegistrationEvent()); } @override void n2fClosePin() { + // renamed ClosePinRegistrationEvent -> ClosePinCreationEvent broadcastEvent(ClosePinRegistrationEvent()); } @override - void n2fClosePinAuth() { - broadcastEvent(ClosePinAuthenticationEvent()); + void n2fEventPinNotAllowed(OWOneginiError error) { + broadcastEvent(PinNotAllowedEvent(error)); } + /// Custom Registration related events @override void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId) { @@ -41,20 +45,28 @@ class OneginiEventListener implements NativeCallFlutterApi { broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); } + /// Pin Authentication related events @override - void n2fHandleRegisteredUrl(String url) { - broadcastEvent(HandleRegisteredUrlEvent(url)); + void n2fOpenPinScreenAuth() { + broadcastEvent(OpenPinAuthenticationEvent()); + } + + @override + void n2fClosePinAuth() { + broadcastEvent(ClosePinAuthenticationEvent()); } @override void n2fNextAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt) { + // renamed from NextAuthenticationAttemptEvent to NextPinAuthenticationAttemptEvent broadcastEvent(NextAuthenticationAttemptEvent(authenticationAttempt)); } + /// Fingerprint related events @override - void n2fOpenAuthOtp(String? message) { - broadcastEvent(OpenAuthOtpEvent(message ?? "")); + void n2fShowScanningFingerprint() { + broadcastEvent(ShowScanningFingerprintEvent()); } @override @@ -63,13 +75,8 @@ class OneginiEventListener implements NativeCallFlutterApi { } @override - void n2fOpenPinRequestScreen() { - broadcastEvent(OpenPinRegistrationEvent()); - } - - @override - void n2fOpenPinScreenAuth() { - broadcastEvent(OpenPinAuthenticationEvent()); + void n2fCloseFingerprintScreen() { + broadcastEvent(CloseFingerprintEvent()); } @override @@ -77,16 +84,18 @@ class OneginiEventListener implements NativeCallFlutterApi { broadcastEvent(NextFingerprintAuthenticationAttempt()); } + /// OTP Mobile authentication related events @override - void n2fShowScanningFingerprint() { - broadcastEvent(ShowScanningFingerprintEvent()); + void n2fOpenAuthOtp(String? message) { + broadcastEvent(OpenAuthOtpEvent(message ?? "")); } @override - void n2fEventPinNotAllowed(OWOneginiError error) { - broadcastEvent(PinNotAllowedEvent(error)); + void n2fCloseAuthOtp() { + broadcastEvent(CloseAuthOtpEvent()); } + /// Helper method void broadcastEvent(OWEvent event) { Onegini.instance.userClient.owEventStreamController.sink.add(event); } From 9ba47180eb1dcef4e6462a839359aa26016c8010 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 13 Apr 2023 12:40:03 +0200 Subject: [PATCH 258/364] FP-65: Update android implementation with preffered authenticator --- .../sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt | 3 ++- .../mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt index 704a2f79..69ca14af 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt @@ -3,9 +3,10 @@ package com.onegini.mobile.sdk.flutter.extensions import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType -fun OWAuthenticatorType.toOneginiInt(): Int { +fun OWAuthenticatorType.toOneginiInt(): Int? { return when (this) { OWAuthenticatorType.PIN -> OneginiAuthenticator.PIN OWAuthenticatorType.BIOMETRIC -> OneginiAuthenticator.FINGERPRINT + OWAuthenticatorType.PREFERRED -> null } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index a16de134..a9c8ab3c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -21,7 +21,7 @@ class AuthenticateUserUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(profileId: String, authenticatorType: OWAuthenticatorType?, callback: (Result) -> Unit) { + operator fun invoke(profileId: String, authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { @@ -29,7 +29,7 @@ class AuthenticateUserUseCase @Inject constructor( } val authenticator = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - .find { it.type == authenticatorType?.toOneginiInt() } + .find { it.type == authenticatorType.toOneginiInt() } authenticate(userProfile, authenticator, callback) } From 01076776d47be14f475c8ffa5a2c78fa5f2c9495 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 13 Apr 2023 12:40:24 +0200 Subject: [PATCH 259/364] FP-65: Update authentication api's in dart --- lib/user_client.dart | 58 ++++++++++++-------------------------------- 1 file changed, 15 insertions(+), 43 deletions(-) diff --git a/lib/user_client.dart b/lib/user_client.dart index b363e7b4..dbaf728b 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -45,24 +45,6 @@ class UserClient { await api.deregisterUser(profileId); } - /// Returns a list of authenticators registered and available to the user. - Future> getRegisteredAuthenticators( - BuildContext? context, String profileId) async { - Onegini.instance.setEventContext(context); - - final registeredAuthenticators = - await api.getRegisteredAuthenticators(profileId); - return registeredAuthenticators.whereType().toList(); - } - - Future> getAllAuthenticators( - BuildContext? context, String profileId) async { - Onegini.instance.setEventContext(context); - - final allAuthenticators = await api.getAllAuthenticators(profileId); - return allAuthenticators.whereType().toList(); - } - Future getAuthenticatedUserProfile() async { return await api.getAuthenticatedUserProfile(); } @@ -74,19 +56,11 @@ class UserClient { Future authenticateUser( BuildContext? context, String profileId, - String? registeredAuthenticatorId, + OWAuthenticatorType authenticatorType, ) async { Onegini.instance.setEventContext(context); - return await api.authenticateUser(profileId, registeredAuthenticatorId); - } - - /// Returns a list of authenticators available to the user, but not yet registered. - Future> getNotRegisteredAuthenticators( - BuildContext? context, String profileId) async { - final notRegisteredAuthenticators = - await api.getNotRegisteredAuthenticators(profileId); - return notRegisteredAuthenticators.whereType().toList(); + return await api.authenticateUser(profileId, authenticatorType); } /// Starts change pin flow. @@ -97,29 +71,27 @@ class UserClient { await api.changePin(); } - /// Registers authenticator from [getNotRegisteredAuthenticators] list. - Future registerAuthenticator( - BuildContext? context, String authenticatorId) async { - Onegini.instance.setEventContext(context); - - await api.registerAuthenticator(authenticatorId); - } - ///Set preferred authenticator /// todo removed boolean return update docu Future setPreferredAuthenticator( - BuildContext? context, String authenticatorId) async { + BuildContext? context, OWAuthenticatorType authenticatorType) async { Onegini.instance.setEventContext(context); + await api.setPreferredAuthenticator(authenticatorType); + } - await api.setPreferredAuthenticator(authenticatorId); + // Gets the preferred authenticator for the given profile + Future getPreferredAuthenticator(String profileId) async { + await api.getPreferredAuthenticator(profileId); } - /// todo removed boolean return update docu - Future deregisterAuthenticator( - BuildContext? context, String authenticatorId) async { - Onegini.instance.setEventContext(context); + Future deregisterBiometricAuthenticator( + OWAuthenticatorType authenticatorType) async { + await api.deregisterBiometricAuthenticator(); + } - await api.deregisterAuthenticator(authenticatorId); + Future registerBiometricAuthenticator( + OWAuthenticatorType authenticatorType) async { + await api.registerBiometricAuthenticator(); } ///Method for log out From f86529f921154e576fc96ca2ef30713f7e73d282 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 13 Apr 2023 12:41:24 +0200 Subject: [PATCH 260/364] FP-65: use new dart api in login_screen --- example/lib/screens/login_screen.dart | 153 +++++--------- example/lib/screens/user_screen.dart | 277 +++++++++++++------------- 2 files changed, 194 insertions(+), 236 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 854b6203..416242bc 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -74,17 +74,10 @@ class _LoginScreenState extends State { } } - authenticateWithPreferredAuthenticator(String profileId) async { - setState(() => {isLoading = true}); - var registrationResponse = await Onegini.instance.userClient - .authenticateUser(context, profileId, null) - .catchError((error) { - setState(() => isLoading = false); - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - if (registrationResponse?.userProfile?.profileId != null) + authenticate(String profileId, OWAuthenticatorType authenticatorType) async { + try { + var registrationResponse = await Onegini.instance.userClient + .authenticateUser(context, profileId, authenticatorType); Navigator.pushAndRemoveUntil( context, MaterialPageRoute( @@ -92,30 +85,11 @@ class _LoginScreenState extends State { userProfileId: registrationResponse.userProfile.profileId, )), (Route route) => false); - } - - authenticateWithRegisteredAuthenticators( - String registeredAuthenticatorId, String profileId) async { - setState(() => {isLoading = true}); - // var result = await Onegini.instance.userClient.setPreferredAuthenticator(context, registeredAuthenticatorId); - // print(result); - - var registrationResponse = await Onegini.instance.userClient - .authenticateUser(context, profileId, registeredAuthenticatorId) - .catchError((error) { - setState(() => isLoading = false); + } catch (error) { if (error is PlatformException) { showFlutterToast(error.message); } - }); - if (registrationResponse.userProfile?.profileId != null) - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) => UserScreen( - userProfileId: registrationResponse.userProfile.profileId, - )), - (Route route) => false); + } } cancelRegistration() async { @@ -143,14 +117,16 @@ class _LoginScreenState extends State { Future getImplicitUserDetails(String profileId) async { var returnString = ""; try { - await Onegini.instance.userClient.authenticateUserImplicitly(profileId, ["read"]); + await Onegini.instance.userClient + .authenticateUserImplicitly(profileId, ["read"]); var response = await Onegini.instance.resourcesMethods.requestResource( - ResourceRequestType.implicit, - RequestDetails(path: "user-id-decorated", method: HttpRequestMethod.get)); + ResourceRequestType.implicit, + RequestDetails( + path: "user-id-decorated", method: HttpRequestMethod.get)); var res = json.decode(response.body); - returnString =res["decorated_user_id"]; + returnString = res["decorated_user_id"]; return returnString; } catch (err) { @@ -243,78 +219,53 @@ class _LoginScreenState extends State { ), ElevatedButton( onPressed: () { - authenticateWithPreferredAuthenticator( + authenticate( userProfiles .data .first - ?.profileId); + ?.profileId, + OWAuthenticatorType + .preferred); }, child: Text( - 'Authenticate with preferred authenticator'), + 'Preferred authenticator'), ), - SizedBox( - height: 10, + Row( + mainAxisAlignment: + MainAxisAlignment + .center, + children: [ + ElevatedButton( + onPressed: () { + authenticate( + userProfiles + .data + .first + ?.profileId, + OWAuthenticatorType + .pin); + }, + child: Text('Pin'), + ), + SizedBox( + height: 10, + width: 10, + ), + ElevatedButton( + onPressed: () { + authenticate( + userProfiles + .data + .first + ?.profileId, + OWAuthenticatorType + .biometric); + }, + child: Text( + 'Biometrics'), + ), + ], ), - FutureBuilder< - List< - OWAuthenticator>>( - future: Onegini - .instance.userClient - .getRegisteredAuthenticators( - context, - userProfiles - .data - .first - ?.profileId), - builder: (BuildContext - context, - registeredAuthenticators) { - return registeredAuthenticators - .hasData - ? PopupMenuButton< - String>( - child: - Container( - padding: - EdgeInsets.all( - 20), - color: Colors - .blue, - child: Text( - "Authenticators", - style: TextStyle( - color: Colors - .white, - fontSize: - 16, - fontWeight: - FontWeight.w700), - ), - ), - onSelected: - (value) { - authenticateWithRegisteredAuthenticators( - userProfiles - .data - .first - ?.profileId, - value); - }, - itemBuilder: - (context) { - return registeredAuthenticators - .data - .map((e) => - PopupMenuItem( - child: Text(e.name ?? ""), - value: e.id, - )) - .toList(); - }) - : SizedBox - .shrink(); - }, - ) ]) : SizedBox.shrink(); }) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 6c5b1bc3..9917a141 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -49,7 +49,7 @@ class _UserScreenState extends State with RouteAware { ]; super.initState(); this.profileId = widget.userProfileId; - getAuthenticators(); + // getAuthenticators(); } @override @@ -66,7 +66,7 @@ class _UserScreenState extends State with RouteAware { @override void didPopNext() { - getAuthenticators(); + // getAuthenticators(); } logOut(BuildContext context) async { @@ -82,70 +82,70 @@ class _UserScreenState extends State with RouteAware { ); } - Future getAuthenticators() async { - notRegisteredAuthenticators = await Onegini.instance.userClient - .getNotRegisteredAuthenticators(context, this.profileId); - - registeredAuthenticators = await Onegini.instance.userClient - .getRegisteredAuthenticators(context, this.profileId); - } - - Future> getAllSortAuthenticators() async { - var allAuthenticators = await Onegini.instance.userClient - .getAllAuthenticators(context, this.profileId); - allAuthenticators.sort((a, b) { - return compareAsciiUpperCase(a.name, b.name); - }); - return allAuthenticators; - } - - Future> getNotRegisteredAuthenticators() async { - var authenticators = await Onegini.instance.userClient - .getNotRegisteredAuthenticators(context, this.profileId); - return authenticators; - } - - registerAuthenticator(String authenticatorId) async { - await Onegini.instance.userClient - .registerAuthenticator(context, authenticatorId) - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - await getAuthenticators(); - setState(() {}); - } - - bool isRegisteredAuthenticator(String authenticatorId) { - for (var authenticator in registeredAuthenticators) { - if (authenticator.id == authenticatorId) return true; - } - return false; - } - - deregisterAuthenticator(String authenticatorId) async { - await Onegini.instance.userClient - .deregisterAuthenticator(context, authenticatorId) - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - await getAuthenticators(); - setState(() {}); - } - - setPreferredAuthenticator(String authenticatorId) async { - await Onegini.instance.userClient - .setPreferredAuthenticator(context, authenticatorId) - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - Navigator.pop(context); - } + // Future getAuthenticators() async { + // notRegisteredAuthenticators = await Onegini.instance.userClient + // .getNotRegisteredAuthenticators(context, this.profileId); + + // registeredAuthenticators = await Onegini.instance.userClient + // .getRegisteredAuthenticators(context, this.profileId); + // } + + // Future> getAllSortAuthenticators() async { + // var allAuthenticators = await Onegini.instance.userClient + // .getAllAuthenticators(context, this.profileId); + // allAuthenticators.sort((a, b) { + // return compareAsciiUpperCase(a.name, b.name); + // }); + // return allAuthenticators; + // } + + // Future> getNotRegisteredAuthenticators() async { + // var authenticators = await Onegini.instance.userClient + // .getNotRegisteredAuthenticators(context, this.profileId); + // return authenticators; + // } + + // registerAuthenticator(String authenticatorId) async { + // await Onegini.instance.userClient + // .registerAuthenticator(context, authenticatorId) + // .catchError((error) { + // if (error is PlatformException) { + // showFlutterToast(error.message); + // } + // }); + // await getAuthenticators(); + // setState(() {}); + // } + + // bool isRegisteredAuthenticator(String authenticatorId) { + // for (var authenticator in registeredAuthenticators) { + // if (authenticator.id == authenticatorId) return true; + // } + // return false; + // } + + // deregisterAuthenticator(String authenticatorId) async { + // await Onegini.instance.userClient + // .deregisterAuthenticator(context, authenticatorId) + // .catchError((error) { + // if (error is PlatformException) { + // showFlutterToast(error.message); + // } + // }); + // await getAuthenticators(); + // setState(() {}); + // } + + // setPreferredAuthenticator(String authenticatorId) async { + // await Onegini.instance.userClient + // .setPreferredAuthenticator(context, authenticatorId) + // .catchError((error) { + // if (error is PlatformException) { + // showFlutterToast(error.message); + // } + // }); + // Navigator.pop(context); + // } deregister(BuildContext context) async { Navigator.pop(context); @@ -209,58 +209,58 @@ class _UserScreenState extends State with RouteAware { DrawerHeader( child: Container(), ), - FutureBuilder>( - future: getAllSortAuthenticators(), - builder: (BuildContext context, snapshot) { - return ListView.builder( - shrinkWrap: true, - itemCount: snapshot.hasData ? snapshot.data.length : 0, - itemBuilder: (context, index) { - return ListTile( - title: Text( - snapshot.data[index].name, - ), - leading: Switch( - value: snapshot.data[index].name == "PIN" - ? true - : isRegisteredAuthenticator( - snapshot.data[index].id), - onChanged: snapshot.data[index].name == "PIN" - ? null - : (value) { - value - ? registerAuthenticator( - snapshot.data[index].id) - : deregisterAuthenticator( - snapshot.data[index].id); - }, - ), - ); - }); - }, - ), - FutureBuilder>( - future: Onegini.instance.userClient - .getRegisteredAuthenticators(context, this.profileId), - builder: (BuildContext context, snapshot) { - return PopupMenuButton( - child: ListTile( - title: Text("set preferred authenticator"), - leading: Icon(Icons.add_to_home_screen), - ), - onSelected: (value) { - setPreferredAuthenticator(value); - }, - itemBuilder: (context) { - return snapshot.data - .map((e) => PopupMenuItem( - child: Text(e.name ?? ""), - value: e.id, - )) - .toList(); - }); - }, - ), + // FutureBuilder>( + // future: getAllSortAuthenticators(), + // builder: (BuildContext context, snapshot) { + // return ListView.builder( + // shrinkWrap: true, + // itemCount: snapshot.hasData ? snapshot.data.length : 0, + // itemBuilder: (context, index) { + // return ListTile( + // title: Text( + // snapshot.data[index].name, + // ), + // leading: Switch( + // value: snapshot.data[index].name == "PIN" + // ? true + // : isRegisteredAuthenticator( + // snapshot.data[index].id), + // onChanged: snapshot.data[index].name == "PIN" + // ? null + // : (value) { + // value + // ? registerAuthenticator( + // snapshot.data[index].id) + // : deregisterAuthenticator( + // snapshot.data[index].id); + // }, + // ), + // ); + // }); + // }, + // ), + // FutureBuilder>( + // future: Onegini.instance.userClient + // .getRegisteredAuthenticators(context, this.profileId), + // builder: (BuildContext context, snapshot) { + // return PopupMenuButton( + // child: ListTile( + // title: Text("set preferred authenticator"), + // leading: Icon(Icons.add_to_home_screen), + // ), + // onSelected: (value) { + // setPreferredAuthenticator(value); + // }, + // itemBuilder: (context) { + // return snapshot.data + // .map((e) => PopupMenuItem( + // child: Text(e.name ?? ""), + // value: e.id, + // )) + // .toList(); + // }); + // }, + // ), ListTile( title: Text("Change pin"), onTap: () => changePin(context), @@ -295,12 +295,13 @@ class Home extends StatelessWidget { enrollMobileAuthentication() async { await Onegini.instance.userClient .enrollMobileAuthentication() - .then((value) => showFlutterToast("Mobile Authentication enrollment success")) + .then((value) => + showFlutterToast("Mobile Authentication enrollment success")) .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); + if (error is PlatformException) { + showFlutterToast(error.message); + } + }); } authWithOpt(BuildContext context) async { @@ -312,13 +313,14 @@ class Home extends StatelessWidget { if (data != null) { await Onegini.instance.userClient - .handleMobileAuthWithOtp(data) - .then((value) => showFlutterToast("OTP1 Authentication is successfull")) - .catchError((error) { - if (error is PlatformException) { - print("otp1"); - print(error.message); - } + .handleMobileAuthWithOtp(data) + .then( + (value) => showFlutterToast("OTP1 Authentication is successfull")) + .catchError((error) { + if (error is PlatformException) { + print("otp1"); + print(error.message); + } }); } } @@ -363,10 +365,11 @@ class Home extends StatelessWidget { performUnauthenticatedRequest() async { var response = await Onegini.instance.resourcesMethods - .requestResourceUnauthenticated(RequestDetails(path: "unauthenticated", method: HttpRequestMethod.get)) + .requestResourceUnauthenticated(RequestDetails( + path: "unauthenticated", method: HttpRequestMethod.get)) .catchError((error) { - print("An error occured $error"); - showFlutterToast("An error occured $error"); + print("An error occured $error"); + showFlutterToast("An error occured $error"); }); showFlutterToast("Response: ${response.body}"); @@ -457,14 +460,18 @@ class _InfoState extends State { Future getApplicationDetails() async { await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - var response = await Onegini.instance.resourcesMethods.requestResource(ResourceRequestType.anonymous, RequestDetails(path: "application-details", method: HttpRequestMethod.get)); + var response = await Onegini.instance.resourcesMethods.requestResource( + ResourceRequestType.anonymous, + RequestDetails( + path: "application-details", method: HttpRequestMethod.get)); var res = json.decode(response.body); return applicationDetailsFromJson(res); } Future getClientResource() async { var response = await Onegini.instance.resourcesMethods - .requestResourceAuthenticated(RequestDetails(path: "devices", method: HttpRequestMethod.get)) + .requestResourceAuthenticated( + RequestDetails(path: "devices", method: HttpRequestMethod.get)) .catchError((error) { print('Caught error: $error'); From 1a62ed5d961383c452e02fecdef3ee0d60d9668c Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 13 Apr 2023 14:47:08 +0200 Subject: [PATCH 261/364] realligned and added comments for event structures, als renamed pigeon events to allign better with its functionality --- .../PinAuthenticationRequestHandler.kt | 6 +- .../sdk/flutter/handlers/PinRequestHandler.kt | 6 +- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 91 +++++++----- example/lib/ow_broadcast_helper.dart | 12 +- .../NativeBridge/Handlers/LoginHandler.swift | 8 +- .../Handlers/RegistrationHandler.swift | 8 +- ios/Classes/Pigeon.swift | 79 +++++----- lib/events/onewelcome_events.dart | 56 ++++---- lib/events/pin_event.dart | 12 +- lib/onegini_event_listener.dart | 27 ++-- lib/pigeon.dart | 135 +++++++++--------- pigeons/onewelcome_pigeon_interface.dart | 43 +++--- 12 files changed, 261 insertions(+), 222 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index 838bb72a..c91d7fc2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -22,7 +22,7 @@ class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: attemptCounter: AuthenticationAttemptCounter ) { callback = oneginiPinCallback - nativeApi.n2fOpenPinScreenAuth { } + nativeApi.n2fOpenPinAuthentication { } } override fun onNextAuthenticationAttempt(attemptCounter: AuthenticationAttemptCounter) { @@ -31,11 +31,11 @@ class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: attemptCounter.maxAttempts.toLong(), attemptCounter.remainingAttempts.toLong() ) - nativeApi.n2fNextAuthenticationAttempt(authenticationAttempt) {} + nativeApi.n2fNextPinAuthenticationAttempt(authenticationAttempt) {} } override fun finishAuthentication() { - nativeApi.n2fClosePinAuth { } + nativeApi.n2fClosePinAuthentication { } callback = null } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index 3a647c6a..97c3da41 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -18,11 +18,11 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu override fun startPinCreation(userProfile: UserProfile, oneginiPinCallback: OneginiPinCallback, p2: Int) { callback = oneginiPinCallback - nativeApi.n2fOpenPinRequestScreen { } + nativeApi.n2fOpenPinCreation { } } override fun onNextPinCreationAttempt(oneginiPinValidationError: OneginiPinValidationError) { - nativeApi.n2fEventPinNotAllowed( + nativeApi.n2fPinNotAllowed( OWOneginiError( oneginiPinValidationError.errorType.toLong(), oneginiPinValidationError.message ?: "" @@ -32,7 +32,7 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu override fun finishPinCreation() { callback = null - nativeApi.n2fClosePin { } + nativeApi.n2fClosePinCreation { } } fun onPinProvided(pin: CharArray): Result { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index 341d391f..f9a2466a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -1277,51 +1277,76 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - /** Called to open OTP authentication. */ - fun n2fOpenAuthOtp(messageArg: String?, callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", codec) - channel.send(listOf(messageArg)) { + /** + * Called to open pin creation screen. + * changed n2fOpenPinRequestScreen into n2fOpenPinCreation + */ + fun n2fOpenPinCreation(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinCreation", codec) + channel.send(null) { callback() } } - /** Called to close OTP authentication. */ - fun n2fCloseAuthOtp(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", codec) + /** + * Called to close pin registration screen. + * changed n2fClosePin into n2fClosePinCreation + */ + fun n2fClosePinCreation(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinCreation", codec) channel.send(null) { callback() } } - /** Called to open pin registration screen. */ - fun n2fOpenPinRequestScreen(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen", codec) + /** + * Called to indicate that the given pin is not allowed for pin creation + * changed n2fEventPinNotAllowed into n2fPinNotAllowed + */ + fun n2fPinNotAllowed(errorArg: OWOneginiError, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed", codec) + channel.send(listOf(errorArg)) { + callback() + } + } + /** + * Called to open pin authentication screen. + * changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication + */ + fun n2fOpenPinAuthentication(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication", codec) channel.send(null) { callback() } } - /** Called to open pin authentication screen. */ - fun n2fOpenPinScreenAuth(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth", codec) + /** + * Called to close pin authentication screen. + * changed n2fClosePinAuth into n2fClosePinAuthentication + */ + fun n2fClosePinAuthentication(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication", codec) channel.send(null) { callback() } } - /** Called to attempt next authentication. */ - fun n2fNextAuthenticationAttempt(authenticationAttemptArg: OWAuthenticationAttempt, callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", codec) + /** + * Called to attempt next pin authentication. + * changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt + */ + fun n2fNextPinAuthenticationAttempt(authenticationAttemptArg: OWAuthenticationAttempt, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt", codec) channel.send(listOf(authenticationAttemptArg)) { callback() } } - /** Called to close pin registration screen. */ - fun n2fClosePin(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin", codec) - channel.send(null) { + /** Called to open OTP authentication. */ + fun n2fOpenAuthOtp(messageArg: String?, callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", codec) + channel.send(listOf(messageArg)) { callback() } } - /** Called to close pin authentication screen. */ - fun n2fClosePinAuth(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth", codec) + /** Called to close OTP authentication. */ + fun n2fCloseAuthOtp(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", codec) channel.send(null) { callback() } @@ -1333,6 +1358,13 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } + /** Called to close fingerprint screen. */ + fun n2fCloseFingerprintScreen(callback: () -> Unit) { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", codec) + channel.send(null) { + callback() + } + } /** Called to scan fingerprint. */ fun n2fShowScanningFingerprint(callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint", codec) @@ -1347,13 +1379,6 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - /** Called to close fingerprint screen. */ - fun n2fCloseFingerprintScreen(callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", codec) - channel.send(null) { - callback() - } - } /** Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) */ fun n2fEventInitCustomRegistration(customInfoArg: OWCustomInfo?, providerIdArg: String, callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration", codec) @@ -1368,10 +1393,4 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - fun n2fEventPinNotAllowed(errorArg: OWOneginiError, callback: () -> Unit) { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed", codec) - channel.send(listOf(errorArg)) { - callback() - } - } } diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index e9f1d771..b56d6104 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -34,14 +34,14 @@ class OWBroadcastHelper { }); // Pin Registration Related Events - StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinRegistrationEvent).listen((event) { + StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinCreationEvent).listen((event) { Navigator.push( context, MaterialPageRoute(builder: (context) => PinRequestScreen()), ); }); - StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinRegistrationEvent).listen((event) { + StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinCreationEvent).listen((event) { if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } @@ -92,9 +92,6 @@ class OWBroadcastHelper { // Pin Authentication related events StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinAuthenticationEvent).listen((event) { - print("open pin auth:"); - print(context); - print(pinScreenController); Navigator.push( context, MaterialPageRoute( @@ -103,8 +100,6 @@ class OWBroadcastHelper { }); StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinAuthenticationEvent).listen((event) { - print("close pin auth"); - print(context); if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } @@ -132,8 +127,7 @@ class OWBroadcastHelper { fingerprintOverlay.remove(); }); - // Generic Authentication related events - StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextAuthenticationAttemptEvent).cast().listen((event) { + StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextPinAuthenticationAttemptEvent).cast().listen((event) { pinScreenController.clearState(); showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); }); diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index 48c04787..da0ea4a0 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -37,21 +37,21 @@ class LoginHandler { failedAttempts: Int64(challenge.previousFailureCount), maxAttempts: Int64(challenge.maxFailureCount), remainingAttempts: Int64(challenge.remainingFailureCount)) - SwiftOneginiPlugin.flutterApi?.n2fNextAuthenticationAttempt(authenticationAttempt: authAttempt) {} + SwiftOneginiPlugin.flutterApi?.n2fNextPinAuthenticationAttempt(authenticationAttempt: authAttempt) {} return } - SwiftOneginiPlugin.flutterApi?.n2fOpenPinScreenAuth {} + SwiftOneginiPlugin.flutterApi?.n2fOpenPinAuthentication {} } func handleDidAuthenticateUser() { pinChallenge = nil - SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} + SwiftOneginiPlugin.flutterApi?.n2fClosePinAuthentication {} } func handleDidFailToAuthenticateUser() { guard pinChallenge != nil else { return } - SwiftOneginiPlugin.flutterApi?.n2fClosePinAuth {} + SwiftOneginiPlugin.flutterApi?.n2fClosePinAuthentication {} pinChallenge = nil } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 07b2af0c..487f9410 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -67,10 +67,10 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func handleDidReceivePinRegistrationChallenge(_ challenge: CreatePinChallenge) { createPinChallenge = challenge if let pinError = mapErrorFromPinChallenge(challenge) { - SwiftOneginiPlugin.flutterApi?.n2fEventPinNotAllowed(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} + SwiftOneginiPlugin.flutterApi?.n2fPinNotAllowed(error: OWOneginiError(code: Int64(pinError.code), message: pinError.errorDescription)) {} } else { // FIXME: we should be sending the pin length here. - SwiftOneginiPlugin.flutterApi?.n2fOpenPinRequestScreen {} + SwiftOneginiPlugin.flutterApi?.n2fOpenPinCreation {} } } @@ -81,14 +81,14 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { createPinChallenge = nil customRegistrationChallenge = nil browserRegistrationChallenge = nil - SwiftOneginiPlugin.flutterApi?.n2fClosePin {} + SwiftOneginiPlugin.flutterApi?.n2fClosePinCreation {} } func handleDidRegisterUser() { createPinChallenge = nil customRegistrationChallenge = nil browserRegistrationChallenge = nil - SwiftOneginiPlugin.flutterApi?.n2fClosePin {} + SwiftOneginiPlugin.flutterApi?.n2fClosePinCreation {} } func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 1d00e25f..e0c5e8dd 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -1177,51 +1177,64 @@ class NativeCallFlutterApi { completion() } } - /// Called to open OTP authentication. - func n2fOpenAuthOtp(message messageArg: String?, completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage([messageArg] as [Any?]) { _ in + /// Called to open pin creation screen. + /// changed n2fOpenPinRequestScreen into n2fOpenPinCreation + func n2fOpenPinCreation(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinCreation", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in completion() } } - /// Called to close OTP authentication. - func n2fCloseAuthOtp(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", binaryMessenger: binaryMessenger, codec: codec) + /// Called to close pin registration screen. + /// changed n2fClosePin into n2fClosePinCreation + func n2fClosePinCreation(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinCreation", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in completion() } } - /// Called to open pin registration screen. - func n2fOpenPinRequestScreen(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage(nil) { _ in + /// Called to indicate that the given pin is not allowed for pin creation + /// changed n2fEventPinNotAllowed into n2fPinNotAllowed + func n2fPinNotAllowed(error errorArg: OWOneginiError, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([errorArg] as [Any?]) { _ in completion() } } /// Called to open pin authentication screen. - func n2fOpenPinScreenAuth(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth", binaryMessenger: binaryMessenger, codec: codec) + /// changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication + func n2fOpenPinAuthentication(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in completion() } } - /// Called to attempt next authentication. - func n2fNextAuthenticationAttempt(authenticationAttempt authenticationAttemptArg: OWAuthenticationAttempt, completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) + /// Called to close pin authentication screen. + /// changed n2fClosePinAuth into n2fClosePinAuthentication + func n2fClosePinAuthentication(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } + /// Called to attempt next pin authentication. + /// changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt + func n2fNextPinAuthenticationAttempt(authenticationAttempt authenticationAttemptArg: OWAuthenticationAttempt, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([authenticationAttemptArg] as [Any?]) { _ in completion() } } - /// Called to close pin registration screen. - func n2fClosePin(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage(nil) { _ in + /// Called to open OTP authentication. + func n2fOpenAuthOtp(message messageArg: String?, completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([messageArg] as [Any?]) { _ in completion() } } - /// Called to close pin authentication screen. - func n2fClosePinAuth(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth", binaryMessenger: binaryMessenger, codec: codec) + /// Called to close OTP authentication. + func n2fCloseAuthOtp(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in completion() } @@ -1233,6 +1246,13 @@ class NativeCallFlutterApi { completion() } } + /// Called to close fingerprint screen. + func n2fCloseFingerprintScreen(completion: @escaping () -> Void) { + let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { _ in + completion() + } + } /// Called to scan fingerprint. func n2fShowScanningFingerprint(completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint", binaryMessenger: binaryMessenger, codec: codec) @@ -1247,13 +1267,6 @@ class NativeCallFlutterApi { completion() } } - /// Called to close fingerprint screen. - func n2fCloseFingerprintScreen(completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage(nil) { _ in - completion() - } - } /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) func n2fEventInitCustomRegistration(customInfo customInfoArg: OWCustomInfo?, providerId providerIdArg: String, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration", binaryMessenger: binaryMessenger, codec: codec) @@ -1268,10 +1281,4 @@ class NativeCallFlutterApi { completion() } } - func n2fEventPinNotAllowed(error errorArg: OWOneginiError, completion: @escaping () -> Void) { - let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed", binaryMessenger: binaryMessenger, codec: codec) - channel.sendMessage([errorArg] as [Any?]) { _ in - completion() - } - } } diff --git a/lib/events/onewelcome_events.dart b/lib/events/onewelcome_events.dart index d87de04b..6fedb843 100644 --- a/lib/events/onewelcome_events.dart +++ b/lib/events/onewelcome_events.dart @@ -5,21 +5,24 @@ abstract class OWEvent { } enum OWAction { - // Browser + // Browser Registration handleRegisteredUrl, // Called to handle registration URL - // Otp + // Otp Mobile Authentication openAuthOtp, // Called to open OTP authentication screen closeAuthOtp, // Called to close OTP authentication screen - // Pin - openPinRegistration, // Called to open pin registration screen. - closePinRegistration, // Called to open pin registration screen. + // Pin Creation + openPinCreation, // Called to open pin registration screen. + closePinCreation, // Called to open pin registration screen. + pinNotAllowed, // Called when the supplied pin for pin creation is not allowed + + // Pin Authentication openPinAuthentication, // Called to open pin authentication screen closePinAuthentication, // Called to close pin authentication screen - pinNotAllowed, // Called when the supplied pin for registration is not allowed + nextPinAuthenticationAttempt, // Called to attempt next authentication. - // Fingerprint + // Fingerprint Authentication openFingerprint, // Called to open fingerprint screen. closeFingerprint, // Called to close fingerprint screen. showScanningFingerprint, // Called to scan fingerprint. @@ -28,44 +31,47 @@ enum OWAction { // CustomRegistration initCustomRegistration, // Called when customRegistration is initialized and a response should be given (only for two-step) finishCustomRegistration, // Called when customRegistration finishes and a final response should be given - - // Authentication - nextAuthenticationAttempt, // Called to attempt next authentication. } extension OWActionExtension on OWAction { String get value { switch (this) { + // Browser Registration case OWAction.handleRegisteredUrl: return "handleRegisteredUrl"; - case OWAction.openAuthOtp: - return "openAuthOtp"; - case OWAction.openPinRegistration: - return "openPinRegistration"; + // Pin Creation + case OWAction.openPinCreation: + return "openPinCreation"; + case OWAction.closePinCreation: + return "closePinCreation"; + case OWAction.pinNotAllowed: + return "pinNotAllowed"; + // Pin Authentication case OWAction.openPinAuthentication: return "openPinAuthentication"; - case OWAction.openFingerprint: - return "openFingerprint"; - case OWAction.closeAuthOtp: - return "closeAuthOtp"; - case OWAction.closePinRegistration: - return "closePinRegistration"; case OWAction.closePinAuthentication: return "closePinAuthentication"; + case OWAction.nextPinAuthenticationAttempt: + return "nextPinAuthenticationAttempt"; + // Fingerprint authentication + case OWAction.openFingerprint: + return "openFingerprint"; case OWAction.closeFingerprint: return "closeFingerprint"; - case OWAction.pinNotAllowed: - return "pinNotAllowed"; case OWAction.showScanningFingerprint: return "showScanningFingerprint"; case OWAction.nextFingerprintAuthenticationAttempt: - return "receivedFingerprint"; + return "nextFingerprintAuthenticationAttempt"; + // OTP Mobile authentication + case OWAction.openAuthOtp: + return "openAuthOtp"; + case OWAction.closeAuthOtp: + return "closeAuthOtp"; + // Custom Registration case OWAction.initCustomRegistration: return "initCustomRegistration"; case OWAction.finishCustomRegistration: return "finishCustomRegistration"; - case OWAction.nextAuthenticationAttempt: - return "nextAuthenticationAttempt"; } } } diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index 1272a573..b9afc851 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -3,12 +3,12 @@ import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/pigeon.dart'; // For Pin Creation -class OpenPinRegistrationEvent extends OWEvent { - OpenPinRegistrationEvent() : super(OWAction.openPinRegistration); +class OpenPinCreationEvent extends OWEvent { + OpenPinCreationEvent() : super(OWAction.openPinCreation); } -class ClosePinRegistrationEvent extends OWEvent { - ClosePinRegistrationEvent() : super(OWAction.closePinRegistration); +class ClosePinCreationEvent extends OWEvent { + ClosePinCreationEvent() : super(OWAction.closePinCreation); } class PinNotAllowedEvent extends OWEvent { @@ -25,7 +25,7 @@ class ClosePinAuthenticationEvent extends OWEvent { ClosePinAuthenticationEvent() : super(OWAction.closePinAuthentication); } -class NextAuthenticationAttemptEvent extends OWEvent { +class NextPinAuthenticationAttemptEvent extends OWEvent { OWAuthenticationAttempt authenticationAttempt; - NextAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextAuthenticationAttempt); + NextPinAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextPinAuthenticationAttempt); } diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 9979cfea..93d4c5fa 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -16,51 +16,50 @@ class OneginiEventListener implements NativeCallFlutterApi { /// Pin Creation related events @override - void n2fOpenPinRequestScreen() { + void n2fOpenPinCreation() { // renamed OpenPinRegistrationEvent to OpenPinCreationEvent - broadcastEvent(OpenPinRegistrationEvent()); + broadcastEvent(OpenPinCreationEvent()); } @override - void n2fClosePin() { + void n2fClosePinCreation() { // renamed ClosePinRegistrationEvent -> ClosePinCreationEvent - broadcastEvent(ClosePinRegistrationEvent()); + broadcastEvent(ClosePinCreationEvent()); } @override - void n2fEventPinNotAllowed(OWOneginiError error) { + void n2fPinNotAllowed(OWOneginiError error) { broadcastEvent(PinNotAllowedEvent(error)); } /// Custom Registration related events @override - void n2fEventFinishCustomRegistration( + void n2fEventInitCustomRegistration( OWCustomInfo? customInfo, String providerId) { - broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); + broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); } @override - void n2fEventInitCustomRegistration( + void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId) { - broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); + broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); } /// Pin Authentication related events @override - void n2fOpenPinScreenAuth() { + void n2fOpenPinAuthentication() { broadcastEvent(OpenPinAuthenticationEvent()); } @override - void n2fClosePinAuth() { + void n2fClosePinAuthentication() { broadcastEvent(ClosePinAuthenticationEvent()); } @override - void n2fNextAuthenticationAttempt( + void n2fNextPinAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt) { - // renamed from NextAuthenticationAttemptEvent to NextPinAuthenticationAttemptEvent - broadcastEvent(NextAuthenticationAttemptEvent(authenticationAttempt)); + broadcastEvent(NextPinAuthenticationAttemptEvent(authenticationAttempt)); } /// Fingerprint related events diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 3c707a62..09dffa9f 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -1370,47 +1370,54 @@ abstract class NativeCallFlutterApi { ///Called to handle registration URL void n2fHandleRegisteredUrl(String url); - /// Called to open OTP authentication. - void n2fOpenAuthOtp(String? message); + /// Called to open pin creation screen. + /// changed n2fOpenPinRequestScreen into n2fOpenPinCreation + void n2fOpenPinCreation(); - /// Called to close OTP authentication. - void n2fCloseAuthOtp(); + /// Called to close pin registration screen. + /// changed n2fClosePin into n2fClosePinCreation + void n2fClosePinCreation(); - /// Called to open pin registration screen. - void n2fOpenPinRequestScreen(); + /// Called to indicate that the given pin is not allowed for pin creation + /// changed n2fEventPinNotAllowed into n2fPinNotAllowed + void n2fPinNotAllowed(OWOneginiError error); /// Called to open pin authentication screen. - void n2fOpenPinScreenAuth(); + /// changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication + void n2fOpenPinAuthentication(); - /// Called to attempt next authentication. - void n2fNextAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); + /// Called to close pin authentication screen. + /// changed n2fClosePinAuth into n2fClosePinAuthentication + void n2fClosePinAuthentication(); - /// Called to close pin registration screen. - void n2fClosePin(); + /// Called to attempt next pin authentication. + /// changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt + void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); - /// Called to close pin authentication screen. - void n2fClosePinAuth(); + /// Called to open OTP authentication. + void n2fOpenAuthOtp(String? message); + + /// Called to close OTP authentication. + void n2fCloseAuthOtp(); /// Called to open fingerprint screen. void n2fOpenFingerprintScreen(); + /// Called to close fingerprint screen. + void n2fCloseFingerprintScreen(); + /// Called to scan fingerprint. void n2fShowScanningFingerprint(); /// Called when fingerprint was received. void n2fNextFingerprintAuthenticationAttempt(); - /// Called to close fingerprint screen. - void n2fCloseFingerprintScreen(); - /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); - void n2fEventPinNotAllowed(OWOneginiError error); - static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( @@ -1433,106 +1440,125 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinCreation', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); - final List args = (message as List?)!; - final String? arg_message = (args[0] as String?); - api.n2fOpenAuthOtp(arg_message); + // ignore message + api.n2fOpenPinCreation(); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinCreation', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fCloseAuthOtp(); + api.n2fClosePinCreation(); + return; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + channel.setMessageHandler(null); + } else { + channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); + final List args = (message as List?)!; + final OWOneginiError? arg_error = (args[0] as OWOneginiError?); + assert(arg_error != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null, expected non-null OWOneginiError.'); + api.n2fPinNotAllowed(arg_error!); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinRequestScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fOpenPinRequestScreen(); + api.n2fOpenPinAuthentication(); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinScreenAuth', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fOpenPinScreenAuth(); + api.n2fClosePinAuthentication(); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); final List args = (message as List?)!; final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); assert(arg_authenticationAttempt != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); - api.n2fNextAuthenticationAttempt(arg_authenticationAttempt!); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); + api.n2fNextPinAuthenticationAttempt(arg_authenticationAttempt!); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePin', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { - // ignore message - api.n2fClosePin(); + assert(message != null, + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + final List args = (message as List?)!; + final String? arg_message = (args[0] as String?); + api.n2fOpenAuthOtp(arg_message); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuth', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseAuthOtp', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fClosePinAuth(); + api.n2fCloseAuthOtp(); return; }); } @@ -1553,42 +1579,42 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fShowScanningFingerprint(); + api.n2fCloseFingerprintScreen(); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fNextFingerprintAuthenticationAttempt(); + api.n2fShowScanningFingerprint(); return; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { // ignore message - api.n2fCloseFingerprintScreen(); + api.n2fNextFingerprintAuthenticationAttempt(); return; }); } @@ -1633,24 +1659,5 @@ abstract class NativeCallFlutterApi { }); } } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); - } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed was null.'); - final List args = (message as List?)!; - final OWOneginiError? arg_error = (args[0] as OWOneginiError?); - assert(arg_error != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventPinNotAllowed was null, expected non-null OWOneginiError.'); - api.n2fEventPinNotAllowed(arg_error!); - return; - }); - } - } } } diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index e25903fd..a2a16d5c 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -259,43 +259,52 @@ abstract class ResourceMethodApi { /// Native calls to Flutter @FlutterApi() abstract class NativeCallFlutterApi { + // Browser Registration ///Called to handle registration URL void n2fHandleRegisteredUrl(String url); - /// Called to open OTP authentication. - void n2fOpenAuthOtp(String? message); + // Pin Creation + /// Called to open pin creation screen. + void n2fOpenPinCreation(); - /// Called to close OTP authentication. - void n2fCloseAuthOtp(); + /// Called to close pin registration screen. + void n2fClosePinCreation(); - /// Called to open pin registration screen. - void n2fOpenPinRequestScreen(); + /// Called to indicate that the given pin is not allowed for pin creation + void n2fPinNotAllowed(OWOneginiError error); + // Pin Authentication /// Called to open pin authentication screen. - void n2fOpenPinScreenAuth(); + void n2fOpenPinAuthentication(); - /// Called to attempt next authentication. - void n2fNextAuthenticationAttempt( + /// Called to close pin authentication screen. + void n2fClosePinAuthentication(); + + /// Called to attempt next pin authentication. + void n2fNextPinAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt); - /// Called to close pin registration screen. - void n2fClosePin(); + // OTP Mobile Authentication + /// Called to open OTP authentication. + void n2fOpenAuthOtp(String? message); - /// Called to close pin authentication screen. - void n2fClosePinAuth(); + /// Called to close OTP authentication. + void n2fCloseAuthOtp(); + // Fingerprint Authentication /// Called to open fingerprint screen. void n2fOpenFingerprintScreen(); + /// Called to close fingerprint screen. + void n2fCloseFingerprintScreen(); + /// Called to scan fingerprint. void n2fShowScanningFingerprint(); /// Called when fingerprint was received. void n2fNextFingerprintAuthenticationAttempt(); - /// Called to close fingerprint screen. - void n2fCloseFingerprintScreen(); - + // Custom Registration /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) void n2fEventInitCustomRegistration( OWCustomInfo? customInfo, String providerId); @@ -303,6 +312,4 @@ abstract class NativeCallFlutterApi { /// Called when the FinishCustomRegistration event occurs and a response should be given void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId); - - void n2fEventPinNotAllowed(OWOneginiError error); } From 4928ec843d0fa59f295aa5f6b9cea1390b8c37d2 Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 13 Apr 2023 15:05:07 +0200 Subject: [PATCH 262/364] fp-77 removed unused models due to pigeon rework and events rework --- lib/constants/constants.dart | 203 -------------------- lib/model/authentication_attempt.dart | 38 ---- lib/model/oneginiAppToWebSingleSignOn.dart | 32 --- lib/model/onegini_error.dart | 54 ------ lib/model/onegini_event.dart | 32 --- lib/model/onegini_list_response.dart | 38 ---- lib/model/onegini_removed_user_profile.dart | 38 ---- lib/model/registration_response.dart | 71 ------- lib/onegini.dart | 5 - lib/user_client.dart | 6 - 10 files changed, 517 deletions(-) delete mode 100644 lib/constants/constants.dart delete mode 100644 lib/model/authentication_attempt.dart delete mode 100644 lib/model/oneginiAppToWebSingleSignOn.dart delete mode 100644 lib/model/onegini_error.dart delete mode 100644 lib/model/onegini_event.dart delete mode 100644 lib/model/onegini_list_response.dart delete mode 100644 lib/model/onegini_removed_user_profile.dart delete mode 100644 lib/model/registration_response.dart diff --git a/lib/constants/constants.dart b/lib/constants/constants.dart deleted file mode 100644 index 341ea317..00000000 --- a/lib/constants/constants.dart +++ /dev/null @@ -1,203 +0,0 @@ -import '../model/onegini_error.dart'; - -/// The class with constant values. -/// -/// Contains names of methods that Flutter calls on native code, and events that comes back to Flutter. -class Constants { - //#region Onegini methods - - /// Start app method name - static const String startAppMethod = 'startApp'; - - // Registration - - /// Register user method name - static const String registerUser = 'registerUser'; - static const String handleRegisteredUserUrl = 'handleRegisteredUserUrl'; - static const String cancelRegistrationMethod = "cancelBrowserRegistration"; - - /// Get identity providers method name - static const String getIdentityProvidersMethod = "getIdentityProviders"; - - /// Accept pin registration request method name - static const String acceptPinRegistrationRequest = - "acceptPinRegistrationRequest"; - - /// Deny pin registration request method name - static const String denyPinRegistrationRequest = "denyPinRegistrationRequest"; - - /// Deregister user method name - static const String deregisterUserMethod = "deregisterUser"; - - // Authentication - - /// Authenticate user method name - static const String authenticateUser = 'authenticateUser'; - - /// Get all not registered authenticators method name - static const String getAllNotRegisteredAuthenticators = - "getAllNotRegisteredAuthenticators"; - - /// Get registered authenticators method name - static const String getRegisteredAuthenticators = - "getRegisteredAuthenticators"; - - /// Get all authenticators method name - static const String getAllAuthenticators = "getAllAuthenticators"; - - /// Register authenticator method name - static const String registerAuthenticator = "registerAuthenticator"; - - /// Accept pin authentication request method name - static const String acceptPinAuthenticationRequest = - "acceptPinAuthenticationRequest"; - - /// Deny pin authentication request method name - static const String denyPinAuthenticationRequest = - "denyPinAuthenticationRequest"; - - /// Logout method name - static const String logout = 'logout'; - static const String setPreferredAuthenticator = "setPreferredAuthenticator"; - static const String deregisterAuthenticator = "deregisterAuthenticator"; - - // Fingerprint - - /// Accept fingerprint authentication request method name - static const String acceptFingerprintAuthenticationRequest = - 'acceptFingerprintAuthenticationRequest'; - - /// Deny fingerprint authentication request method name - static const String denyFingerprintAuthenticationRequest = - "denyFingerprintAuthenticationRequest"; - - /// Fingerprint fallback to pin method name - static const String fingerprintFallbackToPin = "fingerprintFallbackToPin"; - - // OTP - - /// Handle mobile auth with OTP method name - static const String handleMobileAuthWithOtp = "handleMobileAuthWithOtp"; - - /// Accept OTP authentication request method name - static const String acceptOtpAuthenticationRequest = - "acceptOtpAuthenticationRequest"; - - /// Deny OTP authentication request method name - static const String denyOtpAuthenticationRequest = - "denyOtpAuthenticationRequest"; - - // Resources - - /// Get resource method name - static const String getResource = "getResource"; - - /// Get resource anonymous method name - static const String getResourceAnonymous = "getResourceAnonymous"; - - /// Get implicit resource method name - static const String getImplicitResource = "getImplicitResource"; - - /// Get unauthenticated resource method name - static const String getUnauthenticatedResource = "getUnauthenticatedResource"; - - static const String authenticateUserImplicitly = "authenticateUserImplicitly"; - - static const String authenticateDevice = "authenticateDevice"; - - // Other - - /// Get app to web single sign on method name - static const String getAppToWebSingleSignOn = "getAppToWebSingleSignOn"; - static const String getAccessToken = "getAccessToken"; - static const String getRedirectUrl = "getRedirectUrl"; - static const String getAuthenticatedUserProfile = - "getAuthenticatedUserProfile"; - - /// Change pin method name - static const String changePin = "changePin"; - static const String validatePinWithPolicy = "validatePinWithPolicy"; - - /// Get User Profiles - static const String getUserProfiles = "getUserProfiles"; - - // CustomRegistration - // Submit CustomRegistration Action success method - static const String submitCustomRegistrationAction = - "submitCustomRegistrationAction"; - - // Submit CustomRegistration Action error method to cancel custom registration - static const String cancelCustomRegistrationAction = - "cancelCustomRegistrationAction"; - - //#endregion Onegini methods - - //#region Onegini events - - // Pin - - /// Open pin event name - static const String eventOpenPin = "eventOpenPin"; - - /// Open pin auth event name - static const String eventOpenPinAuth = "eventOpenPinAuth"; - - /// Open pin authenticator event name - static const String eventOpenPinAuthenticator = "eventOpenPinAuthenticator"; - - /// Close pin event name - static const String eventClosePin = "eventClosePin"; - - /// Close pin auth event name - static const String eventClosePinAuth = "eventClosePinAuth"; - - /// Next authentication attempt event name - static const String eventNextAuthenticationAttempt = - "eventNextAuthenticationAttempt"; - - ///Handle url for registration - static const String eventHandleRegisteredUrl = "eventHandleRegisteredUrl"; - - // Fingerprint - - /// Open fingerprint auth event name - static const String eventOpenFingerprintAuth = "eventOpenFingerprintAuth"; - - /// Received fingerprint auth event name - static const String eventReceivedFingerprintAuth = - "eventReceivedFingerprintAuth"; - - /// Show scanning fingerprint auth event name - static const String eventShowScanningFingerprintAuth = - "eventShowScanningFingerprintAuth"; - - /// Close fingerprint auth event name - static const String eventCloseFingerprintAuth = "eventCloseFingerprintAuth"; - - // OTP - - /// Open auth OTP event name - static const String eventOpenAuthOTP = "eventOpenAuthOtp"; - - /// Cancel auth OTP event name - static const String eventCancelAuthOTP = "eventCancelAuthOtp"; - - /// Close auth OTP event name - static const String eventCloseAuthOTP = "eventCloseAuthOtp"; - - // Custom events - - /// Event triggered by the initRegistration needs to be responded (only used by two-step) - static const String eventInitCustomRegistration = "eventInitCustomRegistration"; - - /// Event triggered by the finishRegistration needs to be responded - static const String eventFinishCustomRegistration = "eventFinishCustomRegistration"; - - // Error codes - - //When the native type does not correspond with the expected dart type - static OneginiError wrapperTypeError = OneginiError( - message: "The native sdk returned an unexpected type", code: 8019); - -//#endregion Onegini events -} diff --git a/lib/model/authentication_attempt.dart b/lib/model/authentication_attempt.dart deleted file mode 100644 index 97b44e95..00000000 --- a/lib/model/authentication_attempt.dart +++ /dev/null @@ -1,38 +0,0 @@ -// To parse this JSON data, do -// -// final authenticationAttempt = authenticationAttemptFromJson(jsonString); - -import 'dart:convert'; - -/// Parse json to AuthenticationAttempt -AuthenticationAttempt authenticationAttemptFromJson(String str) => - AuthenticationAttempt.fromJson(json.decode(str)); - -/// Parse AuthenticationAttempt to json -String authenticationAttemptToJson(AuthenticationAttempt data) => - json.encode(data.toJson()); - -class AuthenticationAttempt { - AuthenticationAttempt( - {this.failedAttempts, this.maxAttempts, this.remainingAttempts}); - - /// Number of failed attempts - int? failedAttempts; - - /// Number of maximum attempts - int? maxAttempts; - - int? remainingAttempts; - - factory AuthenticationAttempt.fromJson(Map json) => - AuthenticationAttempt( - failedAttempts: json["failedAttempts"], - maxAttempts: json["maxAttempts"], - remainingAttempts: json["remainingAttempts"]); - - Map toJson() => { - "failedAttempts": failedAttempts, - "maxAttempts": maxAttempts, - "remainingAttempts": remainingAttempts - }; -} diff --git a/lib/model/oneginiAppToWebSingleSignOn.dart b/lib/model/oneginiAppToWebSingleSignOn.dart deleted file mode 100644 index 525ef460..00000000 --- a/lib/model/oneginiAppToWebSingleSignOn.dart +++ /dev/null @@ -1,32 +0,0 @@ -// To parse this JSON data, do -// -// final oneginiAppToWebSingleSignOn = oneginiAppToWebSingleSignOnFromJson(jsonString); - -import 'dart:convert'; - -OneginiAppToWebSingleSignOn oneginiAppToWebSingleSignOnFromJson(String str) => - OneginiAppToWebSingleSignOn.fromJson(json.decode(str)); - -String oneginiAppToWebSingleSignOnToJson(OneginiAppToWebSingleSignOn data) => - json.encode(data.toJson()); - -class OneginiAppToWebSingleSignOn { - OneginiAppToWebSingleSignOn({ - this.token, - this.redirectUrl, - }); - - String? token; - String? redirectUrl; - - factory OneginiAppToWebSingleSignOn.fromJson(Map json) => - OneginiAppToWebSingleSignOn( - token: json["token"], - redirectUrl: json["redirectUrl"], - ); - - Map toJson() => { - "token": token, - "redirectUrl": redirectUrl, - }; -} diff --git a/lib/model/onegini_error.dart b/lib/model/onegini_error.dart deleted file mode 100644 index 44f2ab72..00000000 --- a/lib/model/onegini_error.dart +++ /dev/null @@ -1,54 +0,0 @@ -// To parse this JSON data, do -// -// final authenticationAttempt = authenticationAttemptFromJson(jsonString); - -import 'dart:convert'; - -/// Parse json to OneginiError -OneginiError oneginiErrorFromJson(dynamic data) { - var value; - - if (data is Map) { - return OneginiError.fromJson(data); - } - - try { - value = json.decode(data); - } catch (error) { - print("can't decode error"); - } - if (value != null) { - return OneginiError.fromJson(value); - } else { - var error = OneginiError(); - error.code = 8001; - error.message = data; - return error; - } -} - -/// Parse OneginiError to json -String oneginiErrorToJson(OneginiError data) => json.encode(data.toJson()); - -class OneginiError { - OneginiError({ - this.message, - this.code, - }); - - /// Error message - String? message; - - /// Error code - int? code; - - factory OneginiError.fromJson(Map json) => OneginiError( - message: json["message"], - code: json["code"] is int ? json["code"] : int.parse(json["code"]), - ); - - Map toJson() => { - "message": message, - "code": code, - }; -} diff --git a/lib/model/onegini_event.dart b/lib/model/onegini_event.dart deleted file mode 100644 index 320548f0..00000000 --- a/lib/model/onegini_event.dart +++ /dev/null @@ -1,32 +0,0 @@ -import 'dart:convert'; - -/// Parse json to Event -Event eventFromJson(String str) => Event.fromJson(json.decode(str)); - -/// Parse Event to json -String eventToJson(Event data) => json.encode(data.toJson()); - -class Event { - Event({ - this.eventName, - this.eventValue, - }); - - /// Event name - String? eventName; - - /// Event value - dynamic eventValue; - - factory Event.fromJson(Map json) => Event( - eventName: json["eventName"].toString(), - eventValue: json["eventValue"] is Map - ? json["eventValue"] - : json["eventValue"].toString(), - ); - - Map toJson() => { - "eventName": eventName, - "eventValue": eventValue, - }; -} diff --git a/lib/model/onegini_list_response.dart b/lib/model/onegini_list_response.dart deleted file mode 100644 index e909999d..00000000 --- a/lib/model/onegini_list_response.dart +++ /dev/null @@ -1,38 +0,0 @@ -// To parse this JSON data, do -// -// final provider = providerFromJson(jsonString); - -import 'dart:convert'; - -/// Parse json to list of Onegini response -List responseFromJson(String str) => - List.from( - json.decode(str).map((x) => OneginiListResponse.fromJson(x))); - -/// Parse Onegini response list to json -String responseToJson(List data) => - json.encode(List.from(data.map((x) => x.toJson()))); - -class OneginiListResponse { - OneginiListResponse({ - this.id, - this.name, - }); - - /// Response list ic - String? id; - - /// Response list name - String? name; - - factory OneginiListResponse.fromJson(Map json) => - OneginiListResponse( - id: json["id"], - name: json["name"], - ); - - Map toJson() => { - "id": id, - "name": name, - }; -} diff --git a/lib/model/onegini_removed_user_profile.dart b/lib/model/onegini_removed_user_profile.dart deleted file mode 100644 index df32dab0..00000000 --- a/lib/model/onegini_removed_user_profile.dart +++ /dev/null @@ -1,38 +0,0 @@ -// To parse this JSON data, do -// -// final provider = providerFromJson(jsonString); - -import 'dart:convert'; - -/// Parse json to RemovedUserProfile -List removedUserProfileListFromJson(String str) => - List.from( - json.decode(str).map((x) => RemovedUserProfile.fromJson(x))); - -/// Parse RemovedUserProfile to json -String removedUserProfileListToJson(List data) => - json.encode(List.from(data.map((x) => x.toJson()))); - -class RemovedUserProfile { - RemovedUserProfile({ - this.isDefault, - this.profileId, - }); - - /// Is removed profile defaule - bool? isDefault; - - /// Removed profile id - String? profileId; - - factory RemovedUserProfile.fromJson(Map json) => - RemovedUserProfile( - isDefault: json["isDefault"], - profileId: json["profileId"], - ); - - Map toJson() => { - "isDefault": isDefault, - "profileId": profileId, - }; -} diff --git a/lib/model/registration_response.dart b/lib/model/registration_response.dart deleted file mode 100644 index bbac1bb9..00000000 --- a/lib/model/registration_response.dart +++ /dev/null @@ -1,71 +0,0 @@ -// To parse this JSON data, do -// -// final registrationResponse = registrationResponseFromJson(jsonString); - -import 'dart:convert'; - -RegistrationResponse registrationResponseFromJson(String str) => - RegistrationResponse.fromJson(json.decode(str)); - -String registrationResponseToJson(RegistrationResponse data) => - json.encode(data.toJson()); - -class RegistrationResponse { - RegistrationResponse({ - this.userProfile, - this.customInfo, - }); - - UserProfile? userProfile; - CustomInfo? customInfo; - - factory RegistrationResponse.fromJson(Map json) => - RegistrationResponse( - userProfile: UserProfile.fromJson(json["userProfile"]), - customInfo: CustomInfo.fromJson(json["customInfo"]), - ); - - Map toJson() => { - "userProfile": userProfile?.toJson(), - "customInfo": customInfo?.toJson(), - }; -} - -class CustomInfo { - CustomInfo({ - this.status, - this.data, - }); - - int? status; - String? data; - - factory CustomInfo.fromJson(Map? json) => CustomInfo( - status: json?["status"], - data: json?["data"], - ); - - Map toJson() => { - "status": status, - "data": data, - }; -} - -UserProfile userProfileFromJson(String str) => - UserProfile.fromJson(json.decode(str)); - -class UserProfile { - UserProfile({ - this.isDefault, - this.profileId, - }); - - String? profileId; - bool? isDefault; - - factory UserProfile.fromJson(Map json) => - UserProfile(profileId: json["profileId"], isDefault: json["isDefault"]); - - Map toJson() => - {"profileId": profileId, "isDefault": isDefault}; -} diff --git a/lib/onegini.dart b/lib/onegini.dart index 707567bc..ebfbf324 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -1,16 +1,11 @@ import 'dart:async'; -import 'dart:convert'; -import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:onegini/constants/constants.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/resources_methods.dart'; import 'package:onegini/user_client.dart'; import 'package:onegini/pigeon.dart'; -import 'model/onegini_removed_user_profile.dart'; - /// The main class used to call methods. class Onegini { // UserClientApi is the flutter to native api created by the Pigeon package, see /pigeons/README.md diff --git a/lib/user_client.dart b/lib/user_client.dart index 9b28d1cb..6abea88e 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,14 +1,8 @@ import 'dart:async'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/pigeon.dart'; -import 'constants/constants.dart'; -import 'onegini.dart'; - ///Сlass with basic methods available to the developer. class UserClient { final UserClientApi api; From 32acaf4893728e7e640d94e2f8a417e67ede6411 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 10:30:16 +0200 Subject: [PATCH 263/364] FP-65: Update api + add in example app --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 2 +- .../mobile/sdk/flutter/PigeonInterface.kt | 20 +- .../OWAuthenticatorTypeExtension.kt | 3 +- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 15 +- .../useCases/AuthenticateUserUseCase.kt | 4 +- ...kt => GetBiometricAuthenticatorUseCase.kt} | 13 +- ...BiometricAuthenticatorRegisteredUseCase.kt | 20 - example/lib/components/display_toast.dart | 5 +- example/lib/screens/login_screen.dart | 3 +- example/lib/screens/user_screen.dart | 379 ++++++++---------- ios/Classes/Pigeon.swift | 21 +- lib/pigeon.dart | 13 +- lib/user_client.dart | 27 +- pigeons/onewelcome_pigeon_interface.dart | 8 +- 14 files changed, 227 insertions(+), 306 deletions(-) rename android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/{IsBiometricAuthenticatorAvailableUseCase.kt => GetBiometricAuthenticatorUseCase.kt} (55%) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 8bf59265..564edb1c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -7,7 +7,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8043, "Biometric authentication is supported on this device"), + BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8043, "Biometric authentication is not supported on this device"), REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 28e75142..f41c981e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -30,14 +30,13 @@ import com.onegini.mobile.sdk.flutter.useCases.FingerprintFallbackToPinUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAccessTokenUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAppToWebSingleSignOnUseCase import com.onegini.mobile.sdk.flutter.useCases.GetAuthenticatedUserProfileUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetBiometricAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase import com.onegini.mobile.sdk.flutter.useCases.GetPreferredAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase import com.onegini.mobile.sdk.flutter.useCases.GetUserProfilesUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleMobileAuthWithOtpUseCase import com.onegini.mobile.sdk.flutter.useCases.HandleRegisteredUrlUseCase -import com.onegini.mobile.sdk.flutter.useCases.IsBiometricAuthenticatorAvailableUseCase -import com.onegini.mobile.sdk.flutter.useCases.IsBiometricAuthenticatorRegisteredUseCase import com.onegini.mobile.sdk.flutter.useCases.LogoutUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpAcceptAuthenticationRequestUseCase import com.onegini.mobile.sdk.flutter.useCases.OtpDenyAuthenticationRequestUseCase @@ -105,12 +104,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase - @Inject - lateinit var isBiometricAuthenticatorRegisteredUseCase: IsBiometricAuthenticatorRegisteredUseCase - - @Inject - lateinit var isBiometricAuthenticatorAvailableUseCase: IsBiometricAuthenticatorAvailableUseCase - @Inject lateinit var logoutUseCase: LogoutUseCase @@ -159,6 +152,9 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var fingerprintFallbackToPinUseCase: FingerprintFallbackToPinUseCase + @Inject + lateinit var getBiometricAuthenticatorUseCase: GetBiometricAuthenticatorUseCase + @Inject lateinit var resourceRequestUseCase: ResourceRequestUseCase @@ -222,12 +218,12 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { authenticateUserUseCase(profileId, authenticatorType, callback) } - override fun isBiometricAuthenticatorRegistered(profileId: String, callback: (Result) -> Unit) { - isBiometricAuthenticatorRegisteredUseCase(profileId, callback) + override fun authenticateUserPreferred(profileId: String, callback: (Result) -> Unit) { + authenticateUserUseCase(profileId, null, callback) } - override fun isBiometricAuthenticatorAvailable(profileId: String, callback: (Result) -> Unit) { - isBiometricAuthenticatorAvailableUseCase(profileId, callback) + override fun getBiometricAuthenticator(profileId: String, callback: (Result) -> Unit) { + getBiometricAuthenticatorUseCase(profileId, callback) } override fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt index 69ca14af..704a2f79 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/extensions/OWAuthenticatorTypeExtension.kt @@ -3,10 +3,9 @@ package com.onegini.mobile.sdk.flutter.extensions import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType -fun OWAuthenticatorType.toOneginiInt(): Int? { +fun OWAuthenticatorType.toOneginiInt(): Int { return when (this) { OWAuthenticatorType.PIN -> OneginiAuthenticator.PIN OWAuthenticatorType.BIOMETRIC -> OneginiAuthenticator.FINGERPRINT - OWAuthenticatorType.PREFERRED -> null } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index d337ef83..ec9eb77e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -58,8 +58,7 @@ enum class HttpRequestMethod(val raw: Int) { enum class OWAuthenticatorType(val raw: Int) { PIN(0), - BIOMETRIC(1), - PREFERRED(2); + BIOMETRIC(1); companion object { fun ofRaw(raw: Int): OWAuthenticatorType? { @@ -440,8 +439,8 @@ interface UserClientApi { fun deregisterUser(profileId: String, callback: (Result) -> Unit) fun getAuthenticatedUserProfile(callback: (Result) -> Unit) fun authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) - fun isBiometricAuthenticatorRegistered(profileId: String, callback: (Result) -> Unit) - fun isBiometricAuthenticatorAvailable(profileId: String, callback: (Result) -> Unit) + fun authenticateUserPreferred(profileId: String, callback: (Result) -> Unit) + fun getBiometricAuthenticator(profileId: String, callback: (Result) -> Unit) fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) fun deregisterBiometricAuthenticator(callback: (Result) -> Unit) @@ -625,12 +624,12 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.authenticateUserPreferred", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List val profileIdArg = args[0] as String - api.isBiometricAuthenticatorRegistered(profileIdArg) { result: Result -> + api.authenticateUserPreferred(profileIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -645,12 +644,12 @@ interface UserClientApi { } } run { - val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable", codec) + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator", codec) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List val profileIdArg = args[0] as String - api.isBiometricAuthenticatorAvailable(profileIdArg) { result: Result -> + api.getBiometricAuthenticator(profileIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index a9c8ab3c..a16de134 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -21,7 +21,7 @@ class AuthenticateUserUseCase @Inject constructor( private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase ) { - operator fun invoke(profileId: String, authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { + operator fun invoke(profileId: String, authenticatorType: OWAuthenticatorType?, callback: (Result) -> Unit) { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { @@ -29,7 +29,7 @@ class AuthenticateUserUseCase @Inject constructor( } val authenticator = oneginiSDK.oneginiClient.userClient.getRegisteredAuthenticators(userProfile) - .find { it.type == authenticatorType.toOneginiInt() } + .find { it.type == authenticatorType?.toOneginiInt() } authenticate(userProfile, authenticator, callback) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt similarity index 55% rename from android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt rename to android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt index 70b708d5..db354955 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorAvailableUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt @@ -5,16 +5,19 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTI import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject -class IsBiometricAuthenticatorAvailableUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(profileId: String, callback: (Result) -> Unit) { +class GetBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { + operator fun invoke(profileId: String, callback: (Result) -> Unit) { val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } - ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) + val authenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) + + return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC))) - callback(Result.success(true)) } } \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt deleted file mode 100644 index dedd60db..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/IsBiometricAuthenticatorRegisteredUseCase.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import javax.inject.Inject - -class IsBiometricAuthenticatorRegisteredUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(profileId: String, callback: (Result) -> Unit) { - val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } - ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) - val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - val biometricAuthenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } - ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) - - callback(Result.success(biometricAuthenticator.isRegistered)) - } -} \ No newline at end of file diff --git a/example/lib/components/display_toast.dart b/example/lib/components/display_toast.dart index 83b1eca3..3b986064 100644 --- a/example/lib/components/display_toast.dart +++ b/example/lib/components/display_toast.dart @@ -1,9 +1,10 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; -void showFlutterToast(String message) { +void showFlutterToast(String? message) { Fluttertoast.showToast( - msg: message, + msg: message ?? "No message in error", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 4, diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 416242bc..e1b31b85 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -224,8 +224,7 @@ class _LoginScreenState extends State { .data .first ?.profileId, - OWAuthenticatorType - .preferred); + null); }, child: Text( 'Preferred authenticator'), diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 9917a141..9eeb8a65 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'dart:convert'; import "package:collection/collection.dart"; @@ -19,7 +18,7 @@ import 'login_screen.dart'; class UserScreen extends StatefulWidget { final String userProfileId; - const UserScreen({Key key, this.userProfileId}) : super(key: key); + const UserScreen({Key? key, required this.userProfileId}) : super(key: key); @override _UserScreenState createState() => _UserScreenState(); @@ -27,10 +26,9 @@ class UserScreen extends StatefulWidget { class _UserScreenState extends State with RouteAware { int _currentIndex = 0; - List _children; - bool isContainNotRegisteredAuthenticators = true; - List registeredAuthenticators = []; - List notRegisteredAuthenticators = []; + late List _children; + OWAuthenticator? _biometricAuthenticator = null; + OWAuthenticator? _preferredAuthenticator = null; String profileId = ""; void onTabTapped(int index) { @@ -49,24 +47,31 @@ class _UserScreenState extends State with RouteAware { ]; super.initState(); this.profileId = widget.userProfileId; - // getAuthenticators(); + getAuthenticators(); } - @override - void didChangeDependencies() { - super.didChangeDependencies(); - routeObserver.subscribe(this, ModalRoute.of(context)); - } - - @override - void dispose() { - routeObserver.unsubscribe(this); - super.dispose(); - } + getAuthenticators() async { + try { + final preferredAuthenticator = await Onegini.instance.userClient + .getPreferredAuthenticator(profileId); + setState(() { + _preferredAuthenticator = preferredAuthenticator; + }); + } on PlatformException catch (err) { + showFlutterToast(err.message); + } - @override - void didPopNext() { - // getAuthenticators(); + try { + final biometricAuthenticator = await Onegini.instance.userClient + .getBiometricAuthenticator(profileId); + setState(() { + _biometricAuthenticator = biometricAuthenticator; + }); + } on PlatformException catch (err) { + if (err.code != "8043") { + showFlutterToast(err.message); + } + } } logOut(BuildContext context) async { @@ -82,79 +87,7 @@ class _UserScreenState extends State with RouteAware { ); } - // Future getAuthenticators() async { - // notRegisteredAuthenticators = await Onegini.instance.userClient - // .getNotRegisteredAuthenticators(context, this.profileId); - - // registeredAuthenticators = await Onegini.instance.userClient - // .getRegisteredAuthenticators(context, this.profileId); - // } - - // Future> getAllSortAuthenticators() async { - // var allAuthenticators = await Onegini.instance.userClient - // .getAllAuthenticators(context, this.profileId); - // allAuthenticators.sort((a, b) { - // return compareAsciiUpperCase(a.name, b.name); - // }); - // return allAuthenticators; - // } - - // Future> getNotRegisteredAuthenticators() async { - // var authenticators = await Onegini.instance.userClient - // .getNotRegisteredAuthenticators(context, this.profileId); - // return authenticators; - // } - - // registerAuthenticator(String authenticatorId) async { - // await Onegini.instance.userClient - // .registerAuthenticator(context, authenticatorId) - // .catchError((error) { - // if (error is PlatformException) { - // showFlutterToast(error.message); - // } - // }); - // await getAuthenticators(); - // setState(() {}); - // } - - // bool isRegisteredAuthenticator(String authenticatorId) { - // for (var authenticator in registeredAuthenticators) { - // if (authenticator.id == authenticatorId) return true; - // } - // return false; - // } - - // deregisterAuthenticator(String authenticatorId) async { - // await Onegini.instance.userClient - // .deregisterAuthenticator(context, authenticatorId) - // .catchError((error) { - // if (error is PlatformException) { - // showFlutterToast(error.message); - // } - // }); - // await getAuthenticators(); - // setState(() {}); - // } - - // setPreferredAuthenticator(String authenticatorId) async { - // await Onegini.instance.userClient - // .setPreferredAuthenticator(context, authenticatorId) - // .catchError((error) { - // if (error is PlatformException) { - // showFlutterToast(error.message); - // } - // }); - // Navigator.pop(context); - // } - deregister(BuildContext context) async { - Navigator.pop(context); - var profiles = await Onegini.instance.userClient.getUserProfiles(); - var profileId = profiles.first?.profileId; - if (profileId == null) { - return; - } - await Onegini.instance.userClient .deregisterUser(profileId) .catchError((error) { @@ -188,6 +121,60 @@ class _UserScreenState extends State with RouteAware { }); } + Widget biometricAuthenticatorWidget() { + final authenticator = _biometricAuthenticator; + if (authenticator != null) { + return ListTile( + title: Text(authenticator.name), + leading: Switch( + value: authenticator.isRegistered, + onChanged: (newValue) => { + if (newValue) + { + Onegini.instance.userClient + .registerBiometricAuthenticator(context) + .whenComplete(() => getAuthenticators()) + } + else + { + Onegini.instance.userClient + .deregisterBiometricAuthenticator() + .whenComplete(() => getAuthenticators()) + } + }), + ); + } + return SizedBox.shrink(); + } + + Widget preferredAuthenticatorSelectorWidget() { + final biometricAuthenticator = _biometricAuthenticator; + return PopupMenuButton( + child: ListTile( + title: Text("set preferred authenticator"), + leading: Icon(Icons.add_to_home_screen), + ), + onSelected: (value) { + Onegini.instance.userClient + .setPreferredAuthenticator(value) + .whenComplete(() => getAuthenticators()); + }, + itemBuilder: (context) { + return [ + PopupMenuItem( + child: Text("Pin"), + value: OWAuthenticatorType.pin, + ), + if (biometricAuthenticator != null && + biometricAuthenticator.isRegistered) + PopupMenuItem( + child: Text(biometricAuthenticator.name), + value: OWAuthenticatorType.biometric, + ), + ]; + }); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -209,58 +196,21 @@ class _UserScreenState extends State with RouteAware { DrawerHeader( child: Container(), ), - // FutureBuilder>( - // future: getAllSortAuthenticators(), - // builder: (BuildContext context, snapshot) { - // return ListView.builder( - // shrinkWrap: true, - // itemCount: snapshot.hasData ? snapshot.data.length : 0, - // itemBuilder: (context, index) { - // return ListTile( - // title: Text( - // snapshot.data[index].name, - // ), - // leading: Switch( - // value: snapshot.data[index].name == "PIN" - // ? true - // : isRegisteredAuthenticator( - // snapshot.data[index].id), - // onChanged: snapshot.data[index].name == "PIN" - // ? null - // : (value) { - // value - // ? registerAuthenticator( - // snapshot.data[index].id) - // : deregisterAuthenticator( - // snapshot.data[index].id); - // }, - // ), - // ); - // }); - // }, - // ), - // FutureBuilder>( - // future: Onegini.instance.userClient - // .getRegisteredAuthenticators(context, this.profileId), - // builder: (BuildContext context, snapshot) { - // return PopupMenuButton( - // child: ListTile( - // title: Text("set preferred authenticator"), - // leading: Icon(Icons.add_to_home_screen), - // ), - // onSelected: (value) { - // setPreferredAuthenticator(value); - // }, - // itemBuilder: (context) { - // return snapshot.data - // .map((e) => PopupMenuItem( - // child: Text(e.name ?? ""), - // value: e.id, - // )) - // .toList(); - // }); - // }, - // ), + ListTile( + title: Text("Authenticators"), + leading: Icon(Icons.lock_rounded), + ), + ListTile( + title: Text("Pin"), + leading: Switch(value: true, onChanged: null), + ), + biometricAuthenticatorWidget(), + ListTile( + title: Text( + "Preferred Authenticator: ${_preferredAuthenticator?.name} "), + ), + preferredAuthenticatorSelectorWidget(), + Divider(), ListTile( title: Text("Change pin"), onTap: () => changePin(context), @@ -274,7 +224,7 @@ class _UserScreenState extends State with RouteAware { ListTile( title: Text("Deregister"), onTap: () => deregister(context), - leading: Icon(Icons.app_registration), + leading: Icon(Icons.delete), ) ], ), @@ -380,68 +330,52 @@ class Home extends StatelessWidget { return Container( child: Center( child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - getAppToWebSingleSignOn(context); - }, - child: Text('Single Sign On'), - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - enrollMobileAuthentication(); - }, - child: Text('Enroll for Mobile Authentication'), - ), - ElevatedButton( - onPressed: () { - authWithOpt(context); - }, - child: Text('Auth with opt'), - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - userProfiles(context); - }, - child: Text('User profiles'), - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - showAuthenticatedUserProfile(context); - }, - child: Text('Authenticated Userprofile'), - ), - ElevatedButton( - onPressed: () { - showAccessToken(context); - }, - child: Text('Access Token'), - ), - ElevatedButton( - onPressed: () { - performUnauthenticatedRequest(); - }, - child: Text('Perform Unauthenticated Request'), - ), - SizedBox( - height: 20, - ), - ], - ), + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () { + getAppToWebSingleSignOn(context); + }, + child: Text('Single Sign On'), + ), + ElevatedButton( + onPressed: () { + enrollMobileAuthentication(); + }, + child: Text('Enroll for Mobile Authentication'), + ), + ElevatedButton( + onPressed: () { + authWithOpt(context); + }, + child: Text('Auth with opt'), + ), + ElevatedButton( + onPressed: () { + userProfiles(context); + }, + child: Text('User profiles'), + ), + ElevatedButton( + onPressed: () { + showAuthenticatedUserProfile(context); + }, + child: Text('Authenticated Userprofile'), + ), + ElevatedButton( + onPressed: () { + showAccessToken(context); + }, + child: Text('Access Token'), + ), + ElevatedButton( + onPressed: () { + performUnauthenticatedRequest(); + }, + child: Text('Perform Unauthenticated Request'), + ), + ]), ), ); } @@ -450,7 +384,7 @@ class Home extends StatelessWidget { class Info extends StatefulWidget { final String userProfileId; - const Info({Key key, this.userProfileId}) : super(key: key); + const Info({Key? key, required this.userProfileId}) : super(key: key); @override _InfoState createState() => _InfoState(); @@ -505,7 +439,7 @@ class _InfoState extends State { style: TextStyle(fontSize: 18), ), Text( - snapshot.data.applicationIdentifier ?? "", + snapshot.data?.applicationIdentifier ?? "", style: TextStyle(fontSize: 18), ) ], @@ -520,7 +454,7 @@ class _InfoState extends State { style: TextStyle(fontSize: 18), ), Text( - snapshot.data.applicationPlatform ?? "", + snapshot.data?.applicationPlatform ?? "", style: TextStyle(fontSize: 18), ) ], @@ -535,7 +469,7 @@ class _InfoState extends State { style: TextStyle(fontSize: 18), ), Text( - snapshot.data.applicationVersion ?? "", + snapshot.data?.applicationVersion ?? "", style: TextStyle(fontSize: 18), ) ], @@ -552,38 +486,39 @@ class _InfoState extends State { child: FutureBuilder( future: getClientResource(), builder: (context, snapshot) { - return snapshot.hasData + final snapshotData = snapshot.data; + return snapshotData != null ? ListView.builder( - itemCount: snapshot.data.devices.length, + itemCount: snapshotData.devices.length, itemBuilder: (BuildContext context, int index) { return ExpansionTile( - title: Text(snapshot.data.devices[index].name), + title: Text(snapshotData.devices[index].name), expandedCrossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - "Id => ${snapshot.data.devices[index].id}", + "Id => ${snapshotData.devices[index].id}", style: TextStyle(fontSize: 18), ), SizedBox( height: 10, ), Text( - "Application => ${snapshot.data.devices[index].application}", + "Application => ${snapshotData.devices[index].application}", style: TextStyle(fontSize: 18), ), SizedBox( height: 10, ), Text( - "Mobile authentication enabled => ${snapshot.data.devices[index].mobileAuthenticationEnabled.toString()}", + "Mobile authentication enabled => ${snapshotData.devices[index].mobileAuthenticationEnabled.toString()}", style: TextStyle(fontSize: 18), ), SizedBox( height: 10, ), Text( - "Platform => ${snapshot.data.devices[index].platform}", + "Platform => ${snapshotData.devices[index].platform}", style: TextStyle(fontSize: 18), ), SizedBox( @@ -593,7 +528,11 @@ class _InfoState extends State { ); }, ) - : SizedBox.shrink(); + : Center( + child: SizedBox( + child: CircularProgressIndicator(), + ), + ); }, ), ), diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index 83f330c7..045457cc 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -44,7 +44,6 @@ enum HttpRequestMethod: Int { enum OWAuthenticatorType: Int { case pin = 0 case biometric = 1 - case preferred = 2 } enum ResourceRequestType: Int { @@ -406,8 +405,8 @@ protocol UserClientApi { func deregisterUser(profileId: String, completion: @escaping (Result) -> Void) func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) - func isBiometricAuthenticatorRegistered(profileId: String, completion: @escaping (Result) -> Void) - func isBiometricAuthenticatorAvailable(profileId: String, completion: @escaping (Result) -> Void) + func authenticateUserPreferred(profileId: String, completion: @escaping (Result) -> Void) + func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) @@ -571,12 +570,12 @@ class UserClientApiSetup { } else { authenticateUserChannel.setMessageHandler(nil) } - let isBiometricAuthenticatorRegisteredChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered", binaryMessenger: binaryMessenger, codec: codec) + let authenticateUserPreferredChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.authenticateUserPreferred", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - isBiometricAuthenticatorRegisteredChannel.setMessageHandler { message, reply in + authenticateUserPreferredChannel.setMessageHandler { message, reply in let args = message as! [Any] let profileIdArg = args[0] as! String - api.isBiometricAuthenticatorRegistered(profileId: profileIdArg) { result in + api.authenticateUserPreferred(profileId: profileIdArg) { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -586,14 +585,14 @@ class UserClientApiSetup { } } } else { - isBiometricAuthenticatorRegisteredChannel.setMessageHandler(nil) + authenticateUserPreferredChannel.setMessageHandler(nil) } - let isBiometricAuthenticatorAvailableChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable", binaryMessenger: binaryMessenger, codec: codec) + let getBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { - isBiometricAuthenticatorAvailableChannel.setMessageHandler { message, reply in + getBiometricAuthenticatorChannel.setMessageHandler { message, reply in let args = message as! [Any] let profileIdArg = args[0] as! String - api.isBiometricAuthenticatorAvailable(profileId: profileIdArg) { result in + api.getBiometricAuthenticator(profileId: profileIdArg) { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -603,7 +602,7 @@ class UserClientApiSetup { } } } else { - isBiometricAuthenticatorAvailableChannel.setMessageHandler(nil) + getBiometricAuthenticatorChannel.setMessageHandler(nil) } let getPreferredAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 64d7f9de..5aa8adec 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -18,7 +18,6 @@ enum HttpRequestMethod { enum OWAuthenticatorType { pin, biometric, - preferred, } enum ResourceRequestType { @@ -590,9 +589,9 @@ class UserClientApi { } } - Future isBiometricAuthenticatorRegistered(String arg_profileId) async { + Future authenticateUserPreferred(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorRegistered', codec, + 'dev.flutter.pigeon.UserClientApi.authenticateUserPreferred', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_profileId]) as List?; @@ -613,13 +612,13 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as bool?)!; + return (replyList[0] as OWRegistrationResponse?)!; } } - Future isBiometricAuthenticatorAvailable(String arg_profileId) async { + Future getBiometricAuthenticator(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.isBiometricAuthenticatorAvailable', codec, + 'dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_profileId]) as List?; @@ -640,7 +639,7 @@ class UserClientApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as bool?)!; + return (replyList[0] as OWAuthenticator?)!; } } diff --git a/lib/user_client.dart b/lib/user_client.dart index dbaf728b..934c6cd6 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -56,11 +56,14 @@ class UserClient { Future authenticateUser( BuildContext? context, String profileId, - OWAuthenticatorType authenticatorType, + OWAuthenticatorType? authenticatorType, ) async { Onegini.instance.setEventContext(context); - - return await api.authenticateUser(profileId, authenticatorType); + if (authenticatorType != null) { + return await api.authenticateUser(profileId, authenticatorType); + } else { + return await api.authenticateUserPreferred(profileId); + } } /// Starts change pin flow. @@ -74,26 +77,28 @@ class UserClient { ///Set preferred authenticator /// todo removed boolean return update docu Future setPreferredAuthenticator( - BuildContext? context, OWAuthenticatorType authenticatorType) async { - Onegini.instance.setEventContext(context); + OWAuthenticatorType authenticatorType) async { await api.setPreferredAuthenticator(authenticatorType); } // Gets the preferred authenticator for the given profile - Future getPreferredAuthenticator(String profileId) async { - await api.getPreferredAuthenticator(profileId); + Future getPreferredAuthenticator(String profileId) async { + return await api.getPreferredAuthenticator(profileId); } - Future deregisterBiometricAuthenticator( - OWAuthenticatorType authenticatorType) async { + Future deregisterBiometricAuthenticator() async { await api.deregisterBiometricAuthenticator(); } - Future registerBiometricAuthenticator( - OWAuthenticatorType authenticatorType) async { + Future registerBiometricAuthenticator(BuildContext context) async { + Onegini.instance.setEventContext(context); await api.registerBiometricAuthenticator(); } + Future getBiometricAuthenticator(String profileId) async { + return await api.getBiometricAuthenticator(profileId); + } + ///Method for log out /// todo removed boolean return update docu Future logout() async { diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 8ee0c2f4..4b6013ee 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -80,7 +80,6 @@ enum HttpRequestMethod { enum OWAuthenticatorType { pin, biometric, - preferred, } enum ResourceRequestType { authenticated, implicit, anonymous, unauthenticated } @@ -161,11 +160,14 @@ abstract class UserClientApi { OWRegistrationResponse authenticateUser( String profileId, OWAuthenticatorType authenticatorType); + // This api is currently required because pigeon does not allow nullable enums + // as arguments. This is a workaround for that so we still have the nullable + // enum in the user_client api. @async - bool isBiometricAuthenticatorRegistered(String profileId); + OWRegistrationResponse authenticateUserPreferred(String profileId); @async - bool isBiometricAuthenticatorAvailable(String profileId); + OWAuthenticator getBiometricAuthenticator(String profileId); @async OWAuthenticator getPreferredAuthenticator(String profileId); From 53385b5f366e48ab223a57695bb53224b56592d8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 10:55:41 +0200 Subject: [PATCH 264/364] FP-65: Implment biometric authenticator de/register --- .../NativeBridge/Errors/ErrorMapper.swift | 3 + .../Handlers/AuthenticatorsHandler.swift | 30 +++---- .../OneginiModuleSwift+Auth.swift | 12 ++- .../OneginiModuleSwift+Register.swift | 30 +------ ios/Classes/SwiftOneginiPlugin.swift | 81 +++++-------------- 5 files changed, 46 insertions(+), 110 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 2838e26a..7c453369 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -15,6 +15,7 @@ enum OneWelcomeWrapperError: Int { case authenticationNotInProgress = 8037 case otpAuthenticationNotInProgress = 8039 case browserRegistrationNotInProgress = 8040 + case biometricAuthenticationNotAvailable = 8043 // iOS only case providedUrlIncorrect = 8014 @@ -95,6 +96,8 @@ enum OneWelcomeWrapperError: Int { return "Mobile Authentication is already in progress and can not be performed concurrently." case .browserRegistrationNotInProgress: return "Browser registration is currently not in progress." + case .biometricAuthenticationNotAvailable: + return "Biometric authentication is not supported on this device." } } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 259e4ae1..bae6e6cd 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -2,8 +2,8 @@ import Foundation import OneginiSDKiOS protocol BridgeToAuthenticatorsHandlerProtocol { - func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) - func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func registerBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) + func deregisterBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) } @@ -13,30 +13,22 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { init(loginHandler: LoginHandler) { self.loginHandler = loginHandler } - func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) - return - } - + + + func registerBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { // We don't have to check if the authenticator is already registered as the sdk will do that for us. let authenticators = SharedUserClient.instance.authenticators(.all, for: profile) - guard let authenticator = authenticators.first(where: { $0.identifier == authenticatorId }) else { - completion(.failure(FlutterError(.authenticatorNotFound))) + guard let authenticator = authenticators.first(where: { $0.type == AuthenticatorType.biometric }) else { + completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) return } let delegate = AuthenticatorRegistrationDelegateImpl(loginHandler: loginHandler, completion: completion) SharedUserClient.instance.register(authenticator: authenticator, delegate: delegate) } - - func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { - completion(.failure(FlutterError(.authenticatorNotFound))) - return - } - - if authenticator.isRegistered != true { - completion(.failure(FlutterError(.authenticatorNotRegistered))) + + func deregisterBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: {$0.type == AuthenticatorType.biometric}) else { + completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) return } let delegate = AuthenticatorDeregistrationDelegateImpl(completion: completion) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 49e52e03..8e243b4e 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -53,12 +53,20 @@ extension OneginiModuleSwift { bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) } - func deregisterAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { + func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) -> Void { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - bridgeConnector.toAuthenticatorsHandler.deregisterAuthenticator(profile, identifierId, completion) + bridgeConnector.toAuthenticatorsHandler.deregisterBiometricAuthenticator(profile, completion) + } + + func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) -> Void { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + return + } + bridgeConnector.toAuthenticatorsHandler.registerBiometricAuthenticator(profile, completion) } func getAuthenticatedUserProfile() -> Result { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index fe0adc97..cef6f417 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -43,35 +43,7 @@ extension OneginiModuleSwift { public func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.cancelBrowserRegistration(completion) - } - - func registerAuthenticator(_ authenticatorId: String, completion: @escaping (Result) -> Void) { - bridgeConnector.toAuthenticatorsHandler.registerAuthenticator(authenticatorId, completion) - } - - func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { - guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) - } - let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) - return .success(registeredAuthenticators.compactMap { OWAuthenticator($0) }) - } - - func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { - guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) - } - let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) - return .success(notRegisteredAuthenticators.compactMap { OWAuthenticator($0) }) - } - - func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { - guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) - } - let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) - return .success(allAuthenticators.compactMap { OWAuthenticator($0) }) - } + } func getRedirectUrl() -> Result { return .success(ONGClient.sharedInstance().configModel.redirectURL) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index d70f8aca..25c66ccf 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -2,6 +2,7 @@ import Flutter import UIKit import OneginiSDKiOS +extension FlutterError: Error {} extension FlutterError { convenience init(_ error: OneWelcomeWrapperError) { @@ -34,16 +35,6 @@ extension OWCustomInfo { } } -extension OWAuthenticator { - init(_ authenticator: ONGAuthenticator) { - id = authenticator.identifier - name = authenticator.name - isPreferred = authenticator.isPreferred - isRegistered = authenticator.isRegistered - authenticatorType = Int64(authenticator.type.rawValue) - } -} - extension OWIdentityProvider { init(_ identityProvider: ONGIdentityProvider) { id = identityProvider.identifier @@ -80,31 +71,41 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { - <#code#> + OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorType: OWAuthenticatorType) { result in + completion(result.mapError { $0 }) + } } - func isBiometricAuthenticatorRegistered(completion: @escaping (Result) -> Void) { - <#code#> + func authenticateUserPreferred(profileId: String, completion: @escaping (Result) -> Void) { + OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorType: nil) { result in + completion(result.mapError { $0 }) + } } - func isBiometricAuthenticatorAvailable(completion: @escaping (Result) -> Void) { - <#code#> + func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { + } - func getPreferredAuthenticator(completion: @escaping (Result) -> Void) { - <#code#> + func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { + } func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { - <#code#> + OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(OWAuthenticatorType) { result in + completion(result.mapError { $0 }) + } } func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) { - <#code#> + OneginiModuleSwift.sharedInstance.deregisterBiometricAuthenticator() { result in + completion(result.mapError { $0 }) + } } func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) { - <#code#> + OneginiModuleSwift.sharedInstance.registerBiometricAuthenticator() { result in + completion(result.mapError { $0 }) + } } func startApplication(securityControllerClassName: String?, @@ -228,62 +229,22 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } } - func getRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getRegisteredAuthenticators(profileId).mapError { $0 }) - } - - func getAllAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getAllAuthenticators(profileId).mapError { $0 }) - } - func getAuthenticatedUserProfile(completion: @escaping (Result) -> Void) { completion(OneginiModuleSwift.sharedInstance.getAuthenticatedUserProfile().mapError { $0 }) } - func authenticateUser(profileId: String, registeredAuthenticatorId: String?, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorId: registeredAuthenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func getNotRegisteredAuthenticators(profileId: String, completion: @escaping (Result<[OWAuthenticator], Error>) -> Void) { - completion(OneginiModuleSwift.sharedInstance.getNotRegisteredAuthenticators(profileId).mapError { $0 }) - } - func changePin(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.changePin { result in completion(result.mapError { $0 }) } } - func setPreferredAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func deregisterAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.deregisterAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - - func registerAuthenticator(authenticatorId: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.registerAuthenticator(authenticatorId) { result in - completion(result.mapError { $0 }) - } - } - func logout(completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.logOut { result in completion(result.mapError { $0 }) } } - func mobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - - } - func getAppToWebSingleSignOn(url: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.runSingleSignOn(url) { result in completion(result.mapError { $0 }) From 5b8218c79f2c727e25f500c5eaae03f4f1b8e97c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 11:50:35 +0200 Subject: [PATCH 265/364] FP-65: implement authenticateUser and setPreferredAuthenticator --- .../Handlers/AuthenticatorsHandler.swift | 11 +++--- .../OneginiModuleSwift+Auth.swift | 14 +++---- .../OneginiModuleSwift+Register.swift | 2 +- ios/Classes/SwiftOneginiPlugin.swift | 37 ++++++++++++------- 4 files changed, 37 insertions(+), 27 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index bae6e6cd..54a6076d 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -4,7 +4,7 @@ import OneginiSDKiOS protocol BridgeToAuthenticatorsHandlerProtocol { func registerBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) func deregisterBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) - func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) + func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorType: AuthenticatorType, _ completion: @escaping (Result) -> Void) } class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { @@ -13,8 +13,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { init(loginHandler: LoginHandler) { self.loginHandler = loginHandler } - - + func registerBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { // We don't have to check if the authenticator is already registered as the sdk will do that for us. let authenticators = SharedUserClient.instance.authenticators(.all, for: profile) @@ -25,7 +24,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { let delegate = AuthenticatorRegistrationDelegateImpl(loginHandler: loginHandler, completion: completion) SharedUserClient.instance.register(authenticator: authenticator, delegate: delegate) } - + func deregisterBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { guard let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: {$0.type == AuthenticatorType.biometric}) else { completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) @@ -35,8 +34,8 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { SharedUserClient.instance.deregister(authenticator: authenticator, delegate: delegate) } - func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { + func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorType: AuthenticatorType, _ completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.type == authenticatorType}) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 8e243b4e..72d6fedf 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -32,36 +32,36 @@ extension OneginiModuleSwift { bridgeConnector.toAppToWebHandler.signInAppToWeb(targetURL: url, completion: completion) } - func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { + func authenticateUser(profileId: String, authenticatorType: AuthenticatorType?, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) return } - let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.identifier == authenticatorId }) + let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.type == authenticatorType }) bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in completion(result) } } - func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { + func setPreferredAuthenticator(_ authenticatorType: AuthenticatorType, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } - bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) + bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, authenticatorType, completion) } - func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) -> Void { + func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return } bridgeConnector.toAuthenticatorsHandler.deregisterBiometricAuthenticator(profile, completion) } - - func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) -> Void { + + func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) return diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index cef6f417..27e2ef68 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -43,7 +43,7 @@ extension OneginiModuleSwift { public func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) { bridgeConnector.toRegistrationHandler.cancelBrowserRegistration(completion) - } + } func getRedirectUrl() -> Result { return .success(ONGClient.sharedInstance().configModel.redirectURL) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 25c66ccf..b7e73804 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -51,6 +51,17 @@ extension OWRequestResponse { } } +extension OWAuthenticatorType { + func toOneginiType() -> AuthenticatorType { + switch self { + case .biometric: + return AuthenticatorType.biometric + case .pin: + return AuthenticatorType.pin + } + } +} + extension Result where Success == Void { public static var success: Result { .success(()) } } @@ -71,43 +82,43 @@ func toOWCustomInfo(_ info: ONGCustomInfo?) -> OWCustomInfo? { public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, ResourceMethodApi { func authenticateUser(profileId: String, authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorType: OWAuthenticatorType) { result in + OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorType: authenticatorType.toOneginiType()) { result in completion(result.mapError { $0 }) } } - + func authenticateUserPreferred(profileId: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.authenticateUser(profileId: profileId, authenticatorType: nil) { result in completion(result.mapError { $0 }) } } - + func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - + } - + func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - + } - + func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(OWAuthenticatorType) { result in + OneginiModuleSwift.sharedInstance.setPreferredAuthenticator(authenticatorType.toOneginiType()) { result in completion(result.mapError { $0 }) } } - + func deregisterBiometricAuthenticator(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.deregisterBiometricAuthenticator() { result in + OneginiModuleSwift.sharedInstance.deregisterBiometricAuthenticator { result in completion(result.mapError { $0 }) } } - + func registerBiometricAuthenticator(completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.registerBiometricAuthenticator() { result in + OneginiModuleSwift.sharedInstance.registerBiometricAuthenticator { result in completion(result.mapError { $0 }) } } - + func startApplication(securityControllerClassName: String?, configModelClassName: String?, customIdentityProviderConfigs: [OWCustomIdentityProvider]?, From c7a3084652ca231c89f87f0ece6d9775696690d5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 13:04:07 +0200 Subject: [PATCH 266/364] FP-65: Implement getPreferred/biometricAuthenticator --- .../Handlers/AuthenticatorsHandler.swift | 25 +++++++++++++++++++ .../OneginiModuleSwift+Auth.swift | 16 ++++++++++++ ios/Classes/SwiftOneginiPlugin.swift | 8 ++++-- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 54a6076d..8b8814f1 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -48,6 +48,31 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { SharedUserClient.instance.setPreferred(authenticator: authenticator) completion(.success) } + + func getBiometricAuthenticator(_ userProfile: UserProfile, completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.type == AuthenticatorType.biometric}) else { + completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) + return + } + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.biometric))) + } + + func getPreferredAuthenticator(_ userProfile: UserProfile, completion: @escaping (Result) -> Void) { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.isPreferred}) else { + completion(.failure(FlutterError(.authenticatorNotFound))) + return + } + if authenticator.type == AuthenticatorType.biometric { + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.biometric))) + return + } + if authenticator.type == AuthenticatorType.pin { + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.pin))) + return + } + // Should never happen because we don't support custom/fido authenticators + completion(.failure(FlutterError(.genericError))) + } } class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 72d6fedf..0ffd32df 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -69,6 +69,22 @@ extension OneginiModuleSwift { bridgeConnector.toAuthenticatorsHandler.registerBiometricAuthenticator(profile, completion) } + func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + return + } + bridgeConnector.toAuthenticatorsHandler.getBiometricAuthenticator(profile, completion: completion) + } + + func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { + guard let profile = SharedUserClient.instance.authenticatedUserProfile else { + completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + return + } + bridgeConnector.toAuthenticatorsHandler.getPreferredAuthenticator(profile, completion: completion) + } + func getAuthenticatedUserProfile() -> Result { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { return .failure(FlutterError(.noUserProfileIsAuthenticated)) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index b7e73804..e4bc6df5 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -94,11 +94,15 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.getBiometricAuthenticator(profileId: profileId) { result in + completion(result.mapError { $0 }) + } } func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - + OneginiModuleSwift.sharedInstance.getPreferredAuthenticator(profileId: profileId) { result in + completion(result.mapError { $0 }) + } } func setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, completion: @escaping (Result) -> Void) { From e3283c5657d12b256517028a34e7ba027b822558 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 13:46:10 +0200 Subject: [PATCH 267/364] FP-65: Add tests for GetPreferredAuthenticatorUseCaseTests --- .../GetPreferredAuthenticatorUseCase.kt | 5 +- .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 77 ------------- ...NotRegisteredAuthenticatorsUseCaseTests.kt | 99 ----------------- .../GetPreferredAuthenticatorUseCaseTests.kt | 105 ++++++++++++++++++ ...GetRegisteredAuthenticatorsUseCaseTests.kt | 103 ----------------- 5 files changed, 108 insertions(+), 281 deletions(-) delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt create mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt delete mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index ca582e6a..de0740fb 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -2,6 +2,7 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -12,7 +13,7 @@ import javax.inject.Inject class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(callback: (Result) -> Unit) { val authenticator = oneginiSDK.oneginiClient.userClient.preferredAuthenticator - ?: return callback(Result.failure(SdkError(OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED))) + ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) if (authenticator.type == OWAuthenticatorType.PIN.toOneginiInt()) { return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.PIN))) @@ -21,6 +22,6 @@ class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC))) } // This should never happen because we don't support CUSTOM/FIDO authenticators - return callback(Result.failure(SdkError(OneWelcomeWrapperErrors.GENERIC_ERROR).pigeonError())) + return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) } } \ No newline at end of file diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt deleted file mode 100644 index b7013c23..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ /dev/null @@ -1,77 +0,0 @@ -package com.onegini.mobile.sdk - -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import com.onegini.mobile.sdk.flutter.useCases.GetAllAuthenticatorsUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import junit.framework.Assert.fail -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetAllAuthenticatorsUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var oneginiAuthenticatorMock: OneginiAuthenticator - - - private lateinit var getAllAuthenticatorsUseCase: GetAllAuthenticatorsUseCase - - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - getAllAuthenticatorsUseCase = GetAllAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) - } - - @Test - fun `When an unknown or unregistered profileId is given, Then an error should be thrown`() { - val result = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) - } - - @Test - fun `When getAllAuthenticators method return empty set, Then the function should return empty`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(UserProfile("QWERTY"))).thenReturn(emptySet()) - - val result = getAllAuthenticatorsUseCase("QWERTY") - - Assert.assertEquals(result.getOrNull(), mutableListOf>()) - } - - @Test - fun `When a registered profileId is given and getAllAuthenticatorsUseCase contains authenticators, Then an array of maps should be returned`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(UserProfile("QWERTY"))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.name).thenReturn("test") - whenever(oneginiAuthenticatorMock.id).thenReturn("test") - whenever(oneginiAuthenticatorMock.isRegistered).thenReturn(true) - whenever(oneginiAuthenticatorMock.isPreferred).thenReturn(true) - whenever(oneginiAuthenticatorMock.type).thenReturn(5) - - val result = getAllAuthenticatorsUseCase("QWERTY") - - when (val authenticator = result.getOrNull()?.first()) { - is OWAuthenticator -> { - Assert.assertEquals(authenticator.id, "test") - Assert.assertEquals(authenticator.name, "test") - Assert.assertEquals(authenticator.isRegistered, true) - Assert.assertEquals(authenticator.isPreferred, true) - Assert.assertEquals(authenticator.authenticatorType, 5) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt deleted file mode 100644 index 89fbb23e..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.onegini.mobile.sdk - -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import com.onegini.mobile.sdk.flutter.useCases.GetNotRegisteredAuthenticatorsUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import junit.framework.Assert.fail -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.eq -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetNotRegisteredAuthenticatorsUseCaseTests { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator - - @Mock - lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - - private lateinit var getNotRegisteredAuthenticatorsUseCase: GetNotRegisteredAuthenticatorsUseCase - - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - getNotRegisteredAuthenticatorsUseCase = GetNotRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) - } - - @Test - fun `When there are no Unregistered Authenticators, Then an empty set should be returned`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - - val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") - - Assert.assertEquals(result.getOrNull(), mutableListOf>()) - } - - @Test - fun `When the UserProfile is not found, Then an error should be returned`() { - val result = getNotRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) - } - - @Test - fun `When a valid UserProfile is given and multiple not registered authenticators are found, Then getNotRegisteredAuthenticators should return a non-empty set`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getNotRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorFirstMock, - oneginiAuthenticatorSecondMock - ) - ) - whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") - whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") - whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(false) - whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) - whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) - - whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") - whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") - whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(false) - whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) - whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) - - val result = getNotRegisteredAuthenticatorsUseCase("QWERTY") - - when (val authenticators = result.getOrNull()) { - is List -> { - Assert.assertEquals(authenticators[0].id, "firstId") - Assert.assertEquals(authenticators[0].name, "firstName") - Assert.assertEquals(authenticators[0].isRegistered, false) - Assert.assertEquals(authenticators[0].isPreferred, true) - Assert.assertEquals(authenticators[0].authenticatorType, 5) - - Assert.assertEquals(authenticators[1].id, "secondId") - Assert.assertEquals(authenticators[1].name, "secondName") - Assert.assertEquals(authenticators[1].isRegistered, false) - Assert.assertEquals(authenticators[1].isPreferred, false) - Assert.assertEquals(authenticators[1].authenticatorType, 6) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt new file mode 100644 index 00000000..166bdc3f --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -0,0 +1,105 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType +import com.onegini.mobile.sdk.flutter.useCases.GetPreferredAuthenticatorUseCase +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class GetPreferredAuthenticatorUseCaseTests { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var callbackMock: (Result) -> Unit + + @Mock(answer = Answers.RETURNS_SMART_NULLS) + lateinit var oneginiAuthenticator: OneginiAuthenticator + + private lateinit var getPreferredAuthenticatorUseCase: GetPreferredAuthenticatorUseCase + + @Before + fun attach() { + getPreferredAuthenticatorUseCase = GetPreferredAuthenticatorUseCase(oneginiSdk) + } + + @Test + fun `When no user is authenticated, Then should reject with NO_USER_PROFILE_IS_AUTHENTICATED`() { + WhenNoUserAuthenticated() + + getPreferredAuthenticatorUseCase(callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, captor.firstValue.exceptionOrNull()) + } + + @Test + fun `When the preferred authenticator is pin, Then should resolve with a pin authenticator`() { + WhenPreferedAuthenticatorIsPin() + + getPreferredAuthenticatorUseCase(callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.PIN) + } + + @Test + fun `When the preferred authenticator is pin, Then should resolve with a biometric authenticator`() { + WhenPreferedAuthenticatorIsBiometric() + + getPreferredAuthenticatorUseCase(callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.BIOMETRIC) + } + + @Test + fun `When the preferred authenticator is not pin or fingerprint, Then should reject with a generic error`() { + WhenPreferedAuthenticatorIsCustom() + + getPreferredAuthenticatorUseCase(callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) + } + + + + private fun WhenNoUserAuthenticated() { + // preferredAuthenticator is null when no user is authenticated + whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(null) + } + + private fun WhenPreferedAuthenticatorIsPin() { + whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.PIN) + whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + } + + private fun WhenPreferedAuthenticatorIsBiometric() { + whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.FINGERPRINT) + whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + } + + private fun WhenPreferedAuthenticatorIsCustom() { + whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.CUSTOM) + whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + } + +} diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt deleted file mode 100644 index 1ff58766..00000000 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ /dev/null @@ -1,103 +0,0 @@ -package com.onegini.mobile.sdk - -import com.onegini.mobile.sdk.android.client.OneginiClient -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator -import com.onegini.mobile.sdk.flutter.useCases.GetRegisteredAuthenticatorsUseCase -import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase -import junit.framework.Assert.fail -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Answers -import org.mockito.Mock -import org.mockito.junit.MockitoJUnitRunner -import org.mockito.kotlin.eq -import org.mockito.kotlin.whenever - -@RunWith(MockitoJUnitRunner::class) -class GetRegisteredAuthenticatorsUseCaseTests { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - lateinit var oneginiSdk: OneginiSDK - - @Mock - lateinit var clientMock: OneginiClient - - @Mock - lateinit var oneginiAuthenticatorFirstMock: OneginiAuthenticator - - @Mock - lateinit var oneginiAuthenticatorSecondMock: OneginiAuthenticator - - private lateinit var getRegisteredAuthenticatorsUseCase: GetRegisteredAuthenticatorsUseCase - - @Before - fun attach() { - val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) - getRegisteredAuthenticatorsUseCase = GetRegisteredAuthenticatorsUseCase(oneginiSdk, getUserProfileUseCase) - } - - @Test - fun `should return empty list when sdk return empty set`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY") - - Assert.assertEquals(result.getOrNull(), mutableListOf>()) - } - - @Test - fun `When UserProfile is null, Then it should return an error`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) - } - - @Test - fun `When getRegisteredAuthenticators method returns not empty set, Then it should return list of registered authenticators `() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorFirstMock, - oneginiAuthenticatorSecondMock - ) - ) - whenever(oneginiAuthenticatorFirstMock.id).thenReturn("firstId") - whenever(oneginiAuthenticatorFirstMock.name).thenReturn("firstName") - whenever(oneginiAuthenticatorFirstMock.isRegistered).thenReturn(true) - whenever(oneginiAuthenticatorFirstMock.isPreferred).thenReturn(true) - whenever(oneginiAuthenticatorFirstMock.type).thenReturn(5) - - whenever(oneginiAuthenticatorSecondMock.id).thenReturn("secondId") - whenever(oneginiAuthenticatorSecondMock.name).thenReturn("secondName") - whenever(oneginiAuthenticatorSecondMock.isRegistered).thenReturn(true) - whenever(oneginiAuthenticatorSecondMock.isPreferred).thenReturn(false) - whenever(oneginiAuthenticatorSecondMock.type).thenReturn(6) - - val result = getRegisteredAuthenticatorsUseCase("QWERTY") - - when (val authenticators = result.getOrNull()) { - is List -> { - Assert.assertEquals(authenticators[0].id, "firstId") - Assert.assertEquals(authenticators[0].name, "firstName") - Assert.assertEquals(authenticators[0].isRegistered, true) - Assert.assertEquals(authenticators[0].isPreferred, true) - Assert.assertEquals(authenticators[0].authenticatorType, 5) - - Assert.assertEquals(authenticators[1].id, "secondId") - Assert.assertEquals(authenticators[1].name, "secondName") - Assert.assertEquals(authenticators[1].isRegistered, true) - Assert.assertEquals(authenticators[1].isPreferred, false) - Assert.assertEquals(authenticators[1].authenticatorType, 6) - } - else -> fail(UNEXPECTED_ERROR_TYPE.message) - } - } -} From ee5ccf98973ab2eacaab9e2d145bb5b4e64fb8de Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 14:06:12 +0200 Subject: [PATCH 268/364] FP-65: Update tests for AuthenticateUserUseCase --- .../sdk/AuthenticateUserUseCaseTests.kt | 78 ++++++++++--------- 1 file changed, 41 insertions(+), 37 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index 4ae7f0a8..22559193 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -9,6 +9,7 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile @@ -22,6 +23,7 @@ import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.verify @@ -43,29 +45,14 @@ class AuthenticateUserUseCaseTests { private lateinit var authenticateUserUseCase: AuthenticateUserUseCase + private val profileId = "QWERTY" + @Before fun attach() { val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) authenticateUserUseCase = AuthenticateUserUseCase(oneginiSdk, getUserProfileUseCase) } - @Test - fun `When the given authenticator id is null and a valid ProfileId is passed, Then it should call result success with UserProfile and CustomInfo as json`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.authenticateUser(eq(UserProfile("QWERTY")), any())).thenAnswer { - it.getArgument(1).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) - } - - authenticateUserUseCase("QWERTY", null, callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - val testUser = OWUserProfile("QWERTY") - val testInfo = OWCustomInfo(0, "") - Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) - } - } - @Test fun `When the requested UserProfileId is not registered, Then it should call result error`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) @@ -80,39 +67,42 @@ class AuthenticateUserUseCaseTests { } @Test - fun `When the given authenticator id is not found, Then it should return an error`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + fun `When a valid ProfileId is passed and null for authenticatorType, Then it should call result success with with UserProfile and CustomInfo as json`() { + WhenUserProfileExists() + whenever( + oneginiSdk.oneginiClient.userClient.authenticateUser( + anyOrNull(), + anyOrNull() + ) + ).thenAnswer { + it.getArgument(1).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) + } - authenticateUserUseCase("QWERTY", "TEST", callbackMock) + authenticateUserUseCase("QWERTY", null, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + val testUser = OWUserProfile("QWERTY") + val testInfo = OWCustomInfo(0, "") + Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) } } @Test - fun `When the given authenticator id is found and a valid ProfileId is passed, Then it should call result success with with UserProfile and CustomInfo as json`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) - whenever(oneginiAuthenticatorMock.id).thenReturn("TEST") - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorMock - ) - ) + fun `When a valid ProfileId is passed with a non-null authenticatorType which is registered, Then it should call result success with with UserProfile and CustomInfo as json`() { + WhenUserProfileExists() + WhenFingerprintIsRegistered() whenever( oneginiSdk.oneginiClient.userClient.authenticateUser( - eq(UserProfile("QWERTY")), - eq(oneginiAuthenticatorMock), - any() + anyOrNull(), + anyOrNull(), + anyOrNull() ) ).thenAnswer { it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) } - authenticateUserUseCase("QWERTY", "TEST", callbackMock) + authenticateUserUseCase("QWERTY", OWAuthenticatorType.BIOMETRIC, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -124,10 +114,10 @@ class AuthenticateUserUseCaseTests { @Test fun `When authenticateUser return error, Then it should call result error`() { - whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile("QWERTY"))) + WhenUserProfileExists() whenever(oneginiAuthenticationErrorMock.errorType).thenReturn(OneginiAuthenticationError.GENERAL_ERROR) whenever(oneginiAuthenticationErrorMock.message).thenReturn("General error") - whenever(oneginiSdk.oneginiClient.userClient.authenticateUser(eq(UserProfile("QWERTY")), any())).thenAnswer { + whenever(oneginiSdk.oneginiClient.userClient.authenticateUser(eq(UserProfile(profileId)), any())).thenAnswer { it.getArgument(1).onError(oneginiAuthenticationErrorMock) } @@ -140,4 +130,18 @@ class AuthenticateUserUseCaseTests { SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } + + private fun WhenUserProfileExists() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) + } + + private fun WhenFingerprintIsRegistered() { + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + } + } From 1f362d97f0ea0d596f0daa7c6c1541b71d43c1f5 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 14:11:09 +0200 Subject: [PATCH 269/364] FP-65: Update SetPreferredAuthenticatorTests --- .../SetPreferredAuthenticatorUseCaseTests.kt | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index fab4e90a..a75e7669 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -6,6 +6,8 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import org.junit.Assert import org.junit.Before @@ -36,32 +38,50 @@ class SetPreferredAuthenticatorUseCaseTests { } @Test - fun `When no user is authenticated, Then return an error`() { + fun `When no user is authenticated, Then return an NO_USER_PROFILE_IS_AUTHENTICATED error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() + + val result = setPreferredAuthenticatorUseCase(OWAuthenticatorType.BIOMETRIC).exceptionOrNull() + SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) } @Test - fun `When an authenticator id is given that is not related to the authenticated user, Then an error should be thrown`() { + fun `When an authenticatorType is given that is not related to the authenticated user, Then should reject with AUTHENTICATOR_NOT_FOUND`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) - val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() + val result = setPreferredAuthenticatorUseCase(OWAuthenticatorType.BIOMETRIC).exceptionOrNull() + SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, result) } @Test - fun `When the given authenticator id is found and registered, Then it should resolve with success`() { + fun `When the given authenticatorType is biometric and is registered, Then it should resolve with success`() { + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf( + oneginiAuthenticatorMock + ) + ) + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) + + val result = setPreferredAuthenticatorUseCase(OWAuthenticatorType.BIOMETRIC) + + Assert.assertEquals(result.getOrNull(), Unit) + } + + @Test + fun `When the given authenticatorType is pin and is registered, Then it should resolve with success`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( setOf( oneginiAuthenticatorMock ) ) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.PIN) - val result = setPreferredAuthenticatorUseCase("test") + val result = setPreferredAuthenticatorUseCase(OWAuthenticatorType.PIN) Assert.assertEquals(result.getOrNull(), Unit) } From 761fdf7a78ea2233b50f6870e5ed5958e3e1ac29 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 14:21:35 +0200 Subject: [PATCH 270/364] FP-65: Update tests for RegisterBiometricAuthenticatorUseCase --- .../mobile/sdk/flutter/PigeonInterface.kt | 4 -- .../useCases/RegisterAuthenticatorUseCase.kt | 40 ---------------- ...sterBiometricAuthenticatorUseCaseTests.kt} | 48 +++++++------------ 3 files changed, 16 insertions(+), 76 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt rename android/src/test/java/com/onegini/mobile/sdk/{RegisterAuthenticatorUseCaseTests.kt => RegisterBiometricAuthenticatorUseCaseTests.kt} (68%) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index f41c981e..e9934b50 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -44,7 +44,6 @@ import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestAcceptUse import com.onegini.mobile.sdk.flutter.useCases.PinAuthenticationRequestDenyUseCase import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestAcceptUseCase import com.onegini.mobile.sdk.flutter.useCases.PinRegistrationRequestDenyUseCase -import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.RegisterBiometricAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.RegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase @@ -107,9 +106,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var logoutUseCase: LogoutUseCase - @Inject - lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase - @Inject lateinit var registerBiometricAuthenticatorUseCase: RegisterBiometricAuthenticatorUseCase diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt deleted file mode 100644 index 9acd4401..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler -import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError -import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class RegisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { - val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - - val authenticator = oneginiSDK.oneginiClient.userClient - .getAllAuthenticators(authenticatedUserProfile).find { it.id == authenticatorId } - ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) - - oneginiSDK.oneginiClient.userClient.registerAuthenticator(authenticator, object : OneginiAuthenticatorRegistrationHandler { - override fun onSuccess(customInfo: CustomInfo?) { - callback(Result.success(Unit)) - } - - override fun onError(oneginiAuthenticatorRegistrationError: OneginiAuthenticatorRegistrationError) { - callback( - Result.failure( - SdkError( - code = oneginiAuthenticatorRegistrationError.errorType, - message = oneginiAuthenticatorRegistrationError.message - ).pigeonError() - ) - ) - } - } - ) - } -} diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterBiometricAuthenticatorUseCaseTests.kt similarity index 68% rename from android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt rename to android/src/test/java/com/onegini/mobile/sdk/RegisterBiometricAuthenticatorUseCaseTests.kt index fc85e9ad..3eb1b2b9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterBiometricAuthenticatorUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator @@ -10,7 +9,7 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError -import com.onegini.mobile.sdk.flutter.useCases.RegisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.RegisterBiometricAuthenticatorUseCase import org.junit.Assert import org.junit.Before import org.junit.Test @@ -25,13 +24,10 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) -class RegisterAuthenticatorUseCaseTests { +class RegisterBiometricAuthenticatorUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator @@ -41,18 +37,18 @@ class RegisterAuthenticatorUseCaseTests { @Mock lateinit var callbackMock: (Result) -> Unit - private lateinit var registerAuthenticatorUseCase: RegisterAuthenticatorUseCase + private lateinit var registerBiometricAuthenticatorUseCase: RegisterBiometricAuthenticatorUseCase @Before fun attach() { - registerAuthenticatorUseCase = RegisterAuthenticatorUseCase(oneginiSdk) + registerBiometricAuthenticatorUseCase = RegisterBiometricAuthenticatorUseCase(oneginiSdk) } @Test fun `When no user is authenticated, Then it should return error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - registerAuthenticatorUseCase("test", callbackMock) + registerBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -61,42 +57,30 @@ class RegisterAuthenticatorUseCaseTests { } @Test - fun `When authenticator id is not recognised, Then it should return error`() { + fun `When authenticatorType is biometric and this is not available, Then it should return error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") - - registerAuthenticatorUseCase("test", callbackMock) - - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) - } - } - - @Test - fun `When the user has an empty set of authenticators, Then an error should be returned`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + // We have PIN, but not FINGERPRINT + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.PIN) - registerAuthenticatorUseCase("test", callbackMock) + registerBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE, firstValue.exceptionOrNull()) } } @Test - fun `should return CustomInfo class with status and data as a params when given authenticator id found in getNotRegisteredAuthenticators method`() { + fun `When the authenticator is successfully registered, Then should resolve`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { it.getArgument(1).onSuccess(CustomInfo(0, "data")) } - registerAuthenticatorUseCase("test", callbackMock) + registerBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -105,17 +89,17 @@ class RegisterAuthenticatorUseCaseTests { } @Test - fun `should return error when registerAuthenticator method returns error`() { + fun `When registerAuthenticator calls onError, Then should reject with that error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(setOf(oneginiAuthenticatorMock)) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiAuthenticatorRegistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorRegistrationError.GENERAL_ERROR) whenever(oneginiAuthenticatorRegistrationErrorMock.message).thenReturn("General error") whenever(oneginiSdk.oneginiClient.userClient.registerAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { it.getArgument(1).onError(oneginiAuthenticatorRegistrationErrorMock) } - registerAuthenticatorUseCase("test", callbackMock) + registerBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) From 3ba5e534e2b1ccd6f64eb9dfa47c56c3e47399d7 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 14:58:38 +0200 Subject: [PATCH 271/364] FP-65: Update getPreferredAuthenticator implementation to use profileid --- .../mobile/sdk/flutter/PigeonInterface.kt | 2 +- .../GetPreferredAuthenticatorUseCase.kt | 9 ++-- .../GetPreferredAuthenticatorUseCaseTests.kt | 43 ++++++++++--------- 3 files changed, 30 insertions(+), 24 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index e9934b50..daf1a45d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -223,7 +223,7 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) { - getPreferredAuthenticatorUseCase(callback) + getPreferredAuthenticatorUseCase(profileId, callback) } override fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index de0740fb..503396dd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -11,9 +11,12 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(callback: (Result) -> Unit) { - val authenticator = oneginiSDK.oneginiClient.userClient.preferredAuthenticator - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + operator fun invoke(profileId: String, callback: (Result) -> Unit) { + val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } + ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) + val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) + val authenticator = authenticators.find { it.isPreferred } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) if (authenticator.type == OWAuthenticatorType.PIN.toOneginiInt()) { return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.PIN))) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index 166bdc3f..bfd0a262 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -1,6 +1,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert @@ -14,6 +15,7 @@ import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -31,75 +33,76 @@ class GetPreferredAuthenticatorUseCaseTests { private lateinit var getPreferredAuthenticatorUseCase: GetPreferredAuthenticatorUseCase + private val profileId = "QWERTY" @Before fun attach() { getPreferredAuthenticatorUseCase = GetPreferredAuthenticatorUseCase(oneginiSdk) } @Test - fun `When no user is authenticated, Then should reject with NO_USER_PROFILE_IS_AUTHENTICATED`() { - WhenNoUserAuthenticated() - - getPreferredAuthenticatorUseCase(callbackMock) + fun `When no userprofile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { + getPreferredAuthenticatorUseCase(profileId, callbackMock) val captor = argumentCaptor>() verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, captor.firstValue.exceptionOrNull()) } @Test fun `When the preferred authenticator is pin, Then should resolve with a pin authenticator`() { WhenPreferedAuthenticatorIsPin() + WhenUserProfileExists() - getPreferredAuthenticatorUseCase(callbackMock) + getPreferredAuthenticatorUseCase(profileId, callbackMock) val captor = argumentCaptor>() verify(callbackMock).invoke(captor.capture()) - assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.PIN) + assertEquals(OWAuthenticatorType.PIN, captor.firstValue.getOrNull()?.authenticatorType) } @Test - fun `When the preferred authenticator is pin, Then should resolve with a biometric authenticator`() { + fun `When the preferred authenticator is biometric, Then should resolve with a biometric authenticator`() { WhenPreferedAuthenticatorIsBiometric() + WhenUserProfileExists() - getPreferredAuthenticatorUseCase(callbackMock) + getPreferredAuthenticatorUseCase(profileId, callbackMock) val captor = argumentCaptor>() verify(callbackMock).invoke(captor.capture()) - assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.BIOMETRIC) + assertEquals(OWAuthenticatorType.BIOMETRIC, captor.firstValue.getOrNull()?.authenticatorType) } @Test fun `When the preferred authenticator is not pin or fingerprint, Then should reject with a generic error`() { WhenPreferedAuthenticatorIsCustom() + WhenUserProfileExists() - getPreferredAuthenticatorUseCase(callbackMock) + getPreferredAuthenticatorUseCase(profileId, callbackMock) val captor = argumentCaptor>() verify(callbackMock).invoke(captor.capture()) SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) } - - - private fun WhenNoUserAuthenticated() { - // preferredAuthenticator is null when no user is authenticated - whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(null) + private fun WhenUserProfileExists() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) } private fun WhenPreferedAuthenticatorIsPin() { + whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.PIN) - whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } private fun WhenPreferedAuthenticatorIsBiometric() { + whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.FINGERPRINT) - whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } private fun WhenPreferedAuthenticatorIsCustom() { + whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.CUSTOM) - whenever(oneginiSdk.oneginiClient.userClient.preferredAuthenticator).thenReturn(oneginiAuthenticator) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } - } From cfa327511e8a1b5f56d3e0e964ca30cd4d93fa20 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 14:59:42 +0200 Subject: [PATCH 272/364] FP-65: Add tests for GetBiometricAuthenticatorUseCase --- .../mobile/sdk/flutter/SdkErrorAssert.kt | 8 +- .../GetBiometricAuthenticatorUseCaseTests.kt | 85 +++++++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt index 75082638..08182916 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt @@ -10,8 +10,8 @@ class SdkErrorAssert : Assert() { fun assertEquals(expected: OneWelcomeWrapperErrors, actual: Any?) { when (actual) { is FlutterError -> { - assertEquals(actual.code.toInt(), expected.code) - assertEquals(actual.message, expected.message) + assertEquals(expected.code, actual.code.toInt()) + assertEquals(expected.message, actual.message) } else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } @@ -20,8 +20,8 @@ class SdkErrorAssert : Assert() { fun assertEquals(expected: FlutterError, actual: Any?) { when (actual) { is FlutterError -> { - assertEquals(actual.code, expected.code) - assertEquals(actual.message, expected.message) + assertEquals(expected.code, actual.code) + assertEquals(expected.message, actual.message) } else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt new file mode 100644 index 00000000..2f652e81 --- /dev/null +++ b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt @@ -0,0 +1,85 @@ +package com.onegini.mobile.sdk + +import com.onegini.mobile.sdk.android.model.OneginiAuthenticator +import com.onegini.mobile.sdk.android.model.entity.UserProfile +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneginiSDK +import com.onegini.mobile.sdk.flutter.SdkErrorAssert +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType +import com.onegini.mobile.sdk.flutter.useCases.GetBiometricAuthenticatorUseCase +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@RunWith(MockitoJUnitRunner::class) +class GetBiometricAuthenticatorUseCaseTests { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + lateinit var oneginiSdk: OneginiSDK + + @Mock + lateinit var callbackMock: (Result) -> Unit + + @Mock(answer = Answers.RETURNS_SMART_NULLS) + lateinit var oneginiAuthenticator: OneginiAuthenticator + + private lateinit var getBiometricAuthenticatorUseCase: GetBiometricAuthenticatorUseCase + + @Before + fun attach() { + getBiometricAuthenticatorUseCase = GetBiometricAuthenticatorUseCase(oneginiSdk) + } + + private val profileId = "QWERTY" + + @Test + fun `When userProfile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { + getBiometricAuthenticatorUseCase(profileId, callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, captor.firstValue.exceptionOrNull()) + } + + @Test + fun `When the biometric authenticator is not available, Then should reject with BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE`() { + WhenUserProfileExists() + + getBiometricAuthenticatorUseCase(profileId, callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + SdkErrorAssert.assertEquals(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE, captor.firstValue.exceptionOrNull()) + } + + @Test + fun `When the biometric authenticator is available, Then should resolve with the authenticator`() { + WhenUserProfileExists() + WhenBiometricAuthenticatorAvailable() + + getBiometricAuthenticatorUseCase(profileId, callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.BIOMETRIC) + } + + + private fun WhenUserProfileExists() { + whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) + } + + private fun WhenBiometricAuthenticatorAvailable() { + whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.FINGERPRINT) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) + } + +} From 50a72a50e9ff2fb455945bc9558a258c6069417b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 14 Apr 2023 15:11:14 +0200 Subject: [PATCH 273/364] FP-65: Add tests for DeregisterBiometricAuthenticatorUseCase --- .../mobile/sdk/flutter/PigeonInterface.kt | 4 -- .../DeregisterAuthenticatorUseCase.kt | 39 ------------ ...DeregisterBiometricAuthenticatorUseCase.kt | 4 +- ...sterBiometricAuthenticatorUseCaseTests.kt} | 60 +++++++++---------- 4 files changed, 29 insertions(+), 78 deletions(-) delete mode 100644 android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt rename android/src/test/java/com/onegini/mobile/sdk/{DeregisterAuthenticatorUseCaseTests.kt => DeregisterBiometricAuthenticatorUseCaseTests.kt} (62%) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index daf1a45d..b0bcf53c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -20,7 +20,6 @@ import com.onegini.mobile.sdk.flutter.useCases.AuthenticateUserUseCase import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase import com.onegini.mobile.sdk.flutter.useCases.CancelCustomRegistrationActionUseCase import com.onegini.mobile.sdk.flutter.useCases.ChangePinUseCase -import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterBiometricAuthenticatorUseCase import com.onegini.mobile.sdk.flutter.useCases.DeregisterUserUseCase import com.onegini.mobile.sdk.flutter.useCases.EnrollMobileAuthenticationUseCase @@ -66,9 +65,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var cancelCustomRegistrationActionUseCase: CancelCustomRegistrationActionUseCase - @Inject - lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase - @Inject lateinit var deregisterBiometricAuthenticatorUseCase: DeregisterBiometricAuthenticatorUseCase diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt deleted file mode 100644 index 9d288e6a..00000000 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.onegini.mobile.sdk.flutter.useCases - -import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorDeregistrationHandler -import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorDeregistrationError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* -import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.helpers.SdkError -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { - val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) - - val authenticator = oneginiSDK.oneginiClient.userClient - .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } - ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) - - oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(authenticator, object : OneginiAuthenticatorDeregistrationHandler { - override fun onSuccess() { - callback(Result.success(Unit)) - } - - override fun onError(oneginiAuthenticatorDeregistrationError: OneginiAuthenticatorDeregistrationError) { - callback( - Result.failure( - SdkError( - code = oneginiAuthenticatorDeregistrationError.errorType, - message = oneginiAuthenticatorDeregistrationError.message - ).pigeonError() - ) - ) - } - } - ) - } -} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt index c421073c..0d68d109 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterBiometricAuthenticatorUseCase.kt @@ -14,8 +14,8 @@ class DeregisterBiometricAuthenticatorUseCase @Inject constructor(private val on val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) - val biometricAuthenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } - ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE))) + val biometricAuthenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } + ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(biometricAuthenticator, object : OneginiAuthenticatorDeregistrationHandler { override fun onSuccess() { diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterBiometricAuthenticatorUseCaseTests.kt similarity index 62% rename from android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt rename to android/src/test/java/com/onegini/mobile/sdk/DeregisterBiometricAuthenticatorUseCaseTests.kt index e6fe8e32..4f38e2eb 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterBiometricAuthenticatorUseCaseTests.kt @@ -8,7 +8,7 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError -import com.onegini.mobile.sdk.flutter.useCases.DeregisterAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.DeregisterBiometricAuthenticatorUseCase import org.junit.Assert import org.junit.Before import org.junit.Test @@ -23,7 +23,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) -class DeregisterAuthenticatorUseCaseTests { +class DeregisterBiometricAuthenticatorUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK @@ -36,18 +36,18 @@ class DeregisterAuthenticatorUseCaseTests { @Mock lateinit var oneginiAuthenticatorDeregistrationErrorMock: OneginiAuthenticatorDeregistrationError - private lateinit var deregisterAuthenticatorUseCase: DeregisterAuthenticatorUseCase + private lateinit var deregisterBiometricAuthenticatorUseCase: DeregisterBiometricAuthenticatorUseCase @Before fun attach() { - deregisterAuthenticatorUseCase = DeregisterAuthenticatorUseCase(oneginiSdk) + deregisterBiometricAuthenticatorUseCase = DeregisterBiometricAuthenticatorUseCase(oneginiSdk) } @Test fun `When no user is authenticated, Then it should return error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) - deregisterAuthenticatorUseCase("test", callbackMock) + deregisterBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -56,50 +56,46 @@ class DeregisterAuthenticatorUseCaseTests { } @Test - fun `When the given authenticator id is not found within the registered authenticators of the authenticated user, Then it should return an error`() { + fun `When the given Biometric authenticator is not available, Then it should return an BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorMock - ) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf(oneginiAuthenticatorMock) ) - whenever(oneginiAuthenticatorMock.id).thenReturn("other_test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.PIN) - deregisterAuthenticatorUseCase("test", callbackMock) + deregisterBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE, firstValue.exceptionOrNull()) } } @Test - fun `When getRegisteredAuthenticators method returns empty set, Then an error should be returned`() { + fun `When biometric authenticator exists for the authenticated user, Then it should return call userClient_deregisterAuthenticator`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf(oneginiAuthenticatorMock) + ) + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) - deregisterAuthenticatorUseCase("test", callbackMock) + deregisterBiometricAuthenticatorUseCase(callbackMock) - argumentCaptor>().apply { - verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) - } + verify(oneginiSdk.oneginiClient.userClient).deregisterAuthenticator(any(), any()) } @Test - fun `When getRegisteredAuthenticators finds an authenticator for a authenticated user, Then it should return true`() { + fun `When deregisterAuthenticator calls onSuccess, Then it should resolve`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorMock - ) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf(oneginiAuthenticatorMock) ) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { it.getArgument(1).onSuccess() } - deregisterAuthenticatorUseCase("test", callbackMock) + deregisterBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -110,19 +106,17 @@ class DeregisterAuthenticatorUseCaseTests { @Test fun `When deregisterAuthenticator method returns error, Then the function should return an error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( - setOf( - oneginiAuthenticatorMock - ) + whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + setOf(oneginiAuthenticatorMock) ) - whenever(oneginiAuthenticatorMock.id).thenReturn("test") + whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiAuthenticatorDeregistrationErrorMock.errorType).thenReturn(OneginiAuthenticatorDeregistrationError.GENERAL_ERROR) whenever(oneginiAuthenticatorDeregistrationErrorMock.message).thenReturn("General error") whenever(oneginiSdk.oneginiClient.userClient.deregisterAuthenticator(eq(oneginiAuthenticatorMock), any())).thenAnswer { it.getArgument(1).onError(oneginiAuthenticatorDeregistrationErrorMock) } - deregisterAuthenticatorUseCase("test", callbackMock) + deregisterBiometricAuthenticatorUseCase(callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) From 41c1fed8e750873e30d716cc8526be5c60322d74 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 09:16:04 +0200 Subject: [PATCH 274/364] FP-77 Move subscription logic into their own respective classes in the example app --- example/lib/ow_broadcast_helper.dart | 156 ++---------------- example/lib/screens/login_screen.dart | 6 +- example/lib/screens/user_screen.dart | 7 +- .../browser_registration_subscriptions.dart | 21 +++ .../create_pin_subscriptions.dart | 39 +++++ .../custom_registration_subscriptions.dart | 46 ++++++ .../fingerprint_subscriptions.dart | 60 +++++++ .../otp_subscriptions.dart | 33 ++++ .../pin_authentication_subscriptions.dart | 43 +++++ lib/events/generic_event.dart | 5 +- 10 files changed, 266 insertions(+), 150 deletions(-) create mode 100644 example/lib/subscription_handlers/browser_registration_subscriptions.dart create mode 100644 example/lib/subscription_handlers/create_pin_subscriptions.dart create mode 100644 example/lib/subscription_handlers/custom_registration_subscriptions.dart create mode 100644 example/lib/subscription_handlers/fingerprint_subscriptions.dart create mode 100644 example/lib/subscription_handlers/otp_subscriptions.dart create mode 100644 example/lib/subscription_handlers/pin_authentication_subscriptions.dart diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index b56d6104..3468d444 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -1,158 +1,34 @@ import 'dart:async'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; -import 'package:onegini/events/browser_event.dart'; -import 'package:onegini/events/custom_registration_event.dart'; -import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/events/otp_event.dart'; -import 'package:onegini/events/pin_event.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/user_client.dart'; -import 'package:onegini_example/components/display_toast.dart'; -// ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/auth_otp_screen.dart'; -// ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/fingerprint_screen.dart'; -// ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/otp_screen.dart'; -// ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/pin_request_screen.dart'; -// ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/pin_screen.dart'; +import 'package:onegini_example/subscription_handlers/browser_registration_subscriptions.dart'; +import 'package:onegini_example/subscription_handlers/create_pin_subscriptions.dart'; +import 'package:onegini_example/subscription_handlers/custom_registration_subscriptions.dart'; +import 'package:onegini_example/subscription_handlers/fingerprint_subscriptions.dart'; +import 'package:onegini_example/subscription_handlers/pin_authentication_subscriptions.dart'; class OWBroadcastHelper { - static List> initRegistrationListeners(BuildContext context) { + static Stream createStream() { var broadCastController = Onegini.instance.userClient.owEventStreamController; - // Url Registration Related Events - StreamSubscription handleRegisteredUrlSub = broadCastController.stream.where((event) => event is HandleRegisteredUrlEvent).cast().listen((event) { - Onegini.instance.userClient.handleRegisteredUserUrl(event.url, - signInType: WebSignInType.insideApp); - }); - - // Pin Registration Related Events - StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinCreationEvent).listen((event) { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => PinRequestScreen()), - ); - }); - - StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinCreationEvent).listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); - - StreamSubscription pinNotAllowedSub = broadCastController.stream.where((event) => event is PinNotAllowedEvent).cast().listen((event) { - showFlutterToast("${event.error.message} Code: ${event.error.code}"); - }); - - // Custom Registration related events - StreamSubscription initCustomSub = broadCastController.stream.where((event) => event is InitCustomRegistrationEvent).cast().listen((event) { - if (event.providerId == "2-way-otp-api") { - // a 2-way-otp does not require data for the initialization request - OneginiCustomRegistrationCallback() - .submitSuccessAction(event.providerId, null) - .catchError((error) => { - if (error is PlatformException) - {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} - }); - } - }); - - StreamSubscription finishCustomSub = broadCastController.stream.where((event) => event is FinishCustomRegistrationEvent).cast().listen((event) { - if (event.providerId == "2-way-otp-api") { - // a 2-way-otp does not require data for the initialization request - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => OtpScreen( - password: event.customInfo?.data, providerId: event.providerId)), - ); - } - }); - - return [handleRegisteredUrlSub, openPinSub, closePinSub, pinNotAllowedSub, initCustomSub, finishCustomSub]; + return broadCastController.stream.where((event) => event is T).cast(); } - static List> initAuthenticationListeners(BuildContext context) { - var broadCastController = Onegini.instance.userClient.owEventStreamController; - var pinScreenController = PinScreenController(); - var fingerprintOverlay = OverlayEntry(builder: (context) { - return Container( - color: Colors.black12.withOpacity(0.5), - child: Center( - child: CircularProgressIndicator(), - )); - }); - - // Pin Authentication related events - StreamSubscription openPinSub = broadCastController.stream.where((event) => event is OpenPinAuthenticationEvent).listen((event) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PinScreen(controller: pinScreenController)), - ); - }); - - StreamSubscription closePinSub = broadCastController.stream.where((event) => event is ClosePinAuthenticationEvent).listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); + static List> initRegistrationSubscriptions(BuildContext context) { + var browserRegistrationSubs = BrowserRegistrationSubscriptions.getSubscriptions(); + var createPinSubs = CreatePinSubscriptions.getSubscriptions(context); + var customRegistrationSubs = CustomRegistrationSubscriptions.getSubscriptions(context); - // Fingerprint Authentication related events - StreamSubscription openFingerprintSub = broadCastController.stream.where((event) => event is OpenFingerprintEvent).listen((event) { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => FingerprintScreen()), - ); - }); - - StreamSubscription closeFingerprintSub = broadCastController.stream.where((event) => event is CloseFingerprintEvent).listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); - - StreamSubscription showScanningFingerprintSub = broadCastController.stream.where((event) => event is ShowScanningFingerprintEvent).listen((event) { - Overlay.of(context).insert(fingerprintOverlay); - }); - - StreamSubscription receivedFingerprintSub = broadCastController.stream.where((event) => event is NextFingerprintAuthenticationAttempt).listen((event) { - fingerprintOverlay.remove(); - }); - - StreamSubscription nextAuthenticationAttempt = broadCastController.stream.where((event) => event is NextPinAuthenticationAttemptEvent).cast().listen((event) { - pinScreenController.clearState(); - showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); - }); - - return [openPinSub, closePinSub, openFingerprintSub, closeFingerprintSub, showScanningFingerprintSub, receivedFingerprintSub, nextAuthenticationAttempt]; + return browserRegistrationSubs + createPinSubs + customRegistrationSubs; } - static List> initOTPListeners(BuildContext context) { - var broadCastController = Onegini.instance.userClient.owEventStreamController; - - StreamSubscription openAuthOtpSub = broadCastController.stream.where((event) => event is OpenAuthOtpEvent).cast().listen((event) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AuthOtpScreen( - message: event.message, - )), - ); - }); - - StreamSubscription closeAuthOtpSub = broadCastController.stream.where((event) => event is CloseAuthOtpEvent).listen((event) { - Navigator.of(context).pop(); - }); + static List> initAuthenticationSubscriptions(BuildContext context) { + var pinAuthSubs = PinAuthenticationSubscriptions.getSubscriptions(context); + var fingerprintSubs = FingerprintSubscriptions.getSubscriptions(context); - return [openAuthOtpSub, closeAuthOtpSub]; + return pinAuthSubs + fingerprintSubs; } static void stopListening(List> subscriptions) { diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 0fa5e85a..e8029e2e 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -27,9 +27,9 @@ class _LoginScreenState extends State { @override initState() { - // this.broadcastHelper = OWBroadcastHelper(context: context, temp: "1"); - this.registrationSubscriptions = OWBroadcastHelper.initRegistrationListeners(context); - this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationListeners(context); + // Init subscriptipons for registration and authentication + this.registrationSubscriptions = OWBroadcastHelper.initRegistrationSubscriptions(context); + this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationSubscriptions(context); super.initState(); } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index dc0e1f3b..8bba6b9c 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -13,6 +13,7 @@ import 'package:onegini_example/models/application_details.dart'; import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; +import 'package:onegini_example/subscription_handlers/otp_subscriptions.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:onegini/pigeon.dart'; @@ -59,8 +60,8 @@ class _UserScreenState extends State with RouteAware { this.profileId = widget.userProfileId; // Init listeners for changePin, setPreferredAuthenticators - this.registrationSubscriptions = OWBroadcastHelper.initRegistrationListeners(context); - this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationListeners(context); + this.registrationSubscriptions = OWBroadcastHelper.initRegistrationSubscriptions(context); + this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationSubscriptions(context); getAuthenticators(); } @@ -322,7 +323,7 @@ class Home extends StatelessWidget { } authWithOpt(BuildContext context) async { - List otpSubscriptions = OWBroadcastHelper.initOTPListeners(context); + List otpSubscriptions = OtpSubscriptions.getSubscriptions(context); var data = await Navigator.push( context, diff --git a/example/lib/subscription_handlers/browser_registration_subscriptions.dart b/example/lib/subscription_handlers/browser_registration_subscriptions.dart new file mode 100644 index 00000000..a8eac031 --- /dev/null +++ b/example/lib/subscription_handlers/browser_registration_subscriptions.dart @@ -0,0 +1,21 @@ +import 'dart:async'; + +import 'package:onegini/events/browser_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/onegini.dart'; +import 'package:onegini/user_client.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; + +// Event Subscriptions related to the creation of Pin +class BrowserRegistrationSubscriptions { + static List> getSubscriptions() { + return [_getHandleRegisteredUrSub()]; + } + + static StreamSubscription _getHandleRegisteredUrSub() { + return OWBroadcastHelper.createStream().listen((event) { + Onegini.instance.userClient.handleRegisteredUserUrl(event.url, + signInType: WebSignInType.insideApp); + }); + } +} diff --git a/example/lib/subscription_handlers/create_pin_subscriptions.dart b/example/lib/subscription_handlers/create_pin_subscriptions.dart new file mode 100644 index 00000000..76e76418 --- /dev/null +++ b/example/lib/subscription_handlers/create_pin_subscriptions.dart @@ -0,0 +1,39 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/pin_event.dart'; +import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/pin_request_screen.dart'; + +// Event Subscriptions related to the creation of Pin +class CreatePinSubscriptions { + static List> getSubscriptions(BuildContext context) { + return [_getOpenPinCreationSub(context), _getClosePinCreationSub(context), _getPinNotAllowedSub()]; + } + + static StreamSubscription _getOpenPinCreationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => PinRequestScreen()), + ); + }); + } + + static StreamSubscription _getClosePinCreationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + } + + static StreamSubscription _getPinNotAllowedSub() { + return OWBroadcastHelper.createStream().listen((event) { + showFlutterToast("${event.error.message} Code: ${event.error.code}"); + }); + } +} diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart new file mode 100644 index 00000000..b193e172 --- /dev/null +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -0,0 +1,46 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; +import 'package:onegini/events/custom_registration_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/otp_screen.dart'; + +// Event Subscriptions related to Custom Registration +class CustomRegistrationSubscriptions { + static List> getSubscriptions(BuildContext context) { + return [_getInitCustomRegistrationSub(), _getFinishCustomRegistrationSub(context)]; + } + + static StreamSubscription _getInitCustomRegistrationSub() { + return OWBroadcastHelper.createStream().listen((event) { + if (event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + OneginiCustomRegistrationCallback() + .submitSuccessAction(event.providerId, null) + .catchError((error) => { + if (error is PlatformException) + {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} + }); + } + }); + } + + static StreamSubscription _getFinishCustomRegistrationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => OtpScreen( + password: event.customInfo?.data, providerId: event.providerId)), + ); + } + }); + } +} diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart new file mode 100644 index 00000000..32c89e7b --- /dev/null +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -0,0 +1,60 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:onegini/events/fingerprint_event.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/pin_event.dart'; +import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; +import 'package:onegini_example/screens/fingerprint_screen.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/pin_request_screen.dart'; + +// Event Subscriptions related to the creation of Pin +class FingerprintSubscriptions { + static List> getSubscriptions(BuildContext context) { + var fingerprintOverlay = OverlayEntry(builder: (context) { + return Container( + color: Colors.black12.withOpacity(0.5), + child: Center( + child: CircularProgressIndicator(), + )); + }); + + var openSub = _getOpenFingerprintSub(context); + var closeSub = _getCloseFingerprintSub(context); + var showScanningSub = _getShowScanningFingerprintSub(context, fingerprintOverlay); + var receivedSub = _getReceivedFingerprintSub(fingerprintOverlay); + + return [openSub, closeSub, showScanningSub, receivedSub]; + } + + static StreamSubscription _getOpenFingerprintSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => FingerprintScreen()), + ); + }); + } + + static StreamSubscription _getCloseFingerprintSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + } + + static StreamSubscription _getShowScanningFingerprintSub(BuildContext context, OverlayEntry fingerprintOverlay) { + return OWBroadcastHelper.createStream().listen((event) { + Overlay.of(context).insert(fingerprintOverlay); + }); + } + + static StreamSubscription _getReceivedFingerprintSub(OverlayEntry fingerprintOverlay) { + return OWBroadcastHelper.createStream().listen((event) { + fingerprintOverlay.remove(); + }); + } +} \ No newline at end of file diff --git a/example/lib/subscription_handlers/otp_subscriptions.dart b/example/lib/subscription_handlers/otp_subscriptions.dart new file mode 100644 index 00000000..fbc2199e --- /dev/null +++ b/example/lib/subscription_handlers/otp_subscriptions.dart @@ -0,0 +1,33 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/otp_event.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/auth_otp_screen.dart'; + +// Event Subscriptions related to Custom Registration +class OtpSubscriptions { + static List> getSubscriptions(BuildContext context) { + return [_getOpenAuthOtpSub(context), _getCloseAuthOtpSub(context)]; + } + + static StreamSubscription _getOpenAuthOtpSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => AuthOtpScreen( + message: event.message, + )), + ); + }); + } + + static StreamSubscription _getCloseAuthOtpSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.of(context).pop(); + }); + } +} diff --git a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart new file mode 100644 index 00000000..24c19c3c --- /dev/null +++ b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart @@ -0,0 +1,43 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:onegini/events/onewelcome_events.dart'; +import 'package:onegini/events/pin_event.dart'; +import 'package:onegini_example/components/display_toast.dart'; +import 'package:onegini_example/ow_broadcast_helper.dart'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:onegini_example/screens/pin_screen.dart'; + +// Event Subscriptions related to the creation of Pin +class PinAuthenticationSubscriptions { + static List> getSubscriptions(BuildContext context) { + var pinScreenController = PinScreenController(); + + return [_getOpenPinAuthSub(context, pinScreenController), _getClosePinAuthSub(context), _getNextPinAuthAttemptSub(pinScreenController)]; + } + + static StreamSubscription _getOpenPinAuthSub(BuildContext context, PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PinScreen(controller: pinScreenController)), + ); + }); + } + + static StreamSubscription _getClosePinAuthSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); + } + + static StreamSubscription _getNextPinAuthAttemptSub(PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream().listen((event) { + pinScreenController.clearState(); + showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); + }); + } +} diff --git a/lib/events/generic_event.dart b/lib/events/generic_event.dart index 7e559cbb..2c5cb72b 100644 --- a/lib/events/generic_event.dart +++ b/lib/events/generic_event.dart @@ -2,7 +2,4 @@ import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/pigeon.dart'; -class NextAuthenticationAttemptEvent extends OWEvent { - OWAuthenticationAttempt authenticationAttempt; - NextAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextAuthenticationAttempt); -} + From 874836f08d9c25f2fb7108f97be76c337df7038e Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 09:32:20 +0200 Subject: [PATCH 275/364] fp-77 replace geter name for init --- example/lib/ow_broadcast_helper.dart | 10 +++++----- example/lib/screens/user_screen.dart | 2 +- .../browser_registration_subscriptions.dart | 2 +- .../create_pin_subscriptions.dart | 2 +- .../custom_registration_subscriptions.dart | 2 +- .../fingerprint_subscriptions.dart | 2 +- .../lib/subscription_handlers/otp_subscriptions.dart | 2 +- .../pin_authentication_subscriptions.dart | 2 +- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 3468d444..4bcfc201 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -17,16 +17,16 @@ class OWBroadcastHelper { } static List> initRegistrationSubscriptions(BuildContext context) { - var browserRegistrationSubs = BrowserRegistrationSubscriptions.getSubscriptions(); - var createPinSubs = CreatePinSubscriptions.getSubscriptions(context); - var customRegistrationSubs = CustomRegistrationSubscriptions.getSubscriptions(context); + var browserRegistrationSubs = BrowserRegistrationSubscriptions.initSubscriptions(); + var createPinSubs = CreatePinSubscriptions.initSubscriptions(context); + var customRegistrationSubs = CustomRegistrationSubscriptions.initSubscriptions(context); return browserRegistrationSubs + createPinSubs + customRegistrationSubs; } static List> initAuthenticationSubscriptions(BuildContext context) { - var pinAuthSubs = PinAuthenticationSubscriptions.getSubscriptions(context); - var fingerprintSubs = FingerprintSubscriptions.getSubscriptions(context); + var pinAuthSubs = PinAuthenticationSubscriptions.initSubscriptions(context); + var fingerprintSubs = FingerprintSubscriptions.initSubscriptions(context); return pinAuthSubs + fingerprintSubs; } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 8bba6b9c..26cfe855 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -323,7 +323,7 @@ class Home extends StatelessWidget { } authWithOpt(BuildContext context) async { - List otpSubscriptions = OtpSubscriptions.getSubscriptions(context); + List otpSubscriptions = OtpSubscriptions.initSubscriptions(context); var data = await Navigator.push( context, diff --git a/example/lib/subscription_handlers/browser_registration_subscriptions.dart b/example/lib/subscription_handlers/browser_registration_subscriptions.dart index a8eac031..72b51c30 100644 --- a/example/lib/subscription_handlers/browser_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/browser_registration_subscriptions.dart @@ -8,7 +8,7 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; // Event Subscriptions related to the creation of Pin class BrowserRegistrationSubscriptions { - static List> getSubscriptions() { + static List> initSubscriptions() { return [_getHandleRegisteredUrSub()]; } diff --git a/example/lib/subscription_handlers/create_pin_subscriptions.dart b/example/lib/subscription_handlers/create_pin_subscriptions.dart index 76e76418..a4ec2026 100644 --- a/example/lib/subscription_handlers/create_pin_subscriptions.dart +++ b/example/lib/subscription_handlers/create_pin_subscriptions.dart @@ -10,7 +10,7 @@ import 'package:onegini_example/screens/pin_request_screen.dart'; // Event Subscriptions related to the creation of Pin class CreatePinSubscriptions { - static List> getSubscriptions(BuildContext context) { + static List> initSubscriptions(BuildContext context) { return [_getOpenPinCreationSub(context), _getClosePinCreationSub(context), _getPinNotAllowedSub()]; } diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index b193e172..3bf210bc 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -12,7 +12,7 @@ import 'package:onegini_example/screens/otp_screen.dart'; // Event Subscriptions related to Custom Registration class CustomRegistrationSubscriptions { - static List> getSubscriptions(BuildContext context) { + static List> initSubscriptions(BuildContext context) { return [_getInitCustomRegistrationSub(), _getFinishCustomRegistrationSub(context)]; } diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index 32c89e7b..ca41bb63 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -12,7 +12,7 @@ import 'package:onegini_example/screens/pin_request_screen.dart'; // Event Subscriptions related to the creation of Pin class FingerprintSubscriptions { - static List> getSubscriptions(BuildContext context) { + static List> initSubscriptions(BuildContext context) { var fingerprintOverlay = OverlayEntry(builder: (context) { return Container( color: Colors.black12.withOpacity(0.5), diff --git a/example/lib/subscription_handlers/otp_subscriptions.dart b/example/lib/subscription_handlers/otp_subscriptions.dart index fbc2199e..5b457c0c 100644 --- a/example/lib/subscription_handlers/otp_subscriptions.dart +++ b/example/lib/subscription_handlers/otp_subscriptions.dart @@ -9,7 +9,7 @@ import 'package:onegini_example/screens/auth_otp_screen.dart'; // Event Subscriptions related to Custom Registration class OtpSubscriptions { - static List> getSubscriptions(BuildContext context) { + static List> initSubscriptions(BuildContext context) { return [_getOpenAuthOtpSub(context), _getCloseAuthOtpSub(context)]; } diff --git a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart index 24c19c3c..1a7da5bb 100644 --- a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart +++ b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart @@ -10,7 +10,7 @@ import 'package:onegini_example/screens/pin_screen.dart'; // Event Subscriptions related to the creation of Pin class PinAuthenticationSubscriptions { - static List> getSubscriptions(BuildContext context) { + static List> initSubscriptions(BuildContext context) { var pinScreenController = PinScreenController(); return [_getOpenPinAuthSub(context, pinScreenController), _getClosePinAuthSub(context), _getNextPinAuthAttemptSub(pinScreenController)]; From 64e3085bd2183139737cce773b0cb4bdc4d06fb1 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 09:55:57 +0200 Subject: [PATCH 276/364] fp-77 remove unused model for events, updated to private function for broadcasting in listener --- example/lib/models/event.dart | 25 ------------------------- lib/onegini_event_listener.dart | 32 ++++++++++++++++---------------- 2 files changed, 16 insertions(+), 41 deletions(-) delete mode 100644 example/lib/models/event.dart diff --git a/example/lib/models/event.dart b/example/lib/models/event.dart deleted file mode 100644 index 17287d35..00000000 --- a/example/lib/models/event.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'dart:convert'; - -Event eventFromJson(String str) => Event.fromJson(json.decode(str)); - -String eventToJson(Event data) => json.encode(data.toJson()); - -class Event { - Event({ - required this.eventName, - required this.eventValue, - }); - - String eventName; - String eventValue; - - factory Event.fromJson(Map json) => Event( - eventName: json["eventName"], - eventValue: json["eventValue"], - ); - - Map toJson() => { - "eventName": eventName, - "eventValue": eventValue, - }; -} diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 93d4c5fa..51f94d2a 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -11,91 +11,91 @@ class OneginiEventListener implements NativeCallFlutterApi { /// Browser Registration related events @override void n2fHandleRegisteredUrl(String url) { - broadcastEvent(HandleRegisteredUrlEvent(url)); + _broadcastEvent(HandleRegisteredUrlEvent(url)); } /// Pin Creation related events @override void n2fOpenPinCreation() { // renamed OpenPinRegistrationEvent to OpenPinCreationEvent - broadcastEvent(OpenPinCreationEvent()); + _broadcastEvent(OpenPinCreationEvent()); } @override void n2fClosePinCreation() { // renamed ClosePinRegistrationEvent -> ClosePinCreationEvent - broadcastEvent(ClosePinCreationEvent()); + _broadcastEvent(ClosePinCreationEvent()); } @override void n2fPinNotAllowed(OWOneginiError error) { - broadcastEvent(PinNotAllowedEvent(error)); + _broadcastEvent(PinNotAllowedEvent(error)); } /// Custom Registration related events @override void n2fEventInitCustomRegistration( OWCustomInfo? customInfo, String providerId) { - broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); + _broadcastEvent(InitCustomRegistrationEvent(customInfo, providerId)); } @override void n2fEventFinishCustomRegistration( OWCustomInfo? customInfo, String providerId) { - broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); + _broadcastEvent(FinishCustomRegistrationEvent(customInfo, providerId)); } /// Pin Authentication related events @override void n2fOpenPinAuthentication() { - broadcastEvent(OpenPinAuthenticationEvent()); + _broadcastEvent(OpenPinAuthenticationEvent()); } @override void n2fClosePinAuthentication() { - broadcastEvent(ClosePinAuthenticationEvent()); + _broadcastEvent(ClosePinAuthenticationEvent()); } @override void n2fNextPinAuthenticationAttempt( OWAuthenticationAttempt authenticationAttempt) { - broadcastEvent(NextPinAuthenticationAttemptEvent(authenticationAttempt)); + _broadcastEvent(NextPinAuthenticationAttemptEvent(authenticationAttempt)); } /// Fingerprint related events @override void n2fShowScanningFingerprint() { - broadcastEvent(ShowScanningFingerprintEvent()); + _broadcastEvent(ShowScanningFingerprintEvent()); } @override void n2fOpenFingerprintScreen() { - broadcastEvent(OpenFingerprintEvent()); + _broadcastEvent(OpenFingerprintEvent()); } @override void n2fCloseFingerprintScreen() { - broadcastEvent(CloseFingerprintEvent()); + _broadcastEvent(CloseFingerprintEvent()); } @override void n2fNextFingerprintAuthenticationAttempt() { - broadcastEvent(NextFingerprintAuthenticationAttempt()); + _broadcastEvent(NextFingerprintAuthenticationAttempt()); } /// OTP Mobile authentication related events @override void n2fOpenAuthOtp(String? message) { - broadcastEvent(OpenAuthOtpEvent(message ?? "")); + _broadcastEvent(OpenAuthOtpEvent(message ?? "")); } @override void n2fCloseAuthOtp() { - broadcastEvent(CloseAuthOtpEvent()); + _broadcastEvent(CloseAuthOtpEvent()); } /// Helper method - void broadcastEvent(OWEvent event) { + void _broadcastEvent(OWEvent event) { Onegini.instance.userClient.owEventStreamController.sink.add(event); } } From c0e186516a06abcde318b30aee535873fe9b46db Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 10:20:17 +0200 Subject: [PATCH 277/364] FP-77 Moved controller to onegini.dart, and added it to the listener within the constructor, also fixed linting issues --- example/lib/main.dart | 1 - example/lib/ow_broadcast_helper.dart | 2 +- example/lib/screens/user_screen.dart | 1 + .../fingerprint_subscriptions.dart | 4 +--- example/test/widget_test.dart | 1 + lib/onegini.dart | 7 ++++++- lib/onegini_event_listener.dart | 11 +++++++---- lib/user_client.dart | 4 ---- 8 files changed, 17 insertions(+), 14 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 38de7d87..9fac3e5b 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -3,7 +3,6 @@ import 'package:flutter/material.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; -import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/login_screen.dart'; final RouteObserver routeObserver = RouteObserver(); diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 4bcfc201..3b276111 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -11,7 +11,7 @@ import 'package:onegini_example/subscription_handlers/pin_authentication_subscri class OWBroadcastHelper { static Stream createStream() { - var broadCastController = Onegini.instance.userClient.owEventStreamController; + var broadCastController = Onegini.instance.owEventStreamController; return broadCastController.stream.where((event) => event is T).cast(); } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 26cfe855..585c58d8 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -354,6 +354,7 @@ class Home extends StatelessWidget { } }); if (oneginiAppToWebSingleSignOn != null) { + // ignore: deprecated_member_use await launch( oneginiAppToWebSingleSignOn.redirectUrl, enableDomStorage: true, diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index ca41bb63..d70586c9 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -4,11 +4,9 @@ import 'package:flutter/material.dart'; import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/pin_event.dart'; -import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; -import 'package:onegini_example/screens/fingerprint_screen.dart'; // ignore: import_of_legacy_library_into_null_safe -import 'package:onegini_example/screens/pin_request_screen.dart'; +import 'package:onegini_example/screens/fingerprint_screen.dart'; // Event Subscriptions related to the creation of Pin class FingerprintSubscriptions { diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart index 32b9bab2..efe91fab 100644 --- a/example/test/widget_test.dart +++ b/example/test/widget_test.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'package:onegini_example/main.dart'; void main() { diff --git a/lib/onegini.dart b/lib/onegini.dart index ebfbf324..ef49103c 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/services.dart'; +import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/resources_methods.dart'; import 'package:onegini/user_client.dart'; @@ -11,6 +12,10 @@ class Onegini { // UserClientApi is the flutter to native api created by the Pigeon package, see /pigeons/README.md /// User client methods. final UserClientApi api = UserClientApi(); + + // Stream over which OW events will be send + final StreamController owEventStreamController = StreamController.broadcast(); + late final UserClient userClient; Onegini._internal() { @@ -35,7 +40,7 @@ class Onegini { int? connectionTimeout, int? readTimeout, }) async { - NativeCallFlutterApi.setup(OneginiEventListener()); + NativeCallFlutterApi.setup(OneginiEventListener(owEventStreamController)); await api.startApplication( securityControllerClassName, configModelClassName, diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 51f94d2a..7a6e9193 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -1,13 +1,18 @@ +import 'dart:async'; + import 'package:onegini/events/browser_event.dart'; import 'package:onegini/events/custom_registration_event.dart'; import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; -import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; class OneginiEventListener implements NativeCallFlutterApi { + final StreamController broadCastController; + + OneginiEventListener(this.broadCastController); + /// Browser Registration related events @override void n2fHandleRegisteredUrl(String url) { @@ -17,13 +22,11 @@ class OneginiEventListener implements NativeCallFlutterApi { /// Pin Creation related events @override void n2fOpenPinCreation() { - // renamed OpenPinRegistrationEvent to OpenPinCreationEvent _broadcastEvent(OpenPinCreationEvent()); } @override void n2fClosePinCreation() { - // renamed ClosePinRegistrationEvent -> ClosePinCreationEvent _broadcastEvent(ClosePinCreationEvent()); } @@ -96,6 +99,6 @@ class OneginiEventListener implements NativeCallFlutterApi { /// Helper method void _broadcastEvent(OWEvent event) { - Onegini.instance.userClient.owEventStreamController.sink.add(event); + broadCastController.sink.add(event); } } diff --git a/lib/user_client.dart b/lib/user_client.dart index 6abea88e..01cbbfb8 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,6 +1,5 @@ import 'dart:async'; -import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/pigeon.dart'; ///Сlass with basic methods available to the developer. @@ -8,9 +7,6 @@ class UserClient { final UserClientApi api; UserClient(this.api); - // ignore: close_sinks - final owEventStreamController = StreamController.broadcast(); - ///Start registration flow. /// /// If [identityProviderId] is null, starts standard browser registration. From 93baf10a7aab566fce3ad3f0c490e1fe94a08b27 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 10:22:15 +0200 Subject: [PATCH 278/364] fp-77 removed generic events again --- lib/events/generic_event.dart | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 lib/events/generic_event.dart diff --git a/lib/events/generic_event.dart b/lib/events/generic_event.dart deleted file mode 100644 index 2c5cb72b..00000000 --- a/lib/events/generic_event.dart +++ /dev/null @@ -1,5 +0,0 @@ -// Wrapper for Generic Events -import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/pigeon.dart'; - - From 5c2ce8040adec4c281b6c56ac46f89a3c61a9291 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 18 Apr 2023 10:22:20 +0200 Subject: [PATCH 279/364] FP-65: Optimize all imports --- .../com/onegini/mobile/sdk/flutter/OneginiPlugin.kt | 2 +- .../mobile/sdk/flutter/facade/UriFacadeImpl.kt | 4 ++-- .../handlers/PinAuthenticationRequestHandler.kt | 2 +- .../onegini/mobile/sdk/flutter/helpers/SdkError.kt | 3 +-- .../sdk/flutter/useCases/AuthenticateUserUseCase.kt | 1 - .../useCases/CancelBrowserRegistrationUseCase.kt | 2 +- .../useCases/GetPreferredAuthenticatorUseCase.kt | 6 +++--- .../RegisterBiometricAuthenticatorUseCase.kt | 3 ++- .../sdk/flutter/useCases/RegistrationUseCase.kt | 3 +-- .../sdk/flutter/useCases/ResourceRequestUseCase.kt | 8 ++++---- .../useCases/SetPreferredAuthenticatorUseCase.kt | 3 ++- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 13 ++++++------- .../sdk/SetPreferredAuthenticatorUseCaseTests.kt | 1 - 13 files changed, 24 insertions(+), 27 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt index ac9360f9..48faa76d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiPlugin.kt @@ -1,10 +1,10 @@ package com.onegini.mobile.sdk.flutter import androidx.annotation.NonNull -import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import com.onegini.mobile.sdk.flutter.module.FlutterOneWelcomeSdkModule import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceMethodApi +import com.onegini.mobile.sdk.flutter.pigeonPlugin.UserClientApi import io.flutter.embedding.engine.plugins.FlutterPlugin /** OneginiPlugin */ diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt index c94bcbf5..1692d825 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/facade/UriFacadeImpl.kt @@ -1,8 +1,8 @@ package com.onegini.mobile.sdk.flutter.facade -import javax.inject.Singleton -import javax.inject.Inject import android.net.Uri +import javax.inject.Inject +import javax.inject.Singleton @Singleton class UriFacadeImpl @Inject constructor() : UriFacade { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index 838bb72a..77fb1b72 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -4,7 +4,7 @@ import com.onegini.mobile.sdk.android.handlers.request.OneginiPinAuthenticationR import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticationAttempt diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt index b193e691..cb3a177a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/helpers/SdkError.kt @@ -1,8 +1,7 @@ package com.onegini.mobile.sdk.flutter.helpers -import com.onegini.mobile.sdk.android.handlers.error.OneginiError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.GENERIC_ERROR import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_BODY import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_HEADERS import com.onegini.mobile.sdk.flutter.constants.Constants.Companion.RESPONSE_STATUS_CODE diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index a16de134..87b2565b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -5,7 +5,6 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt index 8ae66654..184a395d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt @@ -1,8 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS import javax.inject.Inject class CancelBrowserRegistrationUseCase @Inject constructor() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 503396dd..6fbb581d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -1,8 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.android.model.OneginiAuthenticator -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.GENERIC_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt index c4608284..32df86a9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt @@ -4,7 +4,8 @@ import com.onegini.mobile.sdk.android.handlers.OneginiAuthenticatorRegistrationH import com.onegini.mobile.sdk.android.handlers.error.OneginiAuthenticatorRegistrationError import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index b73a2753..96913a2b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -5,13 +5,12 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiRegistrationError import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider import com.onegini.mobile.sdk.android.model.entity.CustomInfo import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.IDENTITY_PROVIDER_NOT_FOUND import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile - import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index debd6eda..13aee3ac 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -4,13 +4,13 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_RE import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse -import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.POST import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.PUT -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails +import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse +import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import okhttp3.Call import okhttp3.Callback import okhttp3.Headers diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 63e021cc..64bdf7b4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -1,6 +1,7 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATOR_NOT_FOUND +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.extensions.toOneginiInt import com.onegini.mobile.sdk.flutter.helpers.SdkError diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 426be311..99c9aeb1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -1,22 +1,20 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.UserClient +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE import com.onegini.mobile.sdk.flutter.OneginiSDK -import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType -import okhttp3.Callback -import okhttp3.Headers -import okhttp3.Response -import org.mockito.kotlin.any -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST - import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import junit.framework.Assert.fail +import okhttp3.Callback +import okhttp3.Headers import okhttp3.OkHttpClient +import okhttp3.Response import org.junit.Assert import org.junit.Before import org.junit.Test @@ -24,6 +22,7 @@ import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner +import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.times import org.mockito.kotlin.verify diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index a75e7669..f70da774 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -6,7 +6,6 @@ import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.SdkErrorAssert -import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.useCases.SetPreferredAuthenticatorUseCase import org.junit.Assert From ef068ac3eb4d65041c878963a707eec6301f0ee1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 18 Apr 2023 10:32:54 +0200 Subject: [PATCH 280/364] FP-65: Throw a generic error if no preferred authenticator exists --- .../useCases/GetPreferredAuthenticatorUseCase.kt | 3 +-- .../sdk/GetPreferredAuthenticatorUseCaseTests.kt | 11 +++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 6fbb581d..6f17edad 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.GENERIC_ERROR import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -16,7 +15,7 @@ class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) val authenticator = authenticators.find { it.isPreferred } - ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) + ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) if (authenticator.type == OWAuthenticatorType.PIN.toOneginiInt()) { return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.PIN))) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index bfd0a262..6681962e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -60,6 +60,17 @@ class GetPreferredAuthenticatorUseCaseTests { assertEquals(OWAuthenticatorType.PIN, captor.firstValue.getOrNull()?.authenticatorType) } + @Test + fun `When no preferred authenticator exists, Then we reject with a generic error`() { + WhenUserProfileExists() + + getPreferredAuthenticatorUseCase(profileId, callbackMock) + + val captor = argumentCaptor>() + verify(callbackMock).invoke(captor.capture()) + SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) + } + @Test fun `When the preferred authenticator is biometric, Then should resolve with a biometric authenticator`() { WhenPreferedAuthenticatorIsBiometric() From 0f668330397e38f61bae5f1a01cfe4eca7e3e463 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 18 Apr 2023 10:38:49 +0200 Subject: [PATCH 281/364] FP-65: Fix linter problems for Tests --- .../sdk/AuthenticateUserUseCaseTests.kt | 12 +++++----- .../mobile/sdk/ChangePinUseCaseTests.kt | 4 ---- .../GetBiometricAuthenticatorUseCaseTests.kt | 10 ++++----- .../sdk/GetIdentityProvidersUseCaseTests.kt | 3 +-- .../GetPreferredAuthenticatorUseCaseTests.kt | 22 +++++++++---------- .../mobile/sdk/GetRedirectUrlUseCaseTests.kt | 4 ---- .../mobile/sdk/GetUserProfilesUseCaseTests.kt | 6 +---- .../onegini/mobile/sdk/LogoutUseCaseTests.kt | 4 ---- .../mobile/sdk/RegistrationUseCaseTests.kt | 4 ---- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 3 +-- .../SetPreferredAuthenticatorUseCaseTests.kt | 4 ---- .../mobile/sdk/StartAppUseCaseTests.kt | 4 ---- .../sdk/ValidatePinWithPolicyUseCaseTests.kt | 4 ---- 13 files changed, 25 insertions(+), 59 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index 22559193..c8bc90da 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -68,7 +68,7 @@ class AuthenticateUserUseCaseTests { @Test fun `When a valid ProfileId is passed and null for authenticatorType, Then it should call result success with with UserProfile and CustomInfo as json`() { - WhenUserProfileExists() + whenUserProfileExists() whenever( oneginiSdk.oneginiClient.userClient.authenticateUser( anyOrNull(), @@ -90,8 +90,8 @@ class AuthenticateUserUseCaseTests { @Test fun `When a valid ProfileId is passed with a non-null authenticatorType which is registered, Then it should call result success with with UserProfile and CustomInfo as json`() { - WhenUserProfileExists() - WhenFingerprintIsRegistered() + whenUserProfileExists() + whenFingerprintIsRegistered() whenever( oneginiSdk.oneginiClient.userClient.authenticateUser( anyOrNull(), @@ -114,7 +114,7 @@ class AuthenticateUserUseCaseTests { @Test fun `When authenticateUser return error, Then it should call result error`() { - WhenUserProfileExists() + whenUserProfileExists() whenever(oneginiAuthenticationErrorMock.errorType).thenReturn(OneginiAuthenticationError.GENERAL_ERROR) whenever(oneginiAuthenticationErrorMock.message).thenReturn("General error") whenever(oneginiSdk.oneginiClient.userClient.authenticateUser(eq(UserProfile(profileId)), any())).thenAnswer { @@ -131,11 +131,11 @@ class AuthenticateUserUseCaseTests { } } - private fun WhenUserProfileExists() { + private fun whenUserProfileExists() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) } - private fun WhenFingerprintIsRegistered() { + private fun whenFingerprintIsRegistered() { whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( setOf( diff --git a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt index 545bfbf1..bf66e8d1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ChangePinUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiChangePinHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiChangePinError import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -24,9 +23,6 @@ class ChangePinUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var callbackMock: (Result) -> Unit diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt index 2f652e81..72fce6b5 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt @@ -51,7 +51,7 @@ class GetBiometricAuthenticatorUseCaseTests { @Test fun `When the biometric authenticator is not available, Then should reject with BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE`() { - WhenUserProfileExists() + whenUserProfileExists() getBiometricAuthenticatorUseCase(profileId, callbackMock) @@ -62,8 +62,8 @@ class GetBiometricAuthenticatorUseCaseTests { @Test fun `When the biometric authenticator is available, Then should resolve with the authenticator`() { - WhenUserProfileExists() - WhenBiometricAuthenticatorAvailable() + whenUserProfileExists() + whenBiometricAuthenticatorAvailable() getBiometricAuthenticatorUseCase(profileId, callbackMock) @@ -73,11 +73,11 @@ class GetBiometricAuthenticatorUseCaseTests { } - private fun WhenUserProfileExists() { + private fun whenUserProfileExists() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) } - private fun WhenBiometricAuthenticatorAvailable() { + private fun whenBiometricAuthenticatorAvailable() { whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt index 2e44afa8..2e4fa684 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetIdentityProvidersUseCaseTests.kt @@ -5,7 +5,6 @@ import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWIdentityProvider import com.onegini.mobile.sdk.flutter.useCases.GetIdentityProvidersUseCase -import junit.framework.Assert.fail import org.junit.Assert import org.junit.Before import org.junit.Test @@ -64,7 +63,7 @@ class GetIdentityProvidersUseCaseTests { Assert.assertEquals(identityProviders[1].id, "secondId") Assert.assertEquals(identityProviders[1].name, "secondName") } - else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + else -> Assert.fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index 6681962e..2eb85459 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -50,8 +50,8 @@ class GetPreferredAuthenticatorUseCaseTests { @Test fun `When the preferred authenticator is pin, Then should resolve with a pin authenticator`() { - WhenPreferedAuthenticatorIsPin() - WhenUserProfileExists() + whenPreferedAuthenticatorIsPin() + whenUserProfileExists() getPreferredAuthenticatorUseCase(profileId, callbackMock) @@ -62,7 +62,7 @@ class GetPreferredAuthenticatorUseCaseTests { @Test fun `When no preferred authenticator exists, Then we reject with a generic error`() { - WhenUserProfileExists() + whenUserProfileExists() getPreferredAuthenticatorUseCase(profileId, callbackMock) @@ -73,8 +73,8 @@ class GetPreferredAuthenticatorUseCaseTests { @Test fun `When the preferred authenticator is biometric, Then should resolve with a biometric authenticator`() { - WhenPreferedAuthenticatorIsBiometric() - WhenUserProfileExists() + whenPreferedAuthenticatorIsBiometric() + whenUserProfileExists() getPreferredAuthenticatorUseCase(profileId, callbackMock) @@ -85,8 +85,8 @@ class GetPreferredAuthenticatorUseCaseTests { @Test fun `When the preferred authenticator is not pin or fingerprint, Then should reject with a generic error`() { - WhenPreferedAuthenticatorIsCustom() - WhenUserProfileExists() + whenPreferedAuthenticatorIsCustom() + whenUserProfileExists() getPreferredAuthenticatorUseCase(profileId, callbackMock) @@ -95,23 +95,23 @@ class GetPreferredAuthenticatorUseCaseTests { SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) } - private fun WhenUserProfileExists() { + private fun whenUserProfileExists() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(setOf(UserProfile(profileId))) } - private fun WhenPreferedAuthenticatorIsPin() { + private fun whenPreferedAuthenticatorIsPin() { whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.PIN) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } - private fun WhenPreferedAuthenticatorIsBiometric() { + private fun whenPreferedAuthenticatorIsBiometric() { whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.FINGERPRINT) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) } - private fun WhenPreferedAuthenticatorIsCustom() { + private fun whenPreferedAuthenticatorIsCustom() { whenever(oneginiAuthenticator.isPreferred).thenReturn(true) whenever(oneginiAuthenticator.type).thenReturn(OneginiAuthenticator.CUSTOM) whenever(oneginiSdk.oneginiClient.userClient.getAllAuthenticators(any())).thenReturn(setOf(oneginiAuthenticator)) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt index 0465bae5..194800f1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRedirectUrlUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.useCases.GetRedirectUrlUseCase @@ -18,9 +17,6 @@ class GetRedirectUrlUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var oneginiClientConfigModelMock: OneginiClientConfigModel diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt index 0cca897b..ef37aa48 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetUserProfilesUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -20,9 +19,6 @@ class GetUserProfilesUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - private lateinit var getUserProfilesUseCase: GetUserProfilesUseCase @Before @@ -57,7 +53,7 @@ class GetUserProfilesUseCaseTests { Assert.assertEquals(userProfiles[0].profileId, "QWERTY") Assert.assertEquals(userProfiles[1].profileId, "ASDFGH") } - else -> junit.framework.Assert.fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + else -> Assert.fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt index 421dcf3e..afe7b60c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/LogoutUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiLogoutHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiLogoutError import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -24,9 +23,6 @@ class LogoutUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var oneginiLogoutError: OneginiLogoutError diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 64844297..6ec2ff85 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -1,7 +1,6 @@ package com.onegini.mobile.sdk import com.google.common.truth.Truth.assertThat -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiRegistrationHandler import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider import com.onegini.mobile.sdk.android.model.entity.CustomInfo @@ -28,9 +27,6 @@ class RegistrationUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var callbackMock: (Result) -> Unit diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 99c9aeb1..83e83e2b 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -10,7 +10,6 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestResponse import com.onegini.mobile.sdk.flutter.pigeonPlugin.ResourceRequestType import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase -import junit.framework.Assert.fail import okhttp3.Callback import okhttp3.Headers import okhttp3.OkHttpClient @@ -107,7 +106,7 @@ class ResourceRequestUseCaseTests { Assert.assertEquals(error.message, ERROR_CODE_HTTP_REQUEST.message) Assert.assertEquals(((error.details as Map<*, *>).toMap()["response"] as Map<*, *>)["statusCode"], "400") } - else -> fail(UNEXPECTED_ERROR_TYPE.message) + else -> Assert.fail(UNEXPECTED_ERROR_TYPE.message) } } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index f70da774..10ee5721 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.model.OneginiAuthenticator import com.onegini.mobile.sdk.android.model.entity.UserProfile import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.* @@ -23,9 +22,6 @@ class SetPreferredAuthenticatorUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var oneginiAuthenticatorMock: OneginiAuthenticator diff --git a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt index d6e817ab..e71a3e0a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/StartAppUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiInitializationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiInitializationError import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -22,9 +21,6 @@ class StartAppUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var callbackMock: (Result) -> Unit diff --git a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt index 19d5dfad..b1bbc2f0 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ValidatePinWithPolicyUseCaseTests.kt @@ -1,6 +1,5 @@ package com.onegini.mobile.sdk -import com.onegini.mobile.sdk.android.client.OneginiClient import com.onegini.mobile.sdk.android.handlers.OneginiPinValidationHandler import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -28,9 +27,6 @@ class ValidatePinWithPolicyUseCaseTests { @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var oneginiSdk: OneginiSDK - @Mock - lateinit var clientMock: OneginiClient - @Mock lateinit var callbackMock: (Result) -> Unit From 19a861a9e38e65b3d814d79c132059149ccb61af Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 18 Apr 2023 10:43:09 +0200 Subject: [PATCH 282/364] FP-65: Refactor GetPreferredAuthenticator auth-type checking --- .../useCases/GetPreferredAuthenticatorUseCase.kt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 6f17edad..4fce6aa5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -17,13 +17,13 @@ class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD val authenticator = authenticators.find { it.isPreferred } ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) - if (authenticator.type == OWAuthenticatorType.PIN.toOneginiInt()) { - return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.PIN))) - } - if (authenticator.type == OWAuthenticatorType.BIOMETRIC.toOneginiInt()) { - return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC))) - } - // This should never happen because we don't support CUSTOM/FIDO authenticators - return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) + val authenticatorType = when (authenticator.type) { + OWAuthenticatorType.PIN.toOneginiInt() -> OWAuthenticatorType.PIN + OWAuthenticatorType.BIOMETRIC.toOneginiInt() -> OWAuthenticatorType.BIOMETRIC + // This should never happen because we don't support CUSTOM/FIDO authenticators + else -> null + } ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) + + return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, authenticatorType))) } } \ No newline at end of file From 92931ef38d51a62c8df09a9702470ba0848e26f6 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 18 Apr 2023 10:48:45 +0200 Subject: [PATCH 283/364] FP-65: Use getUserProfileUseCase to get the userprofile/error --- .../flutter/useCases/GetBiometricAuthenticatorUseCase.kt | 9 ++++++--- .../flutter/useCases/GetPreferredAuthenticatorUseCase.kt | 9 ++++++--- .../mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt | 4 +++- .../mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt | 4 +++- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt index db354955..2e02b1c6 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt @@ -9,10 +9,13 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject -class GetBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { +class GetBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase) { operator fun invoke(profileId: String, callback: (Result) -> Unit) { - val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } - ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) + val userProfile = try { + getUserProfileUseCase(profileId) + } catch (error: SdkError) { + return callback(Result.failure(error.pigeonError())) + } val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) val authenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 4fce6aa5..075ba74c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -9,10 +9,13 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject -class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { +class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase) { operator fun invoke(profileId: String, callback: (Result) -> Unit) { - val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId } - ?: return callback(Result.failure(SdkError(USER_PROFILE_DOES_NOT_EXIST).pigeonError())) + val userProfile = try { + getUserProfileUseCase(profileId) + } catch (error: SdkError) { + return callback(Result.failure(error.pigeonError())) + } val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) val authenticator = authenticators.find { it.isPreferred } ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt index 72fce6b5..96aa52e6 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt @@ -8,6 +8,7 @@ import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.useCases.GetBiometricAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @@ -35,7 +36,8 @@ class GetBiometricAuthenticatorUseCaseTests { @Before fun attach() { - getBiometricAuthenticatorUseCase = GetBiometricAuthenticatorUseCase(oneginiSdk) + val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) + getBiometricAuthenticatorUseCase = GetBiometricAuthenticatorUseCase(oneginiSdk, getUserProfileUseCase) } private val profileId = "QWERTY" diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index 2eb85459..10e1f710 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -8,6 +8,7 @@ import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticator import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import com.onegini.mobile.sdk.flutter.useCases.GetPreferredAuthenticatorUseCase +import com.onegini.mobile.sdk.flutter.useCases.GetUserProfileUseCase import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @@ -36,7 +37,8 @@ class GetPreferredAuthenticatorUseCaseTests { private val profileId = "QWERTY" @Before fun attach() { - getPreferredAuthenticatorUseCase = GetPreferredAuthenticatorUseCase(oneginiSdk) + val getUserProfileUseCase = GetUserProfileUseCase(oneginiSdk) + getPreferredAuthenticatorUseCase = GetPreferredAuthenticatorUseCase(oneginiSdk, getUserProfileUseCase) } @Test From 64ed6b39beadaf6cb2e877f35269c24f42c2dce3 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 18 Apr 2023 11:35:34 +0200 Subject: [PATCH 284/364] fp-77 add finalizer for event broadcaster --- lib/onegini.dart | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/onegini.dart b/lib/onegini.dart index ef49103c..efe3a1d4 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -13,10 +13,14 @@ class Onegini { /// User client methods. final UserClientApi api = UserClientApi(); + late final UserClient userClient; + // Stream over which OW events will be send final StreamController owEventStreamController = StreamController.broadcast(); - late final UserClient userClient; + // Close the stream when the instance gets stopped + static final Finalizer> _finalizer = + Finalizer((owEventStreamController) => owEventStreamController.close()); Onegini._internal() { userClient = UserClient(api); @@ -24,7 +28,10 @@ class Onegini { static final Onegini instance = Onegini._internal(); - factory Onegini() => instance; + factory Onegini() { + _finalizer.attach(instance, instance.owEventStreamController, detach: instance); + return instance; + } /// Communication channel between flutter and native side. final MethodChannel channel = const MethodChannel('onegini'); From 43c5f2f20af024879ea9a1cc54da9ebeba4600d9 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 10:03:51 +0200 Subject: [PATCH 285/364] fp-38 wip logic for handling malformed incorrect urls --- .../useCases/ResourceRequestUseCase.kt | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 0732a6c4..9a7d5485 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -1,5 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases +import android.util.Patterns import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK @@ -19,8 +20,6 @@ import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.io.IOException -import java.net.MalformedURLException -import java.net.URL import javax.inject.Inject import javax.inject.Singleton @@ -50,18 +49,24 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini .build() } - private fun getCompleteResourceUrl(path: String): String { + private fun getCompleteResourceUrl(path: String): Result { val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - // Check for absolute or relative url - return try { - URL(path) - path - } catch (e: MalformedURLException) { - resourceBaseUrl + path + return when { + isValidUrl(path) -> Result.success(path) + isValidUrl(path + resourceBaseUrl) -> Result.success(path + resourceBaseUrl) + else -> Result.failure( + SdkError( + wrapperError = HTTP_REQUEST_ERROR + ).pigeonError() + ) } } + private fun isValidUrl(path: String): Boolean { + return Patterns.WEB_URL.matcher(path).matches() + } + private fun getHeaders(headers: Map?): Headers { val headerBuilder = Headers.Builder() From a8723615f0af65b2a99506518fbc16c7b9387708 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 19 Apr 2023 11:03:50 +0200 Subject: [PATCH 286/364] FP-65: iOS code style changes --- .../Handlers/AuthenticatorsHandler.swift | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 8b8814f1..0fb91248 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -17,7 +17,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func registerBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { // We don't have to check if the authenticator is already registered as the sdk will do that for us. let authenticators = SharedUserClient.instance.authenticators(.all, for: profile) - guard let authenticator = authenticators.first(where: { $0.type == AuthenticatorType.biometric }) else { + guard let authenticator = authenticators.first(where: { $0.type == .biometric }) else { completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) return } @@ -26,7 +26,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } func deregisterBiometricAuthenticator(_ profile: UserProfile, _ completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: {$0.type == AuthenticatorType.biometric}) else { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.type == .biometric }) else { completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) return } @@ -35,7 +35,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorType: AuthenticatorType, _ completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.type == authenticatorType}) else { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: { $0.type == authenticatorType }) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } @@ -50,24 +50,24 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } func getBiometricAuthenticator(_ userProfile: UserProfile, completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.type == AuthenticatorType.biometric}) else { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: { $0.type == AuthenticatorType.biometric }) else { completion(.failure(FlutterError(.biometricAuthenticationNotAvailable))) return } - completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.biometric))) + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: .biometric))) } func getPreferredAuthenticator(_ userProfile: UserProfile, completion: @escaping (Result) -> Void) { - guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.isPreferred}) else { + guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: { $0.isPreferred }) else { completion(.failure(FlutterError(.authenticatorNotFound))) return } - if authenticator.type == AuthenticatorType.biometric { - completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.biometric))) + if authenticator.type == .biometric { + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: .biometric))) return } - if authenticator.type == AuthenticatorType.pin { - completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: OWAuthenticatorType.pin))) + if authenticator.type == .pin { + completion(.success(OWAuthenticator(id: authenticator.identifier, name: authenticator.name, isRegistered: authenticator.isRegistered, isPreferred: authenticator.isPreferred, authenticatorType: .pin))) return } // Should never happen because we don't support custom/fido authenticators From 62328872efb70186a8eecca87e3777537d22b781 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 14:13:43 +0200 Subject: [PATCH 287/364] fp-38 added check for invalid urls on android + tests --- .../useCases/ResourceRequestUseCase.kt | 47 +++++++++++-------- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 19 ++++++++ example/lib/screens/login_screen.dart | 3 +- 3 files changed, 49 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 9a7d5485..854d42ca 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -26,35 +26,27 @@ import javax.inject.Singleton @Singleton class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { - val resourceClient = getOkHttpClient(type) - val request = buildRequest(details) + val pathResult = getCompleteResourceUrl(details.path) - performCall(resourceClient, request, callback) - } + when { + pathResult.isFailure -> pathResult.exceptionOrNull()?.let { callback(Result.failure(it)) } + pathResult.isSuccess -> { + pathResult.getOrNull()?.let { + val resourceClient = getOkHttpClient(type) + val request = buildRequest(details, it) - private fun getOkHttpClient(type: ResourceRequestType): OkHttpClient { - return when (type) { - ResourceRequestType.AUTHENTICATED -> oneginiSDK.oneginiClient.userClient.resourceOkHttpClient - ResourceRequestType.IMPLICIT -> oneginiSDK.oneginiClient.userClient.implicitResourceOkHttpClient - ResourceRequestType.ANONYMOUS -> oneginiSDK.oneginiClient.deviceClient.anonymousResourceOkHttpClient - ResourceRequestType.UNAUTHENTICATED -> oneginiSDK.oneginiClient.deviceClient.unauthenticatedResourceOkHttpClient + performCall(resourceClient, request, callback) + } + } } } - private fun buildRequest(details: OWRequestDetails): Request { - return Request.Builder() - .url(getCompleteResourceUrl(details.path)) - .headers(getHeaders(details.headers)) - .setMethod(details) - .build() - } - private fun getCompleteResourceUrl(path: String): Result { val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl return when { isValidUrl(path) -> Result.success(path) - isValidUrl(path + resourceBaseUrl) -> Result.success(path + resourceBaseUrl) + isValidUrl(resourceBaseUrl + path) -> Result.success(resourceBaseUrl + path) else -> Result.failure( SdkError( wrapperError = HTTP_REQUEST_ERROR @@ -67,6 +59,23 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini return Patterns.WEB_URL.matcher(path).matches() } + private fun getOkHttpClient(type: ResourceRequestType): OkHttpClient { + return when (type) { + ResourceRequestType.AUTHENTICATED -> oneginiSDK.oneginiClient.userClient.resourceOkHttpClient + ResourceRequestType.IMPLICIT -> oneginiSDK.oneginiClient.userClient.implicitResourceOkHttpClient + ResourceRequestType.ANONYMOUS -> oneginiSDK.oneginiClient.deviceClient.anonymousResourceOkHttpClient + ResourceRequestType.UNAUTHENTICATED -> oneginiSDK.oneginiClient.deviceClient.unauthenticatedResourceOkHttpClient + } + } + + private fun buildRequest(details: OWRequestDetails, path: String): Request { + return Request.Builder() + .url(path) + .headers(getHeaders(details.headers)) + .setMethod(details) + .build() + } + private fun getHeaders(headers: Map?): Headers { val headerBuilder = Headers.Builder() diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 426be311..26d7b897 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -2,6 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.UserClient import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError @@ -13,6 +14,7 @@ import okhttp3.Headers import okhttp3.Response import org.mockito.kotlin.any import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST +import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import junit.framework.Assert.fail @@ -43,6 +45,9 @@ class ResourceRequestUseCaseTests { @Mock lateinit var okhttp3CallMock: okhttp3.Call + @Mock + lateinit var owRequestResponseDetails: OWRequestDetails + @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var responseMock: Response @@ -63,6 +68,20 @@ class ResourceRequestUseCaseTests { whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") } + @Test + fun `When an invalid url is given, Then the function should resolve with an error`() { + whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") + whenever(owRequestResponseDetails.path).thenReturn("https://^%%&^%*^/user-id-decorated") + resourceRequestUseCase(ResourceRequestType.IMPLICIT, owRequestResponseDetails, callbackMock) + + argumentCaptor>().apply { + verify(callbackMock).invoke(capture()) + + val expected = FlutterError(HTTP_REQUEST_ERROR.code.toString(), HTTP_REQUEST_ERROR.message) + SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) + } + } + @Test fun `When a successful http response is send, Then the call should resolve with an OWRequestResponse containing correct information`() { setupSuccessFullResponseMock() diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 854b6203..bf070828 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -146,7 +146,8 @@ class _LoginScreenState extends State { await Onegini.instance.userClient.authenticateUserImplicitly(profileId, ["read"]); var response = await Onegini.instance.resourcesMethods.requestResource( ResourceRequestType.implicit, - RequestDetails(path: "user-id-decorated", method: HttpRequestMethod.get)); + RequestDetails(path: "https://....^%%&^%*^/....user-id-decorated", method: HttpRequestMethod.get)); + // RequestDetails(path: "https://token-mobile.test.onegini.com/resources/user-id-decorated", method: HttpRequestMethod.get)); var res = json.decode(response.body); From ea4ad1077f62bcb2c3845766cc7dd618d0dc3a2e Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 14:36:14 +0200 Subject: [PATCH 288/364] fp-77 move subscription handlers outside of class --- example/lib/ow_broadcast_helper.dart | 10 +- example/lib/screens/user_screen.dart | 2 +- .../browser_registration_subscriptions.dart | 18 ++-- .../create_pin_subscriptions.dart | 46 +++++----- .../custom_registration_subscriptions.dart | 58 ++++++------ .../fingerprint_subscriptions.dart | 92 +++++++++---------- .../otp_subscriptions.dart | 38 ++++---- .../pin_authentication_subscriptions.dart | 52 +++++------ 8 files changed, 152 insertions(+), 164 deletions(-) diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 3b276111..12fcc8dd 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -17,16 +17,16 @@ class OWBroadcastHelper { } static List> initRegistrationSubscriptions(BuildContext context) { - var browserRegistrationSubs = BrowserRegistrationSubscriptions.initSubscriptions(); - var createPinSubs = CreatePinSubscriptions.initSubscriptions(context); - var customRegistrationSubs = CustomRegistrationSubscriptions.initSubscriptions(context); + var browserRegistrationSubs = initBrowserRegistrationSubscriptions(); + var createPinSubs = initCreatePinSubscriptions(context); + var customRegistrationSubs = initCustomRegistrationSubscriptions(context); return browserRegistrationSubs + createPinSubs + customRegistrationSubs; } static List> initAuthenticationSubscriptions(BuildContext context) { - var pinAuthSubs = PinAuthenticationSubscriptions.initSubscriptions(context); - var fingerprintSubs = FingerprintSubscriptions.initSubscriptions(context); + var pinAuthSubs = initPinAuthenticationSubscriptions(context); + var fingerprintSubs = initFingerprintSubscriptions(context); return pinAuthSubs + fingerprintSubs; } diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 585c58d8..e089c74c 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -323,7 +323,7 @@ class Home extends StatelessWidget { } authWithOpt(BuildContext context) async { - List otpSubscriptions = OtpSubscriptions.initSubscriptions(context); + List otpSubscriptions = initOtpSubscriptions(context); var data = await Navigator.push( context, diff --git a/example/lib/subscription_handlers/browser_registration_subscriptions.dart b/example/lib/subscription_handlers/browser_registration_subscriptions.dart index 72b51c30..33267cb3 100644 --- a/example/lib/subscription_handlers/browser_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/browser_registration_subscriptions.dart @@ -7,15 +7,13 @@ import 'package:onegini/user_client.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; // Event Subscriptions related to the creation of Pin -class BrowserRegistrationSubscriptions { - static List> initSubscriptions() { - return [_getHandleRegisteredUrSub()]; - } +List> initBrowserRegistrationSubscriptions() { + return [_getHandleRegisteredUrSub()]; +} - static StreamSubscription _getHandleRegisteredUrSub() { - return OWBroadcastHelper.createStream().listen((event) { - Onegini.instance.userClient.handleRegisteredUserUrl(event.url, - signInType: WebSignInType.insideApp); - }); - } +StreamSubscription _getHandleRegisteredUrSub() { + return OWBroadcastHelper.createStream().listen((event) { + Onegini.instance.userClient.handleRegisteredUserUrl(event.url, + signInType: WebSignInType.insideApp); + }); } diff --git a/example/lib/subscription_handlers/create_pin_subscriptions.dart b/example/lib/subscription_handlers/create_pin_subscriptions.dart index a4ec2026..324ad97b 100644 --- a/example/lib/subscription_handlers/create_pin_subscriptions.dart +++ b/example/lib/subscription_handlers/create_pin_subscriptions.dart @@ -9,31 +9,29 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/pin_request_screen.dart'; // Event Subscriptions related to the creation of Pin -class CreatePinSubscriptions { - static List> initSubscriptions(BuildContext context) { - return [_getOpenPinCreationSub(context), _getClosePinCreationSub(context), _getPinNotAllowedSub()]; - } +List> initCreatePinSubscriptions(BuildContext context) { + return [_getOpenPinCreationSub(context), _getClosePinCreationSub(context), _getPinNotAllowedSub()]; +} - static StreamSubscription _getOpenPinCreationSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => PinRequestScreen()), - ); - }); - } +StreamSubscription _getOpenPinCreationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => PinRequestScreen()), + ); + }); +} - static StreamSubscription _getClosePinCreationSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); - } +StreamSubscription _getClosePinCreationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); +} - static StreamSubscription _getPinNotAllowedSub() { - return OWBroadcastHelper.createStream().listen((event) { - showFlutterToast("${event.error.message} Code: ${event.error.code}"); - }); - } +StreamSubscription _getPinNotAllowedSub() { + return OWBroadcastHelper.createStream().listen((event) { + showFlutterToast("${event.error.message} Code: ${event.error.code}"); + }); } diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index 3bf210bc..986d4fa1 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -11,36 +11,34 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/otp_screen.dart'; // Event Subscriptions related to Custom Registration -class CustomRegistrationSubscriptions { - static List> initSubscriptions(BuildContext context) { - return [_getInitCustomRegistrationSub(), _getFinishCustomRegistrationSub(context)]; - } +List> initCustomRegistrationSubscriptions(BuildContext context) { + return [_getInitCustomRegistrationSub(), _getFinishCustomRegistrationSub(context)]; +} - static StreamSubscription _getInitCustomRegistrationSub() { - return OWBroadcastHelper.createStream().listen((event) { - if (event.providerId == "2-way-otp-api") { - // a 2-way-otp does not require data for the initialization request - OneginiCustomRegistrationCallback() - .submitSuccessAction(event.providerId, null) - .catchError((error) => { - if (error is PlatformException) - {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} - }); - } - }); - } +StreamSubscription _getInitCustomRegistrationSub() { + return OWBroadcastHelper.createStream().listen((event) { + if (event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + OneginiCustomRegistrationCallback() + .submitSuccessAction(event.providerId, null) + .catchError((error) => { + if (error is PlatformException) + {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} + }); + } + }); +} - static StreamSubscription _getFinishCustomRegistrationSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - if (event.providerId == "2-way-otp-api") { - // a 2-way-otp does not require data for the initialization request - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => OtpScreen( - password: event.customInfo?.data, providerId: event.providerId)), - ); - } - }); - } +StreamSubscription _getFinishCustomRegistrationSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (event.providerId == "2-way-otp-api") { + // a 2-way-otp does not require data for the initialization request + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => OtpScreen( + password: event.customInfo?.data, providerId: event.providerId)), + ); + } + }); } diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index d70586c9..744349b4 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -9,50 +9,48 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/fingerprint_screen.dart'; // Event Subscriptions related to the creation of Pin -class FingerprintSubscriptions { - static List> initSubscriptions(BuildContext context) { - var fingerprintOverlay = OverlayEntry(builder: (context) { - return Container( - color: Colors.black12.withOpacity(0.5), - child: Center( - child: CircularProgressIndicator(), - )); - }); - - var openSub = _getOpenFingerprintSub(context); - var closeSub = _getCloseFingerprintSub(context); - var showScanningSub = _getShowScanningFingerprintSub(context, fingerprintOverlay); - var receivedSub = _getReceivedFingerprintSub(fingerprintOverlay); - - return [openSub, closeSub, showScanningSub, receivedSub]; - } - - static StreamSubscription _getOpenFingerprintSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => FingerprintScreen()), - ); - }); - } - - static StreamSubscription _getCloseFingerprintSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); - } - - static StreamSubscription _getShowScanningFingerprintSub(BuildContext context, OverlayEntry fingerprintOverlay) { - return OWBroadcastHelper.createStream().listen((event) { - Overlay.of(context).insert(fingerprintOverlay); - }); - } - - static StreamSubscription _getReceivedFingerprintSub(OverlayEntry fingerprintOverlay) { - return OWBroadcastHelper.createStream().listen((event) { - fingerprintOverlay.remove(); - }); - } -} \ No newline at end of file +List> initFingerprintSubscriptions(BuildContext context) { + var fingerprintOverlay = OverlayEntry(builder: (context) { + return Container( + color: Colors.black12.withOpacity(0.5), + child: Center( + child: CircularProgressIndicator(), + )); + }); + + var openSub = _getOpenFingerprintSub(context); + var closeSub = _getCloseFingerprintSub(context); + var showScanningSub = _getShowScanningFingerprintSub(context, fingerprintOverlay); + var receivedSub = _getReceivedFingerprintSub(fingerprintOverlay); + + return [openSub, closeSub, showScanningSub, receivedSub]; +} + +StreamSubscription _getOpenFingerprintSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => FingerprintScreen()), + ); + }); +} + +StreamSubscription _getCloseFingerprintSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); +} + +StreamSubscription _getShowScanningFingerprintSub(BuildContext context, OverlayEntry fingerprintOverlay) { + return OWBroadcastHelper.createStream().listen((event) { + Overlay.of(context).insert(fingerprintOverlay); + }); +} + +StreamSubscription _getReceivedFingerprintSub(OverlayEntry fingerprintOverlay) { + return OWBroadcastHelper.createStream().listen((event) { + fingerprintOverlay.remove(); + }); +} diff --git a/example/lib/subscription_handlers/otp_subscriptions.dart b/example/lib/subscription_handlers/otp_subscriptions.dart index 5b457c0c..e5fb8c06 100644 --- a/example/lib/subscription_handlers/otp_subscriptions.dart +++ b/example/lib/subscription_handlers/otp_subscriptions.dart @@ -8,26 +8,24 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/auth_otp_screen.dart'; // Event Subscriptions related to Custom Registration -class OtpSubscriptions { - static List> initSubscriptions(BuildContext context) { - return [_getOpenAuthOtpSub(context), _getCloseAuthOtpSub(context)]; - } +List> initOtpSubscriptions(BuildContext context) { + return [_getOpenAuthOtpSub(context), _getCloseAuthOtpSub(context)]; +} - static StreamSubscription _getOpenAuthOtpSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AuthOtpScreen( - message: event.message, - )), - ); - }); - } +StreamSubscription _getOpenAuthOtpSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => AuthOtpScreen( + message: event.message, + )), + ); + }); +} - static StreamSubscription _getCloseAuthOtpSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - Navigator.of(context).pop(); - }); - } +StreamSubscription _getCloseAuthOtpSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.of(context).pop(); + }); } diff --git a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart index 1a7da5bb..80373719 100644 --- a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart +++ b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart @@ -9,35 +9,33 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/pin_screen.dart'; // Event Subscriptions related to the creation of Pin -class PinAuthenticationSubscriptions { - static List> initSubscriptions(BuildContext context) { - var pinScreenController = PinScreenController(); +List> initPinAuthenticationSubscriptions(BuildContext context) { + var pinScreenController = PinScreenController(); - return [_getOpenPinAuthSub(context, pinScreenController), _getClosePinAuthSub(context), _getNextPinAuthAttemptSub(pinScreenController)]; - } + return [_getOpenPinAuthSub(context, pinScreenController), _getClosePinAuthSub(context), _getNextPinAuthAttemptSub(pinScreenController)]; +} - static StreamSubscription _getOpenPinAuthSub(BuildContext context, PinScreenController pinScreenController) { - return OWBroadcastHelper.createStream().listen((event) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PinScreen(controller: pinScreenController)), - ); - }); - } +StreamSubscription _getOpenPinAuthSub(BuildContext context, PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream().listen((event) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PinScreen(controller: pinScreenController)), + ); + }); +} - static StreamSubscription _getClosePinAuthSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { - if (Navigator.of(context).canPop()) { - Navigator.of(context).pop(); - } - }); - } +StreamSubscription _getClosePinAuthSub(BuildContext context) { + return OWBroadcastHelper.createStream().listen((event) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } + }); +} - static StreamSubscription _getNextPinAuthAttemptSub(PinScreenController pinScreenController) { - return OWBroadcastHelper.createStream().listen((event) { - pinScreenController.clearState(); - showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); - }); - } +StreamSubscription _getNextPinAuthAttemptSub(PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream().listen((event) { + pinScreenController.clearState(); + showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); + }); } From dc09108236bb56f8cd0935e5ac036088dd2c4fe6 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 14:41:45 +0200 Subject: [PATCH 289/364] fp-77 re-established working linter and applied linting to relevant dart files --- example/lib/ow_broadcast_helper.dart | 10 +++++-- .../browser_registration_subscriptions.dart | 5 ++-- .../create_pin_subscriptions.dart | 12 ++++++-- .../custom_registration_subscriptions.dart | 29 +++++++++++++------ .../fingerprint_subscriptions.dart | 18 ++++++++---- .../pin_authentication_subscriptions.dart | 29 +++++++++++++------ lib/events/custom_registration_event.dart | 6 ++-- lib/events/fingerprint_event.dart | 3 +- lib/events/pin_event.dart | 3 +- lib/model/request_details.dart | 3 +- lib/onegini.dart | 6 ++-- lib/user_client.dart | 4 +-- 12 files changed, 87 insertions(+), 41 deletions(-) diff --git a/example/lib/ow_broadcast_helper.dart b/example/lib/ow_broadcast_helper.dart index 12fcc8dd..11a70461 100644 --- a/example/lib/ow_broadcast_helper.dart +++ b/example/lib/ow_broadcast_helper.dart @@ -16,7 +16,8 @@ class OWBroadcastHelper { return broadCastController.stream.where((event) => event is T).cast(); } - static List> initRegistrationSubscriptions(BuildContext context) { + static List> initRegistrationSubscriptions( + BuildContext context) { var browserRegistrationSubs = initBrowserRegistrationSubscriptions(); var createPinSubs = initCreatePinSubscriptions(context); var customRegistrationSubs = initCustomRegistrationSubscriptions(context); @@ -24,7 +25,8 @@ class OWBroadcastHelper { return browserRegistrationSubs + createPinSubs + customRegistrationSubs; } - static List> initAuthenticationSubscriptions(BuildContext context) { + static List> initAuthenticationSubscriptions( + BuildContext context) { var pinAuthSubs = initPinAuthenticationSubscriptions(context); var fingerprintSubs = initFingerprintSubscriptions(context); @@ -32,6 +34,8 @@ class OWBroadcastHelper { } static void stopListening(List> subscriptions) { - subscriptions.forEach((element) { element.cancel(); }); + subscriptions.forEach((element) { + element.cancel(); + }); } } diff --git a/example/lib/subscription_handlers/browser_registration_subscriptions.dart b/example/lib/subscription_handlers/browser_registration_subscriptions.dart index 33267cb3..e63534f8 100644 --- a/example/lib/subscription_handlers/browser_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/browser_registration_subscriptions.dart @@ -12,8 +12,9 @@ List> initBrowserRegistrationSubscriptions() { } StreamSubscription _getHandleRegisteredUrSub() { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { Onegini.instance.userClient.handleRegisteredUserUrl(event.url, - signInType: WebSignInType.insideApp); + signInType: WebSignInType.insideApp); }); } diff --git a/example/lib/subscription_handlers/create_pin_subscriptions.dart b/example/lib/subscription_handlers/create_pin_subscriptions.dart index 324ad97b..294c4b6e 100644 --- a/example/lib/subscription_handlers/create_pin_subscriptions.dart +++ b/example/lib/subscription_handlers/create_pin_subscriptions.dart @@ -9,8 +9,13 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/pin_request_screen.dart'; // Event Subscriptions related to the creation of Pin -List> initCreatePinSubscriptions(BuildContext context) { - return [_getOpenPinCreationSub(context), _getClosePinCreationSub(context), _getPinNotAllowedSub()]; +List> initCreatePinSubscriptions( + BuildContext context) { + return [ + _getOpenPinCreationSub(context), + _getClosePinCreationSub(context), + _getPinNotAllowedSub() + ]; } StreamSubscription _getOpenPinCreationSub(BuildContext context) { @@ -23,7 +28,8 @@ StreamSubscription _getOpenPinCreationSub(BuildContext context) { } StreamSubscription _getClosePinCreationSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index 986d4fa1..2c762d00 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -11,33 +11,44 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/otp_screen.dart'; // Event Subscriptions related to Custom Registration -List> initCustomRegistrationSubscriptions(BuildContext context) { - return [_getInitCustomRegistrationSub(), _getFinishCustomRegistrationSub(context)]; +List> initCustomRegistrationSubscriptions( + BuildContext context) { + return [ + _getInitCustomRegistrationSub(), + _getFinishCustomRegistrationSub(context) + ]; } StreamSubscription _getInitCustomRegistrationSub() { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { if (event.providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request OneginiCustomRegistrationCallback() .submitSuccessAction(event.providerId, null) .catchError((error) => { - if (error is PlatformException) - {showFlutterToast(error.message ?? "An error occuring while answering init custom registration")} - }); + if (error is PlatformException) + { + showFlutterToast(error.message ?? + "An error occuring while answering init custom registration") + } + }); } }); } -StreamSubscription _getFinishCustomRegistrationSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { +StreamSubscription _getFinishCustomRegistrationSub( + BuildContext context) { + return OWBroadcastHelper.createStream() + .listen((event) { if (event.providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request Navigator.push( context, MaterialPageRoute( builder: (context) => OtpScreen( - password: event.customInfo?.data, providerId: event.providerId)), + password: event.customInfo?.data, + providerId: event.providerId)), ); } }); diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index 744349b4..f3e5658c 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -9,7 +9,8 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/fingerprint_screen.dart'; // Event Subscriptions related to the creation of Pin -List> initFingerprintSubscriptions(BuildContext context) { +List> initFingerprintSubscriptions( + BuildContext context) { var fingerprintOverlay = OverlayEntry(builder: (context) { return Container( color: Colors.black12.withOpacity(0.5), @@ -20,7 +21,8 @@ List> initFingerprintSubscriptions(BuildContext cont var openSub = _getOpenFingerprintSub(context); var closeSub = _getCloseFingerprintSub(context); - var showScanningSub = _getShowScanningFingerprintSub(context, fingerprintOverlay); + var showScanningSub = + _getShowScanningFingerprintSub(context, fingerprintOverlay); var receivedSub = _getReceivedFingerprintSub(fingerprintOverlay); return [openSub, closeSub, showScanningSub, receivedSub]; @@ -36,20 +38,24 @@ StreamSubscription _getOpenFingerprintSub(BuildContext context) { } StreamSubscription _getCloseFingerprintSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } }); } -StreamSubscription _getShowScanningFingerprintSub(BuildContext context, OverlayEntry fingerprintOverlay) { - return OWBroadcastHelper.createStream().listen((event) { +StreamSubscription _getShowScanningFingerprintSub( + BuildContext context, OverlayEntry fingerprintOverlay) { + return OWBroadcastHelper.createStream() + .listen((event) { Overlay.of(context).insert(fingerprintOverlay); }); } -StreamSubscription _getReceivedFingerprintSub(OverlayEntry fingerprintOverlay) { +StreamSubscription _getReceivedFingerprintSub( + OverlayEntry fingerprintOverlay) { return OWBroadcastHelper.createStream().listen((event) { fingerprintOverlay.remove(); }); diff --git a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart index 80373719..ac93cab3 100644 --- a/example/lib/subscription_handlers/pin_authentication_subscriptions.dart +++ b/example/lib/subscription_handlers/pin_authentication_subscriptions.dart @@ -9,33 +9,44 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/pin_screen.dart'; // Event Subscriptions related to the creation of Pin -List> initPinAuthenticationSubscriptions(BuildContext context) { +List> initPinAuthenticationSubscriptions( + BuildContext context) { var pinScreenController = PinScreenController(); - return [_getOpenPinAuthSub(context, pinScreenController), _getClosePinAuthSub(context), _getNextPinAuthAttemptSub(pinScreenController)]; + return [ + _getOpenPinAuthSub(context, pinScreenController), + _getClosePinAuthSub(context), + _getNextPinAuthAttemptSub(pinScreenController) + ]; } -StreamSubscription _getOpenPinAuthSub(BuildContext context, PinScreenController pinScreenController) { - return OWBroadcastHelper.createStream().listen((event) { +StreamSubscription _getOpenPinAuthSub( + BuildContext context, PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream() + .listen((event) { Navigator.push( context, MaterialPageRoute( - builder: (context) => PinScreen(controller: pinScreenController)), + builder: (context) => PinScreen(controller: pinScreenController)), ); }); } StreamSubscription _getClosePinAuthSub(BuildContext context) { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } }); } -StreamSubscription _getNextPinAuthAttemptSub(PinScreenController pinScreenController) { - return OWBroadcastHelper.createStream().listen((event) { +StreamSubscription _getNextPinAuthAttemptSub( + PinScreenController pinScreenController) { + return OWBroadcastHelper.createStream() + .listen((event) { pinScreenController.clearState(); - showFlutterToast("failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); + showFlutterToast( + "failed attempts ${event.authenticationAttempt.failedAttempts} from ${event.authenticationAttempt.maxAttempts}"); }); } diff --git a/lib/events/custom_registration_event.dart b/lib/events/custom_registration_event.dart index 9316ca82..ebdeb4a0 100644 --- a/lib/events/custom_registration_event.dart +++ b/lib/events/custom_registration_event.dart @@ -5,11 +5,13 @@ import 'package:onegini/pigeon.dart'; class InitCustomRegistrationEvent extends OWEvent { OWCustomInfo? customInfo; String providerId; - InitCustomRegistrationEvent(this.customInfo, this.providerId) : super(OWAction.initCustomRegistration); + InitCustomRegistrationEvent(this.customInfo, this.providerId) + : super(OWAction.initCustomRegistration); } class FinishCustomRegistrationEvent extends OWEvent { OWCustomInfo? customInfo; String providerId; - FinishCustomRegistrationEvent(this.customInfo, this.providerId) : super(OWAction.finishCustomRegistration); + FinishCustomRegistrationEvent(this.customInfo, this.providerId) + : super(OWAction.finishCustomRegistration); } diff --git a/lib/events/fingerprint_event.dart b/lib/events/fingerprint_event.dart index 8103185e..626a85ff 100644 --- a/lib/events/fingerprint_event.dart +++ b/lib/events/fingerprint_event.dart @@ -14,5 +14,6 @@ class ShowScanningFingerprintEvent extends OWEvent { } class NextFingerprintAuthenticationAttempt extends OWEvent { - NextFingerprintAuthenticationAttempt() : super(OWAction.nextFingerprintAuthenticationAttempt); + NextFingerprintAuthenticationAttempt() + : super(OWAction.nextFingerprintAuthenticationAttempt); } diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index b9afc851..4481d5d9 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -27,5 +27,6 @@ class ClosePinAuthenticationEvent extends OWEvent { class NextPinAuthenticationAttemptEvent extends OWEvent { OWAuthenticationAttempt authenticationAttempt; - NextPinAuthenticationAttemptEvent(this.authenticationAttempt) : super(OWAction.nextPinAuthenticationAttempt); + NextPinAuthenticationAttemptEvent(this.authenticationAttempt) + : super(OWAction.nextPinAuthenticationAttempt); } diff --git a/lib/model/request_details.dart b/lib/model/request_details.dart index aca2d40a..c5de8dc7 100644 --- a/lib/model/request_details.dart +++ b/lib/model/request_details.dart @@ -7,5 +7,6 @@ class RequestDetails { Map? headers; String? body; - RequestDetails({required this.path, required this.method, this.headers, this.body}); + RequestDetails( + {required this.path, required this.method, this.headers, this.body}); } diff --git a/lib/onegini.dart b/lib/onegini.dart index efe3a1d4..f8cecaff 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -16,7 +16,8 @@ class Onegini { late final UserClient userClient; // Stream over which OW events will be send - final StreamController owEventStreamController = StreamController.broadcast(); + final StreamController owEventStreamController = + StreamController.broadcast(); // Close the stream when the instance gets stopped static final Finalizer> _finalizer = @@ -29,7 +30,8 @@ class Onegini { static final Onegini instance = Onegini._internal(); factory Onegini() { - _finalizer.attach(instance, instance.owEventStreamController, detach: instance); + _finalizer.attach(instance, instance.owEventStreamController, + detach: instance); return instance; } diff --git a/lib/user_client.dart b/lib/user_client.dart index 01cbbfb8..ae9c0b57 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -36,14 +36,14 @@ class UserClient { } /// Returns a list of authenticators registered and available to the user. - Future> getRegisteredAuthenticators(String profileId) async { + Future> getRegisteredAuthenticators( + String profileId) async { final registeredAuthenticators = await api.getRegisteredAuthenticators(profileId); return registeredAuthenticators.whereType().toList(); } Future> getAllAuthenticators(String profileId) async { - final allAuthenticators = await api.getAllAuthenticators(profileId); return allAuthenticators.whereType().toList(); } From b21fa65b2f4407071705ec5cbc3faa3a5d35282d Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 14:55:44 +0200 Subject: [PATCH 290/364] fp-77 removed unused print and applied linter --- example/lib/screens/login_screen.dart | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index e8029e2e..033c89dd 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -28,15 +28,16 @@ class _LoginScreenState extends State { @override initState() { // Init subscriptipons for registration and authentication - this.registrationSubscriptions = OWBroadcastHelper.initRegistrationSubscriptions(context); - this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationSubscriptions(context); + this.registrationSubscriptions = + OWBroadcastHelper.initRegistrationSubscriptions(context); + this.authenticationSubscriptions = + OWBroadcastHelper.initAuthenticationSubscriptions(context); super.initState(); } @override void dispose() { - print("disposing listeners"); OWBroadcastHelper.stopListening(registrationSubscriptions); OWBroadcastHelper.stopListening(authenticationSubscriptions); @@ -162,14 +163,16 @@ class _LoginScreenState extends State { Future getImplicitUserDetails(String profileId) async { var returnString = ""; try { - await Onegini.instance.userClient.authenticateUserImplicitly(profileId, ["read"]); + await Onegini.instance.userClient + .authenticateUserImplicitly(profileId, ["read"]); var response = await Onegini.instance.resourcesMethods.requestResource( - ResourceRequestType.implicit, - RequestDetails(path: "user-id-decorated", method: HttpRequestMethod.get)); + ResourceRequestType.implicit, + RequestDetails( + path: "user-id-decorated", method: HttpRequestMethod.get)); var res = json.decode(response.body); - returnString =res["decorated_user_id"]; + returnString = res["decorated_user_id"]; return returnString; } catch (err) { @@ -359,8 +362,7 @@ class _LoginScreenState extends State { height: 20, ), FutureBuilder>( - future: Onegini.instance.userClient - .getIdentityProviders(), + future: Onegini.instance.userClient.getIdentityProviders(), builder: (BuildContext context, identityProviders) { return identityProviders.hasData ? PopupMenuButton( From ccceea1285c2ae6c71f6bf41b4a3cd3b5fdae65d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 19 Apr 2023 15:31:41 +0200 Subject: [PATCH 291/364] FP-65: Use profileId given in getAuthenticator methods --- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 0ffd32df..37e52474 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -70,16 +70,16 @@ extension OneginiModuleSwift { } func getBiometricAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + guard let profile = SharedUserClient.instance.userProfiles.first(where: {$0.profileId == profileId }) else { + completion(.failure(FlutterError(.userProfileDoesNotExist))) return } bridgeConnector.toAuthenticatorsHandler.getBiometricAuthenticator(profile, completion: completion) } func getPreferredAuthenticator(profileId: String, completion: @escaping (Result) -> Void) { - guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + guard let profile = SharedUserClient.instance.userProfiles.first(where: {$0.profileId == profileId }) else { + completion(.failure(FlutterError(.userProfileDoesNotExist))) return } bridgeConnector.toAuthenticatorsHandler.getPreferredAuthenticator(profile, completion: completion) From 2baa1b1fef2bdf2d1092bc364c0505074c36b20d Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 19 Apr 2023 15:43:43 +0200 Subject: [PATCH 292/364] FP-38 Check for valid urls for both native sides --- .../mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + .../flutter/useCases/ResourceRequestUseCase.kt | 4 +++- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 4 ++-- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 3 +++ .../NativeBridge/Handlers/ResourcesHandler.swift | 15 +++++++++++++++ 5 files changed, 24 insertions(+), 3 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 3ae938b9..9defa2d5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -14,6 +14,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), + HTTP_REQUEST_URL_ERROR(8043, "OneWelcome: HTTP Request failed due to an invalid url"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 854d42ca..b163daa1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -2,6 +2,7 @@ package com.onegini.mobile.sdk.flutter.useCases import android.util.Patterns import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_URL_ERROR import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -28,6 +29,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini operator fun invoke(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { val pathResult = getCompleteResourceUrl(details.path) + // Additional check for valid url when { pathResult.isFailure -> pathResult.exceptionOrNull()?.let { callback(Result.failure(it)) } pathResult.isSuccess -> { @@ -49,7 +51,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini isValidUrl(resourceBaseUrl + path) -> Result.success(resourceBaseUrl + path) else -> Result.failure( SdkError( - wrapperError = HTTP_REQUEST_ERROR + wrapperError = HTTP_REQUEST_URL_ERROR ).pigeonError() ) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 26d7b897..3b538717 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.UserClient import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_URL_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError @@ -77,7 +77,7 @@ class ResourceRequestUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - val expected = FlutterError(HTTP_REQUEST_ERROR.code.toString(), HTTP_REQUEST_ERROR.message) + val expected = FlutterError(HTTP_REQUEST_URL_ERROR.code.toString(), HTTP_REQUEST_URL_ERROR.message) SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 2838e26a..43f0c898 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -15,6 +15,7 @@ enum OneWelcomeWrapperError: Int { case authenticationNotInProgress = 8037 case otpAuthenticationNotInProgress = 8039 case browserRegistrationNotInProgress = 8040 + case httpRequestUrlError = 8043 // iOS only case providedUrlIncorrect = 8014 @@ -95,6 +96,8 @@ enum OneWelcomeWrapperError: Int { return "Mobile Authentication is already in progress and can not be performed concurrently." case .browserRegistrationNotInProgress: return "Browser registration is currently not in progress." + case .httpRequestUrlError: + return "OneWelcome: HTTP Request failed due to an invalid url." } } } diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 7ee9b0e3..a279850f 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -40,6 +40,13 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { func requestResource(_ requestType: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { Logger.log("requestResource", sender: self) + // Additional check for valid url + let resourceUrl = ONGClient.sharedInstance().configModel.resourceBaseURL ?? "" + if checkValidUrl(details.path) == false && checkValidUrl(resourceUrl + details.path) == false { + completion(.failure(FlutterError(SdkError(.httpRequestUrlError)))) + return + } + let request = generateONGResourceRequest(details) let requestCompletion = getRequestCompletion(completion) @@ -63,6 +70,14 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } private extension ResourcesHandler { + func checkValidUrl(_ path: String) -> Bool { + if let url = URL(string: path) { + return UIApplication.shared.canOpenURL(url) + } + + return false + } + func generateONGResourceRequest(_ details: OWRequestDetails) -> ONGResourceRequest { Logger.log("generateONGResourceRequest", sender: self) From e4d7cd1fdd709fae087a41c5dba5163b9fae266f Mon Sep 17 00:00:00 2001 From: Archifer Date: Thu, 20 Apr 2023 13:49:08 +0200 Subject: [PATCH 293/364] FP-83 Removed IdP ID from custom registration callbacks for consistent errors with iOS --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 43 +++++-- .../mobile/sdk/flutter/PigeonInterface.kt | 8 +- .../mobile/sdk/flutter/pigeonPlugin/Pigeon.kt | 44 ++----- .../providers/CustomRegistrationAction.kt | 2 + .../providers/CustomRegistrationActionImpl.kt | 10 +- .../CancelCustomRegistrationActionUseCase.kt | 8 +- .../SubmitCustomRegistrationActionUseCase.kt | 12 +- example/lib/screens/login_screen.dart | 30 +++++ example/lib/screens/otp_screen.dart | 4 +- .../NativeBridge/Errors/ErrorMapper.swift | 118 +++++++++++------- .../NativeBridge/Errors/SdkError.swift | 6 +- ios/Classes/Pigeon.swift | 20 +-- ios/Classes/SwiftOneginiPlugin.swift | 4 +- .../onegini_custom_registration_callback.dart | 8 +- lib/pigeon.dart | 14 +-- pigeons/onewelcome_pigeon_interface.dart | 4 +- 16 files changed, 190 insertions(+), 145 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 3ae938b9..d789bca9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -2,23 +2,42 @@ package com.onegini.mobile.sdk.flutter enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { GENERIC_ERROR(8000, "Something went wrong"), - USER_PROFILE_DOES_NOT_EXIST(8001, "The requested User profile does not exist"), + + DOES_NOT_EXIST_USER_PROFILE(8001, "The requested User profile does not exist"), + + NOT_FOUND_AUTHENTICATOR(8004, "The requested authenticator is not found"), + NOT_FOUND_IDENTITY_PROVIDER(8004, "The requested identity provider is not found"), + NOT_FOUND_SECURITY_CONTROLLER(8004, "The requested Security controller class is not found"), + + HTTP_REQUEST_ERROR_INTERNAL(8011, "OneWelcome: HTTP Request failed internally"), + HTTP_REQUEST_ERROR_CODE(8011, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + + NOT_IN_PROGRESS_REGISTRATION(8034, "Registration is currently not in progress"), + NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8034, "Custom Registration is currently not in progress"), + NOT_IN_PROGRESS_AUTHENTICATION(8034, "Authentication is currently not in progress"), + NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8034, "Fingerprint Authentication is currently not in progress"), + NOT_IN_PROGRESS_OTP_AUTHENTICATION(8034, "OTP Authentication is currently not in progress"), + NOT_IN_PROGRESS_BROWSER_REGISTRATION(8034, "Browser Registration is currently not in progress"), + NOT_IN_PROGRESS_PIN_CREATION(8034, "Pin Creation is currently not in progress"), + + +// DOES_NOT_EXIST_USER_PROFILE(8001, "The requested User profile does not exist"), NO_USER_PROFILE_IS_AUTHENTICATED(8002, "There is currently no User Profile authenticated"), - AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), - HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), - ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), +// NOT_FOUND_AUTHENTICATOR(8004, "The requested authenticator is not found"), +//HTTP_REQUEST_ERROR_INTERNAL(8011, "OneWelcome: HTTP Request failed internally"), +//HTTP_REQUEST_ERROR_CODE(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), - AUTHENTICATION_NOT_IN_PROGRESS(8037, "Authentication is currently not in progress"), - FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS(8038, "Fingerprint Authentication is currently not in progress"), - OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), - BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), - PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), +// NOT_IN_PROGRESS_REGISTRATION(8034, "Registration is currently not in progress"), +//NOT_IN_PROGRESS_AUTHENTICATION(8037, "Authentication is currently not in progress"), +//NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8038, "Fingerprint Authentication is currently not in progress"), +//NOT_IN_PROGRESS_OTP_AUTHENTICATION(8039, "OTP Authentication is currently not in progress"), +//NOT_IN_PROGRESS_BROWSER_REGISTRATION(8040, "Browser registration is currently not in progress"), +//NOT_IN_PROGRESS_PIN_CREATION(8042, "Pin creation is currently not in progress"), // Errors that only occur on Android - IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), +// NOT_FOUND_IDENTITY_PROVIDER(8005, "The requested identity provider is not found"), ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), - SECURITY_CONTROLLER_NOT_FOUND(8033, "Security controller class not found"), +// NOT_FOUND_SECURITY_CONTROLLER(8033, "Security controller class not found"), UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 21c769a6..d4b04948 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -278,12 +278,12 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } // Callback functions - override fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) { - callback(submitCustomRegistrationActionUseCase(identityProviderId, data)) + override fun submitCustomRegistrationAction(data: String?, callback: (Result) -> Unit) { + callback(submitCustomRegistrationActionUseCase(data)) } - override fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) { - callback(cancelCustomRegistrationActionUseCase(identityProviderId, error)) + override fun cancelCustomRegistrationAction(error: String, callback: (Result) -> Unit) { + callback(cancelCustomRegistrationActionUseCase(error)) } override fun fingerprintFallbackToPin(callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt index f9a2466a..3a946bd1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt @@ -446,8 +446,8 @@ interface UserClientApi { fun authenticateDevice(scopes: List?, callback: (Result) -> Unit) fun authenticateUserImplicitly(profileId: String, scopes: List?, callback: (Result) -> Unit) /** Custom Registration Callbacks */ - fun submitCustomRegistrationAction(identityProviderId: String, data: String?, callback: (Result) -> Unit) - fun cancelCustomRegistrationAction(identityProviderId: String, error: String, callback: (Result) -> Unit) + fun submitCustomRegistrationAction(data: String?, callback: (Result) -> Unit) + fun cancelCustomRegistrationAction(error: String, callback: (Result) -> Unit) /** Fingerprint Callbacks */ fun fingerprintFallbackToPin(callback: (Result) -> Unit) fun fingerprintDenyAuthenticationRequest(callback: (Result) -> Unit) @@ -936,9 +936,8 @@ interface UserClientApi { if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val identityProviderIdArg = args[0] as String - val dataArg = args[1] as String? - api.submitCustomRegistrationAction(identityProviderIdArg, dataArg) { result: Result -> + val dataArg = args[0] as String? + api.submitCustomRegistrationAction(dataArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -956,9 +955,8 @@ interface UserClientApi { if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val identityProviderIdArg = args[0] as String - val errorArg = args[1] as String - api.cancelCustomRegistrationAction(identityProviderIdArg, errorArg) { result: Result -> + val errorArg = args[0] as String + api.cancelCustomRegistrationAction(errorArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(wrapError(error)) @@ -1277,60 +1275,42 @@ class NativeCallFlutterApi(private val binaryMessenger: BinaryMessenger) { callback() } } - /** - * Called to open pin creation screen. - * changed n2fOpenPinRequestScreen into n2fOpenPinCreation - */ + /** Called to open pin creation screen. */ fun n2fOpenPinCreation(callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinCreation", codec) channel.send(null) { callback() } } - /** - * Called to close pin registration screen. - * changed n2fClosePin into n2fClosePinCreation - */ + /** Called to close pin registration screen. */ fun n2fClosePinCreation(callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinCreation", codec) channel.send(null) { callback() } } - /** - * Called to indicate that the given pin is not allowed for pin creation - * changed n2fEventPinNotAllowed into n2fPinNotAllowed - */ + /** Called to indicate that the given pin is not allowed for pin creation */ fun n2fPinNotAllowed(errorArg: OWOneginiError, callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed", codec) channel.send(listOf(errorArg)) { callback() } } - /** - * Called to open pin authentication screen. - * changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication - */ + /** Called to open pin authentication screen. */ fun n2fOpenPinAuthentication(callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication", codec) channel.send(null) { callback() } } - /** - * Called to close pin authentication screen. - * changed n2fClosePinAuth into n2fClosePinAuthentication - */ + /** Called to close pin authentication screen. */ fun n2fClosePinAuthentication(callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication", codec) channel.send(null) { callback() } } - /** - * Called to attempt next pin authentication. - * changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt - */ + /** Called to attempt next pin authentication. */ fun n2fNextPinAuthenticationAttempt(authenticationAttemptArg: OWAuthenticationAttempt, callback: () -> Unit) { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt", codec) channel.send(listOf(authenticationAttemptArg)) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt index 71b71cb0..6aa5d15e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationAction.kt @@ -3,6 +3,8 @@ package com.onegini.mobile.sdk.flutter.providers import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction interface CustomRegistrationAction { + fun isInProgress(): Boolean + fun getCustomRegistrationAction(): OneginiCustomRegistrationAction fun getIdProvider(): String diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index 7cdb2634..e16b273c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk.flutter.providers import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomRegistrationCallback import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -11,6 +11,10 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi class CustomRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null + override fun isInProgress(): Boolean { + return callback != null + } + override fun finishRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback nativeApi.n2fEventFinishCustomRegistration(info?.mapToOwCustomInfo(), providerId) {} @@ -29,7 +33,7 @@ class CustomRegistrationActionImpl(private val providerId: String, private val n customRegistrationCallback.returnSuccess(result) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_REGISTRATION).pigeonError()) } override fun returnError(exception: Exception?): Result { @@ -37,6 +41,6 @@ class CustomRegistrationActionImpl(private val providerId: String, private val n customRegistrationCallback.returnError(exception) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_REGISTRATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt index 9da96b46..4e36cba5 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.IDENTITY_PROVIDER_NOT_FOUND +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -8,9 +8,9 @@ import javax.inject.Singleton @Singleton class CancelCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(identityProviderId: String, error: String): Result { - return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { - null -> Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError()) + operator fun invoke(error: String): Result { + return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.isInProgress() }) { + null -> Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) else -> action.returnError(Exception(error)) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt index 49e41924..10562f71 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.IDENTITY_PROVIDER_NOT_FOUND +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -8,12 +8,10 @@ import javax.inject.Singleton @Singleton class SubmitCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { - operator fun invoke(identityProviderId: String, data: String?): Result { - return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.getIdProvider() == identityProviderId }) { - null -> Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError()) - else -> { - action.returnSuccess(data) - } + operator fun invoke(data: String?): Result { + return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.isInProgress() }) { + null -> Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) + else -> action.returnSuccess(data) } } } diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 033c89dd..90020616 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -4,6 +4,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; import 'package:onegini/callbacks/onegini_registration_callback.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; @@ -150,6 +151,23 @@ class _LoginScreenState extends State { }); } + testFunc() async { + print("ghalooooo"); + + final providers = await Onegini.instance.userClient.getIdentityProviders(); + + if (providers.length > 0) { + OneginiCustomRegistrationCallback() + .submitErrorAction("Registration canceled") + .catchError((error) { + if (error is PlatformException) { + print(error); + showFlutterToast(error.message); + } + }); + } + } + Future> getUserProfiles() async { try { var profiles = await Onegini.instance.userClient.getUserProfiles(); @@ -345,6 +363,18 @@ class _LoginScreenState extends State { SizedBox( height: 20, ), + ElevatedButton( + onPressed: () { + testFunc(); + }, + child: Text('Test button'), + ), + SizedBox( + height: 20, + ), + SizedBox( + height: 20, + ), Text( "──── Register ────", style: TextStyle(fontSize: 30), diff --git a/example/lib/screens/otp_screen.dart b/example/lib/screens/otp_screen.dart index 9a3bc84c..8ba07d00 100644 --- a/example/lib/screens/otp_screen.dart +++ b/example/lib/screens/otp_screen.dart @@ -22,7 +22,7 @@ class _OtpScreenState extends State { ok() async { if (myController.text.isNotEmpty) { OneginiCustomRegistrationCallback() - .submitSuccessAction(widget.providerId, myController.text ?? " ") + .submitSuccessAction(myController.text ?? " ") .catchError((error) => { if (error is PlatformException) {showFlutterToast(error.message)} @@ -34,7 +34,7 @@ class _OtpScreenState extends State { cancel() async { OneginiCustomRegistrationCallback() - .submitErrorAction(widget.providerId, "Registration canceled") + .submitErrorAction("Registration canceled") .catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 2838e26a..5459193d 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -1,39 +1,81 @@ // swiftlint:disable cyclomatic_complexity import OneginiSDKiOS -enum OneWelcomeWrapperError: Int { +enum OneWelcomeWrapperError { // iOS and Android - case genericError = 8000 - case userProfileDoesNotExist = 8001 - case noUserProfileIsAuthenticated = 8002 - case authenticatorNotFound = 8004 - case httpRequestError = 8011 - case errorCodeHttpRequest = 8013 - case registrationNotInProgress = 8034 - case unauthenticatedImplicitly = 8035 - case methodArgumentNotFound = 8036 - case authenticationNotInProgress = 8037 - case otpAuthenticationNotInProgress = 8039 - case browserRegistrationNotInProgress = 8040 + case genericError + case userProfileDoesNotExist + case noUserProfileIsAuthenticated + case authenticatorNotFound + case httpRequestError + case errorCodeHttpRequest + case registrationNotInProgress + case customRegistrationNotInProgress + case unauthenticatedImplicitly + case authenticationNotInProgress + case otpAuthenticationNotInProgress + case browserRegistrationNotInProgress // iOS only - case providedUrlIncorrect = 8014 - case loginCanceled = 8015 - case enrollmentFailed = 8016 - case authenticationCancelled = 8017 - case registrationCancelled = 8020 - case cantHandleOTP = 8021 - case incorrectResourcesAccess = 8022 - case authenticatorNotRegistered = 8023 - case authenticatorDeregistrationCancelled = 8024 - case failedToParseData = 8025 - case responseIsNull = 8026 - case authenticatorIdIsNull = 8027 - case emptyInputValue = 8028 - case unsupportedPinAction = 8029 - case unsupportedCustomRegistrationAction = 8030 - case authenticatorRegistrationCancelled = 8031 - case mobileAuthInProgress = 8041 + case providedUrlIncorrect + case loginCanceled + case enrollmentFailed + case authenticationCancelled + case registrationCancelled + case authenticatorNotRegistered + case authenticatorDeregistrationCancelled + case responseIsNull + case authenticatorRegistrationCancelled + case mobileAuthInProgress + + func code() -> Int { + switch self { + case .genericError: + return 8000 + case .userProfileDoesNotExist: + return 8001 + case .noUserProfileIsAuthenticated: + return 8002 + case .authenticatorNotFound: + return 8004 + case .httpRequestError: + return 8011 + case .errorCodeHttpRequest: + return 8013 + case .registrationNotInProgress, .customRegistrationNotInProgress: + return 8034 + case .unauthenticatedImplicitly: + return 8035 + case .authenticationNotInProgress: + return 8037 + case .otpAuthenticationNotInProgress: + return 8039 + case .browserRegistrationNotInProgress: + return 8040 + + // iOS only + case .providedUrlIncorrect: + return 8014 + case .loginCanceled: + return 8015 + case .enrollmentFailed: + return 8016 + case .authenticationCancelled: + return 8017 + case .registrationCancelled: + return 8020 + case .authenticatorNotRegistered: + return 8023 + case .authenticatorDeregistrationCancelled: + return 8024 + case .responseIsNull: + return 8026 + case .authenticatorRegistrationCancelled: + return 8031 + case .mobileAuthInProgress: + return 8041 + } + } func message() -> String { switch self { @@ -57,34 +99,18 @@ enum OneWelcomeWrapperError: Int { return "Authenticator deregistration cancelled." case .registrationCancelled: return "Registration cancelled." - case .cantHandleOTP: - return "Can't handle otp authentication request." - case .incorrectResourcesAccess: - return "Incorrect access to resources." case .authenticatorNotRegistered: return "This authenticator is not registered." - case .failedToParseData: - return "Failed to parse data." case .responseIsNull: return "Response doesn't contain data." - case .authenticatorIdIsNull: - return "Authenticator ID is empty." - case .emptyInputValue: - return "Empty input value." case .errorCodeHttpRequest: return "OneWelcome: HTTP Request failed. Check Response for more info." case .httpRequestError: return "OneWelcome: HTTP Request failed. Check iosCode and iosMessage for more info." - case .unsupportedPinAction: - return "Unsupported pin action. Contact SDK maintainer." - case .unsupportedCustomRegistrationAction: - return "Unsupported custom registration action. Contact SDK maintainer." case .authenticatorRegistrationCancelled: return "The authenticator-registration was cancelled." case .unauthenticatedImplicitly: return "The requested action requires you to be authenticated implicitly." - case .methodArgumentNotFound: - return "The passed argument from Flutter could not be found." case .registrationNotInProgress: return "Registration is currently not in progress." case .authenticationNotInProgress: diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index 6066ddd7..39906131 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -16,7 +16,7 @@ class SdkError: Error { } init(_ wrapperError: OneWelcomeWrapperError) { - self.code = wrapperError.rawValue + self.code = wrapperError.code() self.errorDescription = wrapperError.message() setGenericDetails() @@ -32,7 +32,7 @@ class SdkError: Error { } init(_ wrapperError: OneWelcomeWrapperError, info: [String: Any?]?) { - self.code = wrapperError.rawValue + self.code = wrapperError.code() self.errorDescription = wrapperError.message() setGenericDetails() @@ -49,7 +49,7 @@ class SdkError: Error { } init(_ wrapperError: OneWelcomeWrapperError, response: ONGResourceResponse?, iosCode: Int? = nil, iosMessage: String? = nil) { - self.code = wrapperError.rawValue + self.code = wrapperError.code() self.errorDescription = wrapperError.message() setGenericDetails() diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/Pigeon.swift index e0c5e8dd..0b23f681 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/Pigeon.swift @@ -418,8 +418,8 @@ protocol UserClientApi { func authenticateDevice(scopes: [String]?, completion: @escaping (Result) -> Void) func authenticateUserImplicitly(profileId: String, scopes: [String]?, completion: @escaping (Result) -> Void) /// Custom Registration Callbacks - func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) - func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) + func submitCustomRegistrationAction(data: String?, completion: @escaping (Result) -> Void) + func cancelCustomRegistrationAction(error: String, completion: @escaping (Result) -> Void) /// Fingerprint Callbacks func fingerprintFallbackToPin(completion: @escaping (Result) -> Void) func fingerprintDenyAuthenticationRequest(completion: @escaping (Result) -> Void) @@ -848,9 +848,8 @@ class UserClientApiSetup { if let api = api { submitCustomRegistrationActionChannel.setMessageHandler { message, reply in let args = message as! [Any] - let identityProviderIdArg = args[0] as! String - let dataArg: String? = nilOrValue(args[1]) - api.submitCustomRegistrationAction(identityProviderId: identityProviderIdArg, data: dataArg) { result in + let dataArg: String? = nilOrValue(args[0]) + api.submitCustomRegistrationAction(data: dataArg) { result in switch result { case .success: reply(wrapResult(nil)) @@ -866,9 +865,8 @@ class UserClientApiSetup { if let api = api { cancelCustomRegistrationActionChannel.setMessageHandler { message, reply in let args = message as! [Any] - let identityProviderIdArg = args[0] as! String - let errorArg = args[1] as! String - api.cancelCustomRegistrationAction(identityProviderId: identityProviderIdArg, error: errorArg) { result in + let errorArg = args[0] as! String + api.cancelCustomRegistrationAction(error: errorArg) { result in switch result { case .success: reply(wrapResult(nil)) @@ -1178,7 +1176,6 @@ class NativeCallFlutterApi { } } /// Called to open pin creation screen. - /// changed n2fOpenPinRequestScreen into n2fOpenPinCreation func n2fOpenPinCreation(completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinCreation", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in @@ -1186,7 +1183,6 @@ class NativeCallFlutterApi { } } /// Called to close pin registration screen. - /// changed n2fClosePin into n2fClosePinCreation func n2fClosePinCreation(completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinCreation", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in @@ -1194,7 +1190,6 @@ class NativeCallFlutterApi { } } /// Called to indicate that the given pin is not allowed for pin creation - /// changed n2fEventPinNotAllowed into n2fPinNotAllowed func n2fPinNotAllowed(error errorArg: OWOneginiError, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([errorArg] as [Any?]) { _ in @@ -1202,7 +1197,6 @@ class NativeCallFlutterApi { } } /// Called to open pin authentication screen. - /// changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication func n2fOpenPinAuthentication(completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in @@ -1210,7 +1204,6 @@ class NativeCallFlutterApi { } } /// Called to close pin authentication screen. - /// changed n2fClosePinAuth into n2fClosePinAuthentication func n2fClosePinAuthentication(completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { _ in @@ -1218,7 +1211,6 @@ class NativeCallFlutterApi { } } /// Called to attempt next pin authentication. - /// changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt func n2fNextPinAuthenticationAttempt(authenticationAttempt authenticationAttemptArg: OWAuthenticationAttempt, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([authenticationAttemptArg] as [Any?]) { _ in diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 07b23f94..173831aa 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -98,7 +98,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } func handleMobileAuthWithOtp(data: String, completion: @escaping (Result) -> Void) { - OneginiModuleSwift.sharedInstance.handleMobileAuthWithOtp2(data) { result in + OneginiModuleSwift.sharedInstance.handleMobileAuthWithOtp(data) { result in completion(result.mapError { $0 }) } } @@ -115,7 +115,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } } - func cancelCustomRegistrationAction(identityProviderId: String, error: String, completion: @escaping (Result) -> Void) { + func cancelCustomRegistrationAction(error: String, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationError(error) { result in completion(result.mapError { $0 }) } diff --git a/lib/callbacks/onegini_custom_registration_callback.dart b/lib/callbacks/onegini_custom_registration_callback.dart index f5692326..ae8e5aec 100644 --- a/lib/callbacks/onegini_custom_registration_callback.dart +++ b/lib/callbacks/onegini_custom_registration_callback.dart @@ -3,11 +3,11 @@ import 'package:onegini/pigeon.dart'; class OneginiCustomRegistrationCallback { final api = UserClientApi(); - Future submitSuccessAction(String identityProviderId, String? data) async { - await api.submitCustomRegistrationAction(identityProviderId, data); + Future submitSuccessAction(String? data) async { + await api.submitCustomRegistrationAction(data); } - Future submitErrorAction(String identityProviderId, String error) async { - await api.cancelCustomRegistrationAction(identityProviderId, error); + Future submitErrorAction(String error) async { + await api.cancelCustomRegistrationAction(error); } } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index 09dffa9f..d6e1d921 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -994,12 +994,12 @@ class UserClientApi { } /// Custom Registration Callbacks - Future submitCustomRegistrationAction(String arg_identityProviderId, String? arg_data) async { + Future submitCustomRegistrationAction(String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_identityProviderId, arg_data]) as List?; + await channel.send([arg_data]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1016,12 +1016,12 @@ class UserClientApi { } } - Future cancelCustomRegistrationAction(String arg_identityProviderId, String arg_error) async { + Future cancelCustomRegistrationAction(String arg_error) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_identityProviderId, arg_error]) as List?; + await channel.send([arg_error]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1371,27 +1371,21 @@ abstract class NativeCallFlutterApi { void n2fHandleRegisteredUrl(String url); /// Called to open pin creation screen. - /// changed n2fOpenPinRequestScreen into n2fOpenPinCreation void n2fOpenPinCreation(); /// Called to close pin registration screen. - /// changed n2fClosePin into n2fClosePinCreation void n2fClosePinCreation(); /// Called to indicate that the given pin is not allowed for pin creation - /// changed n2fEventPinNotAllowed into n2fPinNotAllowed void n2fPinNotAllowed(OWOneginiError error); /// Called to open pin authentication screen. - /// changed n2fOpenPinScreenAuth into n2fOpenPinAuthentication void n2fOpenPinAuthentication(); /// Called to close pin authentication screen. - /// changed n2fClosePinAuth into n2fClosePinAuthentication void n2fClosePinAuthentication(); /// Called to attempt next pin authentication. - /// changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); /// Called to open OTP authentication. diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index a2a16d5c..9c5e3764 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -208,10 +208,10 @@ abstract class UserClientApi { /// Custom Registration Callbacks @async - void submitCustomRegistrationAction(String identityProviderId, String? data); + void submitCustomRegistrationAction(String? data); @async - void cancelCustomRegistrationAction(String identityProviderId, String error); + void cancelCustomRegistrationAction(String error); /// Fingerprint Callbacks @async From 2f1c071fcb85e4c382cb6877b99e78ca9aad9eca Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 15:01:33 +0200 Subject: [PATCH 294/364] Fix a bug where the fingerprint overlay would never disapear --- .../subscription_handlers/fingerprint_subscriptions.dart | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index f3e5658c..cf6621d7 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -20,7 +20,7 @@ List> initFingerprintSubscriptions( }); var openSub = _getOpenFingerprintSub(context); - var closeSub = _getCloseFingerprintSub(context); + var closeSub = _getCloseFingerprintSub(context, fingerprintOverlay); var showScanningSub = _getShowScanningFingerprintSub(context, fingerprintOverlay); var receivedSub = _getReceivedFingerprintSub(fingerprintOverlay); @@ -37,9 +37,11 @@ StreamSubscription _getOpenFingerprintSub(BuildContext context) { }); } -StreamSubscription _getCloseFingerprintSub(BuildContext context) { +StreamSubscription _getCloseFingerprintSub( + BuildContext context, OverlayEntry fingerprintOverlay) { return OWBroadcastHelper.createStream() .listen((event) { + fingerprintOverlay.remove(); if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } @@ -56,7 +58,8 @@ StreamSubscription _getShowScanningFingerprintSub( StreamSubscription _getReceivedFingerprintSub( OverlayEntry fingerprintOverlay) { - return OWBroadcastHelper.createStream().listen((event) { + return OWBroadcastHelper.createStream() + .listen((event) { fingerprintOverlay.remove(); }); } From ec3d338de8a1fec29fb9fe05ba4895fc2218adeb Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 15:09:06 +0200 Subject: [PATCH 295/364] FP-65: Fix some empty/newlines --- .../kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt | 2 -- .../sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt | 2 +- .../flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index b0bcf53c..3dbf9341 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -95,7 +95,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { @Inject lateinit var getUserProfilesUseCase: GetUserProfilesUseCase - @Inject lateinit var handleRegisteredUrlUseCase: HandleRegisteredUrlUseCase @@ -238,7 +237,6 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { changePinUseCase(callback) } - override fun logout(callback: (Result) -> Unit) { logoutUseCase(callback) } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 075ba74c..5d2bca85 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -29,4 +29,4 @@ class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, authenticatorType))) } -} \ No newline at end of file +} diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt index 32df86a9..9a91f996 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterBiometricAuthenticatorUseCase.kt @@ -36,4 +36,4 @@ class RegisterBiometricAuthenticatorUseCase @Inject constructor(private val oneg } }) } -} \ No newline at end of file +} From 3e222807430763bd39854c2e469f4500dc47b7d0 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 15:18:41 +0200 Subject: [PATCH 296/364] FP-65: Don't call callback in getAuthenticator usecases --- .../mobile/sdk/flutter/PigeonInterface.kt | 4 +-- .../GetBiometricAuthenticatorUseCase.kt | 8 ++--- .../GetPreferredAuthenticatorUseCase.kt | 10 +++---- .../GetBiometricAuthenticatorUseCaseTests.kt | 20 ++++--------- .../GetPreferredAuthenticatorUseCaseTests.kt | 30 +++++++------------ 5 files changed, 27 insertions(+), 45 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt index 3dbf9341..68c34e70 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/PigeonInterface.kt @@ -214,11 +214,11 @@ open class PigeonInterface : UserClientApi, ResourceMethodApi { } override fun getBiometricAuthenticator(profileId: String, callback: (Result) -> Unit) { - getBiometricAuthenticatorUseCase(profileId, callback) + callback(getBiometricAuthenticatorUseCase(profileId)) } override fun getPreferredAuthenticator(profileId: String, callback: (Result) -> Unit) { - getPreferredAuthenticatorUseCase(profileId, callback) + callback(getPreferredAuthenticatorUseCase(profileId)) } override fun setPreferredAuthenticator(authenticatorType: OWAuthenticatorType, callback: (Result) -> Unit) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt index 2e02b1c6..9bfc586b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt @@ -10,17 +10,17 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject class GetBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase) { - operator fun invoke(profileId: String, callback: (Result) -> Unit) { + operator fun invoke(profileId: String): Result { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return callback(Result.failure(error.pigeonError())) + return Result.failure(error.pigeonError()) } val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) val authenticator = authenticators.find { it.type == OneginiAuthenticator.FINGERPRINT } - ?: return callback(Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError())) + ?: return Result.failure(SdkError(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE).pigeonError()) - return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC))) + return Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC)) } } \ No newline at end of file diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt index 5d2bca85..782afb15 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetPreferredAuthenticatorUseCase.kt @@ -10,23 +10,23 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWAuthenticatorType import javax.inject.Inject class GetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK, private val getUserProfileUseCase: GetUserProfileUseCase) { - operator fun invoke(profileId: String, callback: (Result) -> Unit) { + operator fun invoke(profileId: String): Result { val userProfile = try { getUserProfileUseCase(profileId) } catch (error: SdkError) { - return callback(Result.failure(error.pigeonError())) + return Result.failure(error.pigeonError()) } val authenticators = oneginiSDK.oneginiClient.userClient.getAllAuthenticators(userProfile) val authenticator = authenticators.find { it.isPreferred } - ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) + ?: return Result.failure(SdkError(GENERIC_ERROR).pigeonError()) val authenticatorType = when (authenticator.type) { OWAuthenticatorType.PIN.toOneginiInt() -> OWAuthenticatorType.PIN OWAuthenticatorType.BIOMETRIC.toOneginiInt() -> OWAuthenticatorType.BIOMETRIC // This should never happen because we don't support CUSTOM/FIDO authenticators else -> null - } ?: return callback(Result.failure(SdkError(GENERIC_ERROR).pigeonError())) + } ?: return Result.failure(SdkError(GENERIC_ERROR).pigeonError()) - return callback(Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, authenticatorType))) + return Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, authenticatorType)) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt index 96aa52e6..3353caf4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt @@ -17,8 +17,6 @@ import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) @@ -44,22 +42,18 @@ class GetBiometricAuthenticatorUseCaseTests { @Test fun `When userProfile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { - getBiometricAuthenticatorUseCase(profileId, callbackMock) + val result = getBiometricAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result.exceptionOrNull()) } @Test fun `When the biometric authenticator is not available, Then should reject with BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE`() { whenUserProfileExists() - getBiometricAuthenticatorUseCase(profileId, callbackMock) + val result = getBiometricAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE, result.exceptionOrNull()) } @Test @@ -67,11 +61,9 @@ class GetBiometricAuthenticatorUseCaseTests { whenUserProfileExists() whenBiometricAuthenticatorAvailable() - getBiometricAuthenticatorUseCase(profileId, callbackMock) + val result = getBiometricAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - assertEquals(captor.firstValue.getOrNull()?.authenticatorType, OWAuthenticatorType.BIOMETRIC) + assertEquals(OWAuthenticatorType.BIOMETRIC, result.getOrNull()?.authenticatorType) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index 10e1f710..aeffeb9d 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -43,11 +43,9 @@ class GetPreferredAuthenticatorUseCaseTests { @Test fun `When no userprofile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { - getPreferredAuthenticatorUseCase(profileId, callbackMock) + val result = getPreferredAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result.exceptionOrNull()) } @Test @@ -55,22 +53,18 @@ class GetPreferredAuthenticatorUseCaseTests { whenPreferedAuthenticatorIsPin() whenUserProfileExists() - getPreferredAuthenticatorUseCase(profileId, callbackMock) + val result = getPreferredAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - assertEquals(OWAuthenticatorType.PIN, captor.firstValue.getOrNull()?.authenticatorType) + assertEquals(OWAuthenticatorType.PIN, result.getOrNull()?.authenticatorType) } @Test fun `When no preferred authenticator exists, Then we reject with a generic error`() { whenUserProfileExists() - getPreferredAuthenticatorUseCase(profileId, callbackMock) + val result = getPreferredAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(GENERIC_ERROR, result.exceptionOrNull()) } @Test @@ -78,11 +72,9 @@ class GetPreferredAuthenticatorUseCaseTests { whenPreferedAuthenticatorIsBiometric() whenUserProfileExists() - getPreferredAuthenticatorUseCase(profileId, callbackMock) + val result = getPreferredAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - assertEquals(OWAuthenticatorType.BIOMETRIC, captor.firstValue.getOrNull()?.authenticatorType) + assertEquals(OWAuthenticatorType.BIOMETRIC, result.getOrNull()?.authenticatorType) } @Test @@ -90,11 +82,9 @@ class GetPreferredAuthenticatorUseCaseTests { whenPreferedAuthenticatorIsCustom() whenUserProfileExists() - getPreferredAuthenticatorUseCase(profileId, callbackMock) + val result = getPreferredAuthenticatorUseCase(profileId) - val captor = argumentCaptor>() - verify(callbackMock).invoke(captor.capture()) - SdkErrorAssert.assertEquals(GENERIC_ERROR, captor.firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(GENERIC_ERROR, result.exceptionOrNull()) } private fun whenUserProfileExists() { From 5fdfcf88f449136d053cb742ad1dd418cff2f938 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 15:27:37 +0200 Subject: [PATCH 297/364] FP-65: Use const strings instead of "QWERTY" in test files --- .../mobile/sdk/AuthenticateUserUseCaseTests.kt | 18 +++++++++--------- .../SetPreferredAuthenticatorUseCaseTests.kt | 13 +++++++------ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index c8bc90da..ce091dfb 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -57,7 +57,7 @@ class AuthenticateUserUseCaseTests { fun `When the requested UserProfileId is not registered, Then it should call result error`() { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) - authenticateUserUseCase("QWERTY", null, callbackMock) + authenticateUserUseCase(profileId, null, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -75,14 +75,14 @@ class AuthenticateUserUseCaseTests { anyOrNull() ) ).thenAnswer { - it.getArgument(1).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) + it.getArgument(1).onSuccess(UserProfile(profileId), CustomInfo(0, "")) } - authenticateUserUseCase("QWERTY", null, callbackMock) + authenticateUserUseCase(profileId, null, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - val testUser = OWUserProfile("QWERTY") + val testUser = OWUserProfile(profileId) val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) } @@ -99,14 +99,14 @@ class AuthenticateUserUseCaseTests { anyOrNull() ) ).thenAnswer { - it.getArgument(2).onSuccess(UserProfile("QWERTY"), CustomInfo(0, "")) + it.getArgument(2).onSuccess(UserProfile(profileId), CustomInfo(0, "")) } - authenticateUserUseCase("QWERTY", OWAuthenticatorType.BIOMETRIC, callbackMock) + authenticateUserUseCase(profileId, OWAuthenticatorType.BIOMETRIC, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - val testUser = OWUserProfile("QWERTY") + val testUser = OWUserProfile(profileId) val testInfo = OWCustomInfo(0, "") Assert.assertEquals(firstValue.getOrNull(), OWRegistrationResponse(testUser, testInfo)) } @@ -121,7 +121,7 @@ class AuthenticateUserUseCaseTests { it.getArgument(1).onError(oneginiAuthenticationErrorMock) } - authenticateUserUseCase("QWERTY", null, callbackMock) + authenticateUserUseCase(profileId, null, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -137,7 +137,7 @@ class AuthenticateUserUseCaseTests { private fun whenFingerprintIsRegistered() { whenever(oneginiAuthenticatorMock.type).thenReturn(OneginiAuthenticator.FINGERPRINT) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile(profileId)))).thenReturn( setOf( oneginiAuthenticatorMock ) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index 10ee5721..289458c4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -27,6 +27,7 @@ class SetPreferredAuthenticatorUseCaseTests { private lateinit var setPreferredAuthenticatorUseCase: SetPreferredAuthenticatorUseCase + private val profileId = "QWERTY" @Before fun attach() { setPreferredAuthenticatorUseCase = SetPreferredAuthenticatorUseCase(oneginiSdk) @@ -43,8 +44,8 @@ class SetPreferredAuthenticatorUseCaseTests { @Test fun `When an authenticatorType is given that is not related to the authenticated user, Then should reject with AUTHENTICATOR_NOT_FOUND`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile(profileId)) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile(profileId)))).thenReturn(emptySet()) val result = setPreferredAuthenticatorUseCase(OWAuthenticatorType.BIOMETRIC).exceptionOrNull() @@ -53,8 +54,8 @@ class SetPreferredAuthenticatorUseCaseTests { @Test fun `When the given authenticatorType is biometric and is registered, Then it should resolve with success`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile(profileId)) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile(profileId)))).thenReturn( setOf( oneginiAuthenticatorMock ) @@ -68,8 +69,8 @@ class SetPreferredAuthenticatorUseCaseTests { @Test fun `When the given authenticatorType is pin and is registered, Then it should resolve with success`() { - whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile("QWERTY")) - whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn( + whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(UserProfile(profileId)) + whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile(profileId)))).thenReturn( setOf( oneginiAuthenticatorMock ) From b7a2ed1dbdc7935410ac18c942a96930b418e507 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 15:38:18 +0200 Subject: [PATCH 298/364] FP-65: Add newline --- .../sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt index 9bfc586b..82093a43 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetBiometricAuthenticatorUseCase.kt @@ -23,4 +23,4 @@ class GetBiometricAuthenticatorUseCase @Inject constructor(private val oneginiSD return Result.success(OWAuthenticator(authenticator.id, authenticator.name, authenticator.isRegistered, authenticator.isPreferred, OWAuthenticatorType.BIOMETRIC)) } -} \ No newline at end of file +} From 67b47d216ec514ae19d0dd4b1c5e80934ae29281 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 19 Apr 2023 16:41:05 +0200 Subject: [PATCH 299/364] FP-51: Use swift api for authenticateDevice and authenticateUserImplicitly --- .../Handlers/ResourcesHandler.swift | 19 ++++++++----------- .../OneginiModuleSwift+Auth.swift | 4 ++-- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 73a668c2..c9d4d251 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -5,7 +5,7 @@ typealias FlutterDataCallback = (Any?, SdkError?) -> Void protocol FetchResourcesHandlerProtocol: AnyObject { func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) - func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) + func authenticateUserImplicitly(_ profile: UserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) func requestResource(_ type: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) } @@ -13,8 +13,7 @@ protocol FetchResourcesHandlerProtocol: AnyObject { class ResourcesHandler: FetchResourcesHandlerProtocol { func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { - Logger.log("authenticateDevice", sender: self) - ONGDeviceClient.sharedInstance().authenticateDevice(scopes) { _, error in + SharedDeviceClient.instance.authenticateDevice(with: scopes) { error in if let error = error { let mappedError = FlutterError(ErrorMapper().mapError(error)) completion(.failure(mappedError)) @@ -24,15 +23,13 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } } - func authenticateUserImplicitly(_ profile: ONGUserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) { - Logger.log("authenticateImplicitly", sender: self) - ONGUserClient.sharedInstance().implicitlyAuthenticateUser(profile, scopes: scopes) { success, error in - if success { - completion(.success) - } else { - // This error construction is obviously not good, but it will work for now till we refactor this later - let mappedError = FlutterError(error.flatMap { ErrorMapper().mapError($0) } ?? SdkError(.genericError)) + func authenticateUserImplicitly(_ profile: UserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) { + SharedUserClient.instance.implicitlyAuthenticate(user: profile, with: scopes) { error in + if let error = error { + let mappedError = FlutterError(ErrorMapper().mapError(error)) completion(.failure(mappedError)) + } else { + completion(.success) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 37e52474..2c1b08bb 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -15,8 +15,8 @@ extension OneginiModuleSwift { public func authenticateUserImplicitly(_ profileId: String, _ scopes: [String]?, completion: @escaping (Result) -> Void) { - guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { + completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) return } From 9b64037c37758b8789216cd1681b2eb5bf7f111d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 16:54:22 +0200 Subject: [PATCH 300/364] FP-51: Use Swift api for resourceRequests --- .../NativeBridge/Errors/SdkError.swift | 10 ++--- .../Handlers/ResourcesHandler.swift | 41 +++++++++---------- ios/Classes/SwiftOneginiPlugin.swift | 2 +- 3 files changed, 26 insertions(+), 27 deletions(-) diff --git a/ios/Classes/NativeBridge/Errors/SdkError.swift b/ios/Classes/NativeBridge/Errors/SdkError.swift index 6066ddd7..afe9b96d 100644 --- a/ios/Classes/NativeBridge/Errors/SdkError.swift +++ b/ios/Classes/NativeBridge/Errors/SdkError.swift @@ -40,7 +40,7 @@ class SdkError: Error { } // Error codes with httResponse information - init(code: Int, errorDescription: String, response: ONGResourceResponse?, iosCode: Int? = nil, iosMessage: String? = nil) { + init(code: Int, errorDescription: String, response: ResourceResponse?, iosCode: Int? = nil, iosMessage: String? = nil) { self.code = code self.errorDescription = errorDescription @@ -48,7 +48,7 @@ class SdkError: Error { setResponseDetails(response, iosCode, iosMessage) } - init(_ wrapperError: OneWelcomeWrapperError, response: ONGResourceResponse?, iosCode: Int? = nil, iosMessage: String? = nil) { + init(_ wrapperError: OneWelcomeWrapperError, response: ResourceResponse?, iosCode: Int? = nil, iosMessage: String? = nil) { self.code = wrapperError.rawValue self.errorDescription = wrapperError.message() @@ -82,7 +82,7 @@ private extension SdkError { } } - func setResponseDetails(_ response: ONGResourceResponse?, _ iosCode: Int?, _ iosMessage: String?) { + func setResponseDetails(_ response: ResourceResponse?, _ iosCode: Int?, _ iosMessage: String?) { if response == nil { details["response"] = [String: Any?]() } else { @@ -100,11 +100,11 @@ private extension SdkError { } } -private extension ONGResourceResponse { +private extension ResourceResponse { func toJSON() -> [String: Any?] { return ["statusCode": statusCode, "headers": allHeaderFields, - "url": rawResponse.url?.absoluteString, + "url": response.url, "body": data != nil ? String(data: data!, encoding: .utf8) : nil ] } diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index c9d4d251..a4f10ee6 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -37,36 +37,35 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { func requestResource(_ requestType: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { Logger.log("requestResource", sender: self) - let request = generateONGResourceRequest(details) + let request = generateResourceRequest(details) let requestCompletion = getRequestCompletion(completion) switch requestType { case ResourceRequestType.implicit: // For consistency with Android we perform this step - if ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() == nil { + + if SharedUserClient.instance.implicitlyAuthenticatedUserProfile == nil { completion(.failure(FlutterError(SdkError(.unauthenticatedImplicitly)))) return } - - ONGUserClient.sharedInstance().fetchImplicitResource(request, completion: requestCompletion) + SharedUserClient.instance.sendImplicitRequest(request, completion: requestCompletion) case ResourceRequestType.anonymous: - ONGDeviceClient.sharedInstance().fetchResource(request, completion: requestCompletion) + SharedDeviceClient.instance.sendRequest(request, completion: requestCompletion) case ResourceRequestType.authenticated: - ONGUserClient.sharedInstance().fetchResource(request, completion: requestCompletion) + SharedUserClient.instance.sendAuthenticatedRequest(request, completion: requestCompletion) case ResourceRequestType.unauthenticated: - ONGDeviceClient.sharedInstance().fetchUnauthenticatedResource(request, completion: requestCompletion) + SharedDeviceClient.instance.sendUnauthenticatedRequest(request, completion: requestCompletion) } } } private extension ResourcesHandler { - func generateONGResourceRequest(_ details: OWRequestDetails) -> ONGResourceRequest { - Logger.log("generateONGResourceRequest", sender: self) - return ONGResourceRequest(path: details.path, - method: details.method.stringValue, - body: details.body?.data(using: .utf8), - headers: getRequestHeaders(details.headers) - ) + func generateResourceRequest(_ details: OWRequestDetails) -> ResourceRequest { + return ResourceRequestFactory.makeResourceRequest(path: details.path, + method: details.method.toHTTPMethod(), + body: details.body?.data(using: .utf8), + headers: getRequestHeaders(details.headers) + ) } func getRequestHeaders(_ headers: [String?: String?]?) -> [String: String]? { @@ -77,9 +76,9 @@ private extension ResourcesHandler { return headers.filter { $0.key != nil && $0.value != nil } as? [String: String] } - func getRequestCompletion(_ completion: @escaping (Result) -> Void) -> ((ONGResourceResponse?, Error?) -> Void)? { + func getRequestCompletion(_ completion: @escaping (Result) -> Void) -> ((ResourceResponse?, Error?) -> Void) { Logger.log("getCompletionRequest", sender: self) - let completionRequest: ((ONGResourceResponse?, Error?) -> Void)? = { response, error in + let completionRequest: ((ResourceResponse?, Error?) -> Void) = { response, error in if let error = error { if response != nil { let flutterError = FlutterError(SdkError(.errorCodeHttpRequest, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) @@ -102,12 +101,12 @@ private extension ResourcesHandler { } private extension HttpRequestMethod { - var stringValue: String { + func toHTTPMethod() -> HTTPMethod { switch self { - case .get: return "GET" - case .post: return "POST" - case .delete: return "DELETE" - case .put: return "PUT" + case .get: return HTTPMethod.get + case .post: return HTTPMethod.post + case .delete: return HTTPMethod.delete + case .put: return HTTPMethod.put } } } diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index e4bc6df5..362c9069 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -43,7 +43,7 @@ extension OWIdentityProvider { } extension OWRequestResponse { - init(_ response: ONGResourceResponse) { + init(_ response: ResourceResponse) { headers = toOWRequestHeaders(response.allHeaderFields) body = String(data: response.data ?? Data(), encoding: .utf8) ?? "" status = Int64(response.statusCode) From 1cd77704e6c7dd0d66753a13d5c8ef838907f149 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 17:40:39 +0200 Subject: [PATCH 301/364] FP-51: Update how we get implicit details and make it nullsafe --- example/lib/screens/login_screen.dart | 156 ++++++++++---------------- 1 file changed, 62 insertions(+), 94 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 80afb071..c8d37bd7 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'dart:async'; import 'dart:convert'; @@ -21,9 +20,8 @@ class LoginScreen extends StatefulWidget { class _LoginScreenState extends State { bool isLoading = false; - OWBroadcastHelper broadcastHelper; - List> registrationSubscriptions; - List> authenticationSubscriptions; + List>? registrationSubscriptions; + List>? authenticationSubscriptions; @override initState() { @@ -94,7 +92,7 @@ class _LoginScreenState extends State { } } - authenticate(String profileId, OWAuthenticatorType authenticatorType) async { + authenticate(String profileId, OWAuthenticatorType? authenticatorType) async { try { var registrationResponse = await Onegini.instance.userClient .authenticateUser(profileId, authenticatorType); @@ -155,6 +153,19 @@ class _LoginScreenState extends State { } } + Widget _buildImplicitUserData(String profileId) { + return FutureBuilder( + future: getImplicitUserDetails(profileId), + builder: (context, snapshot) { + if (snapshot.hasData) { + return Text("${snapshot.data}"); + } else if (snapshot.hasError) { + return Text("Error getting implicit details."); + } + return CircularProgressIndicator(); + }); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -199,95 +210,51 @@ class _LoginScreenState extends State { FutureBuilder>( //userProfiles future: getUserProfiles(), - builder: (context, userProfiles) { - return (userProfiles.hasData && - userProfiles.data.length > 0) + builder: (context, snapshot) { + final userProfileData = snapshot.data; + return (userProfileData != null && + userProfileData.length > 0) ? Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - FutureBuilder( - //implicit - future: getImplicitUserDetails( - userProfiles.data.first?.profileId), - builder: - (context, implicitUserDetails) { - return implicitUserDetails.hasData - ? Column( - crossAxisAlignment: - CrossAxisAlignment.center, - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - Text( - "──── Login ────", - style: TextStyle( - fontSize: 30), - textAlign: - TextAlign.center, - ), - Text( - implicitUserDetails - .data, - style: TextStyle( - fontSize: 20), - textAlign: - TextAlign.center, - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - null); - }, - child: Text( - 'Preferred authenticator'), - ), - Row( - mainAxisAlignment: - MainAxisAlignment - .center, - children: [ - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - OWAuthenticatorType - .pin); - }, - child: Text('Pin'), - ), - SizedBox( - height: 10, - width: 10, - ), - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - OWAuthenticatorType - .biometric); - }, - child: Text( - 'Biometrics'), - ), - ], - ), - ]) - : SizedBox.shrink(); - }) + Text( + "──── Login ────", + style: TextStyle(fontSize: 30), + textAlign: TextAlign.center, + ), + _buildImplicitUserData( + userProfileData.first.profileId), + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + null); + }, + child: Text('Preferred authenticator'), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + OWAuthenticatorType.pin); + }, + child: Text('Pin'), + ), + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + OWAuthenticatorType.biometric); + }, + child: Text('Biometrics'), + ), + ], + ), ]) : SizedBox.shrink(); }), @@ -312,8 +279,9 @@ class _LoginScreenState extends State { ), FutureBuilder>( future: Onegini.instance.userClient.getIdentityProviders(), - builder: (BuildContext context, identityProviders) { - return identityProviders.hasData + builder: (BuildContext context, snapshot) { + final identityProviders = snapshot.data; + return identityProviders != null ? PopupMenuButton( child: Container( padding: EdgeInsets.all(20), @@ -330,9 +298,9 @@ class _LoginScreenState extends State { registrationWithIdentityProvider(value); }, itemBuilder: (context) { - return identityProviders.data + return identityProviders .map((e) => PopupMenuItem( - child: Text(e.name ?? ""), + child: Text(e.name), value: e.id, )) .toList(); From c1d8522a352b54df05860a988739a9be5fbf6388 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 10:00:50 +0200 Subject: [PATCH 302/364] FP-51: Move preferred authenticator into seperate build method --- example/lib/screens/user_screen.dart | 63 ++++++++++++++-------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 409ce1bd..d75e2a63 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'dart:convert'; -import "package:collection/collection.dart"; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/events/onewelcome_events.dart'; @@ -151,7 +150,7 @@ class _UserScreenState extends State with RouteAware { }); } - Widget biometricAuthenticatorWidget() { + Widget _buildBiometricAuthenticatorWidget() { final authenticator = _biometricAuthenticator; if (authenticator != null) { return ListTile( @@ -177,32 +176,38 @@ class _UserScreenState extends State with RouteAware { return SizedBox.shrink(); } - Widget preferredAuthenticatorSelectorWidget() { + Widget _buildPreferredAuthenticatorSelectorWidget() { final biometricAuthenticator = _biometricAuthenticator; - return PopupMenuButton( - child: ListTile( - title: Text("set preferred authenticator"), - leading: Icon(Icons.add_to_home_screen), - ), - onSelected: (value) { - Onegini.instance.userClient - .setPreferredAuthenticator(value) - .whenComplete(() => getAuthenticators()); - }, - itemBuilder: (context) { - return [ - PopupMenuItem( - child: Text("Pin"), - value: OWAuthenticatorType.pin, - ), - if (biometricAuthenticator != null && - biometricAuthenticator.isRegistered) + return Column(mainAxisSize: MainAxisSize.min, children: [ + ListTile( + title: + Text("Preferred Authenticator: ${_preferredAuthenticator?.name} "), + ), + PopupMenuButton( + child: ListTile( + title: Text("set preferred authenticator"), + leading: Icon(Icons.add_to_home_screen), + ), + onSelected: (value) { + Onegini.instance.userClient + .setPreferredAuthenticator(value) + .whenComplete(() => getAuthenticators()); + }, + itemBuilder: (context) { + return [ PopupMenuItem( - child: Text(biometricAuthenticator.name), - value: OWAuthenticatorType.biometric, + child: Text("Pin"), + value: OWAuthenticatorType.pin, ), - ]; - }); + if (biometricAuthenticator != null && + biometricAuthenticator.isRegistered) + PopupMenuItem( + child: Text(biometricAuthenticator.name), + value: OWAuthenticatorType.biometric, + ), + ]; + }) + ]); } @override @@ -234,12 +239,8 @@ class _UserScreenState extends State with RouteAware { title: Text("Pin"), leading: Switch(value: true, onChanged: null), ), - biometricAuthenticatorWidget(), - ListTile( - title: Text( - "Preferred Authenticator: ${_preferredAuthenticator?.name} "), - ), - preferredAuthenticatorSelectorWidget(), + _buildBiometricAuthenticatorWidget(), + _buildPreferredAuthenticatorSelectorWidget(), Divider(), ListTile( title: Text("Change pin"), From 52883b6127e4fa7af5f016706bcb10ed384a144a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 10:38:05 +0200 Subject: [PATCH 303/364] FP-51: Refactor info screen --- example/lib/screens/user_screen.dart | 213 +++++++++++---------------- 1 file changed, 90 insertions(+), 123 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index d75e2a63..56efb1d3 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -421,28 +421,102 @@ class Info extends StatefulWidget { } class _InfoState extends State { - Future getApplicationDetails() async { + Future _getApplicationDetails() async { await Onegini.instance.userClient .authenticateDevice(["read", "write", "application-details"]); - var response = await Onegini.instance.resourcesMethods.requestResource( + final response = await Onegini.instance.resourcesMethods.requestResource( ResourceRequestType.anonymous, RequestDetails( path: "application-details", method: HttpRequestMethod.get)); - var res = json.decode(response.body); - return applicationDetailsFromJson(res); + return applicationDetailsFromJson(response.body); } - Future getClientResource() async { - var response = await Onegini.instance.resourcesMethods + Future _getClientResource() async { + final response = await Onegini.instance.resourcesMethods .requestResourceAuthenticated( - RequestDetails(path: "devices", method: HttpRequestMethod.get)) - .catchError((error) { - print('Caught error: $error'); + RequestDetails(path: "devices", method: HttpRequestMethod.get)); + return clientResourceFromJson(response.body); + } - showFlutterToast(error.message); - }); + FutureBuilder _buildDeviceInfoList() { + return FutureBuilder( + future: _getClientResource(), + builder: (context, snapshot) { + final snapshotData = snapshot.data; + return snapshotData != null + ? ListView.builder( + itemCount: snapshotData.devices.length, + itemBuilder: (BuildContext context, int index) { + return ExpansionTile( + title: Text(snapshotData.devices[index].name), + expandedCrossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListTile( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Id => ${snapshotData.devices[index].id}", + style: TextStyle(fontSize: 15), + ), + SizedBox(height: 10), + Text( + "Application => ${snapshotData.devices[index].application}", + style: TextStyle(fontSize: 15), + ), + SizedBox(height: 10), + Text( + "Mobile authentication enabled => ${snapshotData.devices[index].mobileAuthenticationEnabled.toString()}", + style: TextStyle(fontSize: 15), + ), + SizedBox(height: 10), + Text( + "Platform => ${snapshotData.devices[index].platform}", + style: TextStyle(fontSize: 15), + ), + SizedBox(), + ], + )) + ], + ); + }, + ) + : Center( + child: SizedBox( + child: CircularProgressIndicator(), + ), + ); + }, + ); + } - return clientResourceFromJson(response.body); + FutureBuilder _buildApplicationDetails() { + return FutureBuilder( + future: _getApplicationDetails(), + builder: (context, snapshot) { + return snapshot.hasData + ? Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "application identifier => ${snapshot.data?.applicationIdentifier}", + style: TextStyle(fontSize: 15), + ), + SizedBox(height: 10), + Text( + "application platform => ${snapshot.data?.applicationPlatform}", + style: TextStyle(fontSize: 15), + ), + SizedBox(height: 10), + Text( + "application version => ${snapshot.data?.applicationVersion}", + style: TextStyle(fontSize: 15), + ), + ], + ) + : CircularProgressIndicator(); + }, + ); } @override @@ -453,118 +527,11 @@ class _InfoState extends State { margin: EdgeInsets.all(20), child: Column( children: [ - SizedBox( - height: 20, - ), - FutureBuilder( - future: getApplicationDetails(), - builder: (context, snapshot) { - return snapshot.hasData - ? Column( - children: [ - Row( - children: [ - Text( - "application identifier => ", - style: TextStyle(fontSize: 18), - ), - Text( - snapshot.data?.applicationIdentifier ?? "", - style: TextStyle(fontSize: 18), - ) - ], - ), - SizedBox( - height: 10, - ), - Row( - children: [ - Text( - "application platform => ", - style: TextStyle(fontSize: 18), - ), - Text( - snapshot.data?.applicationPlatform ?? "", - style: TextStyle(fontSize: 18), - ) - ], - ), - SizedBox( - height: 10, - ), - Row( - children: [ - Text( - "application version => ", - style: TextStyle(fontSize: 18), - ), - Text( - snapshot.data?.applicationVersion ?? "", - style: TextStyle(fontSize: 18), - ) - ], - ), - SizedBox( - height: 10, - ), - ], - ) - : Text(""); - }, - ), + SizedBox(height: 20), + _buildApplicationDetails(), + Divider(), Expanded( - child: FutureBuilder( - future: getClientResource(), - builder: (context, snapshot) { - final snapshotData = snapshot.data; - return snapshotData != null - ? ListView.builder( - itemCount: snapshotData.devices.length, - itemBuilder: (BuildContext context, int index) { - return ExpansionTile( - title: Text(snapshotData.devices[index].name), - expandedCrossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - "Id => ${snapshotData.devices[index].id}", - style: TextStyle(fontSize: 18), - ), - SizedBox( - height: 10, - ), - Text( - "Application => ${snapshotData.devices[index].application}", - style: TextStyle(fontSize: 18), - ), - SizedBox( - height: 10, - ), - Text( - "Mobile authentication enabled => ${snapshotData.devices[index].mobileAuthenticationEnabled.toString()}", - style: TextStyle(fontSize: 18), - ), - SizedBox( - height: 10, - ), - Text( - "Platform => ${snapshotData.devices[index].platform}", - style: TextStyle(fontSize: 18), - ), - SizedBox( - height: 10, - ), - ], - ); - }, - ) - : Center( - child: SizedBox( - child: CircularProgressIndicator(), - ), - ); - }, - ), + child: _buildDeviceInfoList(), ), ], ), From 15540544e296a5e62aa37eede9b856fe50c750bd Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 10:51:22 +0200 Subject: [PATCH 304/364] FP-51: Make fingerprintscreen nullsafe --- example/lib/screens/fingerprint_screen.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/example/lib/screens/fingerprint_screen.dart b/example/lib/screens/fingerprint_screen.dart index 29b09ae7..ae1adb99 100644 --- a/example/lib/screens/fingerprint_screen.dart +++ b/example/lib/screens/fingerprint_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_fingerprint_callback.dart'; From 3c376cf412756dc8f53ba27c4fd25ee038be5e79 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 10:51:32 +0200 Subject: [PATCH 305/364] FP-51: Refactor method name --- example/lib/screens/user_screen.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 56efb1d3..c0ef9e27 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -176,7 +176,7 @@ class _UserScreenState extends State with RouteAware { return SizedBox.shrink(); } - Widget _buildPreferredAuthenticatorSelectorWidget() { + Widget _buildPreferredAuthenticatorWidget() { final biometricAuthenticator = _biometricAuthenticator; return Column(mainAxisSize: MainAxisSize.min, children: [ ListTile( @@ -240,7 +240,7 @@ class _UserScreenState extends State with RouteAware { leading: Switch(value: true, onChanged: null), ), _buildBiometricAuthenticatorWidget(), - _buildPreferredAuthenticatorSelectorWidget(), + _buildPreferredAuthenticatorWidget(), Divider(), ListTile( title: Text("Change pin"), From 3e335b8f072aba93ffa896f8e7f09966c832950e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 12:15:50 +0200 Subject: [PATCH 306/364] FP-84: Add workflows.yml for dart linting/formatting on github actions --- .github/workflows/workflow.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/workflow.yml diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml new file mode 100644 index 00000000..c0bdaca9 --- /dev/null +++ b/.github/workflows/workflow.yml @@ -0,0 +1,20 @@ +name: Main workflow +on: [push, pull_request] + +jobs: + lint_and_format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: subosito/flutter-action@v2 + with: + channel: "stable" + - run: flutter --version + - name: Install dependencies + run: dart pub get + - name: Verify formatting + run: dart format --output=none --set-exit-if-changed . + - name: Analyze project source + run: dart analyze --fatal-infos + - name: output + run: echo CACHE-PATH=${{ steps.flutter-action.outputs.CACHE-PATH }} From 235c1a6161537a730e918749e4690cb7af9d92d1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 12:54:52 +0200 Subject: [PATCH 307/364] FP-84: Format the generated code after generation --- pigeons/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/pigeons/README.md b/pigeons/README.md index b886dc63..cacb7909 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -8,6 +8,7 @@ flutter pub run pigeon \ --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ --experimental_swift_out ios/Classes/Pigeon.swift +dart format lib/pigeon.dart ## Missing documentation Pigeon is poorly documented; so to keep knowledge on why and how certain things are done we will refer to pull requests where we obtained information. From 58f2d1fe6f34678b34f8dbac5437691464304f7a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 12:55:14 +0200 Subject: [PATCH 308/364] FP-84: Auto format dart code --- .../onegini_custom_registration_callback.dart | 6 +- .../onegini_fingerprint_callback.dart | 1 + lib/model/request_response.dart | 6 +- lib/pigeon.dart | 243 ++++++++++-------- lib/resources_methods.dart | 111 +++++--- 5 files changed, 227 insertions(+), 140 deletions(-) diff --git a/lib/callbacks/onegini_custom_registration_callback.dart b/lib/callbacks/onegini_custom_registration_callback.dart index f5692326..09d9598a 100644 --- a/lib/callbacks/onegini_custom_registration_callback.dart +++ b/lib/callbacks/onegini_custom_registration_callback.dart @@ -3,11 +3,13 @@ import 'package:onegini/pigeon.dart'; class OneginiCustomRegistrationCallback { final api = UserClientApi(); - Future submitSuccessAction(String identityProviderId, String? data) async { + Future submitSuccessAction( + String identityProviderId, String? data) async { await api.submitCustomRegistrationAction(identityProviderId, data); } - Future submitErrorAction(String identityProviderId, String error) async { + Future submitErrorAction( + String identityProviderId, String error) async { await api.cancelCustomRegistrationAction(identityProviderId, error); } } diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index 2168f702..6d9e3555 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -6,6 +6,7 @@ import 'package:onegini/pigeon.dart'; /// Use this callback when user want authenticate by fingerprint. class OneginiFingerprintCallback { final api = UserClientApi(); + /// Changes the authentication method from fingerprint to PIN. Future fallbackToPin() async { await api.fingerprintFallbackToPin(); diff --git a/lib/model/request_response.dart b/lib/model/request_response.dart index f3bbf4fe..d20670a2 100644 --- a/lib/model/request_response.dart +++ b/lib/model/request_response.dart @@ -5,5 +5,9 @@ class RequestResponse { bool ok; int status; - RequestResponse({required this.headers, required this.body, required this.ok, required this.status}); + RequestResponse( + {required this.headers, + required this.body, + required this.ok, + required this.status}); } diff --git a/lib/pigeon.dart b/lib/pigeon.dart index ace1e4bf..57ec674c 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -384,19 +384,19 @@ class _UserClientApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAppToWebSingleSignOn.decode(readValue(buffer)!); - case 129: + case 129: return OWAuthenticator.decode(readValue(buffer)!); - case 130: + case 130: return OWCustomIdentityProvider.decode(readValue(buffer)!); - case 131: + case 131: return OWCustomInfo.decode(readValue(buffer)!); - case 132: + case 132: return OWIdentityProvider.decode(readValue(buffer)!); - case 133: + case 133: return OWRegistrationResponse.decode(readValue(buffer)!); - case 134: + case 134: return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -415,12 +415,22 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout) async { + Future startApplication( + String? arg_securityControllerClassName, + String? arg_configModelClassName, + List? arg_customIdentityProviderConfigs, + int? arg_connectionTimeout, + int? arg_readTimeout) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.startApplication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout]) as List?; + final List? replyList = await channel.send([ + arg_securityControllerClassName, + arg_configModelClassName, + arg_customIdentityProviderConfigs, + arg_connectionTimeout, + arg_readTimeout + ]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -437,12 +447,13 @@ class UserClientApi { } } - Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { + Future registerUser( + String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_identityProviderId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -464,12 +475,13 @@ class UserClientApi { } } - Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl( + String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_url, arg_signInType]) as List?; + final List? replyList = await channel + .send([arg_url, arg_signInType]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -490,8 +502,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getIdentityProviders', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -539,8 +550,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -562,12 +572,14 @@ class UserClientApi { } } - Future authenticateUser(String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { + Future authenticateUser( + String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_authenticatorType.index]) + as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -589,7 +601,8 @@ class UserClientApi { } } - Future authenticateUserPreferred(String arg_profileId) async { + Future authenticateUserPreferred( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserPreferred', codec, binaryMessenger: _binaryMessenger); @@ -616,7 +629,8 @@ class UserClientApi { } } - Future getBiometricAuthenticator(String arg_profileId) async { + Future getBiometricAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -643,7 +657,8 @@ class UserClientApi { } } - Future getPreferredAuthenticator(String arg_profileId) async { + Future getPreferredAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -670,12 +685,13 @@ class UserClientApi { } } - Future setPreferredAuthenticator(OWAuthenticatorType arg_authenticatorType) async { + Future setPreferredAuthenticator( + OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -694,10 +710,10 @@ class UserClientApi { Future deregisterBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -716,10 +732,10 @@ class UserClientApi { Future registerBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -740,8 +756,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -762,8 +777,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.logout', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -784,8 +798,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -855,8 +868,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -882,8 +894,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getRedirectUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -909,8 +920,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getUserProfiles', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -976,12 +986,13 @@ class UserClientApi { } } - Future authenticateUserImplicitly(String arg_profileId, List? arg_scopes) async { + Future authenticateUserImplicitly( + String arg_profileId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -999,12 +1010,14 @@ class UserClientApi { } /// Custom Registration Callbacks - Future submitCustomRegistrationAction(String arg_identityProviderId, String? arg_data) async { + Future submitCustomRegistrationAction( + String arg_identityProviderId, String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_data]) as List?; + final List? replyList = await channel + .send([arg_identityProviderId, arg_data]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1021,12 +1034,14 @@ class UserClientApi { } } - Future cancelCustomRegistrationAction(String arg_identityProviderId, String arg_error) async { + Future cancelCustomRegistrationAction( + String arg_identityProviderId, String arg_error) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_error]) as List?; + final List? replyList = await channel + .send([arg_identityProviderId, arg_error]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1048,8 +1063,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1068,10 +1082,10 @@ class UserClientApi { Future fingerprintDenyAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1090,10 +1104,10 @@ class UserClientApi { Future fingerprintAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1115,8 +1129,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1135,10 +1148,10 @@ class UserClientApi { Future otpAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1160,8 +1173,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1180,7 +1192,8 @@ class UserClientApi { Future pinAcceptAuthenticationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_pin]) as List?; @@ -1205,8 +1218,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1250,8 +1262,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1287,9 +1298,9 @@ class _ResourceMethodApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWRequestDetails.decode(readValue(buffer)!); - case 129: + case 129: return OWRequestResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1307,12 +1318,13 @@ class ResourceMethodApi { static const MessageCodec codec = _ResourceMethodApiCodec(); - Future requestResource(ResourceRequestType arg_type, OWRequestDetails arg_details) async { + Future requestResource( + ResourceRequestType arg_type, OWRequestDetails arg_details) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.ResourceMethodApi.requestResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_type.index, arg_details]) as List?; + final List? replyList = await channel + .send([arg_type.index, arg_details]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1356,11 +1368,11 @@ class _NativeCallFlutterApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAuthenticationAttempt.decode(readValue(buffer)!); - case 129: + case 129: return OWCustomInfo.decode(readValue(buffer)!); - case 130: + case 130: return OWOneginiError.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1392,12 +1404,13 @@ abstract class NativeCallFlutterApi { void n2fOpenPinAuthentication(); /// Called to close pin authentication screen. - /// changed n2fClosePinAuth into n2fClosePinAuthentication + /// changed n2fClosePinAuth into n2fClosePinAuthentication void n2fClosePinAuthentication(); /// Called to attempt next pin authentication. /// changed n2fNextAuthenticationAttempt into n2fNextPinAuthenticationAttempt - void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); + void n2fNextPinAuthenticationAttempt( + OWAuthenticationAttempt authenticationAttempt); /// Called to open OTP authentication. void n2fOpenAuthOtp(String? message); @@ -1418,22 +1431,26 @@ abstract class NativeCallFlutterApi { void n2fNextFingerprintAuthenticationAttempt(); /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) - void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventInitCustomRegistration( + OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given - void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventFinishCustomRegistration( + OWCustomInfo? customInfo, String providerId); - static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(NativeCallFlutterApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); final List args = (message as List?)!; final String? arg_url = (args[0] as String?); assert(arg_url != null, @@ -1480,7 +1497,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); final List args = (message as List?)!; final OWOneginiError? arg_error = (args[0] as OWOneginiError?); assert(arg_error != null, @@ -1492,7 +1509,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1506,7 +1524,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1520,16 +1539,18 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); final List args = (message as List?)!; - final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); + final OWAuthenticationAttempt? arg_authenticationAttempt = + (args[0] as OWAuthenticationAttempt?); assert(arg_authenticationAttempt != null, 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); api.n2fNextPinAuthenticationAttempt(arg_authenticationAttempt!); @@ -1546,7 +1567,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); api.n2fOpenAuthOtp(arg_message); @@ -1570,7 +1591,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1584,7 +1606,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1598,7 +1621,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1612,7 +1636,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1626,14 +1651,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); @@ -1646,14 +1672,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index 38514b2d..ed008a44 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -8,58 +8,111 @@ class ResourcesMethods { final api = ResourceMethodApi(); /// Gets any type of resource - Future requestResource(ResourceRequestType type, RequestDetails details) async { - var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); + Future requestResource( + ResourceRequestType type, RequestDetails details) async { + var owDetails = OWRequestDetails( + path: details.path, + method: details.method, + headers: details.headers, + body: details.body); var owResponse = await api.requestResource(type, owDetails); - owResponse.headers.removeWhere((key, value) => key == null || value == null); + owResponse.headers + .removeWhere((key, value) => key == null || value == null); var headers = Map.from(owResponse.headers); - return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + return RequestResponse( + headers: headers, + body: owResponse.body, + ok: owResponse.ok, + status: owResponse.status); } - /// Gets resources anonymously. - Future requestResourceAnonymous(RequestDetails details) async { - var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); - var owResponse = await api.requestResource(ResourceRequestType.anonymous, owDetails); - - owResponse.headers.removeWhere((key, value) => key == null || value == null); + Future requestResourceAnonymous( + RequestDetails details) async { + var owDetails = OWRequestDetails( + path: details.path, + method: details.method, + headers: details.headers, + body: details.body); + var owResponse = + await api.requestResource(ResourceRequestType.anonymous, owDetails); + + owResponse.headers + .removeWhere((key, value) => key == null || value == null); var headers = Map.from(owResponse.headers); - return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + return RequestResponse( + headers: headers, + body: owResponse.body, + ok: owResponse.ok, + status: owResponse.status); } /// Gets authenticated resources. - Future requestResourceAuthenticated(RequestDetails details) async { - var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); - var owResponse = await api.requestResource(ResourceRequestType.authenticated, owDetails); - - owResponse.headers.removeWhere((key, value) => key == null || value == null); + Future requestResourceAuthenticated( + RequestDetails details) async { + var owDetails = OWRequestDetails( + path: details.path, + method: details.method, + headers: details.headers, + body: details.body); + var owResponse = + await api.requestResource(ResourceRequestType.authenticated, owDetails); + + owResponse.headers + .removeWhere((key, value) => key == null || value == null); var headers = Map.from(owResponse.headers); - return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + return RequestResponse( + headers: headers, + body: owResponse.body, + ok: owResponse.ok, + status: owResponse.status); } /// Gets implicit resource. - Future requestResourceImplicit(RequestDetails details) async { - var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); - var owResponse = await api.requestResource(ResourceRequestType.implicit, owDetails); - - owResponse.headers.removeWhere((key, value) => key == null || value == null); + Future requestResourceImplicit( + RequestDetails details) async { + var owDetails = OWRequestDetails( + path: details.path, + method: details.method, + headers: details.headers, + body: details.body); + var owResponse = + await api.requestResource(ResourceRequestType.implicit, owDetails); + + owResponse.headers + .removeWhere((key, value) => key == null || value == null); var headers = Map.from(owResponse.headers); - return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + return RequestResponse( + headers: headers, + body: owResponse.body, + ok: owResponse.ok, + status: owResponse.status); } /// Gets unauthenticated resource. - Future requestResourceUnauthenticated(RequestDetails details) async { - var owDetails = OWRequestDetails(path: details.path, method: details.method, headers: details.headers, body: details.body); - var owResponse = await api.requestResource(ResourceRequestType.unauthenticated, owDetails); - - owResponse.headers.removeWhere((key, value) => key == null || value == null); + Future requestResourceUnauthenticated( + RequestDetails details) async { + var owDetails = OWRequestDetails( + path: details.path, + method: details.method, + headers: details.headers, + body: details.body); + var owResponse = await api.requestResource( + ResourceRequestType.unauthenticated, owDetails); + + owResponse.headers + .removeWhere((key, value) => key == null || value == null); var headers = Map.from(owResponse.headers); - return RequestResponse(headers: headers, body: owResponse.body, ok: owResponse.ok, status: owResponse.status); + return RequestResponse( + headers: headers, + body: owResponse.body, + ok: owResponse.ok, + status: owResponse.status); } } From 6f60afa6937750d9d7b266a7583a72d6644b7756 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 13:11:59 +0200 Subject: [PATCH 309/364] FP-84: Use flutter to get packages and run analyze --- .github/workflows/workflow.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml index c0bdaca9..84be9a5c 100644 --- a/.github/workflows/workflow.yml +++ b/.github/workflows/workflow.yml @@ -9,12 +9,13 @@ jobs: - uses: subosito/flutter-action@v2 with: channel: "stable" + architecture: x64 - run: flutter --version - name: Install dependencies - run: dart pub get + run: flutter pub get - name: Verify formatting run: dart format --output=none --set-exit-if-changed . - name: Analyze project source - run: dart analyze --fatal-infos + run: flutter analyze --fatal-infos - name: output run: echo CACHE-PATH=${{ steps.flutter-action.outputs.CACHE-PATH }} From 9eb33eae7d01c994b931162bad54394bcc4ad6f3 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 13:22:48 +0200 Subject: [PATCH 310/364] FP-84: Fix info warnings --- example/lib/components/display_toast.dart | 1 - example/lib/screens/user_screen.dart | 41 ++++++++++--------- .../fingerprint_subscriptions.dart | 1 - 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/example/lib/components/display_toast.dart b/example/lib/components/display_toast.dart index 3b986064..13d14dc0 100644 --- a/example/lib/components/display_toast.dart +++ b/example/lib/components/display_toast.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; void showFlutterToast(String? message) { diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 409ce1bd..b12798ac 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'dart:convert'; -import "package:collection/collection.dart"; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/events/onewelcome_events.dart'; @@ -11,12 +10,14 @@ import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/models/application_details.dart'; import 'package:onegini_example/models/client_resource.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:onegini_example/subscription_handlers/otp_subscriptions.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:onegini/pigeon.dart'; - +// ignore: import_of_legacy_library_into_null_safe import '../main.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'login_screen.dart'; class UserScreen extends StatefulWidget { @@ -304,20 +305,18 @@ class Home extends StatelessWidget { } getAppToWebSingleSignOn(BuildContext context) async { - var oneginiAppToWebSingleSignOn = await Onegini.instance.userClient - .getAppToWebSingleSignOn( - "https://login-mobile.test.onegini.com/personal/dashboard") - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); - if (oneginiAppToWebSingleSignOn != null) { + try { + final oneginiAppToWebSingleSignOn = await Onegini.instance.userClient + .getAppToWebSingleSignOn( + "https://login-mobile.test.onegini.com/personal/dashboard"); + // FIXME: Find a different way to launch this. // ignore: deprecated_member_use await launch( oneginiAppToWebSingleSignOn.redirectUrl, enableDomStorage: true, ); + } on PlatformException catch (error) { + showFlutterToast(error.message); } } @@ -343,15 +342,15 @@ class Home extends StatelessWidget { } performUnauthenticatedRequest() async { - var response = await Onegini.instance.resourcesMethods - .requestResourceUnauthenticated(RequestDetails( - path: "unauthenticated", method: HttpRequestMethod.get)) - .catchError((error) { - print("An error occured $error"); - showFlutterToast("An error occured $error"); - }); - - showFlutterToast("Response: ${response.body}"); + try { + final response = await Onegini.instance.resourcesMethods + .requestResourceUnauthenticated(RequestDetails( + path: "unauthenticated", method: HttpRequestMethod.get)); + showFlutterToast("Response: ${response.body}"); + } on PlatformException catch (error) { + print("An error occured ${error.message}"); + showFlutterToast("An error occured ${error.message}"); + } } @override @@ -435,6 +434,8 @@ class _InfoState extends State { var response = await Onegini.instance.resourcesMethods .requestResourceAuthenticated( RequestDetails(path: "devices", method: HttpRequestMethod.get)) + // Will be fixed in FP-51 + // ignore: body_might_complete_normally_catch_error .catchError((error) { print('Caught error: $error'); diff --git a/example/lib/subscription_handlers/fingerprint_subscriptions.dart b/example/lib/subscription_handlers/fingerprint_subscriptions.dart index cf6621d7..49dfe50d 100644 --- a/example/lib/subscription_handlers/fingerprint_subscriptions.dart +++ b/example/lib/subscription_handlers/fingerprint_subscriptions.dart @@ -3,7 +3,6 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/events/pin_event.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; // ignore: import_of_legacy_library_into_null_safe import 'package:onegini_example/screens/fingerprint_screen.dart'; From 8c161478daf019b49503a614c23cfb3c724e5502 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 13:55:16 +0200 Subject: [PATCH 311/364] FP-84: Remove final output step --- .github/workflows/workflow.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml index 84be9a5c..0c0586d9 100644 --- a/.github/workflows/workflow.yml +++ b/.github/workflows/workflow.yml @@ -17,5 +17,3 @@ jobs: run: dart format --output=none --set-exit-if-changed . - name: Analyze project source run: flutter analyze --fatal-infos - - name: output - run: echo CACHE-PATH=${{ steps.flutter-action.outputs.CACHE-PATH }} From c577f3750c0be2c722b2f61e9ac46d1826325707 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Fri, 21 Apr 2023 14:17:33 +0200 Subject: [PATCH 312/364] FP-84: Update a deprecated way to open url in external browser --- example/lib/screens/user_screen.dart | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index b12798ac..c5ce6dfd 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -309,12 +309,11 @@ class Home extends StatelessWidget { final oneginiAppToWebSingleSignOn = await Onegini.instance.userClient .getAppToWebSingleSignOn( "https://login-mobile.test.onegini.com/personal/dashboard"); - // FIXME: Find a different way to launch this. - // ignore: deprecated_member_use - await launch( - oneginiAppToWebSingleSignOn.redirectUrl, - enableDomStorage: true, - ); + if (!await launchUrl(Uri.parse(oneginiAppToWebSingleSignOn.redirectUrl), + mode: LaunchMode.externalApplication)) { + throw Exception( + 'Could not launch ${oneginiAppToWebSingleSignOn.redirectUrl}'); + } } on PlatformException catch (error) { showFlutterToast(error.message); } From 8c6c0c4986816e4d2dcc7bfd5a4c161937e40b2b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 14:21:06 +0200 Subject: [PATCH 313/364] FP-86: Make auth_otp_screen nullsafe --- example/lib/screens/auth_otp_screen.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/example/lib/screens/auth_otp_screen.dart b/example/lib/screens/auth_otp_screen.dart index 17a4af33..8ea58c13 100644 --- a/example/lib/screens/auth_otp_screen.dart +++ b/example/lib/screens/auth_otp_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_otp_accept_deny_callback.dart'; @@ -7,7 +6,7 @@ import '../components/display_toast.dart'; class AuthOtpScreen extends StatefulWidget { final String message; - const AuthOtpScreen({Key key, this.message}) : super(key: key); + const AuthOtpScreen({Key? key, required this.message}) : super(key: key); @override _AuthOtpScreenState createState() => _AuthOtpScreenState(); From 8d93ecc4cd18462f671a396bc488cfb40793a2b8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 14:36:17 +0200 Subject: [PATCH 314/364] FP-86: Make fingerprint screen nullsafe --- example/lib/screens/fingerprint_screen.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/example/lib/screens/fingerprint_screen.dart b/example/lib/screens/fingerprint_screen.dart index 29b09ae7..ae1adb99 100644 --- a/example/lib/screens/fingerprint_screen.dart +++ b/example/lib/screens/fingerprint_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_fingerprint_callback.dart'; From 4d93f63ce949e258edc2bf89806c38ead881e615 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Thu, 20 Apr 2023 17:40:39 +0200 Subject: [PATCH 315/364] FP-51: Update how we get implicit details and make it nullsafe --- example/lib/screens/login_screen.dart | 156 ++++++++++---------------- 1 file changed, 62 insertions(+), 94 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 80afb071..c8d37bd7 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'dart:async'; import 'dart:convert'; @@ -21,9 +20,8 @@ class LoginScreen extends StatefulWidget { class _LoginScreenState extends State { bool isLoading = false; - OWBroadcastHelper broadcastHelper; - List> registrationSubscriptions; - List> authenticationSubscriptions; + List>? registrationSubscriptions; + List>? authenticationSubscriptions; @override initState() { @@ -94,7 +92,7 @@ class _LoginScreenState extends State { } } - authenticate(String profileId, OWAuthenticatorType authenticatorType) async { + authenticate(String profileId, OWAuthenticatorType? authenticatorType) async { try { var registrationResponse = await Onegini.instance.userClient .authenticateUser(profileId, authenticatorType); @@ -155,6 +153,19 @@ class _LoginScreenState extends State { } } + Widget _buildImplicitUserData(String profileId) { + return FutureBuilder( + future: getImplicitUserDetails(profileId), + builder: (context, snapshot) { + if (snapshot.hasData) { + return Text("${snapshot.data}"); + } else if (snapshot.hasError) { + return Text("Error getting implicit details."); + } + return CircularProgressIndicator(); + }); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -199,95 +210,51 @@ class _LoginScreenState extends State { FutureBuilder>( //userProfiles future: getUserProfiles(), - builder: (context, userProfiles) { - return (userProfiles.hasData && - userProfiles.data.length > 0) + builder: (context, snapshot) { + final userProfileData = snapshot.data; + return (userProfileData != null && + userProfileData.length > 0) ? Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - FutureBuilder( - //implicit - future: getImplicitUserDetails( - userProfiles.data.first?.profileId), - builder: - (context, implicitUserDetails) { - return implicitUserDetails.hasData - ? Column( - crossAxisAlignment: - CrossAxisAlignment.center, - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - Text( - "──── Login ────", - style: TextStyle( - fontSize: 30), - textAlign: - TextAlign.center, - ), - Text( - implicitUserDetails - .data, - style: TextStyle( - fontSize: 20), - textAlign: - TextAlign.center, - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - null); - }, - child: Text( - 'Preferred authenticator'), - ), - Row( - mainAxisAlignment: - MainAxisAlignment - .center, - children: [ - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - OWAuthenticatorType - .pin); - }, - child: Text('Pin'), - ), - SizedBox( - height: 10, - width: 10, - ), - ElevatedButton( - onPressed: () { - authenticate( - userProfiles - .data - .first - ?.profileId, - OWAuthenticatorType - .biometric); - }, - child: Text( - 'Biometrics'), - ), - ], - ), - ]) - : SizedBox.shrink(); - }) + Text( + "──── Login ────", + style: TextStyle(fontSize: 30), + textAlign: TextAlign.center, + ), + _buildImplicitUserData( + userProfileData.first.profileId), + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + null); + }, + child: Text('Preferred authenticator'), + ), + Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + OWAuthenticatorType.pin); + }, + child: Text('Pin'), + ), + ElevatedButton( + onPressed: () { + authenticate( + userProfileData.first.profileId, + OWAuthenticatorType.biometric); + }, + child: Text('Biometrics'), + ), + ], + ), ]) : SizedBox.shrink(); }), @@ -312,8 +279,9 @@ class _LoginScreenState extends State { ), FutureBuilder>( future: Onegini.instance.userClient.getIdentityProviders(), - builder: (BuildContext context, identityProviders) { - return identityProviders.hasData + builder: (BuildContext context, snapshot) { + final identityProviders = snapshot.data; + return identityProviders != null ? PopupMenuButton( child: Container( padding: EdgeInsets.all(20), @@ -330,9 +298,9 @@ class _LoginScreenState extends State { registrationWithIdentityProvider(value); }, itemBuilder: (context) { - return identityProviders.data + return identityProviders .map((e) => PopupMenuItem( - child: Text(e.name ?? ""), + child: Text(e.name), value: e.id, )) .toList(); From 9f1f6d4b2cd8145ba32276b53fbf22e8e1c5f0b7 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 14:38:18 +0200 Subject: [PATCH 316/364] FP-86: Make otp_screen nullsafe --- example/lib/screens/otp_screen.dart | 6 +++--- .../custom_registration_subscriptions.dart | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/example/lib/screens/otp_screen.dart b/example/lib/screens/otp_screen.dart index 9a3bc84c..5a2e41c8 100644 --- a/example/lib/screens/otp_screen.dart +++ b/example/lib/screens/otp_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; @@ -10,7 +9,8 @@ class OtpScreen extends StatefulWidget { final String password; final String providerId; - const OtpScreen({Key key, this.password, this.providerId}) : super(key: key); + const OtpScreen({Key? key, required this.password, required this.providerId}) + : super(key: key); @override _OtpScreenState createState() => _OtpScreenState(); @@ -22,7 +22,7 @@ class _OtpScreenState extends State { ok() async { if (myController.text.isNotEmpty) { OneginiCustomRegistrationCallback() - .submitSuccessAction(widget.providerId, myController.text ?? " ") + .submitSuccessAction(widget.providerId, myController.text) .catchError((error) => { if (error is PlatformException) {showFlutterToast(error.message)} diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index 2c762d00..9149eefb 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -47,7 +47,7 @@ StreamSubscription _getFinishCustomRegistrationSub( context, MaterialPageRoute( builder: (context) => OtpScreen( - password: event.customInfo?.data, + password: event.customInfo?.data ?? "", providerId: event.providerId)), ); } From 9d4205faeb7838364ba0c241f9cacbb42673e0f6 Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 24 Apr 2023 15:15:52 +0200 Subject: [PATCH 317/364] fp-83 error rework structure + combined errors --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 52 +++---- .../onegini/mobile/sdk/flutter/OneginiSDK.kt | 6 +- .../mobile/sdk/flutter/SdkErrorAssert.kt | 5 +- ...FingerprintAuthenticationRequestHandler.kt | 8 +- .../handlers/MobileAuthOtpRequestHandler.kt | 6 +- .../PinAuthenticationRequestHandler.kt | 4 +- .../sdk/flutter/handlers/PinRequestHandler.kt | 6 +- .../CustomTwoStepRegistrationActionImpl.kt | 8 +- .../useCases/AuthenticateUserUseCase.kt | 2 +- .../CancelBrowserRegistrationUseCase.kt | 4 +- .../CancelCustomRegistrationActionUseCase.kt | 4 +- .../DeregisterAuthenticatorUseCase.kt | 4 +- .../flutter/useCases/GetAccessTokenUseCase.kt | 4 +- .../GetAuthenticatedUserProfileUseCase.kt | 4 +- .../flutter/useCases/GetUserProfileUseCase.kt | 2 +- .../useCases/RegisterAuthenticatorUseCase.kt | 4 +- .../flutter/useCases/RegistrationUseCase.kt | 2 +- .../useCases/ResourceRequestUseCase.kt | 20 ++- .../SetPreferredAuthenticatorUseCase.kt | 4 +- .../SubmitCustomRegistrationActionUseCase.kt | 4 +- .../AuthenticateUserImplicitlyUseCaseTests.kt | 2 +- .../sdk/AuthenticateUserUseCaseTests.kt | 4 +- .../CancelBrowserRegistrationUseCaseTest.kt | 4 +- .../DeregisterAuthenticatorUseCaseTests.kt | 6 +- .../mobile/sdk/DeregisterUserUseCaseTests.kt | 2 +- ...tAuthenticationRequestAcceptUseCaseTest.kt | 4 +- ...intAuthenticationRequestDenyUseCaseTest.kt | 4 +- .../FingerprintFallbackToPinUseCaseTest.kt | 4 +- .../mobile/sdk/GetAccessTokenUseCaseTests.kt | 2 +- .../sdk/GetAllAuthenticatorsUseCaseTests.kt | 2 +- ...GetAuthenticatedUserProfileUseCaseTests.kt | 2 +- ...NotRegisteredAuthenticatorsUseCaseTests.kt | 2 +- ...GetRegisteredAuthenticatorsUseCaseTests.kt | 2 +- ...pAcceptAuthenticationRequestUseCaseTest.kt | 4 +- ...OtpDenyAuthenticationRequestUseCaseTest.kt | 4 +- ...nAuthenticationRequestAcceptUseCaseTest.kt | 4 +- ...PinAuthenticationRequestDenyUseCaseTest.kt | 4 +- ...PinRegistrationRequestAcceptUseCaseTest.kt | 2 +- .../PinRegistrationRequestDenyUseCaseTest.kt | 2 +- .../sdk/RegisterAuthenticatorUseCaseTests.kt | 6 +- .../mobile/sdk/RegistrationUseCaseTests.kt | 2 +- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 6 +- .../SetPreferredAuthenticatorUseCaseTests.kt | 4 +- .../custom_registration_subscriptions.dart | 2 +- .../NativeBridge/Errors/ErrorMapper.swift | 133 ++++++++---------- .../Handlers/AuthenticatorsHandler.swift | 12 +- .../Handlers/DeregisterUserHandler.swift | 2 +- .../NativeBridge/Handlers/LoginHandler.swift | 6 +- .../Handlers/MobileAuthHandler.swift | 10 +- .../Handlers/RegistrationHandler.swift | 12 +- .../Handlers/ResourcesHandler.swift | 8 +- .../OneginiModuleSwift+Auth.swift | 12 +- .../OneginiModuleSwift+OTP.swift | 2 +- .../OneginiModuleSwift+Register.swift | 6 +- ios/Classes/SwiftOneginiPlugin.swift | 2 +- .../onegini_fingerprint_callback.dart | 1 + 56 files changed, 218 insertions(+), 221 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index d789bca9..3185216c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -2,42 +2,36 @@ package com.onegini.mobile.sdk.flutter enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { GENERIC_ERROR(8000, "Something went wrong"), - DOES_NOT_EXIST_USER_PROFILE(8001, "The requested User profile does not exist"), - + NOT_AUTHENTICATED_USER(8002, "There is currently no User Profile authenticated"), + NOT_AUTHENTICATED_IMPLICIT(8002, "The requested action requires you to be authenticated implicitly"), NOT_FOUND_AUTHENTICATOR(8004, "The requested authenticator is not found"), - NOT_FOUND_IDENTITY_PROVIDER(8004, "The requested identity provider is not found"), - NOT_FOUND_SECURITY_CONTROLLER(8004, "The requested Security controller class is not found"), - + NOT_FOUND_IDENTITY_PROVIDER(8004, "The requested identity provider is not found"), // Android only + NOT_FOUND_SECURITY_CONTROLLER(8004, "The requested Security controller class is not found"), // Android only HTTP_REQUEST_ERROR_INTERNAL(8011, "OneWelcome: HTTP Request failed internally"), HTTP_REQUEST_ERROR_CODE(8011, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - + ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), // Android only + CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), // Android only NOT_IN_PROGRESS_REGISTRATION(8034, "Registration is currently not in progress"), - NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8034, "Custom Registration is currently not in progress"), NOT_IN_PROGRESS_AUTHENTICATION(8034, "Authentication is currently not in progress"), NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8034, "Fingerprint Authentication is currently not in progress"), NOT_IN_PROGRESS_OTP_AUTHENTICATION(8034, "OTP Authentication is currently not in progress"), - NOT_IN_PROGRESS_BROWSER_REGISTRATION(8034, "Browser Registration is currently not in progress"), - NOT_IN_PROGRESS_PIN_CREATION(8034, "Pin Creation is currently not in progress"), - - -// DOES_NOT_EXIST_USER_PROFILE(8001, "The requested User profile does not exist"), - NO_USER_PROFILE_IS_AUTHENTICATED(8002, "There is currently no User Profile authenticated"), -// NOT_FOUND_AUTHENTICATOR(8004, "The requested authenticator is not found"), -//HTTP_REQUEST_ERROR_INTERNAL(8011, "OneWelcome: HTTP Request failed internally"), -//HTTP_REQUEST_ERROR_CODE(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - -// NOT_IN_PROGRESS_REGISTRATION(8034, "Registration is currently not in progress"), -//NOT_IN_PROGRESS_AUTHENTICATION(8037, "Authentication is currently not in progress"), -//NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8038, "Fingerprint Authentication is currently not in progress"), -//NOT_IN_PROGRESS_OTP_AUTHENTICATION(8039, "OTP Authentication is currently not in progress"), -//NOT_IN_PROGRESS_BROWSER_REGISTRATION(8040, "Browser registration is currently not in progress"), -//NOT_IN_PROGRESS_PIN_CREATION(8042, "Pin creation is currently not in progress"), + NOT_IN_PROGRESS_PIN_CREATION(8034, "Pin Creation is currently not in progress"), // Android only + ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_CANCEL( + 8042, + "Canceling the Custom registration right now is not allowed." + + " Registration is not in progress or pin creation has already started" + ), + ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT( + 8042, + "Submitting the Custom registration right now is not allowed." + + " Registration is not in progress or pin creation has already started" + ), + ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL( + 8042, + "Canceling the Browser registration right now is not allowed." + + " Registration is not in progress or pin creation has already started" + ), + UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), // Android only - // Errors that only occur on Android -// NOT_FOUND_IDENTITY_PROVIDER(8005, "The requested identity provider is not found"), - ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), - CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), -// NOT_FOUND_SECURITY_CONTROLLER(8033, "Security controller class not found"), - UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt index 7177feb2..f0db5e26 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneginiSDK.kt @@ -6,7 +6,7 @@ import com.onegini.mobile.sdk.android.client.OneginiClientBuilder import com.onegini.mobile.sdk.android.model.OneginiClientConfigModel import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.CONFIG_ERROR import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ONEWELCOME_SDK_NOT_INITIALIZED -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.SECURITY_CONTROLLER_NOT_FOUND +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_FOUND_SECURITY_CONTROLLER import com.onegini.mobile.sdk.flutter.errors.FlutterPluginException import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler @@ -122,10 +122,10 @@ class OneginiSDK @Inject constructor( } catch (e: ClassNotFoundException) { e.message?.let { message -> throw SdkError( - code = SECURITY_CONTROLLER_NOT_FOUND.code, + code = NOT_FOUND_SECURITY_CONTROLLER.code, message = message ) - } ?: throw SdkError(SECURITY_CONTROLLER_NOT_FOUND) + } ?: throw SdkError(NOT_FOUND_SECURITY_CONTROLLER) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt index 75082638..fc969056 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/SdkErrorAssert.kt @@ -1,6 +1,7 @@ package com.onegini.mobile.sdk.flutter import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE import org.junit.Assert import javax.inject.Singleton @@ -13,7 +14,7 @@ class SdkErrorAssert : Assert() { assertEquals(actual.code.toInt(), expected.code) assertEquals(actual.message, expected.message) } - else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + else -> fail(UNEXPECTED_ERROR_TYPE.message) } } @@ -23,7 +24,7 @@ class SdkErrorAssert : Assert() { assertEquals(actual.code, expected.code) assertEquals(actual.message, expected.message) } - else -> fail(OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE.message) + else -> fail(UNEXPECTED_ERROR_TYPE.message) } } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt index 823bf2e8..cca9364a 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/FingerprintAuthenticationRequestHandler.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiFingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject @@ -35,20 +35,20 @@ class FingerprintAuthenticationRequestHandler @Inject constructor(private val na return fingerprintCallback?.let { it.acceptAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION).pigeonError()) } fun denyAuthenticationRequest(): Result { return fingerprintCallback?.let { it.denyAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION).pigeonError()) } fun fallbackToPin(): Result { return fingerprintCallback?.let { it.fallbackToPin() Result.success(Unit) - } ?: Result.failure(SdkError(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt index 3de0acda..b7f92d1b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/MobileAuthOtpRequestHandler.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk.flutter.handlers import com.onegini.mobile.sdk.android.handlers.request.OneginiMobileAuthWithOtpRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_OTP_AUTHENTICATION import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import javax.inject.Inject @@ -31,13 +31,13 @@ class MobileAuthOtpRequestHandler @Inject constructor(private val nativeApi: Nat return callback?.let { it.acceptAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_OTP_AUTHENTICATION).pigeonError()) } fun denyAuthenticationRequest(): Result { return callback?.let { it.denyAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(OTP_AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_OTP_AUTHENTICATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt index c91d7fc2..98ecaae4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinAuthenticationRequestHandler.kt @@ -43,13 +43,13 @@ class PinAuthenticationRequestHandler @Inject constructor(private val nativeApi: return callback?.let { it.acceptAuthenticationRequest(pin) Result.success(Unit) - } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_AUTHENTICATION).pigeonError()) } fun denyAuthenticationRequest(): Result { return callback?.let { it.denyAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(AUTHENTICATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_AUTHENTICATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt index 97c3da41..79a45632 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/handlers/PinRequestHandler.kt @@ -4,7 +4,7 @@ import com.onegini.mobile.sdk.android.handlers.error.OneginiPinValidationError import com.onegini.mobile.sdk.android.handlers.request.OneginiCreatePinRequestHandler import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PIN_CREATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_PIN_CREATION import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWOneginiError @@ -39,13 +39,13 @@ class PinRequestHandler @Inject constructor(private val nativeApi: NativeCallFlu return callback?.let { it.acceptAuthenticationRequest(pin) Result.success(Unit) - } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_PIN_CREATION).pigeonError()) } fun cancelPin(): Result { return callback?.let { it.denyAuthenticationRequest() Result.success(Unit) - } ?: Result.failure(SdkError(PIN_CREATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_PIN_CREATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 0caf21da..4e2c8dd1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -12,6 +12,10 @@ import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi class CustomTwoStepRegistrationActionImpl(private val providerId: String, private val nativeApi: NativeCallFlutterApi) : OneginiCustomTwoStepRegistrationAction, CustomRegistrationAction { var callback: OneginiCustomRegistrationCallback? = null + override fun isInProgress(): Boolean { + return callback != null + } + override fun initRegistration(callback: OneginiCustomRegistrationCallback, info: CustomInfo?) { this.callback = callback nativeApi.n2fEventInitCustomRegistration(info?.mapToOwCustomInfo(), providerId) {} @@ -35,7 +39,7 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String, privat customRegistrationCallback.returnSuccess(result) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION).pigeonError()) } override fun returnError(exception: Exception?): Result { @@ -43,6 +47,6 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String, privat customRegistrationCallback.returnError(exception) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt index 228bf538..127646ad 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/AuthenticateUserUseCase.kt @@ -30,7 +30,7 @@ class AuthenticateUserUseCase @Inject constructor( .find { it.id == authenticatorId } when { - authenticatorId != null && authenticator == null -> callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) + authenticatorId != null && authenticator == null -> callback(Result.failure(SdkError(NOT_FOUND_AUTHENTICATOR).pigeonError())) else -> authenticate(userProfile, authenticator, callback) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt index 8ae66654..ec712659 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelBrowserRegistrationUseCase.kt @@ -2,13 +2,13 @@ package com.onegini.mobile.sdk.flutter.useCases import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.helpers.SdkError -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL import javax.inject.Inject class CancelBrowserRegistrationUseCase @Inject constructor() { operator fun invoke(): Result { return when (val browserCallback = BrowserRegistrationRequestHandler.callback) { - null -> Result.failure(SdkError(BROWSER_REGISTRATION_NOT_IN_PROGRESS).pigeonError()) + null -> Result.failure(SdkError(ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL).pigeonError()) else -> { browserCallback.denyRegistration() BrowserRegistrationRequestHandler.callback = null diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt index 4e36cba5..bf14e91f 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/CancelCustomRegistrationActionUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_CANCEL import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -10,7 +10,7 @@ import javax.inject.Singleton class CancelCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(error: String): Result { return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.isInProgress() }) { - null -> Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) + null -> Result.failure(SdkError(ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_CANCEL).pigeonError()) else -> action.returnError(Exception(error)) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt index 9d288e6a..f3e3c0b1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/DeregisterAuthenticatorUseCase.kt @@ -12,11 +12,11 @@ import javax.inject.Singleton class DeregisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + ?: return callback(Result.failure(SdkError(NOT_AUTHENTICATED_USER).pigeonError())) val authenticator = oneginiSDK.oneginiClient.userClient .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } - ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) + ?: return callback(Result.failure(SdkError(NOT_FOUND_AUTHENTICATOR).pigeonError())) oneginiSDK.oneginiClient.userClient.deregisterAuthenticator(authenticator, object : OneginiAuthenticatorDeregistrationHandler { override fun onSuccess() { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt index ad42d616..aebe2c70 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAccessTokenUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_AUTHENTICATED_USER import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -13,6 +13,6 @@ class GetAccessTokenUseCase @Inject constructor(private val oneginiSDK: OneginiS return Result.success(token) } - return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) + return Result.failure(SdkError(NOT_AUTHENTICATED_USER).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt index de1985fe..e95e3533 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetAuthenticatedUserProfileUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NO_USER_PROFILE_IS_AUTHENTICATED +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_AUTHENTICATED_USER import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile @@ -11,7 +11,7 @@ import javax.inject.Singleton class GetAuthenticatedUserProfileUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(): Result { return when (val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile) { - null -> Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) + null -> Result.failure(SdkError(NOT_AUTHENTICATED_USER).pigeonError()) else -> Result.success(OWUserProfile(authenticatedUserProfile.profileId)) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfileUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfileUseCase.kt index 55666641..9866391c 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfileUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/GetUserProfileUseCase.kt @@ -11,7 +11,7 @@ import javax.inject.Singleton class GetUserProfileUseCase @Inject constructor (private val oneginiSDK: OneginiSDK) { operator fun invoke(profileId: String): UserProfile { when (val userProfile = oneginiSDK.oneginiClient.userClient.userProfiles.find { it.profileId == profileId }) { - null -> throw SdkError(OneWelcomeWrapperErrors.USER_PROFILE_DOES_NOT_EXIST) + null -> throw SdkError(OneWelcomeWrapperErrors.DOES_NOT_EXIST_USER_PROFILE) else -> return userProfile } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt index 9acd4401..cd50eed8 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegisterAuthenticatorUseCase.kt @@ -13,11 +13,11 @@ import javax.inject.Singleton class RegisterAuthenticatorUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(authenticatorId: String, callback: (Result) -> Unit) { val authenticatedUserProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return callback(Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError())) + ?: return callback(Result.failure(SdkError(NOT_AUTHENTICATED_USER).pigeonError())) val authenticator = oneginiSDK.oneginiClient.userClient .getAllAuthenticators(authenticatedUserProfile).find { it.id == authenticatorId } - ?: return callback(Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError())) + ?: return callback(Result.failure(SdkError(NOT_FOUND_AUTHENTICATOR).pigeonError())) oneginiSDK.oneginiClient.userClient.registerAuthenticator(authenticator, object : OneginiAuthenticatorRegistrationHandler { override fun onSuccess(customInfo: CustomInfo?) { diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt index b73a2753..149206cd 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt @@ -21,7 +21,7 @@ class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK val identityProvider = oneginiSDK.oneginiClient.userClient.identityProviders.find { it.id == identityProviderId } if (identityProviderId != null && identityProvider == null) { - callback(Result.failure(SdkError(IDENTITY_PROVIDER_NOT_FOUND).pigeonError())) + callback(Result.failure(SdkError(NOT_FOUND_IDENTITY_PROVIDER).pigeonError())) } val registerScopes = scopes?.toTypedArray() diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index debd6eda..8aa9afe0 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -1,7 +1,8 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR_CODE +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR_INTERNAL +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_AUTHENTICATED_IMPLICIT import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRequestDetails @@ -25,6 +26,17 @@ import javax.inject.Singleton @Singleton class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { + if (type == ResourceRequestType.IMPLICIT) { + callback( + Result.failure( + SdkError( + wrapperError = NOT_AUTHENTICATED_IMPLICIT + ).pigeonError() + ) + ) + return + } + val resourceClient = getOkHttpClient(type) val request = buildRequest(details) @@ -94,7 +106,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini callback( Result.failure( SdkError( - code = HTTP_REQUEST_ERROR.code, + code = HTTP_REQUEST_ERROR_INTERNAL.code, message = e.message.toString() ).pigeonError() ) @@ -107,7 +119,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini callback( Result.failure( SdkError( - wrapperError = ERROR_CODE_HTTP_REQUEST, + wrapperError = HTTP_REQUEST_ERROR_CODE, httpResponse = response ).pigeonError() ) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt index 62a1f92c..76db483b 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SetPreferredAuthenticatorUseCase.kt @@ -11,11 +11,11 @@ class SetPreferredAuthenticatorUseCase @Inject constructor(private val oneginiSD operator fun invoke(authenticatorId: String): Result { val userProfile = oneginiSDK.oneginiClient.userClient.authenticatedUserProfile - ?: return Result.failure(SdkError(NO_USER_PROFILE_IS_AUTHENTICATED).pigeonError()) + ?: return Result.failure(SdkError(NOT_AUTHENTICATED_USER).pigeonError()) val authenticator = oneginiSDK.oneginiClient.userClient .getRegisteredAuthenticators(userProfile).find { it.id == authenticatorId } - ?: return Result.failure(SdkError(AUTHENTICATOR_NOT_FOUND).pigeonError()) + ?: return Result.failure(SdkError(NOT_FOUND_AUTHENTICATOR).pigeonError()) oneginiSDK.oneginiClient.userClient.setPreferredAuthenticator(authenticator) return Result.success(Unit) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt index 10562f71..a8f79323 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -10,7 +10,7 @@ import javax.inject.Singleton class SubmitCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(data: String?): Result { return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.isInProgress() }) { - null -> Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) + null -> Result.failure(SdkError(ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT).pigeonError()) else -> action.returnSuccess(data) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt index fbea055f..0d0fcb66 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserImplicitlyUseCaseTests.kt @@ -75,7 +75,7 @@ class AuthenticateUserImplicitlyUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt index 4ae7f0a8..e8c0a849 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/AuthenticateUserUseCaseTests.kt @@ -75,7 +75,7 @@ class AuthenticateUserUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, firstValue.exceptionOrNull()) } } @@ -89,7 +89,7 @@ class AuthenticateUserUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt index 2359fe7b..fb4d92a3 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/CancelBrowserRegistrationUseCaseTest.kt @@ -1,7 +1,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiBrowserRegistrationCallback -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.BROWSER_REGISTRATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.BrowserRegistrationRequestHandler import com.onegini.mobile.sdk.flutter.useCases.CancelBrowserRegistrationUseCase @@ -29,7 +29,7 @@ class CancelBrowserRegistrationUseCaseTest { BrowserRegistrationRequestHandler.callback = null val result = cancelBrowserRegistrationUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(BROWSER_REGISTRATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt index e6fe8e32..90f2e445 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterAuthenticatorUseCaseTests.kt @@ -51,7 +51,7 @@ class DeregisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_AUTHENTICATED_USER, firstValue.exceptionOrNull()) } } @@ -69,7 +69,7 @@ class DeregisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, firstValue.exceptionOrNull()) } } @@ -82,7 +82,7 @@ class DeregisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt index 4ce84d90..a07e504a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/DeregisterUserUseCaseTests.kt @@ -49,7 +49,7 @@ class DeregisterUserUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt index f5b8d43a..6778b535 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestAcceptUseCaseTest.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -37,7 +37,7 @@ class FingerprintAuthenticationRequestAcceptUseCaseTest { fun `When no fingerprint authentication callback is set, Then it should fail with an error`() { val result = fingerprintAuthenticationRequestAcceptUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt index fe6cef0b..72da9d2e 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintAuthenticationRequestDenyUseCaseTest.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -37,7 +37,7 @@ class FingerprintAuthenticationRequestDenyUseCaseTest { fun `When no fingerprint authentication callback is set, Then it should fail with an error`() { val result = fingerprintAuthenticationRequestDenyUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt index 8f5b5ff3..7082de5c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/FingerprintFallbackToPinUseCaseTest.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiFingerprintCallback import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.FingerprintAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -37,7 +37,7 @@ class FingerprintFallbackToPinUseCaseTest { fun `When no fingerprint authentication callback is set, Then it should resolve with an error`() { val result = fingerprintFallbackToPinUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(FINGERPRINT_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt index e55e1409..e0154f4c 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAccessTokenUseCaseTests.kt @@ -30,7 +30,7 @@ class GetAccessTokenUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.accessToken).thenReturn(null) val result = getAccessTokenUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) + SdkErrorAssert.assertEquals(NOT_AUTHENTICATED_USER, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt index b7013c23..925651de 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAllAuthenticatorsUseCaseTests.kt @@ -38,7 +38,7 @@ class GetAllAuthenticatorsUseCaseTests { @Test fun `When an unknown or unregistered profileId is given, Then an error should be thrown`() { val result = getAllAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt index 222a67d1..b9251516 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetAuthenticatedUserProfileUseCaseTests.kt @@ -31,7 +31,7 @@ class GetAuthenticatedUserProfileUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) val result = getAuthenticatedUserProfileUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) + SdkErrorAssert.assertEquals(NOT_AUTHENTICATED_USER, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt index 89fbb23e..2bec12c9 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetNotRegisteredAuthenticatorsUseCaseTests.kt @@ -53,7 +53,7 @@ class GetNotRegisteredAuthenticatorsUseCaseTests { fun `When the UserProfile is not found, Then an error should be returned`() { val result = getNotRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt index 1ff58766..93c08c69 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetRegisteredAuthenticatorsUseCaseTests.kt @@ -57,7 +57,7 @@ class GetRegisteredAuthenticatorsUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.userProfiles).thenReturn(emptySet()) val result = getRegisteredAuthenticatorsUseCase("QWERTY").exceptionOrNull() - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result) + SdkErrorAssert.assertEquals(DOES_NOT_EXIST_USER_PROFILE, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt index 28a1b0db..84965fa4 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpAcceptAuthenticationRequestUseCaseTest.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_OTP_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -40,7 +40,7 @@ class OtpAcceptAuthenticationRequestUseCaseTest { fun `When no otp authentication callback is set, Then it should resolve with an error`() { val result = otpAcceptAuthenticationRequestUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_OTP_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt index 81fc552a..21f844d6 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/OtpDenyAuthenticationRequestUseCaseTest.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiAcceptDenyCallback import com.onegini.mobile.sdk.android.model.entity.OneginiMobileAuthenticationRequest -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.OTP_AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_OTP_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.MobileAuthOtpRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -40,7 +40,7 @@ class OtpDenyAuthenticationRequestUseCaseTest { @Test fun `When no otp authentication callback is set, Then it should resolve with an error`() { val result = otpDenyAuthenticationRequestUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(OTP_AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_OTP_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt index 761f65d2..7f5fa871 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestAcceptUseCaseTest.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -44,7 +44,7 @@ class PinAuthenticationRequestAcceptUseCaseTest { fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinAuthenticationRequestAcceptUseCase("12345").exceptionOrNull() - SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt index 3f3412d4..eea1c9d1 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinAuthenticationRequestDenyUseCaseTest.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiPinCallback import com.onegini.mobile.sdk.android.model.entity.AuthenticationAttemptCounter import com.onegini.mobile.sdk.android.model.entity.UserProfile -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.AUTHENTICATION_NOT_IN_PROGRESS +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_AUTHENTICATION import com.onegini.mobile.sdk.flutter.SdkErrorAssert import com.onegini.mobile.sdk.flutter.handlers.PinAuthenticationRequestHandler import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -44,7 +44,7 @@ class PinAuthenticationRequestDenyUseCaseTest { fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinAuthenticationRequestDenyUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(AUTHENTICATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_AUTHENTICATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt index 60468690..cdda7690 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestAcceptUseCaseTest.kt @@ -40,7 +40,7 @@ class PinRegistrationRequestAcceptUseCaseTest { fun `When no pin registration callback is set, Then it should fail with an error`() { val result = pinRegistrationRequestAcceptUseCase("12345").exceptionOrNull() - SdkErrorAssert.assertEquals(PIN_CREATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_PIN_CREATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt index d494c367..4f95ef76 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/PinRegistrationRequestDenyUseCaseTest.kt @@ -39,7 +39,7 @@ class PinRegistrationRequestDenyUseCaseTest { @Test fun `When no pin registration callback is set, Then it should resolve with an error`() { val result = pinRegistrationRequestDenyUseCase().exceptionOrNull() - SdkErrorAssert.assertEquals(PIN_CREATION_NOT_IN_PROGRESS, result) + SdkErrorAssert.assertEquals(NOT_IN_PROGRESS_PIN_CREATION, result) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt index fc85e9ad..3d7ddc37 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegisterAuthenticatorUseCaseTests.kt @@ -56,7 +56,7 @@ class RegisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_AUTHENTICATED_USER, firstValue.exceptionOrNull()) } } @@ -70,7 +70,7 @@ class RegisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, firstValue.exceptionOrNull()) } } @@ -83,7 +83,7 @@ class RegisterAuthenticatorUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt index 64844297..85ebb166 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/RegistrationUseCaseTests.kt @@ -87,7 +87,7 @@ class RegistrationUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - SdkErrorAssert.assertEquals(IDENTITY_PROVIDER_NOT_FOUND, firstValue.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_IDENTITY_PROVIDER, firstValue.exceptionOrNull()) } } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 426be311..9e45a2c0 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -12,7 +12,7 @@ import okhttp3.Callback import okhttp3.Headers import okhttp3.Response import org.mockito.kotlin.any -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR_CODE import com.onegini.mobile.sdk.flutter.useCases.ResourceRequestUseCase import junit.framework.Assert.fail @@ -104,8 +104,8 @@ class ResourceRequestUseCaseTests { when (val error = firstValue.exceptionOrNull()) { is FlutterError -> { - Assert.assertEquals(error.code.toInt(), ERROR_CODE_HTTP_REQUEST.code) - Assert.assertEquals(error.message, ERROR_CODE_HTTP_REQUEST.message) + Assert.assertEquals(error.code.toInt(), HTTP_REQUEST_ERROR_CODE.code) + Assert.assertEquals(error.message, HTTP_REQUEST_ERROR_CODE.message) Assert.assertEquals(((error.details as Map<*, *>).toMap()["response"] as Map<*, *>)["statusCode"], "400") } else -> fail(UNEXPECTED_ERROR_TYPE.message) diff --git a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt index fab4e90a..4f0d3e79 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/SetPreferredAuthenticatorUseCaseTests.kt @@ -39,7 +39,7 @@ class SetPreferredAuthenticatorUseCaseTests { fun `When no user is authenticated, Then return an error`() { whenever(oneginiSdk.oneginiClient.userClient.authenticatedUserProfile).thenReturn(null) val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() - SdkErrorAssert.assertEquals(NO_USER_PROFILE_IS_AUTHENTICATED, result) + SdkErrorAssert.assertEquals(NOT_AUTHENTICATED_USER, result) } @Test @@ -48,7 +48,7 @@ class SetPreferredAuthenticatorUseCaseTests { whenever(oneginiSdk.oneginiClient.userClient.getRegisteredAuthenticators(eq(UserProfile("QWERTY")))).thenReturn(emptySet()) val result = setPreferredAuthenticatorUseCase("test").exceptionOrNull() - SdkErrorAssert.assertEquals(AUTHENTICATOR_NOT_FOUND, result) + SdkErrorAssert.assertEquals(NOT_FOUND_AUTHENTICATOR, result) } @Test diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index 2c762d00..9eb58de0 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -25,7 +25,7 @@ StreamSubscription _getInitCustomRegistrationSub() { if (event.providerId == "2-way-otp-api") { // a 2-way-otp does not require data for the initialization request OneginiCustomRegistrationCallback() - .submitSuccessAction(event.providerId, null) + .submitSuccessAction(null) .catchError((error) => { if (error is PlatformException) { diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 5459193d..9afe4265 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -2,78 +2,57 @@ import OneginiSDKiOS enum OneWelcomeWrapperError { - // iOS and Android case genericError - case userProfileDoesNotExist - case noUserProfileIsAuthenticated - case authenticatorNotFound - case httpRequestError - case errorCodeHttpRequest - case registrationNotInProgress - case customRegistrationNotInProgress - case unauthenticatedImplicitly - case authenticationNotInProgress - case otpAuthenticationNotInProgress - case browserRegistrationNotInProgress - - // iOS only - case providedUrlIncorrect - case loginCanceled - case enrollmentFailed - case authenticationCancelled - case registrationCancelled - case authenticatorNotRegistered - case authenticatorDeregistrationCancelled - case responseIsNull - case authenticatorRegistrationCancelled - case mobileAuthInProgress + case doesNotExistUserProfile + case notAuthenticatedUser + case notAuthenticatedImplicit + case notFoundAuthenticator + case httpRequestErrorInternal + case httpRequestErrorCode + case httpRequestErrorNoResponse // ios only + case providedUrlIncorrect // ios only + case enrollmentFailed // ios only + case processCanceledLogin // ios only + case processCanceledAuthentication // ios only + case processCanceledRegistration // ios only + case processCanceledAuthenticatorDeregistration // ios only + case processCanceledAuthenticatorRegistration // ios only + case authenticatorNotRegistered // ios only + case notInProgressRegistration + case notInProgressAuthentication + case notInProgressOtpAuthentication + case notInProgressPinCreation + case alreadyInProgressMobileAuth // ios only + case actionNotAllowedCustomRegistrationCancel + case actionNotAllowedCustomRegistrationSubmit + case actionNotAllowedBrowserRegistrationCancel func code() -> Int { switch self { case .genericError: return 8000 - case .userProfileDoesNotExist: + case .doesNotExistUserProfile: return 8001 - case .noUserProfileIsAuthenticated: + case .notAuthenticatedUser, .notAuthenticatedImplicit: return 8002 - case .authenticatorNotFound: + case .notFoundAuthenticator: return 8004 - case .httpRequestError: + case .httpRequestErrorInternal, .httpRequestErrorCode, .httpRequestErrorNoResponse: return 8011 - case .errorCodeHttpRequest: - return 8013 - case .registrationNotInProgress, .customRegistrationNotInProgress: - return 8034 - case .unauthenticatedImplicitly: - return 8035 - case .authenticationNotInProgress: - return 8037 - case .otpAuthenticationNotInProgress: - return 8039 - case .browserRegistrationNotInProgress: - return 8040 - - // iOS only case .providedUrlIncorrect: return 8014 - case .loginCanceled: - return 8015 case .enrollmentFailed: return 8016 - case .authenticationCancelled: + case .processCanceledAuthentication, .processCanceledRegistration, .processCanceledLogin, .processCanceledAuthenticatorRegistration, .processCanceledAuthenticatorDeregistration: return 8017 - case .registrationCancelled: - return 8020 case .authenticatorNotRegistered: return 8023 - case .authenticatorDeregistrationCancelled: - return 8024 - case .responseIsNull: - return 8026 - case .authenticatorRegistrationCancelled: - return 8031 - case .mobileAuthInProgress: + case .notInProgressRegistration, .notInProgressAuthentication, .notInProgressOtpAuthentication, .notInProgressPinCreation: + return 8034 + case .alreadyInProgressMobileAuth: return 8041 + case .actionNotAllowedCustomRegistrationSubmit, .actionNotAllowedCustomRegistrationCancel, .actionNotAllowedBrowserRegistrationCancel: + return 8042 } } @@ -81,46 +60,52 @@ enum OneWelcomeWrapperError { switch self { case .genericError: return "Something went wrong." - case .userProfileDoesNotExist: + case .doesNotExistUserProfile: return "The requested User profile does not exist." - case .noUserProfileIsAuthenticated: + case .notAuthenticatedUser: return "There is currently no User Profile authenticated." - case .authenticatorNotFound: + case .notAuthenticatedImplicit: + return "The requested action requires you to be authenticated implicitly." + case .notFoundAuthenticator: return "The requested authenticator is not found." case .providedUrlIncorrect: return "Provided url is incorrect." case .enrollmentFailed: return "Enrollment failed. Please try again or contact maintainer." - case .loginCanceled: + case .processCanceledLogin: return "Login cancelled." - case .authenticationCancelled: + case .processCanceledAuthentication: return "Authentication cancelled." - case .authenticatorDeregistrationCancelled: + case .processCanceledAuthenticatorDeregistration: return "Authenticator deregistration cancelled." - case .registrationCancelled: + case .processCanceledRegistration: return "Registration cancelled." case .authenticatorNotRegistered: return "This authenticator is not registered." - case .responseIsNull: - return "Response doesn't contain data." - case .errorCodeHttpRequest: + case .httpRequestErrorNoResponse: + return "OneWelcome: HTTP Request failed. Response doesn't contain data." + case .httpRequestErrorCode: return "OneWelcome: HTTP Request failed. Check Response for more info." - case .httpRequestError: + case .httpRequestErrorInternal: return "OneWelcome: HTTP Request failed. Check iosCode and iosMessage for more info." - case .authenticatorRegistrationCancelled: + case .processCanceledAuthenticatorRegistration: return "The authenticator-registration was cancelled." - case .unauthenticatedImplicitly: - return "The requested action requires you to be authenticated implicitly." - case .registrationNotInProgress: + case .notInProgressRegistration: return "Registration is currently not in progress." - case .authenticationNotInProgress: + case .notInProgressAuthentication: return "Authentication is currently not in progress." - case .otpAuthenticationNotInProgress: + case .notInProgressOtpAuthentication: return "OTP Authentication is currently not in progress." - case .mobileAuthInProgress: + case .notInProgressPinCreation: + return "Pin Creation is currently not in progress" + case .alreadyInProgressMobileAuth: return "Mobile Authentication is already in progress and can not be performed concurrently." - case .browserRegistrationNotInProgress: - return "Browser registration is currently not in progress." + case .actionNotAllowedCustomRegistrationSubmit: + return "Submitting the Custom registration right now is not allowed. Registration is not in progress or pin creation has already started." + case .actionNotAllowedCustomRegistrationCancel: + return "Canceling the Custom registration right now is not allowed. Registration is not in progress or pin creation has already started." + case .actionNotAllowedBrowserRegistrationCancel: + return "Canceling the Browser registration right now is not allowed. Registration is not in progress or pin creation has already started." } } } diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 259e4ae1..3745d261 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -15,14 +15,14 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { } func registerAuthenticator(_ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.notAuthenticatedUser))) return } // We don't have to check if the authenticator is already registered as the sdk will do that for us. let authenticators = SharedUserClient.instance.authenticators(.all, for: profile) guard let authenticator = authenticators.first(where: { $0.identifier == authenticatorId }) else { - completion(.failure(FlutterError(.authenticatorNotFound))) + completion(.failure(FlutterError(.notFoundAuthenticator))) return } let delegate = AuthenticatorRegistrationDelegateImpl(loginHandler: loginHandler, completion: completion) @@ -31,7 +31,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func deregisterAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { - completion(.failure(FlutterError(.authenticatorNotFound))) + completion(.failure(FlutterError(.notFoundAuthenticator))) return } @@ -45,7 +45,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { func setPreferredAuthenticator(_ userProfile: UserProfile, _ authenticatorId: String, _ completion: @escaping (Result) -> Void) { guard let authenticator = SharedUserClient.instance.authenticators(.all, for: userProfile).first(where: {$0.identifier == authenticatorId}) else { - completion(.failure(FlutterError(.authenticatorNotFound))) + completion(.failure(FlutterError(.notFoundAuthenticator))) return } @@ -84,7 +84,7 @@ class AuthenticatorRegistrationDelegateImpl: AuthenticatorRegistrationDelegate { func userClient(_ userClient: UserClient, didFailToRegister authenticator: Authenticator, for userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToRegister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.authenticatorRegistrationCancelled))) + completion(.failure(FlutterError(.processCanceledAuthenticatorRegistration))) } else { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) @@ -117,7 +117,7 @@ class AuthenticatorDeregistrationDelegateImpl: AuthenticatorDeregistrationDelega func userClient(_ userClient: UserClient, didFailToDeregister authenticator: Authenticator, forUser userProfile: UserProfile, error: Error) { Logger.log("[AUTH] userClient didFailToDeregister ONGAuthenticator", sender: self) if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.authenticatorDeregistrationCancelled))) + completion(.failure(FlutterError(.processCanceledAuthenticatorDeregistration))) } else { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) diff --git a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift index 6e7a275f..2f4493b3 100644 --- a/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/DeregisterUserHandler.swift @@ -8,7 +8,7 @@ protocol DeregisterUserHandlerProtocol: AnyObject { class DeregisterUserHandler: DeregisterUserHandlerProtocol { func deregister(profileId: String, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { - completion(.failure(FlutterError(.userProfileDoesNotExist))) + completion(.failure(FlutterError(.doesNotExistUserProfile))) return } SharedUserClient.instance.deregister(user: profile) { error in diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index da0ea4a0..c59c45af 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -6,7 +6,7 @@ class LoginHandler { func handlePin(pin: String, completion: (Result) -> Void) { guard let pinChallenge = pinChallenge else { - completion(.failure(FlutterError(.authenticationNotInProgress))) + completion(.failure(FlutterError(.notInProgressAuthentication))) return } pinChallenge.sender.respond(with: pin, to: pinChallenge) @@ -15,7 +15,7 @@ class LoginHandler { func cancelPinAuthentication(completion: (Result) -> Void) { guard let pinChallenge = pinChallenge else { - completion(.failure(FlutterError(.authenticationNotInProgress))) + completion(.failure(FlutterError(.notInProgressAuthentication))) return } pinChallenge.sender.cancel(pinChallenge) @@ -92,7 +92,7 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { loginHandler.handleDidFailToAuthenticateUser() if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.loginCanceled))) + completion(.failure(FlutterError(.processCanceledLogin))) } else { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) diff --git a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift index dfe78a0c..50ce82a8 100644 --- a/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/MobileAuthHandler.swift @@ -21,13 +21,13 @@ extension MobileAuthHandler: MobileAuthConnectorToHandlerProtocol { // Check to prevent breaking iOS SDK; https://onewelcome.atlassian.net/browse/SDKIOS-987 guard SharedUserClient.instance.authenticatedUserProfile != nil else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.notAuthenticatedUser))) return } // Prevent concurrent OTP mobile authentication flows at same time; https://onewelcome.atlassian.net/browse/SDKIOS-989 guard !isFlowInProgress else { - completion(.failure(FlutterError(.mobileAuthInProgress))) + completion(.failure(FlutterError(.alreadyInProgressMobileAuth))) return } @@ -53,7 +53,7 @@ extension MobileAuthHandler: MobileAuthConnectorToHandlerProtocol { func acceptMobileAuthRequest(completion: @escaping (Result) -> Void) { Logger.log("acceptMobileAuthRequest", sender: self) guard let callback = mobileAuthCallback else { - completion(.failure(FlutterError(SdkError(.otpAuthenticationNotInProgress)))) + completion(.failure(FlutterError(SdkError(.notInProgressOtpAuthentication)))) return } @@ -65,7 +65,7 @@ extension MobileAuthHandler: MobileAuthConnectorToHandlerProtocol { func denyMobileAuthRequest(completion: @escaping (Result) -> Void) { Logger.log("denyMobileAuthRequest", sender: self) guard let callback = mobileAuthCallback else { - completion(.failure(FlutterError(SdkError(.otpAuthenticationNotInProgress)))) + completion(.failure(FlutterError(SdkError(.notInProgressOtpAuthentication)))) return } @@ -113,7 +113,7 @@ class MobileAuthDelegate: MobileAuthRequestDelegate { SwiftOneginiPlugin.flutterApi?.n2fCloseAuthOtp {} if error.code == ONGGenericError.actionCancelled.rawValue { - handleMobileAuthCompletion(.failure(FlutterError(SdkError(.authenticationCancelled)))) + handleMobileAuthCompletion(.failure(FlutterError(SdkError(.processCanceledAuthentication)))) } else { let mappedError = ErrorMapper().mapError(error) handleMobileAuthCompletion(.failure(FlutterError(mappedError))) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 487f9410..f07baea0 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -48,7 +48,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func handlePin(pin: String, completion: (Result) -> Void) { guard let createPinChallenge = createPinChallenge else { - completion(.failure(FlutterError(.registrationNotInProgress))) + completion(.failure(FlutterError(.notInProgressPinCreation))) return } createPinChallenge.sender.respond(with: pin, to: createPinChallenge) @@ -57,7 +57,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func cancelPinRegistration(completion: (Result) -> Void) { guard let createPinChallenge = self.createPinChallenge else { - completion(.failure(FlutterError(.registrationNotInProgress))) + completion(.failure(FlutterError(.notInProgressPinCreation))) return } createPinChallenge.sender.cancel(createPinChallenge) @@ -113,7 +113,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func submitCustomRegistrationSuccess(_ data: String?, _ completion: @escaping (Result) -> Void) { guard let customRegistrationChallenge = self.customRegistrationChallenge else { - completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) + completion(.failure(SdkError(OneWelcomeWrapperError.actionNotAllowedCustomRegistrationSubmit).flutterError())) return } customRegistrationChallenge.sender.respond(with: data, to: customRegistrationChallenge) @@ -122,7 +122,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func cancelCustomRegistration(_ error: String, _ completion: @escaping (Result) -> Void) { guard let customRegistrationChallenge = self.customRegistrationChallenge else { - completion(.failure(SdkError(OneWelcomeWrapperError.registrationNotInProgress).flutterError())) + completion(.failure(SdkError(OneWelcomeWrapperError.actionNotAllowedCustomRegistrationCancel).flutterError())) return } customRegistrationChallenge.sender.cancel(customRegistrationChallenge) @@ -131,7 +131,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func cancelBrowserRegistration(_ completion: @escaping (Result) -> Void) { guard let browserRegistrationChallenge = self.browserRegistrationChallenge else { - completion(.failure(FlutterError(.browserRegistrationNotInProgress))) + completion(.failure(FlutterError(.actionNotAllowedBrowserRegistrationCancel))) return } browserRegistrationChallenge.sender.cancel(browserRegistrationChallenge) @@ -186,7 +186,7 @@ class RegistrationDelegateImpl: RegistrationDelegate { func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { registrationHandler.handleDidFailToRegister() if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.registrationCancelled))) + completion(.failure(FlutterError(.processCanceledRegistration))) } else { let mappedError = ErrorMapper().mapError(error) completion(.failure(FlutterError(mappedError))) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 73a668c2..a4a5756c 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -47,7 +47,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { case ResourceRequestType.implicit: // For consistency with Android we perform this step if ONGUserClient.sharedInstance().implicitlyAuthenticatedUserProfile() == nil { - completion(.failure(FlutterError(SdkError(.unauthenticatedImplicitly)))) + completion(.failure(FlutterError(SdkError(.notAuthenticatedImplicit)))) return } @@ -85,17 +85,17 @@ private extension ResourcesHandler { let completionRequest: ((ONGResourceResponse?, Error?) -> Void)? = { response, error in if let error = error { if response != nil { - let flutterError = FlutterError(SdkError(.errorCodeHttpRequest, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) + let flutterError = FlutterError(SdkError(.httpRequestErrorCode, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) completion(.failure(flutterError)) } else { - let flutterError = FlutterError(SdkError(.httpRequestError, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) + let flutterError = FlutterError(SdkError(.httpRequestErrorInternal, response: response, iosCode: error.code, iosMessage: error.localizedDescription)) completion(.failure(flutterError)) } } else { if let response = response { completion(.success(OWRequestResponse(response))) } else { - completion(.failure(FlutterError(SdkError(.responseIsNull)))) + completion(.failure(FlutterError(SdkError(.httpRequestErrorNoResponse)))) } } } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 49e52e03..f35ba020 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -16,7 +16,7 @@ extension OneginiModuleSwift { public func authenticateUserImplicitly(_ profileId: String, _ scopes: [String]?, completion: @escaping (Result) -> Void) { guard let profile = ONGClient.sharedInstance().userClient.userProfiles().first(where: { $0.profileId == profileId }) else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.notAuthenticatedUser))) return } @@ -35,7 +35,7 @@ extension OneginiModuleSwift { func authenticateUser(profileId: String, authenticatorId: String?, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.userProfiles.first(where: { $0.profileId == profileId }) else { - completion(.failure(SdkError(.userProfileDoesNotExist).flutterError())) + completion(.failure(SdkError(.doesNotExistUserProfile).flutterError())) return } let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.identifier == authenticatorId }) @@ -47,7 +47,7 @@ extension OneginiModuleSwift { func setPreferredAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.notAuthenticatedUser))) return } bridgeConnector.toAuthenticatorsHandler.setPreferredAuthenticator(profile, identifierId, completion) @@ -55,7 +55,7 @@ extension OneginiModuleSwift { func deregisterAuthenticator(_ identifierId: String, completion: @escaping (Result) -> Void) { guard let profile = SharedUserClient.instance.authenticatedUserProfile else { - completion(.failure(FlutterError(.noUserProfileIsAuthenticated))) + completion(.failure(FlutterError(.notAuthenticatedUser))) return } bridgeConnector.toAuthenticatorsHandler.deregisterAuthenticator(profile, identifierId, completion) @@ -63,14 +63,14 @@ extension OneginiModuleSwift { func getAuthenticatedUserProfile() -> Result { guard let profile = ONGUserClient.sharedInstance().authenticatedUserProfile() else { - return .failure(FlutterError(.noUserProfileIsAuthenticated)) + return .failure(FlutterError(.notAuthenticatedUser)) } return .success(OWUserProfile(profile)) } func getAccessToken() -> Result { guard let accessToken = ONGUserClient.sharedInstance().accessToken else { - return .failure(FlutterError(.noUserProfileIsAuthenticated)) + return .failure(FlutterError(.notAuthenticatedUser)) } return .success(accessToken) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift index 9afcca83..65334a45 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+OTP.swift @@ -3,7 +3,7 @@ import OneginiSDKiOS import Flutter extension OneginiModuleSwift { - func handleMobileAuthWithOtp2(_ otp: String, completion: @escaping (Result) -> Void) { + func handleMobileAuthWithOtp(_ otp: String, completion: @escaping (Result) -> Void) { bridgeConnector.toMobileAuthHandler.handleMobileAuthWithOtp(otp: otp, completion: completion) } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift index fe0adc97..4ce71e2d 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Register.swift @@ -51,7 +51,7 @@ extension OneginiModuleSwift { func getRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) + return .failure(FlutterError(.doesNotExistUserProfile)) } let registeredAuthenticators = ONGUserClient.sharedInstance().registeredAuthenticators(forUser: profile) return .success(registeredAuthenticators.compactMap { OWAuthenticator($0) }) @@ -59,7 +59,7 @@ extension OneginiModuleSwift { func getNotRegisteredAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) + return .failure(FlutterError(.doesNotExistUserProfile)) } let notRegisteredAuthenticators = ONGUserClient.sharedInstance().nonRegisteredAuthenticators(forUser: profile) return .success(notRegisteredAuthenticators.compactMap { OWAuthenticator($0) }) @@ -67,7 +67,7 @@ extension OneginiModuleSwift { func getAllAuthenticators(_ profileId: String) -> Result<[OWAuthenticator], FlutterError> { guard let profile = ONGUserClient.sharedInstance().userProfiles().first(where: { $0.profileId == profileId }) else { - return .failure(FlutterError(.userProfileDoesNotExist)) + return .failure(FlutterError(.doesNotExistUserProfile)) } let allAuthenticators = ONGUserClient.sharedInstance().allAuthenticators(forUser: profile) return .success(allAuthenticators.compactMap { OWAuthenticator($0) }) diff --git a/ios/Classes/SwiftOneginiPlugin.swift b/ios/Classes/SwiftOneginiPlugin.swift index 173831aa..d7d1a00a 100644 --- a/ios/Classes/SwiftOneginiPlugin.swift +++ b/ios/Classes/SwiftOneginiPlugin.swift @@ -109,7 +109,7 @@ public class SwiftOneginiPlugin: NSObject, FlutterPlugin, UserClientApi, Resourc } } - func submitCustomRegistrationAction(identityProviderId: String, data: String?, completion: @escaping (Result) -> Void) { + func submitCustomRegistrationAction(data: String?, completion: @escaping (Result) -> Void) { OneginiModuleSwift.sharedInstance.submitCustomRegistrationSuccess(data) { result in completion(result.mapError { $0 }) } diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index 2168f702..6d9e3555 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -6,6 +6,7 @@ import 'package:onegini/pigeon.dart'; /// Use this callback when user want authenticate by fingerprint. class OneginiFingerprintCallback { final api = UserClientApi(); + /// Changes the authentication method from fingerprint to PIN. Future fallbackToPin() async { await api.fingerprintFallbackToPin(); From 2e65cc3aa4bc7ea70a3fb0b03a6e66582194d331 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 15:17:19 +0200 Subject: [PATCH 318/364] FP-86: Make pin_request_screen nullsafe --- example/lib/screens/pin_request_screen.dart | 35 +++++++++++---------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/example/lib/screens/pin_request_screen.dart b/example/lib/screens/pin_request_screen.dart index f19fa75c..aaacacca 100644 --- a/example/lib/screens/pin_request_screen.dart +++ b/example/lib/screens/pin_request_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_pin_registration_callback.dart'; @@ -13,9 +12,9 @@ class PinRequestScreen extends StatefulWidget { final bool customAuthenticator; const PinRequestScreen( - {Key key, + {Key? key, this.confirmation = false, - this.previousCode, + this.previousCode = "", this.customAuthenticator = false}) : super(key: key); @@ -24,34 +23,34 @@ class PinRequestScreen extends StatefulWidget { } class _PinRequestScreenState extends State { - var pinCode = List.filled(5, null); + var pinCode = List.filled(5, ""); enterNum(String num) { for (var i = 0; i < pinCode.length; i++) { - if (pinCode[i] == null) { + if (pinCode[i] == "") { setState(() => pinCode[i] = num); break; } } - if (!pinCode.contains(null)) { + if (!pinCode.contains("")) { done(); } } clearAllDigits() { for (var i = 0; i < pinCode.length; i++) { - setState(() => pinCode[i] = null); + setState(() => pinCode[i] = ""); } } removeLast() { for (var i = 0; i < pinCode.length; i++) { - if (pinCode[i] == null && i != 0) { - setState(() => pinCode[i - 1] = null); + if (pinCode[i] == "" && i != 0) { + setState(() => pinCode[i - 1] = ""); break; } - if (pinCode[i] != null && i == pinCode.length - 1) { - setState(() => pinCode[i] = null); + if (pinCode[i] != "" && i == pinCode.length - 1) { + setState(() => pinCode[i] = ""); break; } } @@ -134,11 +133,11 @@ class _PinRequestScreenState extends State { NumPad( enterNum: enterNum, removeLast: removeLast, - done: null, + done: () => {}, ), SizedBox( height: 10, - ) + ), ], ), ), @@ -147,7 +146,7 @@ class _PinRequestScreenState extends State { } Widget pinItem(String item) { - return item == null + return item == "" ? Container( width: 10, height: 2, @@ -165,7 +164,11 @@ class NumPad extends StatelessWidget { final Function removeLast; final Function done; - const NumPad({Key key, this.enterNum, this.removeLast, this.done}) + const NumPad( + {Key? key, + required this.enterNum, + required this.removeLast, + required this.done}) : super(key: key); @override @@ -226,7 +229,7 @@ class NumPad extends StatelessWidget { child: Container( margin: EdgeInsets.all(2), child: TextButton( - onPressed: onTap, + onPressed: () => onTap(), child: Text( text, style: TextStyle(fontSize: 20), From 0447ef91dd7b1bf13ab57c0301226a711e10fffa Mon Sep 17 00:00:00 2001 From: Archifer Date: Mon, 24 Apr 2023 15:48:12 +0200 Subject: [PATCH 319/364] FP-83 Added logic for consistent errors for 1. implicit resource calls, and removal of cancel specific errors on iOS regarding login and registration --- .../sdk/flutter/useCases/ResourceRequestUseCase.kt | 3 ++- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 8 +------- ios/Classes/NativeBridge/Handlers/LoginHandler.swift | 8 ++------ .../NativeBridge/Handlers/RegistrationHandler.swift | 9 +++------ 4 files changed, 8 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 8aa9afe0..71de34c2 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -26,7 +26,8 @@ import javax.inject.Singleton @Singleton class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(type: ResourceRequestType, details: OWRequestDetails, callback: (Result) -> Unit) { - if (type == ResourceRequestType.IMPLICIT) { + // Align with iOS behavior + if (type == ResourceRequestType.IMPLICIT && oneginiSDK.oneginiClient.userClient.implicitlyAuthenticatedUserProfile == null) { callback( Result.failure( SdkError( diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 9afe4265..a95f5e18 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -12,9 +12,7 @@ enum OneWelcomeWrapperError { case httpRequestErrorNoResponse // ios only case providedUrlIncorrect // ios only case enrollmentFailed // ios only - case processCanceledLogin // ios only case processCanceledAuthentication // ios only - case processCanceledRegistration // ios only case processCanceledAuthenticatorDeregistration // ios only case processCanceledAuthenticatorRegistration // ios only case authenticatorNotRegistered // ios only @@ -43,7 +41,7 @@ enum OneWelcomeWrapperError { return 8014 case .enrollmentFailed: return 8016 - case .processCanceledAuthentication, .processCanceledRegistration, .processCanceledLogin, .processCanceledAuthenticatorRegistration, .processCanceledAuthenticatorDeregistration: + case .processCanceledAuthentication, .processCanceledAuthenticatorRegistration, .processCanceledAuthenticatorDeregistration: return 8017 case .authenticatorNotRegistered: return 8023 @@ -72,14 +70,10 @@ enum OneWelcomeWrapperError { return "Provided url is incorrect." case .enrollmentFailed: return "Enrollment failed. Please try again or contact maintainer." - case .processCanceledLogin: - return "Login cancelled." case .processCanceledAuthentication: return "Authentication cancelled." case .processCanceledAuthenticatorDeregistration: return "Authenticator deregistration cancelled." - case .processCanceledRegistration: - return "Registration cancelled." case .authenticatorNotRegistered: return "This authenticator is not registered." case .httpRequestErrorNoResponse: diff --git a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift index c59c45af..65dfec61 100644 --- a/ios/Classes/NativeBridge/Handlers/LoginHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/LoginHandler.swift @@ -91,11 +91,7 @@ class AuthenticationDelegateImpl: AuthenticationDelegate { func userClient(_ userClient: UserClient, didFailToAuthenticateUser profile: UserProfile, authenticator: Authenticator, error: Error) { loginHandler.handleDidFailToAuthenticateUser() - if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.processCanceledLogin))) - } else { - let mappedError = ErrorMapper().mapError(error) - completion(.failure(FlutterError(mappedError))) - } + let mappedError = ErrorMapper().mapError(error) + completion(.failure(FlutterError(mappedError))) } } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index f07baea0..19271046 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -185,12 +185,9 @@ class RegistrationDelegateImpl: RegistrationDelegate { func userClient(_ userClient: UserClient, didFailToRegisterUserWith identityProvider: IdentityProvider, error: Error) { registrationHandler.handleDidFailToRegister() - if error.code == ONGGenericError.actionCancelled.rawValue { - completion(.failure(FlutterError(.processCanceledRegistration))) - } else { - let mappedError = ErrorMapper().mapError(error) - completion(.failure(FlutterError(mappedError))) - } + + let mappedError = ErrorMapper().mapError(error) + completion(.failure(FlutterError(mappedError))) } } From ae85e669b9594f6c2667b25427d3aaa00d4ee7f1 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 15:51:13 +0200 Subject: [PATCH 320/364] FP-86: Make pin_screen nullsafe --- example/lib/screens/pin_screen.dart | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/example/lib/screens/pin_screen.dart b/example/lib/screens/pin_screen.dart index 3777ecb1..26aa471e 100644 --- a/example/lib/screens/pin_screen.dart +++ b/example/lib/screens/pin_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/callbacks/onegini_pin_authentication_callback.dart'; @@ -8,18 +7,18 @@ import '../components/display_toast.dart'; class PinScreen extends StatefulWidget { final PinScreenController controller; - PinScreen({this.controller}); + PinScreen({required this.controller}); @override _PinScreenState createState() => _PinScreenState(controller); } class PinScreenController { - void Function() clearState; + void Function() clearState = () => {}; } class _PinScreenState extends State { - List pinCode = List.filled(5, null); + List pinCode = List.filled(5, ""); var isLoading = false; _PinScreenState(PinScreenController _controller) { @@ -29,13 +28,13 @@ class _PinScreenState extends State { void clearState() { setState(() { isLoading = false; - pinCode = List.filled(5, null); + pinCode = List.filled(5, ""); }); } enterNum(String num) { for (var i = 0; i < pinCode.length; i++) { - if (pinCode[i] == null) { + if (pinCode[i] == "") { setState(() => pinCode[i] = num); // if last pin digit is provided if (i == pinCode.length - 1) { @@ -48,12 +47,12 @@ class _PinScreenState extends State { removeLast() { for (var i = 0; i < pinCode.length; i++) { - if (pinCode[i] == null && i != 0) { - setState(() => pinCode[i - 1] = null); + if (pinCode[i] == "" && i != 0) { + setState(() => pinCode[i - 1] = ""); break; } - if (pinCode[i] != null && i == pinCode.length - 1) { - setState(() => pinCode[i] = null); + if (pinCode[i] != "" && i == pinCode.length - 1) { + setState(() => pinCode[i] = ""); break; } } @@ -124,7 +123,7 @@ class _PinScreenState extends State { } Widget pinItem(String item) { - return item == null + return item == "" ? Container( width: 10, height: 2, @@ -141,7 +140,8 @@ class NumPad extends StatelessWidget { final Function(String) enterNum; final Function removeLast; - const NumPad({Key key, this.enterNum, this.removeLast}) : super(key: key); + const NumPad({Key? key, required this.enterNum, required this.removeLast}) + : super(key: key); @override Widget build(BuildContext context) { @@ -201,7 +201,7 @@ class NumPad extends StatelessWidget { child: Container( margin: EdgeInsets.all(2), child: TextButton( - onPressed: onTap, + onPressed: () => onTap(), child: Text( text, style: TextStyle(fontSize: 20), From 4533ab300ae04b57faea7d803294f1157a79ef6b Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 15:58:39 +0200 Subject: [PATCH 321/364] FP-86: Make qr_screen nullsafe This was done pretty dirty and will likely require a refactor later --- example/lib/screens/qr_scan_screen.dart | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/example/lib/screens/qr_scan_screen.dart b/example/lib/screens/qr_scan_screen.dart index 26302e64..3413fd58 100644 --- a/example/lib/screens/qr_scan_screen.dart +++ b/example/lib/screens/qr_scan_screen.dart @@ -1,4 +1,3 @@ -// @dart = 2.10 import 'dart:io'; import 'package:flutter/material.dart'; @@ -10,9 +9,8 @@ class QrScanScreen extends StatefulWidget { } class _QrScanScreenState extends State { - Barcode result; int counter = 0; - QRViewController controller; + QRViewController? controller; final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); // In order to get hot reload to work we need to pause the camera if the platform @@ -21,26 +19,29 @@ class _QrScanScreenState extends State { void reassemble() { super.reassemble(); if (Platform.isAndroid) { - controller.pauseCamera(); + controller?.pauseCamera(); } - controller.resumeCamera(); + controller?.resumeCamera(); } - void onQRViewCreated(QRViewController controllerr) { - setState(() => controller = controllerr); + void onQRViewCreated(QRViewController controller) { + setState(() => this.controller = controller); controller.scannedDataStream.listen((scanData) { if (counter >= 1) { return; } - sendDataBack(scanData.code); + final code = scanData.code; + if (code != null) { + sendDataBack(code); + } }); } sendDataBack(String data) async { counter++; - await controller.pauseCamera(); + await controller?.pauseCamera(); if (counter >= 1) { - controller.stopCamera(); + controller?.stopCamera(); Navigator.of(context)..pop(data); } } From 1c4f4ce6469d56d7b958b2e4a5e8efe0779c0baa Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 15:59:54 +0200 Subject: [PATCH 322/364] FP-86: Make main.dart nullsafe --- example/lib/main.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 9fac3e5b..09b02507 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,5 +1,5 @@ -// @dart = 2.10 import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; import 'package:onegini/pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; @@ -63,7 +63,7 @@ class _BodyWidgetState extends State { ], connectionTimeout: 5, readTimeout: 25); - } catch (error) { + } on PlatformException catch (error) { showFlutterToast(error.message); } From 178f8b112c260a45323d38feb23692cf926c409a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 24 Apr 2023 16:28:28 +0200 Subject: [PATCH 323/364] FP-86: Re-add spacing between buttons on homepage --- example/lib/screens/login_screen.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index c8d37bd7..25227e48 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -245,6 +245,7 @@ class _LoginScreenState extends State { }, child: Text('Pin'), ), + SizedBox(height: 10, width: 10), ElevatedButton( onPressed: () { authenticate( From cecef291a5ad1ef0794b1c6909e9b55643590a17 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 09:53:17 +0200 Subject: [PATCH 324/364] fp-83 update linter to exclude pigeon generated files --- analysis_options.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/analysis_options.yaml b/analysis_options.yaml index 61b6c4de..dbe441e6 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -9,6 +9,10 @@ # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml +analyzer: + exclude: + - lib/pigeon.dart + linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` From 7b12898791c21ed5153e1c45864601c9ca643ccc Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 10:00:40 +0200 Subject: [PATCH 325/364] fp-83 update format in pigeon --- lib/pigeon.dart | 227 +++++++++++++++++++++++++++--------------------- 1 file changed, 126 insertions(+), 101 deletions(-) diff --git a/lib/pigeon.dart b/lib/pigeon.dart index a74632f7..108efe9f 100644 --- a/lib/pigeon.dart +++ b/lib/pigeon.dart @@ -384,19 +384,19 @@ class _UserClientApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAppToWebSingleSignOn.decode(readValue(buffer)!); - case 129: + case 129: return OWAuthenticator.decode(readValue(buffer)!); - case 130: + case 130: return OWCustomIdentityProvider.decode(readValue(buffer)!); - case 131: + case 131: return OWCustomInfo.decode(readValue(buffer)!); - case 132: + case 132: return OWIdentityProvider.decode(readValue(buffer)!); - case 133: + case 133: return OWRegistrationResponse.decode(readValue(buffer)!); - case 134: + case 134: return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -415,12 +415,22 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout) async { + Future startApplication( + String? arg_securityControllerClassName, + String? arg_configModelClassName, + List? arg_customIdentityProviderConfigs, + int? arg_connectionTimeout, + int? arg_readTimeout) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.startApplication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout]) as List?; + final List? replyList = await channel.send([ + arg_securityControllerClassName, + arg_configModelClassName, + arg_customIdentityProviderConfigs, + arg_connectionTimeout, + arg_readTimeout + ]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -437,12 +447,13 @@ class UserClientApi { } } - Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { + Future registerUser( + String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_identityProviderId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -464,12 +475,13 @@ class UserClientApi { } } - Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl( + String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_url, arg_signInType]) as List?; + final List? replyList = await channel + .send([arg_url, arg_signInType]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -490,8 +502,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getIdentityProviders', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -539,8 +550,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -562,12 +572,14 @@ class UserClientApi { } } - Future authenticateUser(String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { + Future authenticateUser( + String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_authenticatorType.index]) + as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -589,7 +601,8 @@ class UserClientApi { } } - Future authenticateUserPreferred(String arg_profileId) async { + Future authenticateUserPreferred( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserPreferred', codec, binaryMessenger: _binaryMessenger); @@ -616,7 +629,8 @@ class UserClientApi { } } - Future getBiometricAuthenticator(String arg_profileId) async { + Future getBiometricAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -643,7 +657,8 @@ class UserClientApi { } } - Future getPreferredAuthenticator(String arg_profileId) async { + Future getPreferredAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -670,12 +685,13 @@ class UserClientApi { } } - Future setPreferredAuthenticator(OWAuthenticatorType arg_authenticatorType) async { + Future setPreferredAuthenticator( + OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -694,10 +710,10 @@ class UserClientApi { Future deregisterBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -716,10 +732,10 @@ class UserClientApi { Future registerBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -740,8 +756,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -762,8 +777,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.logout', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -784,8 +798,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -855,8 +868,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -882,8 +894,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getRedirectUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -909,8 +920,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getUserProfiles', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -976,12 +986,13 @@ class UserClientApi { } } - Future authenticateUserImplicitly(String arg_profileId, List? arg_scopes) async { + Future authenticateUserImplicitly( + String arg_profileId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1001,7 +1012,8 @@ class UserClientApi { /// Custom Registration Callbacks Future submitCustomRegistrationAction(String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_data]) as List?; @@ -1023,7 +1035,8 @@ class UserClientApi { Future cancelCustomRegistrationAction(String arg_error) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_error]) as List?; @@ -1048,8 +1061,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1068,10 +1080,10 @@ class UserClientApi { Future fingerprintDenyAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1090,10 +1102,10 @@ class UserClientApi { Future fingerprintAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1115,8 +1127,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1135,10 +1146,10 @@ class UserClientApi { Future otpAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1160,8 +1171,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1180,7 +1190,8 @@ class UserClientApi { Future pinAcceptAuthenticationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_pin]) as List?; @@ -1205,8 +1216,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1250,8 +1260,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1287,9 +1296,9 @@ class _ResourceMethodApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWRequestDetails.decode(readValue(buffer)!); - case 129: + case 129: return OWRequestResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1307,12 +1316,13 @@ class ResourceMethodApi { static const MessageCodec codec = _ResourceMethodApiCodec(); - Future requestResource(ResourceRequestType arg_type, OWRequestDetails arg_details) async { + Future requestResource( + ResourceRequestType arg_type, OWRequestDetails arg_details) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.ResourceMethodApi.requestResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_type.index, arg_details]) as List?; + final List? replyList = await channel + .send([arg_type.index, arg_details]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1356,11 +1366,11 @@ class _NativeCallFlutterApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAuthenticationAttempt.decode(readValue(buffer)!); - case 129: + case 129: return OWCustomInfo.decode(readValue(buffer)!); - case 130: + case 130: return OWOneginiError.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1391,7 +1401,8 @@ abstract class NativeCallFlutterApi { void n2fClosePinAuthentication(); /// Called to attempt next pin authentication. - void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); + void n2fNextPinAuthenticationAttempt( + OWAuthenticationAttempt authenticationAttempt); /// Called to open OTP authentication. void n2fOpenAuthOtp(String? message); @@ -1412,22 +1423,26 @@ abstract class NativeCallFlutterApi { void n2fNextFingerprintAuthenticationAttempt(); /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) - void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventInitCustomRegistration( + OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given - void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventFinishCustomRegistration( + OWCustomInfo? customInfo, String providerId); - static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(NativeCallFlutterApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); final List args = (message as List?)!; final String? arg_url = (args[0] as String?); assert(arg_url != null, @@ -1474,7 +1489,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); final List args = (message as List?)!; final OWOneginiError? arg_error = (args[0] as OWOneginiError?); assert(arg_error != null, @@ -1486,7 +1501,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1500,7 +1516,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1514,16 +1531,18 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); final List args = (message as List?)!; - final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); + final OWAuthenticationAttempt? arg_authenticationAttempt = + (args[0] as OWAuthenticationAttempt?); assert(arg_authenticationAttempt != null, 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); api.n2fNextPinAuthenticationAttempt(arg_authenticationAttempt!); @@ -1540,7 +1559,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); api.n2fOpenAuthOtp(arg_message); @@ -1564,7 +1583,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1578,7 +1598,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1592,7 +1613,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1606,7 +1628,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1620,14 +1643,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); @@ -1640,14 +1664,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); From 4e66feb09883999091388c205f5308ffed8fb509 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 10:36:02 +0200 Subject: [PATCH 326/364] FP-38 Update when statement with result object --- .../useCases/ResourceRequestUseCase.kt | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 9a47a4ff..37232c68 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -30,22 +30,20 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini val pathResult = getCompleteResourceUrl(details.path) // Additional check for valid url - when { - pathResult.isFailure -> pathResult.exceptionOrNull()?.let { callback(Result.failure(it)) } - pathResult.isSuccess -> { - pathResult.getOrNull()?.let { - val resourceClient = getOkHttpClient(type) - val request = buildRequest(details, it) - - performCall(resourceClient, request, callback) - } - } + pathResult.onSuccess { + val resourceClient = getOkHttpClient(type) + val request = buildRequest(details, it) + + performCall(resourceClient, request, callback) + } + + pathResult.onFailure { + callback(Result.failure(it)) } } private fun getCompleteResourceUrl(path: String): Result { val resourceBaseUrl = oneginiSDK.oneginiClient.configModel.resourceBaseUrl - return when { isValidUrl(path) -> Result.success(path) isValidUrl(resourceBaseUrl + path) -> Result.success(resourceBaseUrl + path) From c59b129127a4561b9fc211d10f1be69ebd8312df Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 11:12:20 +0200 Subject: [PATCH 327/364] fp-38 reallign invalid url error code on both ios and android --- .../mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 2 +- .../sdk/flutter/useCases/ResourceRequestUseCase.kt | 4 ++-- .../onegini/mobile/sdk/ResourceRequestUseCaseTests.kt | 4 ++-- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 9 +++------ .../NativeBridge/Handlers/RegistrationHandler.swift | 4 ++-- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 2 +- .../ModuleExtensions/OneginiModuleSwift+Auth.swift | 2 +- 7 files changed, 12 insertions(+), 15 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 75b02cca..b027b5c9 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -7,6 +7,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { AUTHENTICATOR_NOT_FOUND(8004, "The requested authenticator is not found"), HTTP_REQUEST_ERROR(8011, "OneWelcome: HTTP Request failed internally"), ERROR_CODE_HTTP_REQUEST(8013, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + PROVIDED_URL_INCORRECT(8014, "The provided url is invalid or incorrect"), BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8043, "Biometric authentication is not supported on this device"), REGISTRATION_NOT_IN_PROGRESS(8034, "Registration is currently not in progress"), @@ -15,7 +16,6 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { OTP_AUTHENTICATION_NOT_IN_PROGRESS(8039, "OTP Authentication is currently not in progress"), BROWSER_REGISTRATION_NOT_IN_PROGRESS(8040, "Browser registration is currently not in progress"), PIN_CREATION_NOT_IN_PROGRESS(8042, "Pin creation is currently not in progress"), - HTTP_REQUEST_URL_ERROR(8043, "OneWelcome: HTTP Request failed due to an invalid url"), // Errors that only occur on Android IDENTITY_PROVIDER_NOT_FOUND(8005, "The requested identity provider is not found"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 37232c68..e178832e 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk.flutter.useCases import android.util.Patterns import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_URL_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError @@ -49,7 +49,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini isValidUrl(resourceBaseUrl + path) -> Result.success(resourceBaseUrl + path) else -> Result.failure( SdkError( - wrapperError = HTTP_REQUEST_URL_ERROR + wrapperError = PROVIDED_URL_INCORRECT ).pigeonError() ) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 14bf61a4..4dcb7f6a 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.UserClient import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_URL_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET @@ -75,7 +75,7 @@ class ResourceRequestUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - val expected = FlutterError(HTTP_REQUEST_URL_ERROR.code.toString(), HTTP_REQUEST_URL_ERROR.message) + val expected = FlutterError(PROVIDED_URL_INCORRECT.code.toString(), PROVIDED_URL_INCORRECT.message) SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 7ce406d2..bbdd80ed 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -15,11 +15,10 @@ enum OneWelcomeWrapperError: Int { case authenticationNotInProgress = 8037 case otpAuthenticationNotInProgress = 8039 case browserRegistrationNotInProgress = 8040 - case httpRequestUrlError = 8050 case biometricAuthenticationNotAvailable = 8043 // iOS only - case providedUrlIncorrect = 8014 + case invalidUrl = 8014 case loginCanceled = 8015 case enrollmentFailed = 8016 case authenticationCancelled = 8017 @@ -47,8 +46,8 @@ enum OneWelcomeWrapperError: Int { return "There is currently no User Profile authenticated." case .authenticatorNotFound: return "The requested authenticator is not found." - case .providedUrlIncorrect: - return "Provided url is incorrect." + case .invalidUrl: + return "The provided url is invalid or incorrect." case .enrollmentFailed: return "Enrollment failed. Please try again or contact maintainer." case .loginCanceled: @@ -97,8 +96,6 @@ enum OneWelcomeWrapperError: Int { return "Mobile Authentication is already in progress and can not be performed concurrently." case .browserRegistrationNotInProgress: return "Browser registration is currently not in progress." - case .httpRequestUrlError: - return "OneWelcome: HTTP Request failed due to an invalid url." case .biometricAuthenticationNotAvailable: return "Biometric authentication is not supported on this device." } diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 487f9410..d66ec007 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -100,11 +100,11 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func processRedirectURL(url: String, webSignInType: Int) -> Result { let webSignInType = WebSignInType(rawValue: webSignInType) guard let url = URL.init(string: url) else { - return .failure(FlutterError(.providedUrlIncorrect)) + return .failure(FlutterError(.invalidUrl)) } if webSignInType != .insideApp && !UIApplication.shared.canOpenURL(url) { - return .failure(FlutterError(.providedUrlIncorrect)) + return .failure(FlutterError(.invalidUrl)) } presentBrowserUserRegistrationView(registrationUserURL: url, webSignInType: webSignInType) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index a279850f..be4a4d8b 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -43,7 +43,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { // Additional check for valid url let resourceUrl = ONGClient.sharedInstance().configModel.resourceBaseURL ?? "" if checkValidUrl(details.path) == false && checkValidUrl(resourceUrl + details.path) == false { - completion(.failure(FlutterError(SdkError(.httpRequestUrlError)))) + completion(.failure(FlutterError(SdkError(.invalidUrl)))) return } diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 37e52474..3c1e76a7 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -26,7 +26,7 @@ extension OneginiModuleSwift { func runSingleSignOn(_ path: String, completion: @escaping (Result) -> Void) { guard let url = URL(string: path) else { - completion(.failure(FlutterError(.providedUrlIncorrect))) + completion(.failure(FlutterError(.invalidUrl))) return } bridgeConnector.toAppToWebHandler.signInAppToWeb(targetURL: url, completion: completion) From d0b83f0989175542a9b86147fa7a0b630dff916d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 25 Apr 2023 13:02:36 +0200 Subject: [PATCH 328/364] FP-86: Remove not required null checks --- example/lib/screens/login_screen.dart | 30 +++++++++++++-------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 25227e48..2f9fd2ad 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -52,14 +52,13 @@ class _LoginScreenState extends State { ["read"], ); - if (registrationResponse.userProfile.profileId != null) - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) => UserScreen( - userProfileId: registrationResponse.userProfile.profileId, - )), - (Route route) => false); + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => UserScreen( + userProfileId: registrationResponse.userProfile.profileId, + )), + (Route route) => false); } catch (error) { setState(() => isLoading = false); if (error is PlatformException) { @@ -76,14 +75,13 @@ class _LoginScreenState extends State { ["read"], ); - if (registrationResponse.userProfile.profileId != null) - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) => UserScreen( - userProfileId: registrationResponse.userProfile.profileId, - )), - (Route route) => false); + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => UserScreen( + userProfileId: registrationResponse.userProfile.profileId, + )), + (Route route) => false); } catch (error) { setState(() => isLoading = false); if (error is PlatformException) { From 7c3cd09304a1d8e2add7d53fbe5d16bbcdf4ea50 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 13:08:21 +0200 Subject: [PATCH 329/364] fp-83 fix tests --- .../mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt | 2 +- .../mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt index 3353caf4..2cf90284 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetBiometricAuthenticatorUseCaseTests.kt @@ -44,7 +44,7 @@ class GetBiometricAuthenticatorUseCaseTests { fun `When userProfile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { val result = getBiometricAuthenticatorUseCase(profileId) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_USER_PROFILE, result.exceptionOrNull()) } @Test diff --git a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt index aeffeb9d..91897b32 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/GetPreferredAuthenticatorUseCaseTests.kt @@ -17,8 +17,6 @@ import org.mockito.Answers import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(MockitoJUnitRunner::class) @@ -45,7 +43,7 @@ class GetPreferredAuthenticatorUseCaseTests { fun `When no userprofile does not exist, Then should reject with USER_PROFILE_DOES_NOT_EXIST`() { val result = getPreferredAuthenticatorUseCase(profileId) - SdkErrorAssert.assertEquals(USER_PROFILE_DOES_NOT_EXIST, result.exceptionOrNull()) + SdkErrorAssert.assertEquals(NOT_FOUND_USER_PROFILE, result.exceptionOrNull()) } @Test From 7cbebea9267a780b459a3c41124fe07decf3a92b Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 15:02:56 +0200 Subject: [PATCH 330/364] fp-38 update var name and readd apply --- .../sdk/flutter/useCases/ResourceRequestUseCase.kt | 5 ++++- .../onegini/mobile/sdk/ResourceRequestUseCaseTests.kt | 10 +++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index e178832e..c716eba4 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -1,9 +1,11 @@ package com.onegini.mobile.sdk.flutter.useCases +import android.net.Uri +import android.util.Log import android.util.Patterns import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ERROR_CODE_HTTP_REQUEST -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.DELETE @@ -21,6 +23,7 @@ import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.io.IOException +import java.net.URI import javax.inject.Inject import javax.inject.Singleton diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 4dcb7f6a..c2d98eba 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -44,7 +44,7 @@ class ResourceRequestUseCaseTests { lateinit var okhttp3CallMock: okhttp3.Call @Mock - lateinit var owRequestResponseDetails: OWRequestDetails + lateinit var owRequestDetails: OWRequestDetails @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var responseMock: Response @@ -69,8 +69,8 @@ class ResourceRequestUseCaseTests { @Test fun `When an invalid url is given, Then the function should resolve with an error`() { whenever(oneginiSdk.oneginiClient.configModel.resourceBaseUrl).thenReturn("https://token-mobile.test.onegini.com/resources/") - whenever(owRequestResponseDetails.path).thenReturn("https://^%%&^%*^/user-id-decorated") - resourceRequestUseCase(ResourceRequestType.IMPLICIT, owRequestResponseDetails, callbackMock) + whenever(owRequestDetails.path).thenReturn("https://^%%&^%*^/user-id-decorated") + resourceRequestUseCase(ResourceRequestType.IMPLICIT, owRequestDetails, callbackMock) argumentCaptor>().apply { verify(callbackMock).invoke(capture()) @@ -84,7 +84,7 @@ class ResourceRequestUseCaseTests { fun `When a successful http response is send, Then the call should resolve with an OWRequestResponse containing correct information`() { setupSuccessFullResponseMock() whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) - argumentCaptor { + argumentCaptor().apply { whenever( okhttp3CallMock.enqueue(capture()) ).thenAnswer { @@ -106,7 +106,7 @@ class ResourceRequestUseCaseTests { fun `When a successful http response is send but with an error http code, Then the call should resolve with an flutter error`() { setupErrorFullResponseMock() whenever(resourceOkHttpClientMock.newCall(any())).thenReturn(okhttp3CallMock) - argumentCaptor { + argumentCaptor().apply { whenever( okhttp3CallMock.enqueue(capture()) ).thenAnswer { From 65e60bfbb567d6f3818c6ad4bd1c547ca8aee06b Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 15:09:41 +0200 Subject: [PATCH 331/364] fp-38 reformat --- pigeons/onewelcome_pigeon_interface.dart | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 165bd3f5..557eb373 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -133,13 +133,12 @@ class OWCustomIdentityProvider { abstract class UserClientApi { @async void startApplication( - String? securityControllerClassName, - String? configModelClassName, - List? customIdentityProviderConfigs, - int? connectionTimeout, - int? readTimeout, - List? additionalResourceUrls - ); + String? securityControllerClassName, + String? configModelClassName, + List? customIdentityProviderConfigs, + int? connectionTimeout, + int? readTimeout, + List? additionalResourceUrls); @async OWRegistrationResponse registerUser( From d642de4e0aff44ab5fbe44cc9b5c9c6de7f32db4 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 16:28:20 +0200 Subject: [PATCH 332/364] FP-83 Ungrouped error codes to be closer to native sdk and changed not allowed custom submit into not in progress --- .../sdk/flutter/OneWelcomeWrapperErrors.kt | 41 +++++++--------- .../providers/CustomRegistrationActionImpl.kt | 6 +-- .../CustomTwoStepRegistrationActionImpl.kt | 4 +- .../SubmitCustomRegistrationActionUseCase.kt | 4 +- .../NativeBridge/Errors/ErrorMapper.swift | 48 +++++++++++++------ .../Handlers/RegistrationHandler.swift | 2 +- 6 files changed, 59 insertions(+), 46 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 912c2d8f..1d1aa273 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -2,36 +2,31 @@ package com.onegini.mobile.sdk.flutter enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { GENERIC_ERROR(8000, "Something went wrong"), - NOT_AUTHENTICATED_USER(8002, "There is currently no User Profile authenticated"), - NOT_AUTHENTICATED_IMPLICIT(8002, "The requested action requires you to be authenticated implicitly"), - NOT_FOUND_USER_PROFILE(8004, "The requested User profile is not found"), - NOT_FOUND_AUTHENTICATOR(8004, "The requested authenticator is not found"), - NOT_FOUND_IDENTITY_PROVIDER(8004, "The requested identity provider is not found"), // Android only - NOT_FOUND_SECURITY_CONTROLLER(8004, "The requested Security controller class is not found"), // Android only - HTTP_REQUEST_ERROR_INTERNAL(8011, "OneWelcome: HTTP Request failed internally"), - HTTP_REQUEST_ERROR_CODE(8011, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), - ONEWELCOME_SDK_NOT_INITIALIZED(8012, "OneWelcomeSDK is not initialized"), // Android only - CONFIG_ERROR(8032, "Something went wrong while setting the configuration"), // Android only - NOT_IN_PROGRESS_REGISTRATION(8034, "Registration is currently not in progress"), - NOT_IN_PROGRESS_AUTHENTICATION(8034, "Authentication is currently not in progress"), - NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8034, "Fingerprint Authentication is currently not in progress"), - NOT_IN_PROGRESS_OTP_AUTHENTICATION(8034, "OTP Authentication is currently not in progress"), - NOT_IN_PROGRESS_PIN_CREATION(8034, "Pin Creation is currently not in progress"), // Android only + NOT_AUTHENTICATED_USER(8040, "There is currently no User Profile authenticated"), + NOT_AUTHENTICATED_IMPLICIT(8041, "The requested action requires you to be authenticated implicitly"), + NOT_FOUND_USER_PROFILE(8042, "The requested User profile is not found"), + NOT_FOUND_AUTHENTICATOR(8043, "The requested authenticator is not found"), + NOT_FOUND_IDENTITY_PROVIDER(8044, "The requested identity provider is not found"), + NOT_FOUND_SECURITY_CONTROLLER(8045, "The requested Security controller class is not found"), // Android only + HTTP_REQUEST_ERROR_INTERNAL(8046, "OneWelcome: HTTP Request failed internally"), + HTTP_REQUEST_ERROR_CODE(8047, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + ONEWELCOME_SDK_NOT_INITIALIZED(8049, "OneWelcomeSDK is not initialized"), // Android only + NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8051, "Custom Registration is currently not in progress"), + NOT_IN_PROGRESS_AUTHENTICATION(8052, "Authentication is currently not in progress"), + NOT_IN_PROGRESS_OTP_AUTHENTICATION(8053, "OTP Authentication is currently not in progress"), + NOT_IN_PROGRESS_PIN_CREATION(8054, "Pin Creation is currently not in progress"), + NOT_IN_PROGRESS_FINGERPRINT_AUTHENTICATION(8055, "Fingerprint Authentication is currently not in progress"), ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_CANCEL( - 8042, + 8057, "Canceling the Custom registration right now is not allowed." + " Registration is not in progress or pin creation has already started" ), - ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT( - 8042, - "Submitting the Custom registration right now is not allowed." + - " Registration is not in progress or pin creation has already started" - ), ACTION_NOT_ALLOWED_BROWSER_REGISTRATION_CANCEL( - 8042, + 8058, "Canceling the Browser registration right now is not allowed." + " Registration is not in progress or pin creation has already started" ), - BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8043, "Biometric authentication is not supported on this device"), + CONFIG_ERROR(8059, "Something went wrong while setting the configuration"), // Android only + BIOMETRIC_AUTHENTICATION_NOT_AVAILABLE(8060, "Biometric authentication is not supported on this device"), UNEXPECTED_ERROR_TYPE(8999, "An unexpected error type was returned"), // Android only } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt index e16b273c..2a5aade7 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomRegistrationActionImpl.kt @@ -3,7 +3,7 @@ package com.onegini.mobile.sdk.flutter.providers import com.onegini.mobile.sdk.android.handlers.action.OneginiCustomRegistrationAction import com.onegini.mobile.sdk.android.handlers.request.callback.OneginiCustomRegistrationCallback import com.onegini.mobile.sdk.android.model.entity.CustomInfo -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION import com.onegini.mobile.sdk.flutter.helpers.SdkError import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo import com.onegini.mobile.sdk.flutter.pigeonPlugin.NativeCallFlutterApi @@ -33,7 +33,7 @@ class CustomRegistrationActionImpl(private val providerId: String, private val n customRegistrationCallback.returnSuccess(result) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(NOT_IN_PROGRESS_REGISTRATION).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) } override fun returnError(exception: Exception?): Result { @@ -41,6 +41,6 @@ class CustomRegistrationActionImpl(private val providerId: String, private val n customRegistrationCallback.returnError(exception) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(NOT_IN_PROGRESS_REGISTRATION).pigeonError()) + } ?: Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt index 4e2c8dd1..cb42d338 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/providers/CustomTwoStepRegistrationActionImpl.kt @@ -39,7 +39,7 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String, privat customRegistrationCallback.returnSuccess(result) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION).pigeonError()) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) } override fun returnError(exception: Exception?): Result { @@ -47,6 +47,6 @@ class CustomTwoStepRegistrationActionImpl(private val providerId: String, privat customRegistrationCallback.returnError(exception) callback = null Result.success(Unit) - } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_REGISTRATION).pigeonError()) + } ?: Result.failure(SdkError(OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) } } diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt index a8f79323..10562f71 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/SubmitCustomRegistrationActionUseCase.kt @@ -1,6 +1,6 @@ package com.onegini.mobile.sdk.flutter.useCases -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_IN_PROGRESS_CUSTOM_REGISTRATION import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.helpers.SdkError import javax.inject.Inject @@ -10,7 +10,7 @@ import javax.inject.Singleton class SubmitCustomRegistrationActionUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) { operator fun invoke(data: String?): Result { return when (val action = oneginiSDK.getCustomRegistrationActions().find { it.isInProgress() }) { - null -> Result.failure(SdkError(ACTION_NOT_ALLOWED_CUSTOM_REGISTRATION_SUBMIT).pigeonError()) + null -> Result.failure(SdkError(NOT_IN_PROGRESS_CUSTOM_REGISTRATION).pigeonError()) else -> action.returnSuccess(data) } } diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 55b1ecf5..d2c205be 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -15,9 +15,9 @@ enum OneWelcomeWrapperError { case notInProgressAuthentication case notInProgressOtpAuthentication case notInProgressPinCreation + case notInProgressCustomRegistration case alreadyInProgressMobileAuth // ios only case actionNotAllowedCustomRegistrationCancel - case actionNotAllowedCustomRegistrationSubmit case actionNotAllowedBrowserRegistrationCancel case biometricAuthenticationNotAvailable @@ -25,22 +25,40 @@ enum OneWelcomeWrapperError { switch self { case .genericError: return 8000 - case .notAuthenticatedUser, .notAuthenticatedImplicit: - return 8002 - case .notFoundUserProfile, .notFoundAuthenticator, .notFoundIdentityProvider: - return 8004 - case .httpRequestErrorInternal, .httpRequestErrorCode, .httpRequestErrorNoResponse: - return 8011 - case .providedUrlIncorrect: - return 8014 - case .notInProgressAuthentication, .notInProgressOtpAuthentication, .notInProgressPinCreation: - return 8034 - case .alreadyInProgressMobileAuth: + case .notAuthenticatedUser: + return 8040 + case .notAuthenticatedImplicit: return 8041 - case .actionNotAllowedCustomRegistrationSubmit, .actionNotAllowedCustomRegistrationCancel, .actionNotAllowedBrowserRegistrationCancel: + case .notFoundUserProfile: return 8042 - case .biometricAuthenticationNotAvailable: + case .notFoundAuthenticator: return 8043 + case .notFoundIdentityProvider: + return 8044 + case .httpRequestErrorInternal: + return 8046 + case .httpRequestErrorCode: + return 8047 + case .httpRequestErrorNoResponse: + return 8048 + case .providedUrlIncorrect: + return 8050 + case .notInProgressCustomRegistration: + return 8051 + case .notInProgressAuthentication: + return 8052 + case .notInProgressOtpAuthentication: + return 8053 + case .notInProgressPinCreation: + return 8054 + case .alreadyInProgressMobileAuth: + return 8056 + case .actionNotAllowedCustomRegistrationCancel: + return 8057 + case .actionNotAllowedBrowserRegistrationCancel: + return 8058 + case .biometricAuthenticationNotAvailable: + return 8060 } } @@ -74,7 +92,7 @@ enum OneWelcomeWrapperError { return "Pin Creation is currently not in progress" case .alreadyInProgressMobileAuth: return "Mobile Authentication is already in progress and can not be performed concurrently." - case .actionNotAllowedCustomRegistrationSubmit: + case .notInProgressCustomRegistration: return "Submitting the Custom registration right now is not allowed. Registration is not in progress or pin creation has already started." case .actionNotAllowedCustomRegistrationCancel: return "Canceling the Custom registration right now is not allowed. Registration is not in progress or pin creation has already started." diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 6fcf32ea..f176bcbb 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -119,7 +119,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func submitCustomRegistrationSuccess(_ data: String?, _ completion: @escaping (Result) -> Void) { guard let customRegistrationChallenge = self.customRegistrationChallenge else { - completion(.failure(SdkError(OneWelcomeWrapperError.actionNotAllowedCustomRegistrationSubmit).flutterError())) + completion(.failure(SdkError(OneWelcomeWrapperError.notInProgressCustomRegistration).flutterError())) return } customRegistrationChallenge.sender.respond(with: data, to: customRegistrationChallenge) From 260d9f9bdbf18ed550b0e17f390f40ceea0260da Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 16:34:55 +0200 Subject: [PATCH 333/364] fp-83 re-align error messages --- .../com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 2 +- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 1d1aa273..4dbaeb55 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -9,7 +9,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { NOT_FOUND_IDENTITY_PROVIDER(8044, "The requested identity provider is not found"), NOT_FOUND_SECURITY_CONTROLLER(8045, "The requested Security controller class is not found"), // Android only HTTP_REQUEST_ERROR_INTERNAL(8046, "OneWelcome: HTTP Request failed internally"), - HTTP_REQUEST_ERROR_CODE(8047, "OneWelcome: HTTP Request returned an error code. Check Response for more info"), + HTTP_REQUEST_ERROR_CODE(8047, "OneWelcome: HTTP Request returned an http error code. Check Response for more info"), ONEWELCOME_SDK_NOT_INITIALIZED(8049, "OneWelcomeSDK is not initialized"), // Android only NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8051, "Custom Registration is currently not in progress"), NOT_IN_PROGRESS_AUTHENTICATION(8052, "Authentication is currently not in progress"), diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index d2c205be..e2866e36 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -81,9 +81,9 @@ enum OneWelcomeWrapperError { case .httpRequestErrorNoResponse: return "OneWelcome: HTTP Request failed. Response doesn't contain data." case .httpRequestErrorCode: - return "OneWelcome: HTTP Request failed. Check Response for more info." + return "OneWelcome: HTTP Request returned an http error code. Check Response for more info." case .httpRequestErrorInternal: - return "OneWelcome: HTTP Request failed. Check iosCode and iosMessage for more info." + return "OneWelcome: HTTP Request failed internally. Check iosCode and iosMessage for more info." case .notInProgressAuthentication: return "Authentication is currently not in progress." case .notInProgressOtpAuthentication: From 9ba34dd3c16e6bf0f7c5a89b6d52c8ebc8d4f3e4 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 16:43:21 +0200 Subject: [PATCH 334/364] FP-83 Update error messages regarding resource requests --- .../onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 4 ++-- ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 4dbaeb55..1180af82 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -8,8 +8,8 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { NOT_FOUND_AUTHENTICATOR(8043, "The requested authenticator is not found"), NOT_FOUND_IDENTITY_PROVIDER(8044, "The requested identity provider is not found"), NOT_FOUND_SECURITY_CONTROLLER(8045, "The requested Security controller class is not found"), // Android only - HTTP_REQUEST_ERROR_INTERNAL(8046, "OneWelcome: HTTP Request failed internally"), - HTTP_REQUEST_ERROR_CODE(8047, "OneWelcome: HTTP Request returned an http error code. Check Response for more info"), + HTTP_REQUEST_ERROR_INTERNAL(8046, "The resource Request failed internally"), + HTTP_REQUEST_ERROR_CODE(8047, "The resource Request returned an HTTP error code. Check Response for more info"), ONEWELCOME_SDK_NOT_INITIALIZED(8049, "OneWelcomeSDK is not initialized"), // Android only NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8051, "Custom Registration is currently not in progress"), NOT_IN_PROGRESS_AUTHENTICATION(8052, "Authentication is currently not in progress"), diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index e2866e36..ba6c9ad3 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -79,11 +79,11 @@ enum OneWelcomeWrapperError { case .providedUrlIncorrect: return "Provided url is incorrect." case .httpRequestErrorNoResponse: - return "OneWelcome: HTTP Request failed. Response doesn't contain data." + return "The resource Request failed. The HTTP response doesn't contain data." case .httpRequestErrorCode: - return "OneWelcome: HTTP Request returned an http error code. Check Response for more info." + return "The resource Request returned an http error code. Check Response for more info." case .httpRequestErrorInternal: - return "OneWelcome: HTTP Request failed internally. Check iosCode and iosMessage for more info." + return "The resource Request failed internally. Check iosCode and iosMessage for more info." case .notInProgressAuthentication: return "Authentication is currently not in progress." case .notInProgressOtpAuthentication: From 8f360a9a765719e7f29ac2617924af0c8b6dc336 Mon Sep 17 00:00:00 2001 From: Archifer Date: Tue, 25 Apr 2023 16:52:49 +0200 Subject: [PATCH 335/364] fp-38 rename function --- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index be4a4d8b..232a383b 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -42,7 +42,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { // Additional check for valid url let resourceUrl = ONGClient.sharedInstance().configModel.resourceBaseURL ?? "" - if checkValidUrl(details.path) == false && checkValidUrl(resourceUrl + details.path) == false { + if isValidUrl(details.path) == false && isValidUrl(resourceUrl + details.path) == false { completion(.failure(FlutterError(SdkError(.invalidUrl)))) return } @@ -70,7 +70,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } private extension ResourcesHandler { - func checkValidUrl(_ path: String) -> Bool { + func isValidUrl(_ path: String) -> Bool { if let url = URL(string: path) { return UIApplication.shared.canOpenURL(url) } From 57123a66a37941e94fdce91b992464cb4ffb97f1 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 09:24:41 +0200 Subject: [PATCH 336/364] fp-38 rename error and fix if statement for registration --- .../mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 2 +- .../flutter/useCases/ResourceRequestUseCase.kt | 4 ++-- .../mobile/sdk/ResourceRequestUseCaseTests.kt | 4 ++-- example/ios/Runner.xcodeproj/project.pbxproj | 15 ++++++++++++--- example/ios/Runner/Info.plist | 12 ++++++------ ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 6 +++--- .../Handlers/RegistrationHandler.swift | 2 +- 7 files changed, 27 insertions(+), 18 deletions(-) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index d2d1d802..14c7432d 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -11,7 +11,7 @@ enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { HTTP_REQUEST_ERROR_INTERNAL(8046, "The resource Request failed internally"), HTTP_REQUEST_ERROR_CODE(8047, "The resource Request returned an HTTP error code. Check Response for more info"), ONEWELCOME_SDK_NOT_INITIALIZED(8049, "OneWelcomeSDK is not initialized"), // Android only - PROVIDED_URL_INCORRECT(8050, "The provided url is invalid or incorrect"), + INVALID_URL(8050, "The provided url is invalid or incorrect"), NOT_IN_PROGRESS_CUSTOM_REGISTRATION(8051, "Custom Registration is currently not in progress"), NOT_IN_PROGRESS_AUTHENTICATION(8052, "Authentication is currently not in progress"), NOT_IN_PROGRESS_OTP_AUTHENTICATION(8053, "OTP Authentication is currently not in progress"), diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt index 6d72cf31..28508ed1 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/ResourceRequestUseCase.kt @@ -1,7 +1,7 @@ package com.onegini.mobile.sdk.flutter.useCases import android.util.Patterns -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.INVALID_URL import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR_CODE import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.HTTP_REQUEST_ERROR_INTERNAL import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_AUTHENTICATED_IMPLICIT @@ -62,7 +62,7 @@ class ResourceRequestUseCase @Inject constructor(private val oneginiSDK: Onegini isValidUrl(resourceBaseUrl + path) -> Result.success(resourceBaseUrl + path) else -> Result.failure( SdkError( - wrapperError = PROVIDED_URL_INCORRECT + wrapperError = INVALID_URL ).pigeonError() ) } diff --git a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt index 53ccebc5..a1296429 100644 --- a/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt +++ b/android/src/test/java/com/onegini/mobile/sdk/ResourceRequestUseCaseTests.kt @@ -2,7 +2,7 @@ package com.onegini.mobile.sdk import com.onegini.mobile.sdk.android.client.UserClient import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.UNEXPECTED_ERROR_TYPE -import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.PROVIDED_URL_INCORRECT +import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.INVALID_URL import com.onegini.mobile.sdk.flutter.OneginiSDK import com.onegini.mobile.sdk.flutter.pigeonPlugin.FlutterError import com.onegini.mobile.sdk.flutter.pigeonPlugin.HttpRequestMethod.GET @@ -75,7 +75,7 @@ class ResourceRequestUseCaseTests { argumentCaptor>().apply { verify(callbackMock).invoke(capture()) - val expected = FlutterError(PROVIDED_URL_INCORRECT.code.toString(), PROVIDED_URL_INCORRECT.message) + val expected = FlutterError(INVALID_URL.code.toString(), INVALID_URL.message) SdkErrorAssert.assertEquals(expected, firstValue.exceptionOrNull()) } } diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 6b9ecbf2..de70df70 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -669,8 +669,10 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 47G5S528XM; + DEVELOPMENT_TEAM = 5ZQB7UCHP8; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -688,6 +690,7 @@ ); PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; @@ -993,8 +996,10 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 47G5S528XM; + DEVELOPMENT_TEAM = 5ZQB7UCHP8; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -1013,6 +1018,7 @@ OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; @@ -1026,8 +1032,10 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 47G5S528XM; + DEVELOPMENT_TEAM = 5ZQB7UCHP8; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -1045,6 +1053,7 @@ ); PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist index d2b45d41..d865a04a 100644 --- a/example/ios/Runner/Info.plist +++ b/example/ios/Runner/Info.plist @@ -2,6 +2,8 @@ + CADisableMinimumFrameDurationOnPhone + CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable @@ -41,10 +43,12 @@ NSCameraUsageDescription Need to access your camera to scan QR code - NSLocalNetworkUsageDescription - Set to your desired customized permission dialog text. NSFaceIDUsageDescription Please provide access to your Face ID + NSLocalNetworkUsageDescription + Set to your desired customized permission dialog text. + UIApplicationSupportsIndirectInputEvents + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile @@ -64,9 +68,5 @@ io.flutter.embedded_views_preview - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index 70279ac3..b347b63f 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -11,7 +11,7 @@ enum OneWelcomeWrapperError { case httpRequestErrorInternal case httpRequestErrorCode case httpRequestErrorNoResponse // ios only - case providedUrlIncorrect + case invalidUrl case notInProgressAuthentication case notInProgressOtpAuthentication case notInProgressPinCreation @@ -41,7 +41,7 @@ enum OneWelcomeWrapperError { return 8047 case .httpRequestErrorNoResponse: return 8048 - case .providedUrlIncorrect: + case .invalidUrl: return 8050 case .notInProgressCustomRegistration: return 8051 @@ -76,7 +76,7 @@ enum OneWelcomeWrapperError { return "The requested authenticator is not found." case .notFoundIdentityProvider: return "The requested identity provider is not found" - case .providedUrlIncorrect: + case .invalidUrl: return "Provided url is incorrect." case .httpRequestErrorNoResponse: return "The resource Request failed. The HTTP response doesn't contain data." diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index 46b03bfc..a6dd9735 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -94,7 +94,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) - if providerId != nil && identityProvider != nil { + if providerId != nil && identityProvider == nil { completion(.failure(SdkError(OneWelcomeWrapperError.notFoundIdentityProvider).flutterError())) return } From 3f41a539d32e34637e4553b07f90328b4c612197 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 09:25:57 +0200 Subject: [PATCH 337/364] fp-hotfix-idprovider hotfix for id provider registration --- ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift index f176bcbb..b4c2fc4d 100644 --- a/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/RegistrationHandler.swift @@ -94,7 +94,7 @@ class RegistrationHandler: NSObject, BrowserHandlerToRegisterHandlerProtocol { func registerUser(_ providerId: String?, scopes: [String]?, completion: @escaping (Result) -> Void) { let identityProvider = SharedUserClient.instance.identityProviders.first(where: { $0.identifier == providerId}) - if providerId != nil && identityProvider != nil { + if providerId != nil && identityProvider == nil { completion(.failure(SdkError(OneWelcomeWrapperError.notFoundIdentityProvider).flutterError())) return } From 55a73d28c2e041129b62503c3577bdfa8d3f94b2 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 09:55:07 +0200 Subject: [PATCH 338/364] fp-38 revert pbxproj file --- example/ios/Runner.xcodeproj/project.pbxproj | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index de70df70..6b9ecbf2 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -669,10 +669,8 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 5ZQB7UCHP8; + DEVELOPMENT_TEAM = 47G5S528XM; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -690,7 +688,6 @@ ); PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; @@ -996,10 +993,8 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 5ZQB7UCHP8; + DEVELOPMENT_TEAM = 47G5S528XM; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -1018,7 +1013,6 @@ OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; @@ -1032,10 +1026,8 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 5ZQB7UCHP8; + DEVELOPMENT_TEAM = 47G5S528XM; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", @@ -1053,7 +1045,6 @@ ); PRODUCT_BUNDLE_IDENTIFIER = com.onegini.plugin.oneginiExample; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; From f44448e3627b121fbc814a8c3c84432954f25fb5 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 09:59:24 +0200 Subject: [PATCH 339/364] fp-39 revert info.plist changes --- example/ios/Runner/Info.plist | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist index d865a04a..d2b45d41 100644 --- a/example/ios/Runner/Info.plist +++ b/example/ios/Runner/Info.plist @@ -2,8 +2,6 @@ - CADisableMinimumFrameDurationOnPhone - CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable @@ -43,12 +41,10 @@ NSCameraUsageDescription Need to access your camera to scan QR code - NSFaceIDUsageDescription - Please provide access to your Face ID NSLocalNetworkUsageDescription Set to your desired customized permission dialog text. - UIApplicationSupportsIndirectInputEvents - + NSFaceIDUsageDescription + Please provide access to your Face ID UILaunchStoryboardName LaunchScreen UIMainStoryboardFile @@ -68,5 +64,9 @@ io.flutter.embedded_views_preview + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + From c5b58e635a6b2080ece3fe9ac7de0557ec7b9aaf Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 10:49:24 +0200 Subject: [PATCH 340/364] FP-79-12-2 Update ios sdk to version 12.2.0 --- example/ios/Podfile.lock | 12 ++++++------ ios/onegini.podspec | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 769468f9..19d044fa 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -21,14 +21,14 @@ PODS: - MTBBarcodeScanner (5.0.11) - onegini (1.2.1): - Flutter - - OneginiSDKiOS (~> 12.1.1) - - OneginiSDKiOS (12.1.1): + - OneginiSDKiOS (~> 12.2.0) + - OneginiSDKiOS (12.2.0): - AFNetworking (~> 4.0.1) - Typhoon (~> 4.0.8) - qr_code_scanner (0.2.0): - Flutter - MTBBarcodeScanner - - SwiftLint (0.50.3) + - SwiftLint (0.51.0) - Toast (4.0.0) - Typhoon (4.0.9): - Typhoon/DeallocNotifier (= 4.0.9) @@ -76,10 +76,10 @@ SPEC CHECKSUMS: Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 fluttertoast: eb263d302cc92e04176c053d2385237e9f43fad0 MTBBarcodeScanner: f453b33c4b7dfe545d8c6484ed744d55671788cb - onegini: b50096e5ee0b261f160acf4437bba6a85a5188d0 - OneginiSDKiOS: 81e27e24e901cfe41e09f46b8c673fd5b5b855e9 + onegini: 8fe0e3bd452b73f7586851c284669aa2d4466d9e + OneginiSDKiOS: 5bbc97d65252dc6a0ec431895fb4377ddea61ae1 qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e - SwiftLint: 77f7cb2b9bb81ab4a12fcc86448ba3f11afa50c6 + SwiftLint: 1b7561918a19e23bfed960e40759086e70f4dba5 Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Typhoon: 1973c93ecfb3edb963d78b10e715bc2911475bd2 url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de diff --git a/ios/onegini.podspec b/ios/onegini.podspec index 3ca69701..53c88459 100644 --- a/ios/onegini.podspec +++ b/ios/onegini.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.platform = :ios, '13.0' # *************************** - s.dependency 'OneginiSDKiOS', '~> 12.1.1' + s.dependency 'OneginiSDKiOS', '~> 12.2.0' # *************************** # Flutter.framework does not contain a i386 slice. From bc1522c3ee73198427fcd7421362bf0d93e0bc62 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 11:06:50 +0200 Subject: [PATCH 341/364] FP-RENAME-PIGEON-FILES renamed pigeon files to better indicate that those are auto generated --- analysis_options.yaml | 2 +- .../{Pigeon.kt => AutoGeneratedPigeon.kt} | 0 example/lib/main.dart | 2 +- example/lib/screens/login_screen.dart | 2 +- example/lib/screens/user_screen.dart | 2 +- ...Pigeon.swift => AutoGeneratedPigeon.swift} | 72 +++--- ...pigeon.dart => auto_generated_pigeon.dart} | 229 ++++++++---------- .../onegini_custom_registration_callback.dart | 2 +- .../onegini_fingerprint_callback.dart | 2 +- .../onegini_otp_accept_deny_callback.dart | 2 +- .../onegini_pin_authentication_callback.dart | 2 +- .../onegini_pin_registration_callback.dart | 2 +- .../onegini_registration_callback.dart | 2 +- lib/events/custom_registration_event.dart | 2 +- lib/events/pin_event.dart | 2 +- lib/model/request_details.dart | 2 +- lib/onegini.dart | 2 +- lib/onegini_event_listener.dart | 2 +- lib/resources_methods.dart | 2 +- lib/user_client.dart | 2 +- pigeons/README.md | 8 +- 21 files changed, 158 insertions(+), 185 deletions(-) rename android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/{Pigeon.kt => AutoGeneratedPigeon.kt} (100%) rename ios/Classes/{Pigeon.swift => AutoGeneratedPigeon.swift} (97%) rename lib/{pigeon.dart => auto_generated_pigeon.dart} (89%) diff --git a/analysis_options.yaml b/analysis_options.yaml index dbe441e6..69388509 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -11,7 +11,7 @@ include: package:flutter_lints/flutter.yaml analyzer: exclude: - - lib/pigeon.dart + - lib/auto_generated_pigeon.dart linter: # The lint rules applied to this project can be customized in the diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt similarity index 100% rename from android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt rename to android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt diff --git a/example/lib/main.dart b/example/lib/main.dart index fc2ff7e6..605f014d 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/screens/login_screen.dart'; diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 2f9fd2ad..5b14630e 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -7,7 +7,7 @@ import 'package:onegini/callbacks/onegini_registration_callback.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/user_screen.dart'; diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index c5ce6dfd..c8664e38 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -14,7 +14,7 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:onegini_example/subscription_handlers/otp_subscriptions.dart'; import 'package:url_launcher/url_launcher.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; // ignore: import_of_legacy_library_into_null_safe import '../main.dart'; // ignore: import_of_legacy_library_into_null_safe diff --git a/ios/Classes/Pigeon.swift b/ios/Classes/AutoGeneratedPigeon.swift similarity index 97% rename from ios/Classes/Pigeon.swift rename to ios/Classes/AutoGeneratedPigeon.swift index f21082fb..c5db89b7 100644 --- a/ios/Classes/Pigeon.swift +++ b/ios/Classes/AutoGeneratedPigeon.swift @@ -68,7 +68,7 @@ struct OWUserProfile { } func toList() -> [Any?] { return [ - profileId, + profileId ] } } @@ -76,7 +76,7 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { var status: Int64 - var data: String? = nil + var data: String? static func fromList(_ list: [Any]) -> OWCustomInfo? { let status = list[0] is Int64 ? list[0] as! Int64 : Int64(list[0] as! Int32) @@ -90,7 +90,7 @@ struct OWCustomInfo { func toList() -> [Any?] { return [ status, - data, + data ] } } @@ -112,7 +112,7 @@ struct OWIdentityProvider { func toList() -> [Any?] { return [ id, - name, + name ] } } @@ -146,7 +146,7 @@ struct OWAuthenticator { name, isRegistered, isPreferred, - authenticatorType.rawValue, + authenticatorType.rawValue ] } } @@ -168,7 +168,7 @@ struct OWAppToWebSingleSignOn { func toList() -> [Any?] { return [ token, - redirectUrl, + redirectUrl ] } } @@ -176,11 +176,11 @@ struct OWAppToWebSingleSignOn { /// Generated class from Pigeon that represents data sent in messages. struct OWRegistrationResponse { var userProfile: OWUserProfile - var customInfo: OWCustomInfo? = nil + var customInfo: OWCustomInfo? static func fromList(_ list: [Any]) -> OWRegistrationResponse? { let userProfile = OWUserProfile.fromList(list[0] as! [Any])! - var customInfo: OWCustomInfo? = nil + var customInfo: OWCustomInfo? if let customInfoList = list[1] as! [Any]? { customInfo = OWCustomInfo.fromList(customInfoList) } @@ -193,7 +193,7 @@ struct OWRegistrationResponse { func toList() -> [Any?] { return [ userProfile.toList(), - customInfo?.toList(), + customInfo?.toList() ] } } @@ -202,8 +202,8 @@ struct OWRegistrationResponse { struct OWRequestDetails { var path: String var method: HttpRequestMethod - var headers: [String?: String?]? = nil - var body: String? = nil + var headers: [String?: String?]? + var body: String? static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String @@ -223,7 +223,7 @@ struct OWRequestDetails { path, method.rawValue, headers, - body, + body ] } } @@ -253,7 +253,7 @@ struct OWRequestResponse { headers, body, ok, - status, + status ] } } @@ -279,7 +279,7 @@ struct OWAuthenticationAttempt { return [ failedAttempts, maxAttempts, - remainingAttempts, + remainingAttempts ] } } @@ -301,7 +301,7 @@ struct OWOneginiError { func toList() -> [Any?] { return [ code, - message, + message ] } } @@ -323,7 +323,7 @@ struct OWCustomIdentityProvider { func toList() -> [Any?] { return [ providerId, - isTwoStep, + isTwoStep ] } } @@ -509,7 +509,7 @@ class UserClientApiSetup { let getIdentityProvidersChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getIdentityProviders", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getIdentityProvidersChannel.setMessageHandler { _, reply in - api.getIdentityProviders() { result in + api.getIdentityProviders { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -541,7 +541,7 @@ class UserClientApiSetup { let getAuthenticatedUserProfileChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAuthenticatedUserProfileChannel.setMessageHandler { _, reply in - api.getAuthenticatedUserProfile() { result in + api.getAuthenticatedUserProfile { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -642,7 +642,7 @@ class UserClientApiSetup { let deregisterBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterBiometricAuthenticatorChannel.setMessageHandler { _, reply in - api.deregisterBiometricAuthenticator() { result in + api.deregisterBiometricAuthenticator { result in switch result { case .success: reply(wrapResult(nil)) @@ -657,7 +657,7 @@ class UserClientApiSetup { let registerBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerBiometricAuthenticatorChannel.setMessageHandler { _, reply in - api.registerBiometricAuthenticator() { result in + api.registerBiometricAuthenticator { result in switch result { case .success: reply(wrapResult(nil)) @@ -672,7 +672,7 @@ class UserClientApiSetup { let changePinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.changePin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { changePinChannel.setMessageHandler { _, reply in - api.changePin() { result in + api.changePin { result in switch result { case .success: reply(wrapResult(nil)) @@ -687,7 +687,7 @@ class UserClientApiSetup { let logoutChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.logout", binaryMessenger: binaryMessenger, codec: codec) if let api = api { logoutChannel.setMessageHandler { _, reply in - api.logout() { result in + api.logout { result in switch result { case .success: reply(wrapResult(nil)) @@ -702,7 +702,7 @@ class UserClientApiSetup { let enrollMobileAuthenticationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", binaryMessenger: binaryMessenger, codec: codec) if let api = api { enrollMobileAuthenticationChannel.setMessageHandler { _, reply in - api.enrollMobileAuthentication() { result in + api.enrollMobileAuthentication { result in switch result { case .success: reply(wrapResult(nil)) @@ -751,7 +751,7 @@ class UserClientApiSetup { let getAccessTokenChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAccessToken", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAccessTokenChannel.setMessageHandler { _, reply in - api.getAccessToken() { result in + api.getAccessToken { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -766,7 +766,7 @@ class UserClientApiSetup { let getRedirectUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRedirectUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getRedirectUrlChannel.setMessageHandler { _, reply in - api.getRedirectUrl() { result in + api.getRedirectUrl { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -781,7 +781,7 @@ class UserClientApiSetup { let getUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getUserProfiles", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getUserProfilesChannel.setMessageHandler { _, reply in - api.getUserProfiles() { result in + api.getUserProfiles { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -884,7 +884,7 @@ class UserClientApiSetup { let fingerprintFallbackToPinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintFallbackToPinChannel.setMessageHandler { _, reply in - api.fingerprintFallbackToPin() { result in + api.fingerprintFallbackToPin { result in switch result { case .success: reply(wrapResult(nil)) @@ -899,7 +899,7 @@ class UserClientApiSetup { let fingerprintDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.fingerprintDenyAuthenticationRequest() { result in + api.fingerprintDenyAuthenticationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -914,7 +914,7 @@ class UserClientApiSetup { let fingerprintAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in - api.fingerprintAcceptAuthenticationRequest() { result in + api.fingerprintAcceptAuthenticationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -930,7 +930,7 @@ class UserClientApiSetup { let otpDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { otpDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.otpDenyAuthenticationRequest() { result in + api.otpDenyAuthenticationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -945,7 +945,7 @@ class UserClientApiSetup { let otpAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { otpAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in - api.otpAcceptAuthenticationRequest() { result in + api.otpAcceptAuthenticationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -961,7 +961,7 @@ class UserClientApiSetup { let pinDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.pinDenyAuthenticationRequest() { result in + api.pinDenyAuthenticationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -994,7 +994,7 @@ class UserClientApiSetup { let pinDenyRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinDenyRegistrationRequestChannel.setMessageHandler { _, reply in - api.pinDenyRegistrationRequest() { result in + api.pinDenyRegistrationRequest { result in switch result { case .success: reply(wrapResult(nil)) @@ -1027,7 +1027,7 @@ class UserClientApiSetup { let cancelBrowserRegistrationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", binaryMessenger: binaryMessenger, codec: codec) if let api = api { cancelBrowserRegistrationChannel.setMessageHandler { _, reply in - api.cancelBrowserRegistration() { result in + api.cancelBrowserRegistration { result in switch result { case .success: reply(wrapResult(nil)) @@ -1164,13 +1164,13 @@ class NativeCallFlutterApiCodec: FlutterStandardMessageCodec { /// Generated class from Pigeon that represents Flutter messages that can be called from Swift. class NativeCallFlutterApi { private let binaryMessenger: FlutterBinaryMessenger - init(binaryMessenger: FlutterBinaryMessenger){ + init(binaryMessenger: FlutterBinaryMessenger) { self.binaryMessenger = binaryMessenger } var codec: FlutterStandardMessageCodec { return NativeCallFlutterApiCodec.shared } - ///Called to handle registration URL + /// Called to handle registration URL func n2fHandleRegisteredUrl(url urlArg: String, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([urlArg] as [Any?]) { _ in diff --git a/lib/pigeon.dart b/lib/auto_generated_pigeon.dart similarity index 89% rename from lib/pigeon.dart rename to lib/auto_generated_pigeon.dart index 635b1a43..02a9477c 100644 --- a/lib/pigeon.dart +++ b/lib/auto_generated_pigeon.dart @@ -384,19 +384,19 @@ class _UserClientApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAppToWebSingleSignOn.decode(readValue(buffer)!); - case 129: + case 129: return OWAuthenticator.decode(readValue(buffer)!); - case 130: + case 130: return OWCustomIdentityProvider.decode(readValue(buffer)!); - case 131: + case 131: return OWCustomInfo.decode(readValue(buffer)!); - case 132: + case 132: return OWIdentityProvider.decode(readValue(buffer)!); - case 133: + case 133: return OWRegistrationResponse.decode(readValue(buffer)!); - case 134: + case 134: return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -415,24 +415,12 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future startApplication( - String? arg_securityControllerClassName, - String? arg_configModelClassName, - List? arg_customIdentityProviderConfigs, - int? arg_connectionTimeout, - int? arg_readTimeout, - List? arg_additionalResourceUrls) async { + Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout, List? arg_additionalResourceUrls) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.startApplication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_securityControllerClassName, - arg_configModelClassName, - arg_customIdentityProviderConfigs, - arg_connectionTimeout, - arg_readTimeout, - arg_additionalResourceUrls - ]) as List?; + final List? replyList = + await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout, arg_additionalResourceUrls]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -449,13 +437,12 @@ class UserClientApi { } } - Future registerUser( - String? arg_identityProviderId, List? arg_scopes) async { + Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identityProviderId, arg_scopes]) as List?; + final List? replyList = + await channel.send([arg_identityProviderId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -477,13 +464,12 @@ class UserClientApi { } } - Future handleRegisteredUserUrl( - String arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_url, arg_signInType]) as List?; + final List? replyList = + await channel.send([arg_url, arg_signInType]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -504,7 +490,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getIdentityProviders', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -552,7 +539,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -574,14 +562,12 @@ class UserClientApi { } } - Future authenticateUser( - String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { + Future authenticateUser(String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_profileId, arg_authenticatorType.index]) - as List?; + final List? replyList = + await channel.send([arg_profileId, arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -603,8 +589,7 @@ class UserClientApi { } } - Future authenticateUserPreferred( - String arg_profileId) async { + Future authenticateUserPreferred(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserPreferred', codec, binaryMessenger: _binaryMessenger); @@ -631,8 +616,7 @@ class UserClientApi { } } - Future getBiometricAuthenticator( - String arg_profileId) async { + Future getBiometricAuthenticator(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -659,8 +643,7 @@ class UserClientApi { } } - Future getPreferredAuthenticator( - String arg_profileId) async { + Future getPreferredAuthenticator(String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -687,13 +670,12 @@ class UserClientApi { } } - Future setPreferredAuthenticator( - OWAuthenticatorType arg_authenticatorType) async { + Future setPreferredAuthenticator(OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_authenticatorType.index]) as List?; + final List? replyList = + await channel.send([arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -712,10 +694,10 @@ class UserClientApi { Future deregisterBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', - codec, + 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -734,10 +716,10 @@ class UserClientApi { Future registerBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', - codec, + 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -758,7 +740,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -779,7 +762,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.logout', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -800,7 +784,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -870,7 +855,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -896,7 +882,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getRedirectUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -922,7 +909,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getUserProfiles', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -988,13 +976,12 @@ class UserClientApi { } } - Future authenticateUserImplicitly( - String arg_profileId, List? arg_scopes) async { + Future authenticateUserImplicitly(String arg_profileId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_profileId, arg_scopes]) as List?; + final List? replyList = + await channel.send([arg_profileId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1014,8 +1001,7 @@ class UserClientApi { /// Custom Registration Callbacks Future submitCustomRegistrationAction(String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', - codec, + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_data]) as List?; @@ -1037,8 +1023,7 @@ class UserClientApi { Future cancelCustomRegistrationAction(String arg_error) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', - codec, + 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_error]) as List?; @@ -1063,7 +1048,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1082,10 +1068,10 @@ class UserClientApi { Future fingerprintDenyAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', - codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1104,10 +1090,10 @@ class UserClientApi { Future fingerprintAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', - codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1129,7 +1115,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1148,10 +1135,10 @@ class UserClientApi { Future otpAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', - codec, + 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1173,7 +1160,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1192,8 +1180,7 @@ class UserClientApi { Future pinAcceptAuthenticationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', - codec, + 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_pin]) as List?; @@ -1218,7 +1205,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1262,7 +1250,8 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; + final List? replyList = + await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1298,9 +1287,9 @@ class _ResourceMethodApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWRequestDetails.decode(readValue(buffer)!); - case 129: + case 129: return OWRequestResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1318,13 +1307,12 @@ class ResourceMethodApi { static const MessageCodec codec = _ResourceMethodApiCodec(); - Future requestResource( - ResourceRequestType arg_type, OWRequestDetails arg_details) async { + Future requestResource(ResourceRequestType arg_type, OWRequestDetails arg_details) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.ResourceMethodApi.requestResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_type.index, arg_details]) as List?; + final List? replyList = + await channel.send([arg_type.index, arg_details]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1368,11 +1356,11 @@ class _NativeCallFlutterApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAuthenticationAttempt.decode(readValue(buffer)!); - case 129: + case 129: return OWCustomInfo.decode(readValue(buffer)!); - case 130: + case 130: return OWOneginiError.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1403,8 +1391,7 @@ abstract class NativeCallFlutterApi { void n2fClosePinAuthentication(); /// Called to attempt next pin authentication. - void n2fNextPinAuthenticationAttempt( - OWAuthenticationAttempt authenticationAttempt); + void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); /// Called to open OTP authentication. void n2fOpenAuthOtp(String? message); @@ -1425,26 +1412,22 @@ abstract class NativeCallFlutterApi { void n2fNextFingerprintAuthenticationAttempt(); /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) - void n2fEventInitCustomRegistration( - OWCustomInfo? customInfo, String providerId); + void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given - void n2fEventFinishCustomRegistration( - OWCustomInfo? customInfo, String providerId); + void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); - static void setup(NativeCallFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); final List args = (message as List?)!; final String? arg_url = (args[0] as String?); assert(arg_url != null, @@ -1491,7 +1474,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); final List args = (message as List?)!; final OWOneginiError? arg_error = (args[0] as OWOneginiError?); assert(arg_error != null, @@ -1503,8 +1486,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1518,8 +1500,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1533,18 +1514,16 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); final List args = (message as List?)!; - final OWAuthenticationAttempt? arg_authenticationAttempt = - (args[0] as OWAuthenticationAttempt?); + final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); assert(arg_authenticationAttempt != null, 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); api.n2fNextPinAuthenticationAttempt(arg_authenticationAttempt!); @@ -1561,7 +1540,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); api.n2fOpenAuthOtp(arg_message); @@ -1585,8 +1564,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1600,8 +1578,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1615,8 +1592,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1630,8 +1606,7 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1645,15 +1620,14 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); @@ -1666,15 +1640,14 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', - codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); diff --git a/lib/callbacks/onegini_custom_registration_callback.dart b/lib/callbacks/onegini_custom_registration_callback.dart index ae8e5aec..52f59616 100644 --- a/lib/callbacks/onegini_custom_registration_callback.dart +++ b/lib/callbacks/onegini_custom_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; class OneginiCustomRegistrationCallback { final api = UserClientApi(); diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index 6d9e3555..abae9b2a 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -1,5 +1,5 @@ import 'dart:async'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// A callback of fingerprint authentication. /// diff --git a/lib/callbacks/onegini_otp_accept_deny_callback.dart b/lib/callbacks/onegini_otp_accept_deny_callback.dart index 938a1ba2..283deae4 100644 --- a/lib/callbacks/onegini_otp_accept_deny_callback.dart +++ b/lib/callbacks/onegini_otp_accept_deny_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// A callback for mobile authentication with OTP class OneginiOtpAcceptDenyCallback { diff --git a/lib/callbacks/onegini_pin_authentication_callback.dart b/lib/callbacks/onegini_pin_authentication_callback.dart index fbaae4c5..5c208e43 100644 --- a/lib/callbacks/onegini_pin_authentication_callback.dart +++ b/lib/callbacks/onegini_pin_authentication_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// A callback for pin AUTHENTICATION. class OneginiPinAuthenticationCallback { diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index e9a79dd4..ca094f43 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// A callback for pin REGISTRATION. class OneginiPinRegistrationCallback { diff --git a/lib/callbacks/onegini_registration_callback.dart b/lib/callbacks/onegini_registration_callback.dart index 75697b75..a1251b23 100644 --- a/lib/callbacks/onegini_registration_callback.dart +++ b/lib/callbacks/onegini_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// A callback for registration. class OneginiRegistrationCallback { diff --git a/lib/events/custom_registration_event.dart b/lib/events/custom_registration_event.dart index ebdeb4a0..bb3914d6 100644 --- a/lib/events/custom_registration_event.dart +++ b/lib/events/custom_registration_event.dart @@ -1,6 +1,6 @@ // Wrapper for Custom Registration Events import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; class InitCustomRegistrationEvent extends OWEvent { OWCustomInfo? customInfo; diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index 4481d5d9..f301684f 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -1,6 +1,6 @@ // Wrapper for Pin Events import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; // For Pin Creation class OpenPinCreationEvent extends OWEvent { diff --git a/lib/model/request_details.dart b/lib/model/request_details.dart index c5de8dc7..ca6f9c26 100644 --- a/lib/model/request_details.dart +++ b/lib/model/request_details.dart @@ -1,4 +1,4 @@ -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; // Wrapper class for pigeon class to enforce non null map values. class RequestDetails { diff --git a/lib/onegini.dart b/lib/onegini.dart index a51352df..22ca655b 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -5,7 +5,7 @@ import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/resources_methods.dart'; import 'package:onegini/user_client.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// The main class used to call methods. class Onegini { diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 7a6e9193..06e1d1d2 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -6,7 +6,7 @@ import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; class OneginiEventListener implements NativeCallFlutterApi { final StreamController broadCastController; diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index ed008a44..c309c258 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -1,7 +1,7 @@ import 'model/request_details.dart'; import 'model/request_response.dart'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; /// The class with resources methods class ResourcesMethods { diff --git a/lib/user_client.dart b/lib/user_client.dart index 58f40a36..44b70c8a 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,6 +1,6 @@ import 'dart:async'; -import 'package:onegini/pigeon.dart'; +import 'package:onegini/auto_generated_pigeon.dart'; ///Сlass with basic methods available to the developer. class UserClient { diff --git a/pigeons/README.md b/pigeons/README.md index cacb7909..00871652 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -4,11 +4,11 @@ Pidgeon is used within this project to enable type-save communication between th Command for code generation which is performed from top level: flutter pub run pigeon \ --input pigeons/onewelcome_pigeon_interface.dart \ - --dart_out lib/pigeon.dart \ - --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.kt \ + --dart_out lib/auto_generated_pigeon.dart \ + --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ - --experimental_swift_out ios/Classes/Pigeon.swift -dart format lib/pigeon.dart + --experimental_swift_out ios/Classes/AutoGeneratedPigeon.swift +dart format lib/auto_generated_pigeon.dart ## Missing documentation Pigeon is poorly documented; so to keep knowledge on why and how certain things are done we will refer to pull requests where we obtained information. From 5831a8ad80d6ad198ff84397ef660af3e7292c4c Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 11:10:56 +0200 Subject: [PATCH 342/364] fp-rename pigeon files update format of auto generation --- lib/auto_generated_pigeon.dart | 229 ++++++++++++++++++--------------- 1 file changed, 128 insertions(+), 101 deletions(-) diff --git a/lib/auto_generated_pigeon.dart b/lib/auto_generated_pigeon.dart index 02a9477c..635b1a43 100644 --- a/lib/auto_generated_pigeon.dart +++ b/lib/auto_generated_pigeon.dart @@ -384,19 +384,19 @@ class _UserClientApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAppToWebSingleSignOn.decode(readValue(buffer)!); - case 129: + case 129: return OWAuthenticator.decode(readValue(buffer)!); - case 130: + case 130: return OWCustomIdentityProvider.decode(readValue(buffer)!); - case 131: + case 131: return OWCustomInfo.decode(readValue(buffer)!); - case 132: + case 132: return OWIdentityProvider.decode(readValue(buffer)!); - case 133: + case 133: return OWRegistrationResponse.decode(readValue(buffer)!); - case 134: + case 134: return OWUserProfile.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -415,12 +415,24 @@ class UserClientApi { static const MessageCodec codec = _UserClientApiCodec(); - Future startApplication(String? arg_securityControllerClassName, String? arg_configModelClassName, List? arg_customIdentityProviderConfigs, int? arg_connectionTimeout, int? arg_readTimeout, List? arg_additionalResourceUrls) async { + Future startApplication( + String? arg_securityControllerClassName, + String? arg_configModelClassName, + List? arg_customIdentityProviderConfigs, + int? arg_connectionTimeout, + int? arg_readTimeout, + List? arg_additionalResourceUrls) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.startApplication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_securityControllerClassName, arg_configModelClassName, arg_customIdentityProviderConfigs, arg_connectionTimeout, arg_readTimeout, arg_additionalResourceUrls]) as List?; + final List? replyList = await channel.send([ + arg_securityControllerClassName, + arg_configModelClassName, + arg_customIdentityProviderConfigs, + arg_connectionTimeout, + arg_readTimeout, + arg_additionalResourceUrls + ]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -437,12 +449,13 @@ class UserClientApi { } } - Future registerUser(String? arg_identityProviderId, List? arg_scopes) async { + Future registerUser( + String? arg_identityProviderId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.registerUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identityProviderId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_identityProviderId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -464,12 +477,13 @@ class UserClientApi { } } - Future handleRegisteredUserUrl(String arg_url, int arg_signInType) async { + Future handleRegisteredUserUrl( + String arg_url, int arg_signInType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.handleRegisteredUserUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_url, arg_signInType]) as List?; + final List? replyList = await channel + .send([arg_url, arg_signInType]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -490,8 +504,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getIdentityProviders', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -539,8 +552,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -562,12 +574,14 @@ class UserClientApi { } } - Future authenticateUser(String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { + Future authenticateUser( + String arg_profileId, OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUser', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_authenticatorType.index]) + as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -589,7 +603,8 @@ class UserClientApi { } } - Future authenticateUserPreferred(String arg_profileId) async { + Future authenticateUserPreferred( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserPreferred', codec, binaryMessenger: _binaryMessenger); @@ -616,7 +631,8 @@ class UserClientApi { } } - Future getBiometricAuthenticator(String arg_profileId) async { + Future getBiometricAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getBiometricAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -643,7 +659,8 @@ class UserClientApi { } } - Future getPreferredAuthenticator(String arg_profileId) async { + Future getPreferredAuthenticator( + String arg_profileId) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); @@ -670,12 +687,13 @@ class UserClientApi { } } - Future setPreferredAuthenticator(OWAuthenticatorType arg_authenticatorType) async { + Future setPreferredAuthenticator( + OWAuthenticatorType arg_authenticatorType) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.setPreferredAuthenticator', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_authenticatorType.index]) as List?; + final List? replyList = await channel + .send([arg_authenticatorType.index]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -694,10 +712,10 @@ class UserClientApi { Future deregisterBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -716,10 +734,10 @@ class UserClientApi { Future registerBiometricAuthenticator() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', codec, + 'dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -740,8 +758,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.changePin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -762,8 +779,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.logout', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -784,8 +800,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -855,8 +870,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -882,8 +896,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getRedirectUrl', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -909,8 +922,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.getUserProfiles', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -976,12 +988,13 @@ class UserClientApi { } } - Future authenticateUserImplicitly(String arg_profileId, List? arg_scopes) async { + Future authenticateUserImplicitly( + String arg_profileId, List? arg_scopes) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.authenticateUserImplicitly', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_profileId, arg_scopes]) as List?; + final List? replyList = await channel + .send([arg_profileId, arg_scopes]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1001,7 +1014,8 @@ class UserClientApi { /// Custom Registration Callbacks Future submitCustomRegistrationAction(String? arg_data) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.submitCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_data]) as List?; @@ -1023,7 +1037,8 @@ class UserClientApi { Future cancelCustomRegistrationAction(String arg_error) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', codec, + 'dev.flutter.pigeon.UserClientApi.cancelCustomRegistrationAction', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_error]) as List?; @@ -1048,8 +1063,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1068,10 +1082,10 @@ class UserClientApi { Future fingerprintDenyAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1090,10 +1104,10 @@ class UserClientApi { Future fingerprintAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1115,8 +1129,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1135,10 +1148,10 @@ class UserClientApi { Future otpAcceptAuthenticationRequest() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1160,8 +1173,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1180,7 +1192,8 @@ class UserClientApi { Future pinAcceptAuthenticationRequest(String arg_pin) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', codec, + 'dev.flutter.pigeon.UserClientApi.pinAcceptAuthenticationRequest', + codec, binaryMessenger: _binaryMessenger); final List? replyList = await channel.send([arg_pin]) as List?; @@ -1205,8 +1218,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1250,8 +1262,7 @@ class UserClientApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1287,9 +1298,9 @@ class _ResourceMethodApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWRequestDetails.decode(readValue(buffer)!); - case 129: + case 129: return OWRequestResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1307,12 +1318,13 @@ class ResourceMethodApi { static const MessageCodec codec = _ResourceMethodApiCodec(); - Future requestResource(ResourceRequestType arg_type, OWRequestDetails arg_details) async { + Future requestResource( + ResourceRequestType arg_type, OWRequestDetails arg_details) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.ResourceMethodApi.requestResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_type.index, arg_details]) as List?; + final List? replyList = await channel + .send([arg_type.index, arg_details]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -1356,11 +1368,11 @@ class _NativeCallFlutterApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return OWAuthenticationAttempt.decode(readValue(buffer)!); - case 129: + case 129: return OWCustomInfo.decode(readValue(buffer)!); - case 130: + case 130: return OWOneginiError.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -1391,7 +1403,8 @@ abstract class NativeCallFlutterApi { void n2fClosePinAuthentication(); /// Called to attempt next pin authentication. - void n2fNextPinAuthenticationAttempt(OWAuthenticationAttempt authenticationAttempt); + void n2fNextPinAuthenticationAttempt( + OWAuthenticationAttempt authenticationAttempt); /// Called to open OTP authentication. void n2fOpenAuthOtp(String? message); @@ -1412,22 +1425,26 @@ abstract class NativeCallFlutterApi { void n2fNextFingerprintAuthenticationAttempt(); /// Called when the InitCustomRegistration event occurs and a response should be given (only for two-step) - void n2fEventInitCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventInitCustomRegistration( + OWCustomInfo? customInfo, String providerId); /// Called when the FinishCustomRegistration event occurs and a response should be given - void n2fEventFinishCustomRegistration(OWCustomInfo? customInfo, String providerId); + void n2fEventFinishCustomRegistration( + OWCustomInfo? customInfo, String providerId); - static void setup(NativeCallFlutterApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(NativeCallFlutterApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl was null.'); final List args = (message as List?)!; final String? arg_url = (args[0] as String?); assert(arg_url != null, @@ -1474,7 +1491,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fPinNotAllowed was null.'); final List args = (message as List?)!; final OWOneginiError? arg_error = (args[0] as OWOneginiError?); assert(arg_error != null, @@ -1486,7 +1503,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenPinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1500,7 +1518,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fClosePinAuthentication', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1514,16 +1533,18 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null.'); final List args = (message as List?)!; - final OWAuthenticationAttempt? arg_authenticationAttempt = (args[0] as OWAuthenticationAttempt?); + final OWAuthenticationAttempt? arg_authenticationAttempt = + (args[0] as OWAuthenticationAttempt?); assert(arg_authenticationAttempt != null, 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fNextPinAuthenticationAttempt was null, expected non-null OWAuthenticationAttempt.'); api.n2fNextPinAuthenticationAttempt(arg_authenticationAttempt!); @@ -1540,7 +1561,7 @@ abstract class NativeCallFlutterApi { } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenAuthOtp was null.'); final List args = (message as List?)!; final String? arg_message = (args[0] as String?); api.n2fOpenAuthOtp(arg_message); @@ -1564,7 +1585,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fOpenFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1578,7 +1600,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fCloseFingerprintScreen', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1592,7 +1615,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fShowScanningFingerprint', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1606,7 +1630,8 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fNextFingerprintAuthenticationAttempt', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); @@ -1620,14 +1645,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventInitCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); @@ -1640,14 +1666,15 @@ abstract class NativeCallFlutterApi { } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', codec, + 'dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); + 'Argument for dev.flutter.pigeon.NativeCallFlutterApi.n2fEventFinishCustomRegistration was null.'); final List args = (message as List?)!; final OWCustomInfo? arg_customInfo = (args[0] as OWCustomInfo?); final String? arg_providerId = (args[1] as String?); From 210068ca16bd9cfb40b0920a993fb89a21fca393 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 14:25:07 +0200 Subject: [PATCH 343/364] FP-79-12-2-2 Update iOS SDK to 12.2.2 --- example/ios/Podfile.lock | 8 ++++---- .../NativeBridge/Handlers/AuthenticatorsHandler.swift | 2 +- ios/onegini.podspec | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 19d044fa..7d71c831 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -21,8 +21,8 @@ PODS: - MTBBarcodeScanner (5.0.11) - onegini (1.2.1): - Flutter - - OneginiSDKiOS (~> 12.2.0) - - OneginiSDKiOS (12.2.0): + - OneginiSDKiOS (~> 12.2.2) + - OneginiSDKiOS (12.2.2): - AFNetworking (~> 4.0.1) - Typhoon (~> 4.0.8) - qr_code_scanner (0.2.0): @@ -76,8 +76,8 @@ SPEC CHECKSUMS: Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 fluttertoast: eb263d302cc92e04176c053d2385237e9f43fad0 MTBBarcodeScanner: f453b33c4b7dfe545d8c6484ed744d55671788cb - onegini: 8fe0e3bd452b73f7586851c284669aa2d4466d9e - OneginiSDKiOS: 5bbc97d65252dc6a0ec431895fb4377ddea61ae1 + onegini: 28cf385b65961a518044f8ad5d0657193c4c3312 + OneginiSDKiOS: 33f5b66aacefbb54825ecde2d6b3e1fb22117dbd qr_code_scanner: bb67d64904c3b9658ada8c402e8b4d406d5d796e SwiftLint: 1b7561918a19e23bfed960e40759086e70f4dba5 Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 diff --git a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift index 9deec1f1..d130a402 100644 --- a/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/AuthenticatorsHandler.swift @@ -40,7 +40,7 @@ class AuthenticatorsHandler: BridgeToAuthenticatorsHandlerProtocol { return } - SharedUserClient.instance.setPreferred(authenticator: authenticator) + SharedUserClient.instance.setPreferredAuthenticator(authenticator) completion(.success) } diff --git a/ios/onegini.podspec b/ios/onegini.podspec index 53c88459..1304390d 100644 --- a/ios/onegini.podspec +++ b/ios/onegini.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.platform = :ios, '13.0' # *************************** - s.dependency 'OneginiSDKiOS', '~> 12.2.0' + s.dependency 'OneginiSDKiOS', '~> 12.2.2' # *************************** # Flutter.framework does not contain a i386 slice. From bb663909b4cfd459134d6686617dcb924feed92d Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 26 Apr 2023 15:26:43 +0200 Subject: [PATCH 344/364] Add logic for qr_registration idp --- example/lib/main.dart | 4 +++- .../custom_registration_subscriptions.dart | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index fc2ff7e6..dd945f97 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -59,7 +59,9 @@ class _BodyWidgetState extends State { "com.onegini.mobile.onegini_example.OneginiConfigModel", customIdentityProviderConfigs: [ OWCustomIdentityProvider( - providerId: "2-way-otp-api", isTwoStep: true) + providerId: "2-way-otp-api", isTwoStep: true), + OWCustomIdentityProvider( + providerId: "qr_registration", isTwoStep: false) ], connectionTimeout: 5, readTimeout: 25, diff --git a/example/lib/subscription_handlers/custom_registration_subscriptions.dart b/example/lib/subscription_handlers/custom_registration_subscriptions.dart index eec7d952..feff1034 100644 --- a/example/lib/subscription_handlers/custom_registration_subscriptions.dart +++ b/example/lib/subscription_handlers/custom_registration_subscriptions.dart @@ -51,5 +51,10 @@ StreamSubscription _getFinishCustomRegistrationSub( providerId: event.providerId)), ); } + if (event.providerId == "qr_registration") { + // This identity provider is set up to accept a body with 'Onegini' + // Normally this would contain some single use token. + OneginiCustomRegistrationCallback().submitSuccessAction('Onegini'); + } }); } From 821ba8d6706aa5192b5dd791b9a832d2e41b8f37 Mon Sep 17 00:00:00 2001 From: Archifer Date: Wed, 26 Apr 2023 15:57:50 +0200 Subject: [PATCH 345/364] fp-rename renamed pigeon files once again --- .../{AutoGeneratedPigeon.kt => Pigeon.gen.kt} | 0 example/lib/main.dart | 2 +- example/lib/screens/login_screen.dart | 2 +- example/lib/screens/user_screen.dart | 2 +- ...GeneratedPigeon.swift => Pigeon.gen.swift} | 72 +++++++++---------- .../onegini_custom_registration_callback.dart | 2 +- .../onegini_fingerprint_callback.dart | 2 +- .../onegini_otp_accept_deny_callback.dart | 2 +- .../onegini_pin_authentication_callback.dart | 2 +- .../onegini_pin_registration_callback.dart | 2 +- .../onegini_registration_callback.dart | 2 +- lib/events/custom_registration_event.dart | 2 +- lib/events/pin_event.dart | 2 +- lib/model/request_details.dart | 2 +- lib/onegini.dart | 2 +- ...generated_pigeon.dart => onegini.gen.dart} | 0 lib/onegini_event_listener.dart | 2 +- lib/resources_methods.dart | 2 +- lib/user_client.dart | 2 +- pigeons/README.md | 8 +-- pigeons/onewelcome_pigeon_interface.dart | 6 -- 21 files changed, 56 insertions(+), 62 deletions(-) rename android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/{AutoGeneratedPigeon.kt => Pigeon.gen.kt} (100%) rename ios/Classes/{AutoGeneratedPigeon.swift => Pigeon.gen.swift} (97%) rename lib/{auto_generated_pigeon.dart => onegini.gen.dart} (100%) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.gen.kt similarity index 100% rename from android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt rename to android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.gen.kt diff --git a/example/lib/main.dart b/example/lib/main.dart index 605f014d..95718941 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; import 'package:onegini_example/components/display_toast.dart'; import 'package:onegini_example/screens/login_screen.dart'; diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 5b14630e..fac24bcd 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -7,7 +7,7 @@ import 'package:onegini/callbacks/onegini_registration_callback.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/user_screen.dart'; diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index c8664e38..8c75c157 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -14,7 +14,7 @@ import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/qr_scan_screen.dart'; import 'package:onegini_example/subscription_handlers/otp_subscriptions.dart'; import 'package:url_launcher/url_launcher.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; // ignore: import_of_legacy_library_into_null_safe import '../main.dart'; // ignore: import_of_legacy_library_into_null_safe diff --git a/ios/Classes/AutoGeneratedPigeon.swift b/ios/Classes/Pigeon.gen.swift similarity index 97% rename from ios/Classes/AutoGeneratedPigeon.swift rename to ios/Classes/Pigeon.gen.swift index c5db89b7..f21082fb 100644 --- a/ios/Classes/AutoGeneratedPigeon.swift +++ b/ios/Classes/Pigeon.gen.swift @@ -68,7 +68,7 @@ struct OWUserProfile { } func toList() -> [Any?] { return [ - profileId + profileId, ] } } @@ -76,7 +76,7 @@ struct OWUserProfile { /// Generated class from Pigeon that represents data sent in messages. struct OWCustomInfo { var status: Int64 - var data: String? + var data: String? = nil static func fromList(_ list: [Any]) -> OWCustomInfo? { let status = list[0] is Int64 ? list[0] as! Int64 : Int64(list[0] as! Int32) @@ -90,7 +90,7 @@ struct OWCustomInfo { func toList() -> [Any?] { return [ status, - data + data, ] } } @@ -112,7 +112,7 @@ struct OWIdentityProvider { func toList() -> [Any?] { return [ id, - name + name, ] } } @@ -146,7 +146,7 @@ struct OWAuthenticator { name, isRegistered, isPreferred, - authenticatorType.rawValue + authenticatorType.rawValue, ] } } @@ -168,7 +168,7 @@ struct OWAppToWebSingleSignOn { func toList() -> [Any?] { return [ token, - redirectUrl + redirectUrl, ] } } @@ -176,11 +176,11 @@ struct OWAppToWebSingleSignOn { /// Generated class from Pigeon that represents data sent in messages. struct OWRegistrationResponse { var userProfile: OWUserProfile - var customInfo: OWCustomInfo? + var customInfo: OWCustomInfo? = nil static func fromList(_ list: [Any]) -> OWRegistrationResponse? { let userProfile = OWUserProfile.fromList(list[0] as! [Any])! - var customInfo: OWCustomInfo? + var customInfo: OWCustomInfo? = nil if let customInfoList = list[1] as! [Any]? { customInfo = OWCustomInfo.fromList(customInfoList) } @@ -193,7 +193,7 @@ struct OWRegistrationResponse { func toList() -> [Any?] { return [ userProfile.toList(), - customInfo?.toList() + customInfo?.toList(), ] } } @@ -202,8 +202,8 @@ struct OWRegistrationResponse { struct OWRequestDetails { var path: String var method: HttpRequestMethod - var headers: [String?: String?]? - var body: String? + var headers: [String?: String?]? = nil + var body: String? = nil static func fromList(_ list: [Any]) -> OWRequestDetails? { let path = list[0] as! String @@ -223,7 +223,7 @@ struct OWRequestDetails { path, method.rawValue, headers, - body + body, ] } } @@ -253,7 +253,7 @@ struct OWRequestResponse { headers, body, ok, - status + status, ] } } @@ -279,7 +279,7 @@ struct OWAuthenticationAttempt { return [ failedAttempts, maxAttempts, - remainingAttempts + remainingAttempts, ] } } @@ -301,7 +301,7 @@ struct OWOneginiError { func toList() -> [Any?] { return [ code, - message + message, ] } } @@ -323,7 +323,7 @@ struct OWCustomIdentityProvider { func toList() -> [Any?] { return [ providerId, - isTwoStep + isTwoStep, ] } } @@ -509,7 +509,7 @@ class UserClientApiSetup { let getIdentityProvidersChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getIdentityProviders", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getIdentityProvidersChannel.setMessageHandler { _, reply in - api.getIdentityProviders { result in + api.getIdentityProviders() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -541,7 +541,7 @@ class UserClientApiSetup { let getAuthenticatedUserProfileChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAuthenticatedUserProfile", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAuthenticatedUserProfileChannel.setMessageHandler { _, reply in - api.getAuthenticatedUserProfile { result in + api.getAuthenticatedUserProfile() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -642,7 +642,7 @@ class UserClientApiSetup { let deregisterBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.deregisterBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { deregisterBiometricAuthenticatorChannel.setMessageHandler { _, reply in - api.deregisterBiometricAuthenticator { result in + api.deregisterBiometricAuthenticator() { result in switch result { case .success: reply(wrapResult(nil)) @@ -657,7 +657,7 @@ class UserClientApiSetup { let registerBiometricAuthenticatorChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.registerBiometricAuthenticator", binaryMessenger: binaryMessenger, codec: codec) if let api = api { registerBiometricAuthenticatorChannel.setMessageHandler { _, reply in - api.registerBiometricAuthenticator { result in + api.registerBiometricAuthenticator() { result in switch result { case .success: reply(wrapResult(nil)) @@ -672,7 +672,7 @@ class UserClientApiSetup { let changePinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.changePin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { changePinChannel.setMessageHandler { _, reply in - api.changePin { result in + api.changePin() { result in switch result { case .success: reply(wrapResult(nil)) @@ -687,7 +687,7 @@ class UserClientApiSetup { let logoutChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.logout", binaryMessenger: binaryMessenger, codec: codec) if let api = api { logoutChannel.setMessageHandler { _, reply in - api.logout { result in + api.logout() { result in switch result { case .success: reply(wrapResult(nil)) @@ -702,7 +702,7 @@ class UserClientApiSetup { let enrollMobileAuthenticationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.enrollMobileAuthentication", binaryMessenger: binaryMessenger, codec: codec) if let api = api { enrollMobileAuthenticationChannel.setMessageHandler { _, reply in - api.enrollMobileAuthentication { result in + api.enrollMobileAuthentication() { result in switch result { case .success: reply(wrapResult(nil)) @@ -751,7 +751,7 @@ class UserClientApiSetup { let getAccessTokenChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getAccessToken", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getAccessTokenChannel.setMessageHandler { _, reply in - api.getAccessToken { result in + api.getAccessToken() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -766,7 +766,7 @@ class UserClientApiSetup { let getRedirectUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getRedirectUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getRedirectUrlChannel.setMessageHandler { _, reply in - api.getRedirectUrl { result in + api.getRedirectUrl() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -781,7 +781,7 @@ class UserClientApiSetup { let getUserProfilesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.getUserProfiles", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getUserProfilesChannel.setMessageHandler { _, reply in - api.getUserProfiles { result in + api.getUserProfiles() { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -884,7 +884,7 @@ class UserClientApiSetup { let fingerprintFallbackToPinChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintFallbackToPin", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintFallbackToPinChannel.setMessageHandler { _, reply in - api.fingerprintFallbackToPin { result in + api.fingerprintFallbackToPin() { result in switch result { case .success: reply(wrapResult(nil)) @@ -899,7 +899,7 @@ class UserClientApiSetup { let fingerprintDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.fingerprintDenyAuthenticationRequest { result in + api.fingerprintDenyAuthenticationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -914,7 +914,7 @@ class UserClientApiSetup { let fingerprintAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.fingerprintAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { fingerprintAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in - api.fingerprintAcceptAuthenticationRequest { result in + api.fingerprintAcceptAuthenticationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -930,7 +930,7 @@ class UserClientApiSetup { let otpDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { otpDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.otpDenyAuthenticationRequest { result in + api.otpDenyAuthenticationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -945,7 +945,7 @@ class UserClientApiSetup { let otpAcceptAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.otpAcceptAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { otpAcceptAuthenticationRequestChannel.setMessageHandler { _, reply in - api.otpAcceptAuthenticationRequest { result in + api.otpAcceptAuthenticationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -961,7 +961,7 @@ class UserClientApiSetup { let pinDenyAuthenticationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyAuthenticationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinDenyAuthenticationRequestChannel.setMessageHandler { _, reply in - api.pinDenyAuthenticationRequest { result in + api.pinDenyAuthenticationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -994,7 +994,7 @@ class UserClientApiSetup { let pinDenyRegistrationRequestChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.pinDenyRegistrationRequest", binaryMessenger: binaryMessenger, codec: codec) if let api = api { pinDenyRegistrationRequestChannel.setMessageHandler { _, reply in - api.pinDenyRegistrationRequest { result in + api.pinDenyRegistrationRequest() { result in switch result { case .success: reply(wrapResult(nil)) @@ -1027,7 +1027,7 @@ class UserClientApiSetup { let cancelBrowserRegistrationChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserClientApi.cancelBrowserRegistration", binaryMessenger: binaryMessenger, codec: codec) if let api = api { cancelBrowserRegistrationChannel.setMessageHandler { _, reply in - api.cancelBrowserRegistration { result in + api.cancelBrowserRegistration() { result in switch result { case .success: reply(wrapResult(nil)) @@ -1164,13 +1164,13 @@ class NativeCallFlutterApiCodec: FlutterStandardMessageCodec { /// Generated class from Pigeon that represents Flutter messages that can be called from Swift. class NativeCallFlutterApi { private let binaryMessenger: FlutterBinaryMessenger - init(binaryMessenger: FlutterBinaryMessenger) { + init(binaryMessenger: FlutterBinaryMessenger){ self.binaryMessenger = binaryMessenger } var codec: FlutterStandardMessageCodec { return NativeCallFlutterApiCodec.shared } - /// Called to handle registration URL + ///Called to handle registration URL func n2fHandleRegisteredUrl(url urlArg: String, completion: @escaping () -> Void) { let channel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.NativeCallFlutterApi.n2fHandleRegisteredUrl", binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([urlArg] as [Any?]) { _ in diff --git a/lib/callbacks/onegini_custom_registration_callback.dart b/lib/callbacks/onegini_custom_registration_callback.dart index 52f59616..463baf2c 100644 --- a/lib/callbacks/onegini_custom_registration_callback.dart +++ b/lib/callbacks/onegini_custom_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; class OneginiCustomRegistrationCallback { final api = UserClientApi(); diff --git a/lib/callbacks/onegini_fingerprint_callback.dart b/lib/callbacks/onegini_fingerprint_callback.dart index abae9b2a..7e153f32 100644 --- a/lib/callbacks/onegini_fingerprint_callback.dart +++ b/lib/callbacks/onegini_fingerprint_callback.dart @@ -1,5 +1,5 @@ import 'dart:async'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// A callback of fingerprint authentication. /// diff --git a/lib/callbacks/onegini_otp_accept_deny_callback.dart b/lib/callbacks/onegini_otp_accept_deny_callback.dart index 283deae4..441244c2 100644 --- a/lib/callbacks/onegini_otp_accept_deny_callback.dart +++ b/lib/callbacks/onegini_otp_accept_deny_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// A callback for mobile authentication with OTP class OneginiOtpAcceptDenyCallback { diff --git a/lib/callbacks/onegini_pin_authentication_callback.dart b/lib/callbacks/onegini_pin_authentication_callback.dart index 5c208e43..dea375c4 100644 --- a/lib/callbacks/onegini_pin_authentication_callback.dart +++ b/lib/callbacks/onegini_pin_authentication_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// A callback for pin AUTHENTICATION. class OneginiPinAuthenticationCallback { diff --git a/lib/callbacks/onegini_pin_registration_callback.dart b/lib/callbacks/onegini_pin_registration_callback.dart index ca094f43..94fae29c 100644 --- a/lib/callbacks/onegini_pin_registration_callback.dart +++ b/lib/callbacks/onegini_pin_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// A callback for pin REGISTRATION. class OneginiPinRegistrationCallback { diff --git a/lib/callbacks/onegini_registration_callback.dart b/lib/callbacks/onegini_registration_callback.dart index a1251b23..3eb02db2 100644 --- a/lib/callbacks/onegini_registration_callback.dart +++ b/lib/callbacks/onegini_registration_callback.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// A callback for registration. class OneginiRegistrationCallback { diff --git a/lib/events/custom_registration_event.dart b/lib/events/custom_registration_event.dart index bb3914d6..89792013 100644 --- a/lib/events/custom_registration_event.dart +++ b/lib/events/custom_registration_event.dart @@ -1,6 +1,6 @@ // Wrapper for Custom Registration Events import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; class InitCustomRegistrationEvent extends OWEvent { OWCustomInfo? customInfo; diff --git a/lib/events/pin_event.dart b/lib/events/pin_event.dart index f301684f..aa6e1fe1 100644 --- a/lib/events/pin_event.dart +++ b/lib/events/pin_event.dart @@ -1,6 +1,6 @@ // Wrapper for Pin Events import 'package:onegini/events/onewelcome_events.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; // For Pin Creation class OpenPinCreationEvent extends OWEvent { diff --git a/lib/model/request_details.dart b/lib/model/request_details.dart index ca6f9c26..700509f8 100644 --- a/lib/model/request_details.dart +++ b/lib/model/request_details.dart @@ -1,4 +1,4 @@ -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; // Wrapper class for pigeon class to enforce non null map values. class RequestDetails { diff --git a/lib/onegini.dart b/lib/onegini.dart index 22ca655b..27dfc597 100644 --- a/lib/onegini.dart +++ b/lib/onegini.dart @@ -5,7 +5,7 @@ import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/onegini_event_listener.dart'; import 'package:onegini/resources_methods.dart'; import 'package:onegini/user_client.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// The main class used to call methods. class Onegini { diff --git a/lib/auto_generated_pigeon.dart b/lib/onegini.gen.dart similarity index 100% rename from lib/auto_generated_pigeon.dart rename to lib/onegini.gen.dart diff --git a/lib/onegini_event_listener.dart b/lib/onegini_event_listener.dart index 06e1d1d2..a7341c93 100644 --- a/lib/onegini_event_listener.dart +++ b/lib/onegini_event_listener.dart @@ -6,7 +6,7 @@ import 'package:onegini/events/fingerprint_event.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/events/otp_event.dart'; import 'package:onegini/events/pin_event.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; class OneginiEventListener implements NativeCallFlutterApi { final StreamController broadCastController; diff --git a/lib/resources_methods.dart b/lib/resources_methods.dart index c309c258..31dd960b 100644 --- a/lib/resources_methods.dart +++ b/lib/resources_methods.dart @@ -1,7 +1,7 @@ import 'model/request_details.dart'; import 'model/request_response.dart'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; /// The class with resources methods class ResourcesMethods { diff --git a/lib/user_client.dart b/lib/user_client.dart index 44b70c8a..5a913976 100644 --- a/lib/user_client.dart +++ b/lib/user_client.dart @@ -1,6 +1,6 @@ import 'dart:async'; -import 'package:onegini/auto_generated_pigeon.dart'; +import 'package:onegini/onegini.gen.dart'; ///Сlass with basic methods available to the developer. class UserClient { diff --git a/pigeons/README.md b/pigeons/README.md index 00871652..8ddb188f 100644 --- a/pigeons/README.md +++ b/pigeons/README.md @@ -4,11 +4,11 @@ Pidgeon is used within this project to enable type-save communication between th Command for code generation which is performed from top level: flutter pub run pigeon \ --input pigeons/onewelcome_pigeon_interface.dart \ - --dart_out lib/auto_generated_pigeon.dart \ - --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/AutoGeneratedPigeon.kt \ + --dart_out lib/onegini.gen.dart \ + --experimental_kotlin_out ./android/src/main/kotlin/com/onegini/mobile/sdk/flutter/pigeonPlugin/Pigeon.gen.kt \ --experimental_kotlin_package "com.onegini.mobile.sdk.flutter.pigeonPlugin" \ - --experimental_swift_out ios/Classes/AutoGeneratedPigeon.swift -dart format lib/auto_generated_pigeon.dart + --experimental_swift_out ios/Classes/Pigeon.gen.swift +dart format lib/onegini.gen.dart ## Missing documentation Pigeon is poorly documented; so to keep knowledge on why and how certain things are done we will refer to pull requests where we obtained information. diff --git a/pigeons/onewelcome_pigeon_interface.dart b/pigeons/onewelcome_pigeon_interface.dart index 87fe7ab5..f3fd3c91 100644 --- a/pigeons/onewelcome_pigeon_interface.dart +++ b/pigeons/onewelcome_pigeon_interface.dart @@ -21,12 +21,6 @@ class OWUserProfile { OWUserProfile({required this.profileId}); } -class OWRemovedUserProfile { - String profileId; - - OWRemovedUserProfile(this.profileId); -} - class OWCustomInfo { int status; String? data; From 713a50238b82e63fb9a547b6c640d0ec387d444c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 26 Apr 2023 16:12:20 +0200 Subject: [PATCH 346/364] Also attempt to cancel customRegistration during during our cancel --- example/lib/screens/login_screen.dart | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 2f9fd2ad..242df9e8 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/callbacks/onegini_custom_registration_callback.dart'; import 'package:onegini/callbacks/onegini_registration_callback.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; @@ -110,14 +111,14 @@ class _LoginScreenState extends State { cancelRegistration() async { setState(() => isLoading = false); - - await OneginiRegistrationCallback() - .cancelBrowserRegistration() - .catchError((error) { - if (error is PlatformException) { - showFlutterToast(error.message); - } - }); + try { + await Future.any([ + OneginiRegistrationCallback().cancelBrowserRegistration(), + OneginiCustomRegistrationCallback().submitErrorAction('Canceled') + ]); + } on PlatformException catch (error) { + showFlutterToast(error.message); + } } Future> getUserProfiles() async { From f11788561652e8ddfb90abb66a7401937e2de55e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 26 Apr 2023 16:20:18 +0200 Subject: [PATCH 347/364] Update the errorcode for which we check during getBiometricAuthenticator --- example/lib/screens/user_screen.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index c5ce6dfd..a38aa3c6 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -84,7 +84,7 @@ class _UserScreenState extends State with RouteAware { _biometricAuthenticator = biometricAuthenticator; }); } on PlatformException catch (err) { - if (err.code != "8043") { + if (err.code != "8060") { showFlutterToast(err.message); } } From c4a4e347600b0402a80cedc364144b78fcd7d83c Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 1 May 2023 10:41:35 +0200 Subject: [PATCH 348/364] FP-87: Split the build method into seperate private helpers --- example/lib/screens/login_screen.dart | 241 +++++++++++++------------- 1 file changed, 120 insertions(+), 121 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index cb9d174b..03f4b6ea 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -181,136 +181,135 @@ class _LoginScreenState extends State { ), body: isLoading ? Center( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - CircularProgressIndicator(), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - cancelRegistration(); - }, - child: Text('Cancel'), - ), - ], - ), + child: _buildCancelRegistrationWidget(), ) : Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - SizedBox( - height: 20, - ), - FutureBuilder>( - //userProfiles - future: getUserProfiles(), - builder: (context, snapshot) { - final userProfileData = snapshot.data; - return (userProfileData != null && - userProfileData.length > 0) - ? Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - "──── Login ────", - style: TextStyle(fontSize: 30), - textAlign: TextAlign.center, - ), - _buildImplicitUserData( - userProfileData.first.profileId), - ElevatedButton( - onPressed: () { - authenticate( - userProfileData.first.profileId, - null); - }, - child: Text('Preferred authenticator'), - ), - Row( - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () { - authenticate( - userProfileData.first.profileId, - OWAuthenticatorType.pin); - }, - child: Text('Pin'), - ), - SizedBox(height: 10, width: 10), - ElevatedButton( - onPressed: () { - authenticate( - userProfileData.first.profileId, - OWAuthenticatorType.biometric); - }, - child: Text('Biometrics'), - ), - ], - ), - ]) - : SizedBox.shrink(); - }), - SizedBox( - height: 20, - ), - Text( - "──── Register ────", - style: TextStyle(fontSize: 30), - ), - SizedBox( - height: 20, - ), - ElevatedButton( - onPressed: () { - openWeb(); - }, - child: Text('Run WEB'), - ), - SizedBox( - height: 20, - ), - FutureBuilder>( - future: Onegini.instance.userClient.getIdentityProviders(), - builder: (BuildContext context, snapshot) { - final identityProviders = snapshot.data; - return identityProviders != null - ? PopupMenuButton( - child: Container( - padding: EdgeInsets.all(20), - color: Colors.blue, - child: Text( - "Run with providers", - style: TextStyle( - color: Colors.white, - fontSize: 16, - fontWeight: FontWeight.w700), - ), - ), - onSelected: (value) { - registrationWithIdentityProvider(value); - }, - itemBuilder: (context) { - return identityProviders - .map((e) => PopupMenuItem( - child: Text(e.name), - value: e.id, - )) - .toList(); - }) - : SizedBox.shrink(); - }, - ), + SizedBox(height: 20), + _buildLoginWidget(), + SizedBox(height: 20), + _buildRegisterWidget(), ], ), ), ); } + + FutureBuilder> _buildLoginWidget() { + return FutureBuilder>( + //userProfiles + future: getUserProfiles(), + builder: (context, snapshot) { + final userProfileData = snapshot.data; + return (userProfileData != null && userProfileData.length > 0) + ? Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "──── Login ────", + style: TextStyle(fontSize: 30), + textAlign: TextAlign.center, + ), + _buildImplicitUserData(userProfileData.first.profileId), + ElevatedButton( + onPressed: () { + authenticate(userProfileData.first.profileId, null); + }, + child: Text('Preferred authenticator'), + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () { + authenticate(userProfileData.first.profileId, + OWAuthenticatorType.pin); + }, + child: Text('Pin'), + ), + SizedBox(height: 10, width: 10), + ElevatedButton( + onPressed: () { + authenticate(userProfileData.first.profileId, + OWAuthenticatorType.biometric); + }, + child: Text('Biometrics'), + ), + ], + ), + ]) + : SizedBox.shrink(); + }); + } + + Column _buildRegisterWidget() { + return Column( + children: [ + Text( + "──── Register ────", + style: TextStyle(fontSize: 30), + ), + SizedBox(height: 20), + ElevatedButton( + onPressed: () { + openWeb(); + }, + child: Text('Run WEB'), + ), + SizedBox(height: 20), + FutureBuilder>( + future: Onegini.instance.userClient.getIdentityProviders(), + builder: (BuildContext context, snapshot) { + final identityProviders = snapshot.data; + return identityProviders != null + ? PopupMenuButton( + child: Container( + padding: EdgeInsets.all(20), + color: Colors.blue, + child: Text( + "Run with providers", + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w700), + ), + ), + onSelected: (value) { + registrationWithIdentityProvider(value); + }, + itemBuilder: (context) { + return identityProviders + .map((e) => PopupMenuItem( + child: Text(e.name), + value: e.id, + )) + .toList(); + }) + : SizedBox.shrink(); + }, + ), + ], + ); + } + + Column _buildCancelRegistrationWidget() { + return Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 20), + ElevatedButton( + onPressed: () { + cancelRegistration(); + }, + child: Text('Cancel'), + ), + ], + ); + } } From 5754b77f15fb61f1bbb94acbb39ab0e39888da2e Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 1 May 2023 11:44:37 +0200 Subject: [PATCH 349/364] FP-87: Add a profileId selector on login screen --- example/lib/screens/login_screen.dart | 40 +++++++++++++++++++-------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 03f4b6ea..5c25874a 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -11,6 +11,7 @@ import 'package:onegini/onegini.dart'; import 'package:onegini/onegini.gen.dart'; import 'package:onegini_example/ow_broadcast_helper.dart'; import 'package:onegini_example/screens/user_screen.dart'; +import 'package:collection/collection.dart'; import '../components/display_toast.dart'; @@ -23,6 +24,7 @@ class _LoginScreenState extends State { bool isLoading = false; List>? registrationSubscriptions; List>? authenticationSubscriptions; + String? selectedProfileId; @override initState() { @@ -31,7 +33,6 @@ class _LoginScreenState extends State { OWBroadcastHelper.initRegistrationSubscriptions(context); this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationSubscriptions(context); - super.initState(); } @@ -124,6 +125,9 @@ class _LoginScreenState extends State { Future> getUserProfiles() async { try { var profiles = await Onegini.instance.userClient.getUserProfiles(); + if (selectedProfileId == null) { + selectedProfileId = profiles.firstOrNull?.profileId; + } return profiles; } catch (err) { print("caught error in getUserProfiles: $err"); @@ -132,7 +136,6 @@ class _LoginScreenState extends State { } Future getImplicitUserDetails(String profileId) async { - var returnString = ""; try { await Onegini.instance.userClient .authenticateUserImplicitly(profileId, ["read"]); @@ -143,9 +146,7 @@ class _LoginScreenState extends State { var res = json.decode(response.body); - returnString = res["decorated_user_id"]; - - return returnString; + return res["decorated_user_id"]; } catch (err) { print("Caught error: $err"); return "Error occured check logs"; @@ -204,7 +205,10 @@ class _LoginScreenState extends State { future: getUserProfiles(), builder: (context, snapshot) { final userProfileData = snapshot.data; - return (userProfileData != null && userProfileData.length > 0) + final profileId = selectedProfileId; + return (userProfileData != null && + userProfileData.length > 0 && + profileId != null) ? Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, @@ -214,10 +218,11 @@ class _LoginScreenState extends State { style: TextStyle(fontSize: 30), textAlign: TextAlign.center, ), - _buildImplicitUserData(userProfileData.first.profileId), + _buildSelectUserProfile(userProfileData), + _buildImplicitUserData(profileId), ElevatedButton( onPressed: () { - authenticate(userProfileData.first.profileId, null); + authenticate(profileId, null); }, child: Text('Preferred authenticator'), ), @@ -226,16 +231,15 @@ class _LoginScreenState extends State { children: [ ElevatedButton( onPressed: () { - authenticate(userProfileData.first.profileId, - OWAuthenticatorType.pin); + authenticate(profileId, OWAuthenticatorType.pin); }, child: Text('Pin'), ), SizedBox(height: 10, width: 10), ElevatedButton( onPressed: () { - authenticate(userProfileData.first.profileId, - OWAuthenticatorType.biometric); + authenticate( + profileId, OWAuthenticatorType.biometric); }, child: Text('Biometrics'), ), @@ -246,6 +250,18 @@ class _LoginScreenState extends State { }); } + DropdownButton _buildSelectUserProfile(List profiles) { + return DropdownButton( + value: selectedProfileId, + items: profiles + .map((e) => + DropdownMenuItem(value: e.profileId, child: Text(e.profileId))) + .toList(), + onChanged: (profileId) => { + setState(() => {selectedProfileId = profileId}) + }); + } + Column _buildRegisterWidget() { return Column( children: [ From bd2b76c73e2a8da5c4c02149d28645b0d5e35462 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 1 May 2023 11:48:01 +0200 Subject: [PATCH 350/364] FP-87: Add a profileId menu item to the user_screen sidebar --- example/lib/screens/user_screen.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 848d69f2..cdfd3426 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -227,6 +227,11 @@ class _UserScreenState extends State with RouteAware { DrawerHeader( child: Container(), ), + ListTile( + title: Text("ProfileId: ${profileId}"), + leading: Icon(Icons.person), + ), + Divider(), ListTile( title: Text("Authenticators"), leading: Icon(Icons.lock_rounded), From 7aebc0614f84935cbf9c704b95225a98e2357375 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 1 May 2023 12:13:47 +0200 Subject: [PATCH 351/364] FP-87: Improve state handling for userProfiles in login_screen --- example/lib/screens/login_screen.dart | 98 +++++++++++++-------------- 1 file changed, 47 insertions(+), 51 deletions(-) diff --git a/example/lib/screens/login_screen.dart b/example/lib/screens/login_screen.dart index 5c25874a..cbe4729c 100644 --- a/example/lib/screens/login_screen.dart +++ b/example/lib/screens/login_screen.dart @@ -24,6 +24,7 @@ class _LoginScreenState extends State { bool isLoading = false; List>? registrationSubscriptions; List>? authenticationSubscriptions; + List userProfiles = []; String? selectedProfileId; @override @@ -34,6 +35,7 @@ class _LoginScreenState extends State { this.authenticationSubscriptions = OWBroadcastHelper.initAuthenticationSubscriptions(context); super.initState(); + getUserProfiles(); } @override @@ -124,10 +126,13 @@ class _LoginScreenState extends State { Future> getUserProfiles() async { try { - var profiles = await Onegini.instance.userClient.getUserProfiles(); - if (selectedProfileId == null) { - selectedProfileId = profiles.firstOrNull?.profileId; - } + final profiles = await Onegini.instance.userClient.getUserProfiles(); + setState(() { + userProfiles = profiles; + if (selectedProfileId == null) { + selectedProfileId = profiles.firstOrNull?.profileId; + } + }); return profiles; } catch (err) { print("caught error in getUserProfiles: $err"); @@ -199,55 +204,46 @@ class _LoginScreenState extends State { ); } - FutureBuilder> _buildLoginWidget() { - return FutureBuilder>( - //userProfiles - future: getUserProfiles(), - builder: (context, snapshot) { - final userProfileData = snapshot.data; - final profileId = selectedProfileId; - return (userProfileData != null && - userProfileData.length > 0 && - profileId != null) - ? Column( - crossAxisAlignment: CrossAxisAlignment.center, + Widget _buildLoginWidget() { + final profileId = selectedProfileId; + return (userProfiles.length > 0 && profileId != null) + ? Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "──── Login ────", + style: TextStyle(fontSize: 30), + textAlign: TextAlign.center, + ), + _buildSelectUserProfile(userProfiles), + _buildImplicitUserData(profileId), + ElevatedButton( + onPressed: () { + authenticate(profileId, null); + }, + child: Text('Preferred authenticator'), + ), + Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - "──── Login ────", - style: TextStyle(fontSize: 30), - textAlign: TextAlign.center, - ), - _buildSelectUserProfile(userProfileData), - _buildImplicitUserData(profileId), - ElevatedButton( - onPressed: () { - authenticate(profileId, null); - }, - child: Text('Preferred authenticator'), - ), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () { - authenticate(profileId, OWAuthenticatorType.pin); - }, - child: Text('Pin'), - ), - SizedBox(height: 10, width: 10), - ElevatedButton( - onPressed: () { - authenticate( - profileId, OWAuthenticatorType.biometric); - }, - child: Text('Biometrics'), - ), - ], - ), - ]) - : SizedBox.shrink(); - }); + ElevatedButton( + onPressed: () { + authenticate(profileId, OWAuthenticatorType.pin); + }, + child: Text('Pin'), + ), + SizedBox(height: 10, width: 10), + ElevatedButton( + onPressed: () { + authenticate(profileId, OWAuthenticatorType.biometric); + }, + child: Text('Biometrics'), + ), + ], + ), + ]) + : SizedBox.shrink(); } DropdownButton _buildSelectUserProfile(List profiles) { From 2c6acaa8113514629ddb4e1735eadeeb576eca30 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Mon, 1 May 2023 12:18:58 +0200 Subject: [PATCH 352/364] FP-87: Fix device info not loading correctly --- example/lib/screens/user_screen.dart | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index cdfd3426..7750e2dd 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -430,8 +429,7 @@ class _InfoState extends State { ResourceRequestType.anonymous, RequestDetails( path: "application-details", method: HttpRequestMethod.get)); - var res = json.decode(response.body); - return applicationDetailsFromJson(res); + return applicationDetailsFromJson(response.body); } Future getClientResource() async { @@ -470,11 +468,11 @@ class _InfoState extends State { children: [ Text( "application identifier => ", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ), Text( snapshot.data?.applicationIdentifier ?? "", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ) ], ), @@ -485,11 +483,11 @@ class _InfoState extends State { children: [ Text( "application platform => ", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ), Text( snapshot.data?.applicationPlatform ?? "", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ) ], ), @@ -500,11 +498,11 @@ class _InfoState extends State { children: [ Text( "application version => ", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ), Text( snapshot.data?.applicationVersion ?? "", - style: TextStyle(fontSize: 18), + style: TextStyle(fontSize: 15), ) ], ), From 21025f9554ee3456eb104b06f92c7dd820707ee0 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 2 May 2023 13:01:49 +0200 Subject: [PATCH 353/364] Add enums for all error_codes --- lib/errors/error_codes.dart | 137 ++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 lib/errors/error_codes.dart diff --git a/lib/errors/error_codes.dart b/lib/errors/error_codes.dart new file mode 100644 index 00000000..d7ae9149 --- /dev/null +++ b/lib/errors/error_codes.dart @@ -0,0 +1,137 @@ +// Dev note: When editing these error codes, make sure to update them in the native wrapper code aswel. + +/// Errors from the flutter sdk, some of these errors can only occur on a single platform. +enum WrapperErrorCodes { + genericError(code: 8000), + notAuthenticatedUser(code: 8040), + notAuthenticatedImplicit(code: 8041), + notFoundUserProfile(code: 8042), + notFoundAuthenticator(code: 8043), + notFoundIdentityProvider(code: 8044), + + /// Android only + notFoundSecurityController(code: 8045), + + httpRequestErrorInternal(code: 8046), + httpRequestErrorCode(code: 8047), + + /// iOS only + httpRequestErrorNoResponse(code: 8048), + + /// Android only + onewelcomeSdkNotInitialized(code: 8049), + + invalidUrl(code: 8050), + notInProgressCustomRegistration(code: 8051), + notInProgressAuthentication(code: 8052), + notInProgressOtpAuthentication(code: 8053), + notInProgressPinCreation(code: 8054), + notInProgressFingerprintAuthentication(code: 8055), + + /// iOS only. Android will throw actionAlreadyInProgress + alreadyInProgressMobileAuth(code: 8056), + + actionNotAllowedCustomRegistrationCancel(code: 8057), + actionNotAllowedBrowserRegistrationCancel(code: 8058), + + /// Android only + configError(code: 8059), + + biometricAuthenticationNotAvailable(code: 8060); + + final int code; + + const WrapperErrorCodes({required this.code}); +} + +/// Error from the native sdk's, some of these errors can only occur on a single platform. +enum PlatformErrorCodes { + networkConnectivityProblem(code: 9000), + serverNotReachable(code: 9001), + deviceDeregistered(code: 9002), + userDeregistered(code: 9003), + outdatedApp(code: 9004), + outdatedOs(code: 9005), + actionCanceled(code: 9006), + actionAlreadyInProgress(code: 9007), + deviceRegistrationError(code: 9008), + + /// iOS only + authenticationErrorInvalidPin(code: 9009), + + userNotAuthenticated(code: 9010), + pinBlacklisted(code: 9011), + pinIsASequence(code: 9012), + pinUsesSimilarDigits(code: 9013), + wrongPinLength(code: 9014), + invalidAuthenticator(code: 9015), + deviceAlreadyEnrolled(code: 9016), + enrollmentNotAvailable(code: 9017), + userAlreadyEnrolled(code: 9018), + userDisenrolled(code: 9020), + mobileAuthenticationNotEnrolled(code: 9021), + authenticatorDeregistered(code: 9022), + + /// Android only + mobileAuthenticationDisenrolled(code: 9023), + + dataStorageNotAvailable(code: 9024), + + /// iOS only + genericErrorUnrecoverableDataState(code: 9025), + + /// iOS only + userNotAuthenticatedImplicitly(code: 9026), + + customAuthenticatorFailure(code: 9027), + + /// iOS only + alreadyHandled(code: 9029), + + authenticationErrorBiometricAuthenticatorFailure(code: 9030), + + /// Android only + invalidDatetime(code: 9031), + + generalError(code: 10000), + configurationError(code: 10001), + invalidState(code: 10002), + localDeregistration(code: 10003), + authenticatorAlreadyRegistered(code: 10004), + + /// Android only + fidoAuthenticationDisabledDeprecated(code: 10005), + + authenticatorNotSupported(code: 10006), + authenticatorNotRegistered(code: 10007), + authenticatorPinDeregistrationNotPossible(code: 10008), + localLogout(code: 10009), + + /// iOS only + fetchInvalidMethod(code: 10010), + + deviceNotAuthenticated(code: 10012), + mobileAuthenticationRequestNotFound(code: 10013), + invalidRequest(code: 10015), + + /// Android only + fidoServerNotReachableDeprecated(code: 10016), + + customAuthenticationDisabled(code: 10017), + notHandleable(code: 10018), + + /// iOS only + fetchInvalidHeaders(code: 10019), + + /// Android only + invalidIdentityProvider(code: 10020), + + customRegistrationExpired(code: 10021), + customRegistrationFailure(code: 10022), + singleSignOnDisabled(code: 10023), + appIntegrityFailure(code: 10024); + + final int code; + + const PlatformErrorCodes({required this.code}); +} From 2756366f1d31b23185e48ae536427a97fd188221 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 2 May 2023 13:13:43 +0200 Subject: [PATCH 354/364] Use Error enums where hardcoded values were used --- example/lib/screens/user_screen.dart | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 7750e2dd..239019a0 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:onegini/errors/error_codes.dart'; import 'package:onegini/events/onewelcome_events.dart'; import 'package:onegini/model/request_details.dart'; import 'package:onegini/onegini.dart'; @@ -83,7 +84,8 @@ class _UserScreenState extends State with RouteAware { _biometricAuthenticator = biometricAuthenticator; }); } on PlatformException catch (err) { - if (err.code != "8060") { + if (err.code != + WrapperErrorCodes.biometricAuthenticationNotAvailable.code) { showFlutterToast(err.message); } } @@ -136,12 +138,11 @@ class _UserScreenState extends State with RouteAware { Onegini.instance.userClient.changePin().catchError((error) { if (error is PlatformException) { showFlutterToast(error.message); - // FIXME: this should be extracted into a seperate method and should also use constants (dont exist yet) - if (error.code == "8002" || - error.code == "9002" || - error.code == "9003" || - error.code == "9010" || - error.code == "10012") { + // FIXME: this should be extracted into a seperate method + if (error.code == WrapperErrorCodes.notAuthenticatedUser || + error.code == PlatformErrorCodes.deviceDeregistered || + error.code == PlatformErrorCodes.userDeregistered || + error.code == PlatformErrorCodes.userNotAuthenticated) { Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => LoginScreen()), From e3eb71279e7f353e7ec1695a800c07e355523c52 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 2 May 2023 13:14:12 +0200 Subject: [PATCH 355/364] Add comments to make sure both places get adjusted --- .../com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt | 1 + ios/Classes/NativeBridge/Errors/ErrorMapper.swift | 1 + 2 files changed, 2 insertions(+) diff --git a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt index 14c7432d..6bcfcaac 100644 --- a/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt +++ b/android/src/main/kotlin/com/onegini/mobile/sdk/flutter/OneWelcomeWrapperErrors.kt @@ -1,5 +1,6 @@ package com.onegini.mobile.sdk.flutter +// When editing these errors, make sure to also update the errors in lib/errors/error_codes.dart enum class OneWelcomeWrapperErrors(val code: Int, val message: String) { GENERIC_ERROR(8000, "Something went wrong"), NOT_AUTHENTICATED_USER(8040, "There is currently no User Profile authenticated"), diff --git a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift index b347b63f..1806be38 100644 --- a/ios/Classes/NativeBridge/Errors/ErrorMapper.swift +++ b/ios/Classes/NativeBridge/Errors/ErrorMapper.swift @@ -1,6 +1,7 @@ // swiftlint:disable cyclomatic_complexity import OneginiSDKiOS +// When editing these errors, make sure to also update the errors in lib/errors/error_codes.dart enum OneWelcomeWrapperError { case genericError case notAuthenticatedUser From 1982f3dc0d20e5eef1e9fe1f94fb1ff1356528e8 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Tue, 2 May 2023 14:40:57 +0200 Subject: [PATCH 356/364] Update max-sdk to 4.0.0 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 9357c204..69409ca8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,7 +4,7 @@ version: 2.0.1 homepage: https://www.onegini.com environment: - sdk: ">=2.12.0 <3.0.0" + sdk: ">=2.12.0 <4.0.0" flutter: ">=1.12.0" dependencies: From fdf4692ce0926a05bb04493feea07788a6a2494f Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 10:04:32 +0200 Subject: [PATCH 357/364] Remove generated files from swiftlint --- example/ios/.swiftlint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/ios/.swiftlint.yml b/example/ios/.swiftlint.yml index e36d81bd..39c7f2d1 100644 --- a/example/ios/.swiftlint.yml +++ b/example/ios/.swiftlint.yml @@ -14,7 +14,7 @@ excluded: # paths to ignore during linting. Takes precedence over `included`. - .swiftlint.yml - OneginiTests - OneginiUITests - - .symlinks/plugins/onegini/ios/Classes/Pigeon.swift + - .symlinks/plugins/onegini/ios/Classes/Pigeon.gen.swift # If true, SwiftLint will not fail if no lintable files are found. allow_zero_lintable_files: false From 2a19e2d3c2a3ff317e14960eb5c87435ab8d1f21 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 10:06:22 +0200 Subject: [PATCH 358/364] Change the error_codes to static const String instead of enum --- example/lib/screens/user_screen.dart | 3 +- lib/errors/error_codes.dart | 166 +++++++++++++-------------- 2 files changed, 81 insertions(+), 88 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index 239019a0..5ec3aa12 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -84,8 +84,7 @@ class _UserScreenState extends State with RouteAware { _biometricAuthenticator = biometricAuthenticator; }); } on PlatformException catch (err) { - if (err.code != - WrapperErrorCodes.biometricAuthenticationNotAvailable.code) { + if (err.code != WrapperErrorCodes.biometricAuthenticationNotAvailable) { showFlutterToast(err.message); } } diff --git a/lib/errors/error_codes.dart b/lib/errors/error_codes.dart index d7ae9149..1459d4bf 100644 --- a/lib/errors/error_codes.dart +++ b/lib/errors/error_codes.dart @@ -1,137 +1,131 @@ // Dev note: When editing these error codes, make sure to update them in the native wrapper code aswel. /// Errors from the flutter sdk, some of these errors can only occur on a single platform. -enum WrapperErrorCodes { - genericError(code: 8000), - notAuthenticatedUser(code: 8040), - notAuthenticatedImplicit(code: 8041), - notFoundUserProfile(code: 8042), - notFoundAuthenticator(code: 8043), - notFoundIdentityProvider(code: 8044), +class WrapperErrorCodes { + static const String genericError = "8000"; + static const String notAuthenticatedUser = "8040"; + static const String notAuthenticatedImplicit = "8041"; + static const String notFoundUserProfile = "8042"; + static const String notFoundAuthenticator = "8043"; + static const String notFoundIdentityProvider = "8044"; /// Android only - notFoundSecurityController(code: 8045), + static const String notFoundSecurityController = "8045"; - httpRequestErrorInternal(code: 8046), - httpRequestErrorCode(code: 8047), + static const String httpRequestErrorInternal = "8046"; + static const String httpRequestErrorCode = "8047"; /// iOS only - httpRequestErrorNoResponse(code: 8048), + static const String httpRequestErrorNoResponse = "8048"; /// Android only - onewelcomeSdkNotInitialized(code: 8049), + static const String onewelcomeSdkNotInitialized = "8049"; - invalidUrl(code: 8050), - notInProgressCustomRegistration(code: 8051), - notInProgressAuthentication(code: 8052), - notInProgressOtpAuthentication(code: 8053), - notInProgressPinCreation(code: 8054), - notInProgressFingerprintAuthentication(code: 8055), + static const String invalidUrl = "8050"; + static const String notInProgressCustomRegistration = "8051"; + static const String notInProgressAuthentication = "8052"; + static const String notInProgressOtpAuthentication = "8053"; + static const String notInProgressPinCreation = "8054"; + static const String notInProgressFingerprintAuthentication = "8055"; /// iOS only. Android will throw actionAlreadyInProgress - alreadyInProgressMobileAuth(code: 8056), + static const String alreadyInProgressMobileAuth = "8056"; - actionNotAllowedCustomRegistrationCancel(code: 8057), - actionNotAllowedBrowserRegistrationCancel(code: 8058), + static const String actionNotAllowedCustomRegistrationCancel = "8057"; + static const String actionNotAllowedBrowserRegistrationCancel = "8058"; /// Android only - configError(code: 8059), + static const String configError = "8059"; - biometricAuthenticationNotAvailable(code: 8060); - - final int code; - - const WrapperErrorCodes({required this.code}); + static const String biometricAuthenticationNotAvailable = "8060"; } +const String networkConnectivityProblem = "9000"; + /// Error from the native sdk's, some of these errors can only occur on a single platform. -enum PlatformErrorCodes { - networkConnectivityProblem(code: 9000), - serverNotReachable(code: 9001), - deviceDeregistered(code: 9002), - userDeregistered(code: 9003), - outdatedApp(code: 9004), - outdatedOs(code: 9005), - actionCanceled(code: 9006), - actionAlreadyInProgress(code: 9007), - deviceRegistrationError(code: 9008), +class PlatformErrorCodes { + static const String networkConnectivityProblem = "9000"; + static const String serverNotReachable = "9001"; + static const String deviceDeregistered = "9002"; + static const String userDeregistered = "9003"; + static const String outdatedApp = "9004"; + static const String outdatedOs = "9005"; + static const String actionCanceled = "9006"; + static const String actionAlreadyInProgress = "9007"; + static const String deviceRegistrationError = "9008"; /// iOS only - authenticationErrorInvalidPin(code: 9009), - - userNotAuthenticated(code: 9010), - pinBlacklisted(code: 9011), - pinIsASequence(code: 9012), - pinUsesSimilarDigits(code: 9013), - wrongPinLength(code: 9014), - invalidAuthenticator(code: 9015), - deviceAlreadyEnrolled(code: 9016), - enrollmentNotAvailable(code: 9017), - userAlreadyEnrolled(code: 9018), - userDisenrolled(code: 9020), - mobileAuthenticationNotEnrolled(code: 9021), - authenticatorDeregistered(code: 9022), + static const String authenticationErrorInvalidPin = "9009"; + + static const String userNotAuthenticated = "9010"; + static const String pinBlacklisted = "9011"; + static const String pinIsASequence = "9012"; + static const String pinUsesSimilarDigits = "9013"; + static const String wrongPinLength = "9014"; + static const String invalidAuthenticator = "9015"; + static const String deviceAlreadyEnrolled = "9016"; + static const String enrollmentNotAvailable = "9017"; + static const String userAlreadyEnrolled = "9018"; + static const String userDisenrolled = "9020"; + static const String mobileAuthenticationNotEnrolled = "9021"; + static const String authenticatorDeregistered = "9022"; /// Android only - mobileAuthenticationDisenrolled(code: 9023), + static const String mobileAuthenticationDisenrolled = "9023"; - dataStorageNotAvailable(code: 9024), + static const String dataStorageNotAvailable = "9024"; /// iOS only - genericErrorUnrecoverableDataState(code: 9025), + static const String genericErrorUnrecoverableDataState = "9025"; /// iOS only - userNotAuthenticatedImplicitly(code: 9026), + static const String userNotAuthenticatedImplicitly = "9026"; - customAuthenticatorFailure(code: 9027), + static const String customAuthenticatorFailure = "9027"; /// iOS only - alreadyHandled(code: 9029), + static const String alreadyHandled = "9029"; - authenticationErrorBiometricAuthenticatorFailure(code: 9030), + static const String authenticationErrorBiometricAuthenticatorFailure = "9030"; /// Android only - invalidDatetime(code: 9031), + static const String invalidDatetime = "9031"; - generalError(code: 10000), - configurationError(code: 10001), - invalidState(code: 10002), - localDeregistration(code: 10003), - authenticatorAlreadyRegistered(code: 10004), + static const String generalError = "10000"; + static const String configurationError = "10001"; + static const String invalidState = "10002"; + static const String localDeregistration = "10003"; + static const String authenticatorAlreadyRegistered = "10004"; /// Android only - fidoAuthenticationDisabledDeprecated(code: 10005), + static const String fidoAuthenticationDisabledDeprecated = "10005"; - authenticatorNotSupported(code: 10006), - authenticatorNotRegistered(code: 10007), - authenticatorPinDeregistrationNotPossible(code: 10008), - localLogout(code: 10009), + static const String authenticatorNotSupported = "10006"; + static const String authenticatorNotRegistered = "10007"; + static const String authenticatorPinDeregistrationNotPossible = "10008"; + static const String localLogout = "10009"; /// iOS only - fetchInvalidMethod(code: 10010), + static const String fetchInvalidMethod = "10010"; - deviceNotAuthenticated(code: 10012), - mobileAuthenticationRequestNotFound(code: 10013), - invalidRequest(code: 10015), + static const String deviceNotAuthenticated = "10012"; + static const String mobileAuthenticationRequestNotFound = "10013"; + static const String invalidRequest = "10015"; /// Android only - fidoServerNotReachableDeprecated(code: 10016), + static const String fidoServerNotReachableDeprecated = "10016"; - customAuthenticationDisabled(code: 10017), - notHandleable(code: 10018), + static const String customAuthenticationDisabled = "10017"; + static const String notHandleable = "10018"; /// iOS only - fetchInvalidHeaders(code: 10019), + static const String fetchInvalidHeaders = "10019"; /// Android only - invalidIdentityProvider(code: 10020), - - customRegistrationExpired(code: 10021), - customRegistrationFailure(code: 10022), - singleSignOnDisabled(code: 10023), - appIntegrityFailure(code: 10024); - - final int code; + static const String invalidIdentityProvider = "10020"; - const PlatformErrorCodes({required this.code}); + static const String customRegistrationExpired = "10021"; + static const String customRegistrationFailure = "10022"; + static const String singleSignOnDisabled = "10023"; + static const String appIntegrityFailure = "10024"; } From a6607c8c1f952ac294be3f97a14ef2922b83d86a Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 11:29:29 +0200 Subject: [PATCH 359/364] FP-51: Re-add logging --- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 58b2b9ab..88dbc61e 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -13,6 +13,7 @@ protocol FetchResourcesHandlerProtocol: AnyObject { class ResourcesHandler: FetchResourcesHandlerProtocol { func authenticateDevice(_ scopes: [String]?, completion: @escaping (Result) -> Void) { + Logger.log("authenticateDevice", sender: self) SharedDeviceClient.instance.authenticateDevice(with: scopes) { error in if let error = error { let mappedError = FlutterError(ErrorMapper().mapError(error)) @@ -24,6 +25,7 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { } func authenticateUserImplicitly(_ profile: UserProfile, scopes: [String]?, completion: @escaping (Result) -> Void) { + Logger.log("authenticateUserImplicitly", sender: self) SharedUserClient.instance.implicitlyAuthenticate(user: profile, with: scopes) { error in if let error = error { let mappedError = FlutterError(ErrorMapper().mapError(error)) @@ -36,7 +38,6 @@ class ResourcesHandler: FetchResourcesHandlerProtocol { func requestResource(_ requestType: ResourceRequestType, _ details: OWRequestDetails, completion: @escaping (Result) -> Void) { Logger.log("requestResource", sender: self) - // Additional check for valid url let resourceUrl = ONGClient.sharedInstance().configModel.resourceBaseURL ?? "" if isValidUrl(details.path) == false && isValidUrl(resourceUrl + details.path) == false { From bb57dd6c7c50d80d6b2708dc7b6697d3658fd1a2 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 11:37:54 +0200 Subject: [PATCH 360/364] FP-51: Update Logger string to match new function name --- ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift index 88dbc61e..d45cfcd5 100644 --- a/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift +++ b/ios/Classes/NativeBridge/Handlers/ResourcesHandler.swift @@ -76,7 +76,7 @@ private extension ResourcesHandler { } func generateResourceRequest(_ details: OWRequestDetails) -> ResourceRequest { - Logger.log("generateONGResourceRequest", sender: self) + Logger.log("generateResourceRequest", sender: self) return ResourceRequestFactory.makeResourceRequest(path: details.path, method: details.method.toHTTPMethod(), From e9be6b3cfc4d837d54976ac8dd70326611182118 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 14:49:38 +0200 Subject: [PATCH 361/364] Fix a bug where fallback to pin was not working correctly on ios It was possible to pass in an available but not registered authenticator into the authenticate_user method if biometrics were available but not registered. This would result in an error instead of fallback to pin. This commit fixes that by only checking registered authenticators when authenticating user. --- .../NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift index 3daaf9a7..512fff47 100644 --- a/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift +++ b/ios/Classes/NativeBridge/ModuleExtensions/OneginiModuleSwift+Auth.swift @@ -38,7 +38,7 @@ extension OneginiModuleSwift { completion(.failure(SdkError(.notFoundUserProfile).flutterError())) return } - let authenticator = SharedUserClient.instance.authenticators(.all, for: profile).first(where: { $0.type == authenticatorType }) + let authenticator = SharedUserClient.instance.authenticators(.registered, for: profile).first(where: { $0.type == authenticatorType }) bridgeConnector.toLoginHandler.authenticateUser(profile, authenticator: authenticator) { result in completion(result) From 85e727854bd908905cfeba01c078447d2207b339 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 14:54:20 +0200 Subject: [PATCH 362/364] Fix an overflow issue on the Drawer on smaller devices --- example/lib/screens/user_screen.dart | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/example/lib/screens/user_screen.dart b/example/lib/screens/user_screen.dart index bae4b2cc..4a2f15c2 100644 --- a/example/lib/screens/user_screen.dart +++ b/example/lib/screens/user_screen.dart @@ -227,16 +227,14 @@ class _UserScreenState extends State with RouteAware { ), body: _children[_currentIndex], drawer: Drawer( - child: Column( + child: ListView( children: [ DrawerHeader( - child: Container(), - ), - ListTile( - title: Text("ProfileId: ${profileId}"), - leading: Icon(Icons.person), + child: ListTile( + title: Text("ProfileId: ${profileId}"), + leading: Icon(Icons.person), + ), ), - Divider(), ListTile( title: Text("Authenticators"), leading: Icon(Icons.lock_rounded), From 1cd2715a4c6ba3a5c5cf750a5b10eb740fe87214 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 15:33:21 +0200 Subject: [PATCH 363/364] Update changelog --- CHANGELOG.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index de025ffc..bd991747 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,45 @@ +## 3.0.0, May 3, 2023 +You can find the full changelog [here](https://developer.onewelcome.com/flutter/plugin/v2-x) and an overview containing the upgrade instructions [here](https://developer.onewelcome.com/flutter/plugin/v2-0). + +[iOS] Wrapper SDK now uses the latest OneWelcome iOS native SDK 12.2.2 + +* Events are now propagated using Streams and have been renamed to more accurately describe their purpose. +* Removed the following events + - eventOther + - openPinAuthenticator + - eventError +* startApplication now no longer requires a OneginiListener parameter. +* All BuildContext requirements from functions have been removed. +* Resource requests now allow absolute paths. +* Allow for Resource Requests to other resource servers than the one in the tokenserver config file, this is only possible if the server has a correct certificate. +* Updated several parameters and return types of functions. +* Functions are now fully typesafe and nullsafe due to the use of [Pigeon](https://pub.dev/packages/pigeon) internally. +* Updates several functions to no longer return a boolean status but instead resolve/reject. + - setPreferredAuthenticator + - deregisterBiometricAuthenticator + - logout + - authenticateDevice + - validatePinWithPolicy + - authenticateUserImplicitly + - deregisterUser +* submitSuccessAction and submitErrorAction for custom registration no longer require an identity provider id. +* getAppToWebSingleSignOn now returns the actual error code instead of a general error when failing. +* OneginiPinRegistrationCallback.acceptAuthenticationRequest No longer takes a map as a second argument. +* Renamed several resourceRequest functions and added a generic requestResource which takes a type as extra argument. +* Reworked error codes and added constants for all errors(wrapper and native) in lib/errors/error_codes.dart +* Reworked mobileAuthWithOtp. +* Reworked authentication + - Removed getRegisteredAuthenticators + - Removed getAllAuthenticators + - Removed registerAuthenticator + - Added deregisterBiometricAuthenticator + - Added registerBiometricAuthenticator + - Added getBiometricAuthenticator + - Added getPreferredAuthenticator + - Changed setPreferredAuthenticator + - Changed authenticateUser +* Allow sdk <4.0.0 + ## 2.0.1, March 2, 2023 Updated the README From 709f9ae4f0472c24abeb7e2ec26bf1dd1dc11b85 Mon Sep 17 00:00:00 2001 From: Michiel Vrins Date: Wed, 3 May 2023 15:34:26 +0200 Subject: [PATCH 364/364] Update versions for release --- README.md | 2 +- pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 487ffd3e..8a8b83c1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ in pubspec.yaml add this: dependencies: - onegini: 2.0.1 + onegini: 3.0.0 `flutter clean` diff --git a/pubspec.yaml b/pubspec.yaml index 69409ca8..79ec54e5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: onegini description: The Onegini Flutter Plugin is a plugin that allows you to utilize the Onegini Mobile SDKs in your Flutter applications. -version: 2.0.1 +version: 3.0.0 homepage: https://www.onegini.com environment: