DEV Community

Cover image for Checkout the latest Books by Login via Mobile Number feature using HMS Account Kit in Books App (React Native)
HMS Community
HMS Community

Posted on

Checkout the latest Books by Login via Mobile Number feature using HMS Account Kit in Books App (React Native)

Introduction

In this article, I will be integrating Huawei Account Kit in an Application. Account Kit provides you with simple, secure and quick sign-in and authorization functions. By integrating the Auth Service SDK into our app, we can easily and quickly provide functions such as registration and sign-in for our users. We can choose to provide our users with one or more of the authentication modes like Mobile number, Email address, Facebook, WeChat etc. We will integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.

React Native

React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.

Requirements

  1. Any operating system (MacOS, Linux and Windows).
  2. Must have a Huawei phone with HMS 4.0.2.300 or later.
  3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
  4. Minimum API Level 21 is required.
  5. Required EMUI 9.0.0 and later version devices.

Integrate HMS Dependencies

  • First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.

  • Create a project in android studio, refer Creating an Android Studio Project.

  • Generate a SHA-256 certificate fingerprint.

  • To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
    Or use cmd as explained in SHA256 CODE

  • Create an App in AppGallery Connect.

  • Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.

Image description

  • Enter SHA-256 certificate fingerprint and click Save, as follows.

Image description

  • Click Manage APIs tab and enable Account Kit.

Image description

React Native Project Preparation

  • Environment set up, refer below link.
    https://reactnative.dev/docs/environment-setup

  • Create project using below command.
    react-native init project name

  • Download the React Native Account Kit SDK and paste it under Node Modules directory of React Native project. If you cannot find node modules run below command under project directory using CLI.
    “npm install” & “npm link”

  • Configure android level build.gradle
    Add to buildscript/repositories and allprojects/repositories
    maven {url 'http://developer.huawei.com/repo/'}

  • Configure app level build.gradle. (Add to dependencies)
    Implementation project (“:react-native-hms-account”)

  • Linking the HMS Account Kit Sdk.
    Run below command in the project directory
    react-native link react-native-hms-account

  • Add below permissions to Android.manifest file.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Enter fullscreen mode Exit fullscreen mode
  • Enabling Auth Service (i). Sign in to AppGallery Connect and click My projects. (ii). Click a project that you want to enable Auth Service from the project list. (iii). Choose Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.

Image description

(iv). Click Enable in the row of each authentication mode to be enabled.
Image description

For more details visit this documentation.

Development

• Registering an Account

  • Apply for a verification code for mobile number-based registration. The verification code will be sent to the user's mobile number to ensure that the mobile number belongs to this user. Call PhoneAuthProvider.requestVerifyCode to apply for a registration verification code.
let settings = new VerifyCodeSettings(
              VerifyCodeAction.REGISTER_OR_LOGIN,
              "zh_CN",
              30
            );
            PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
              .then((verifyCodeResult) => {
                // verifyCodeResult.shortestInterval
                // verifyCodeResult.validityPeriod
              })
              .catch((error) => {
                // error
              });
Enter fullscreen mode Exit fullscreen mode
  • Register a user using a mobile number. Call AGCAuth.createPhoneUser to register a user. After the registration is successful, the user signs in automatically, and you do not need to call the sign-in API again. The password is optional, and the user can sign in using a verification code.
AGCAuth.getInstance()
  .createPhoneUser(
    "countryCode",
    "phoneNumber",
    "password if you want",
    "verifyCode"
  )
  .then((signInResult) => {
    // signInResult.user
  })
  .catch((error) => {
    // error
  });
Enter fullscreen mode Exit fullscreen mode
  • After successful sign-in, call AGCAuth.currentUser to obtain user account data.
AGCAuth.getInstance()
  .currentUser()
  .then((user) => {
    if (user) {
      // A user signed in
    }
  });
Enter fullscreen mode Exit fullscreen mode

• Signing In with a Password

  • On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
AGCAuth.getInstance()
  .currentUser()
  .then((user) => {
    if (user) {
      // A user signed in
    }
  });
Enter fullscreen mode Exit fullscreen mode
  • Call AGCAuth.signIn for sign-in.
let credential = PhoneAuthProvider.credentialWithPassword(
    "countryCode",
    "phoneNumber",
    "password"
  );
  AGCAuth.getInstance()
    .signIn(credential)
    .then((signInResult) => {
      if (signInResult && signInResult.user) {
        // signInResult.user get user info
      }
    })
    .catch((error) => {
      // error
    });

Enter fullscreen mode Exit fullscreen mode
  • After successful sign-in, call AGCAuth.currentUser to obtain user account data.

• Signing In with a Verification Code

  • On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
AGCAuth.getInstance()
       .currentUser()
       .then((user) => {
          if (user) {
            // A user signed in
          }
        });
Enter fullscreen mode Exit fullscreen mode
  • Call PhoneAuthProvider.requestVerifyCode to apply for a verification code.
let settings = new VerifyCodeSettings(
      VerifyCodeAction.REGISTER_OR_LOGIN,
      "zh_CN",
      30
    );
    PhoneAuthProvider.requestVerifyCode("countryCode", "phoneNumber", settings)
      .then((verifyCodeResult) => {
        // verifyCodeResult.shortestInterval
        // verifyCodeResult.validityPeriod
      })
      .catch((error) => {
        // error
      });
Enter fullscreen mode Exit fullscreen mode
  • Call AGCAuth.signIn for sign-in.
let credential = PhoneAuthProvider.credentialWithVerifyCode(
        "countryCode",
        "phoneNumber",
        null,
        "verificationCode"
      );
      AGCAuth.getInstance()
        .signIn(credential)
        .then((signInResult) => {
          if (signInResult && signInResult.user) {
            // signInResult.user get user info
          }
        })
        .catch((error) => {
          // error
        });

Enter fullscreen mode Exit fullscreen mode
  • After successful sign-in, call AGCAuth.currentUser to obtain user account data.

Testing
Run the android App using the below command.
react-native run-android

Result

Image description
Image description
Image description

Conclusion

In this article, we have learnt that how to integrate the mobile number authentication mode into the app, so that our users can use mobile numbers and passwords or verification codes to sign in to the app securely.

Reference

Account Kit: Documentation
Account Kit: Training Video

Top comments (0)