0.0.3 • Published 6 years ago

rn-face-touch-id v0.0.3

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

React Native Fingerprint Scanner

React Native Version Version NPM

React Native Fingerprint Scanner is a React Native library for authenticating users with Fingerprint, Touch ID and Face ID.

iOS Version

The usage of the TouchID and FaceID is based on a framework, named Local Authentication.

It provides a Default View that prompts the user to place a finger to the iPhone’s button for scanning.

Android Version

Using an expandable Android Fingerprint API library, which combines Samsung and MeiZu's official Fingerprint API.

Samsung and MeiZu's Fingerprint SDK supports most devices which system versions less than Android 6.0.

Table of Contents

Installation

$ npm install rn-face-touch-id --save

Automatic Configuration

$ react-native link rn-face-touch-id

Manual Configuration

iOS

  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modulesrn-face-touch-id and add ReactNativeFingerprintScanner.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libReactNativeFingerprintScanner.a to your project's Build PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)

Android

  1. Open up android/app/src/main/java/[...]/MainActivity.java
  • Add import com.hieuvp.fingerprint.ReactNativeFingerprintScannerPackage; to the imports at the top of the file
  • Add new ReactNativeFingerprintScannerPackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
    include ':rn-face-touch-id'
    project(':rn-face-touch-id').projectDir = new File(rootProject.projectDir, '../node_modules/rn-face-touch-id/android')
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
    compile project(':rn-face-touch-id')

