Git Product home page Git Product logo

moko-biometry's Introduction

moko-biometry
GitHub license Download kotlin-version

Mobile Kotlin biometry

This is a Kotlin Multiplatform library that provides authentication by FaceId and TouchId(Fingerprint)

Table of Contents

Features

  • Biometric user authentication - allows you to use familiar user authentication methods from business logic
  • Compose Multiplatform support (partly, mobile platforms: Android, iOS)

Requirements

  • Gradle version 6.8+
  • Android API 16+
  • iOS version 11.0+

Installation

root build.gradle

allprojects {
    repositories {
        mavenCentral()
    }
}

project build.gradle

dependencies {
    commonMainApi("dev.icerock.moko:biometry:0.4.0")

    // Compose Multiplatform
    commonMainApi("dev.icerock.moko:biometry-compose:0.4.0")

    // Jetpack Compose (only for android, if you don't use multiplatform)
    implementation("dev.icerock.moko:biometry-compose:0.4.0")
}

Usage

common

In commonMain we should create ViewModel like:

class SampleViewModel(
    val biometryAuthenticator: BiometryAuthenticator
) : ViewModel() {

    fun tryToAuth() = viewModelScope.launch {
        try {
            val isSuccess = biometryAuthenticator.checkBiometryAuthentication(
                requestTitle = "Biometry".desc(),
                requestReason = "Just for test".desc(),
                failureButtonText = "Oops".desc(),
                allowDeviceCredentials = false // true - if biometric permission is not granted user can authorise by device creds
            )

            if (isSuccess) {
                // Do something onSuccess
            }
        } catch (throwable: Throwable) {
            // Do something onFailed
        }
    }
}

After create ViewModel, let's integrate on platform.

Android

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: SampleViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Create viewModel from common code.
        viewModel = getViewModel {
            SampleViewModel(
                // Pass platform implementation of the Biometry Authenticator
                // to a common code
                biometryAuthenticator = BiometryAuthenticator(
                    applicationContext = applicationContext
                )
            )
        }

        // Binds the Biometry Authenticator to the view lifecycle
        viewModel.biometryAuthenticator.bind(
            lifecycle = this@MainActivity.lifecycle,
            fragmentManager = supportFragmentManager
        )
    }
}

Compose:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setContent {
            val biometryFactory: BiometryAuthenticatorFactory = rememberBiometryAuthenticatorFactory()

            // Create viewModel from common code
            val viewModel = getViewModel {
                SampleViewModel(
                    // Pass platform implementation of the Biometry Authenticator
                    // to a common code
                    biometryAuthenticator = biometryFactory.createBiometryAuthenticator()
                )
            }

            // Binds the Biometry Authenticator to the view lifecycle
            BindBiometryAuthenticatorEffect(viewModel.biometryAuthenticator)

            // Same screen content here
        }
    }
}

iOS:

class SampleViewController: UIViewController {
    
    private var viewModel: SampleViewModel!
        
    override func viewDidLoad() {
        super.viewDidLoad()

        self.viewModel = SampleViewModel(
            biometryAuthenticator: BiometryBiometryAuthenticator(),
        )
    }
    
    @IBAction private func loginAction() {
        self.viewModel.tryToAuth()
    }
}

Additionally, you need add NSFaceIDUsageDescription key in Info.plist of your project:

<key>NSFaceIDUsageDescription</key>
<string>$(PRODUCT_NAME) Authentication with TouchId or FaceID</string>

Compose Multiplatform:

@Composable
fun BiometryScreen() {
    val biometryFactory: BiometryAuthenticatorFactory = rememberBiometryAuthenticatorFactory()
    
    BiometryScreen(
        viewModel = getViewModel(
            key = "biometry-screen",
            factory = viewModelFactory {
                BiometryViewModel(
                    biometryAuthenticator = biometryAuthenticatorFactory.createBiometryAuthenticator()
                )
            }
        )
    )
}

@Composable
private fun BiometryScreen(
    viewModel: BiometryViewModel
) = NavigationScreen(title = "moko-biometry") { paddingValues ->
    BindBiometryAuthenticatorEffect(viewModel.biometryAuthenticator)

    val text: String by viewModel.result.collectAsState()

    Column(
        modifier = Modifier.fillMaxSize().padding(paddingValues),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = text)

        Button(onClick = viewModel::onButtonClick) {
            Text(text = "Click on me")
        }
    }
}

Samples

Please see more examples in the sample directory.

Set Up Locally

Contributing

All development (both new features and bug fixes) is performed in the develop branch. This way master always contains the sources of the most recently released version. Please send PRs with bug fixes to the develop branch. Documentation fixes in the markdown files are an exception to this rule. They are updated directly in master.

The develop branch is pushed to master on release.

For more details on contributing please see the contributing guide.

License

Copyright 2021 IceRock MAG Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

moko-biometry's People

Contributors

alex009 avatar anton6tak avatar dorofeev avatar exndy avatar tetraquark avatar tunetab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

moko-biometry's Issues

Change name, fix logic or provide correct description on failureButtonText

Right now, on Android, failureButtonText is used for a button to cancel biometry dialog when fallback to backup notification method is not specified. It doesn't correspond to the text in mpp here and probably is not used the same way on iOS. The name creates misunderstanding, because it implies something like "Biometrics failure" text to be used for it, but actually on Android you should use just "Cancel"

Unable to build ios-app

When attempting to build the sample iOS app, I encountered the following error consistently across both Xcode and command line:

ld: framework 'Pods_TestProj' not found
clang: error: linker command failed with exit code 1 (use -v to see invocation)
FAILURE: Build failed with an exception.

This issue persists on the master branch. Here are the pertinent version details:

  • Xcode version: 15.3
  • Kotlin version: 1.9.22
  • Compose Multiplatform version: 1.5.12

Steps Taken:

In an attempt to resolve the issue, I tried upgrading both Kotlin and Compose versions. However, this resulted in a different error. After adding the @OptIn annotation, the build succeeded, but the simulator failed to launch.

Expected Outcome:

I was expecting the demo FaceID app to launch successfully. However, due to my limited familiarity with iOS development, I'm uncertain if testing Face ID on the simulator is feasible without proper Apple entitlements.

Additional Error Details:

Upon further investigation, the build failure was accompanied by the following error message:

* What went wrong:
Execution failed for task ':biometry:compileKotlinIosSimulatorArm64'.
> Compilation finished with errors

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.6.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 4s
4 actionable tasks: 4 executed
Command PhaseScriptExecution failed with a nonzero exit code

Incorrect implementation of Android isTouchIdEnabled function

Android implementation of function isTouchIdEnabled works incorrect - e.g. it will return true if the device has a biometric sensor, but no fingerprints have been added yet. I think that this is not the behavior of the function that a developer expects.


At the moment, the correct way is to use androidx library: https://developer.android.com/reference/androidx/biometric/BiometricManager#canAuthenticate(int)
Something like this

return BiometricManager.from(context).run {
    canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS
}

Desktop support

At first thx for your awesome libraries and great effort.

I'm using Biometry Auth in my KMP app and worked fine until I added Desktop support. I get this error

No matching variant of dev.icerock.moko:biometry-compose:0.4.0 was found. The consumer was configured to find a library for use during compile-time, preferably optimized for standard JVMs, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' but:
          - Variant 'debugApiElements-published' capability dev.icerock.moko:biometry-compose:0.4.0 declares a library for use during compile-time:
              - Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm'

I know that Desktop has no touch or face ID but is there a way to exclude JVM targets from using this library or we can provide a custom auth screen for Desktop with pin number or even let the user provides his own implementation for it when isBiometricAvailable returns false?

Crash on replace compose screen

Cannot replace compose screen when I launch Biometry

java.lang.IllegalStateException: **no event up from DESTROYED** at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.kt:250) at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.kt:287) at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.kt:136) at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.kt:119) at cafe.adriel.voyager.androidx.AndroidScreenLifecycleOwner.onStop(AndroidScreenLifecycleOwner.kt:110) at cafe.adriel.voyager.androidx.AndroidScreenLifecycleOwner.access$onStop(AndroidScreenLifecycleOwner.kt:44) at cafe.adriel.voyager.androidx.AndroidScreenLifecycleOwner$LifecycleDisposableEffect$1$invoke$$inlined$onDispose$1.dispose(Effects.kt:485) at androidx.compose.runtime.DisposableEffectImpl.onForgotten(Effects.kt:87) at androidx.compose.runtime.CompositionImpl$RememberEventDispatcher.dispatchRememberObservers(Composition.kt:1264) at androidx.compose.runtime.CompositionImpl.applyChangesInLocked(Composition.kt:975) at androidx.compose.runtime.CompositionImpl.applyChanges(Composition.kt:996) at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$1.invoke(Recomposer.kt:636) at androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$1.invoke(Recomposer.kt:548) at androidx.compose.ui.platform.AndroidUiFrameClock$withFrameNanos$2$callback$1.doFrame(AndroidUiFrameClock.android.kt:41) at androidx.compose.ui.platform.AndroidUiDispatcher

Add support for option use / not use device's pincode

Need add new option allowDeviceCredentials to expect fun checkBiometryAuthentication method and add support on platforms side

For iOS use LAPolicyDeviceOwnerAuthenticationWithBiometrics / LAPolicyDeviceOwnerAuthentication policy
For Android support already done based on credentialAllowed = true

Update moko-resources dependency without cinterop-pluralizedString

In moko-resources 0.21.0 release cinterop was removed as unused. But Kotlin/Native have own list of dependencies inside klib. All libraries, that depends on moko-resources, have inside own manifest file in klib dependency to dev.icerock.moko:resources-cinterop-pluralizedString. So gradle download new version of moko-resources (0.21.0) and try to compile project, but Kotlin/Native see own dependencies list and see that moko-biometry depends on dev.icerock.moko:resources-cinterop-pluralizedString but that library not exist anymore and gradle not download it.
As result we see:

error: could not find "dev.icerock.moko:resources-cinterop-pluralizedString" in [/Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/bin, /Users/amikhailov/.konan/klib, /Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/klib/common, /Users/amikhailov/.konan/kotlin-native-prebuilt-macos-aarch64-1.8.10/klib/platform/ios_arm64]

need to publish new version with updated moko resources

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.