Extra Configuration

  1. Make sure the following versions are all correct in android/app/build.gradle

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.3"
    ...
        defaultConfig {
          targetSdkVersion 25
  2. Add necessary rules to android/app/proguard-rules.pro

    # MeiZu Fingerprint
    
    -keep class com.fingerprints.service.** { *; }
    -dontwarn com.fingerprints.service.**
    
    # Samsung Fingerprint
    
    -keep class com.samsung.android.sdk.** { *; }
    -dontwarn com.samsung.android.sdk.**

Example

Example Source Code

iOS Implementation

import React, { Component, PropTypes } from 'react';
import { AlertIOS } from 'react-native';
import FingerprintScanner from 'rn-face-touch-id';

class FingerprintPopup extends Component {

  componentDidMount() {
    FingerprintScanner
      .authenticate({ description: 'Scan your fingerprint on the device scanner to continue' })
      .then(() => {
        this.props.handlePopupDismissed();
        AlertIOS.alert('Authenticated successfully');
      })
      .catch((error) => {
        this.props.handlePopupDismissed();
        AlertIOS.alert(error.message);
      });
  }

  render() {
    return false;
  }
}

FingerprintPopup.propTypes = {
  handlePopupDismissed: PropTypes.func.isRequired,
};

export default FingerprintPopup;

Android Implementation

import React, { Component, PropTypes } from 'react';
import {
  Alert,
  Image,
  Text,
  TouchableOpacity,
  View,
  ViewPropTypes
} from 'react-native';
import FingerprintScanner from 'rn-face-touch-id';

import ShakingText from './ShakingText.component';
import styles from './FingerprintPopup.component.styles';

class FingerprintPopup extends Component {

  constructor(props) {
    super(props);
    this.state = { errorMessage: undefined };
  }

  componentDidMount() {
    FingerprintScanner
      .authenticate({ onAttempt: this.handleAuthenticationAttempted })
      .then(() => {
        this.props.handlePopupDismissed();
        Alert.alert('Fingerprint Authentication', 'Authenticated successfully');
      })
      .catch((error) => {
        this.setState({ errorMessage: error.message });
        this.description.shake();
      });
  }

  componentWillUnmount() {
    FingerprintScanner.release();
  }

  handleAuthenticationAttempted = (error) => {
    this.setState({ errorMessage: error.message });
    this.description.shake();
  };

  render() {
    const { errorMessage } = this.state;
    const { style, handlePopupDismissed } = this.props;

    return (
      <View style={styles.container}>
        <View style={[styles.contentContainer, style]}>

          <Image
            style={styles.logo}
            source={require('./assets/finger_print.png')}
          />

          <Text style={styles.heading}>
            Fingerprint{'\n'}Authentication
          </Text>
          <ShakingText
            ref={(instance) => { this.description = instance; }}
            style={styles.description(!!errorMessage)}>
            {errorMessage || 'Scan your fingerprint on the\ndevice scanner to continue'}
          </ShakingText>

          <TouchableOpacity
            style={styles.buttonContainer}
            onPress={handlePopupDismissed}
          >
            <Text style={styles.buttonText}>
              BACK TO MAIN
            </Text>
          </TouchableOpacity>

        </View>
      </View>
    );
  }
}

FingerprintPopup.propTypes = {
  style: ViewPropTypes.style,
  handlePopupDismissed: PropTypes.func.isRequired,
};

export default FingerprintPopup;

API

isSensorAvailable(): (Android, iOS)

Checks if Fingerprint Scanner is able to be used by now.

  • Returns a Promise<string>
  • biometryType: String - the type of biometric authentication supported by the device.
  • error: FingerprintScannerError { name, message } - the reason of failure.
componentDidMount() {
  FingerprintScanner
    .isSensorAvailable()
    .then(biometryType => this.setState({ biometryType }))
    .catch(error => this.setState({ errorMessage: error.message }));
}

authenticate({ description, fallbackEnabled }): (iOS)

Starts Fingerprint authentication on iOS.

  • Returns a Promise
  • description: String - the string to explain the request for user authentication.
  • fallbackEnabled: Boolean - default to true, whether to display fallback button (e.g. Enter Password).
componentDidMount() {
  FingerprintScanner
    .authenticate({ description: 'Scan your fingerprint on the device scanner to continue' })
    .then(() => {
      this.props.handlePopupDismissed();
      AlertIOS.alert('Authenticated successfully');
    })
    .catch((error) => {
      this.props.handlePopupDismissed();
      AlertIOS.alert(error.message);
    });
}

authenticate({ onAttempt }): (Android)

Starts Fingerprint authentication on Android.

  • Returns a Promise
  • onAttempt: Function - a callback function when users are trying to scan their fingerprint but failed.
componentDidMount() {
  FingerprintScanner
    .authenticate({ onAttempt: this.handleAuthenticationAttempted })
    .then(() => {
      this.props.handlePopupDismissed();
      Alert.alert('Fingerprint Authentication', 'Authenticated successfully');
    })
    .catch((error) => {
      this.setState({ errorMessage: error.message });
      this.description.shake();
    });
}

release(): (Android)

Stops fingerprint scanner listener and optimizes memory.

  • Returns a Void
componentWillUnmount() {
  FingerprintScanner.release();
}

Types of Biometrics

Value
FINGERPRINT
FACE

Errors

NameMessage
AuthenticationFailedAuthentication was not successful because the user failed to provide valid credentials
AuthenticationNotMatchNo match
DeviceLockedThe device is locked temporarily
FingerprintScannerNotAvailableAuthentication could not start because Fingerprint Scanner is not available on the device
FingerprintScannerNotEnrolledAuthentication could not start because Fingerprint Scanner has no enrolled fingers
FingerprintScannerNotSupportedDevice does not support Fingerprint Scanner
FingerprintScannerUnknownErrorCould not authenticate for an unknown reason
PasscodeNotSetAuthentication could not start because the passcode is not set on the device
SystemCancelAuthentication was canceled by system - e.g. if another application came to foreground while the authentication dialog was up
UserCancelAuthentication was canceled by the user - e.g. the user tapped Cancel in the dialog
UserFallbackAuthentication was canceled because the user tapped the fallback button (Enter Password)

MIT License

Copyright (C) 2017 Van Phu Hieu

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.