Biometric/Pin

Cotter's iOS SDK helps you easily add a Biometric prompt or PIN fallback to your app. This is useful for protecting transactions or sensitive information like medical records.

Overview

Enabling PIN and Biometric using Cotter's Android SDK consists of:

  1. Initializing Cotter

  2. Calling functions to start PIN and Biometric Enrollment

  3. Verify Biometric or PIN before an action

  4. Enabling and disabling Biometric or PIN in Settings

What you're building

Steps

Step 1. Installation

We use Cocoapods as our SDK host. If you're using Cocoapods, add this to your Podfile

pod 'Cotter'

Otherwise please open an issue at our Github Issues page.

Then simply run pod install

Step 2. Set allowed Authentication Methods in the Developer Dashboard

You need to set allowed methods for authentication your users. To allow PIN and BIOMETRIC, go to https://dev.cotter.app/rules

Remember to select the correct project in the dropdown list

Step 3. Initializing Cotter

You will have to do import Cotter on the file that will use Cotter. Then do initialization as follows

import Cotter...let cotter = Cotter(
 apiSecretKey: <your-api-secret-key>,
 apiKeyID: <your-api-key-id>,
 cotterURL: "https://www.cotter.app/api/v0",
 userID: <your-user-id>, // user’s id that will be created later
 configuration: <your-cotter-config>
)

example:

import Cotter...let cotter = Cotter(
 apiSecretKey: "<API_SECRET_KEY>",
 apiKeyID: "<API_KEY_ID>",
 cotterURL: "https://www.cotter.app/api/v0",
 userID: "hello@example.com",
 configuration: [:]
 );

Step 4. Creating a User

1. Registering a new User

/* https://www.cotter.app/api/v0/user/create */
CotterAPIService.shared.registerUser(
  userID: <your-user-id>,
  cb: { response in
    // handle Result (Swift 5 enum) callback here
  }
)

Response:

{
  "ID": "9449e9e9-00e0-4d6b-a4b6-28c5b22b0b0f",
  "created_at": "2020-01-21T12:40:21.200727668Z",
  "update_at": "2020-01-21T12:40:21.200727668Z",
  "deleted_at": null,
  "issuer": "<your key ID>",
  "client_user_id": "<Your User Identifier (string)>",
  "enrolled": [],
  "default_method": null
}

Example:

// registerUserCb is a simple callback that handles the cases for 
// the API Call
func registerUserCb(_ response: CotterResult<CotterUser>){
    switch response{
    case .success(let user):
        print("successfully registered the \(user)")

    case .failure(let err):
        // you can put exhaustive error handling here
        switch err{
        case CotterAPIError.decoding:
            print("this is decoding error on registering user")
            break
        case CotterAPIError.network:
            print("this is network error on registering user")
            break
        case CotterAPIError.status:
            print("this is not successful error")
            break
        default:
            print("error registering user: \(err)")
        }
    }
}

// call the API using our client
CotterAPIService.shared.registerUser(
    userID: "hello@example.com",
    cb: registerUserCb
)

2. Get a User

/* https://www.cotter.app/api/v0/user/:your_user_id */
CotterAPIService.shared.getUser(
  userID: <your-user-id>,
  cb: { response in
    // handle Result (Swift 5 enum) callback here
  }
)

Response:

{
  "ID": "9449e9e9-00e0-4d6b-a4b6-28c5b22b0b0f",
  "created_at": "2020-01-21T12:40:21.200727668Z",
  "update_at": "2020-01-21T12:40:21.200727668Z",
  "deleted_at": null,
  "issuer": "<your key ID>",
  "client_user_id": "<Your User Identifier (string)>",
  "enrolled": ["PIN", "BIOMETRIC"],
  "default_method": "BIOMETRIC"
}

Example:

func enrollCb(response: CotterResult<CotterUser>) {
    switch response {
    case .success(let resp):
        self.yourLabel.text = resp.enrolled.joined(separator: ", ")
    case .failure(let err):
        // we can handle multiple error results here
        switch err {
        case CotterAPIError.status(code: 500):
            print("internal server error")
        case CotterAPIError.status(code: 404):
            print("user not found")
        default:
            print(err.localizedDescription)
        }
    }
}

CotterAPIService.shared.getUser(userID:self.userID, cb:enrollCb)

Step 5. Enroll PIN or Biometric

For starting authentication flow, you need to have the following:

  • The UIViewController you want to attach Cotter to

  • The UIViewController MUST have a NavigationController set (i.e. self.navigationController cannot be nil)

// initialization
let cotter = Cotter(...)cotter.PinEnrollment.startEnrollment(
 vc: <your-vc>,
 animated: true,
 cb: <your-callback>
);

example:

class SomeUIVC: UIViewController {
  var cotter: Cotter?
  override func viewDidLoad() {
      super.viewDidLoad()
      // cotter initialization here
      self.cotter = Cotter(
          apiSecretKey: "588d6f67-0981-4718-899b-bcd512de1aca",
          apiKeyID: "w4FK6Zz0XIhtGY3o5biI",
          userID: "hello@example.com",
          cotterURL: "https://www.cotter.app/api/v0",
          configuration: [:]
        );
      cotter.startEnrollment(
        vc: self,
        animated: true,
        cb: { (token: String, err: Error?) in
            if err != nil {
                // handle error
                return
            }
            // handle success
        }
      )
  }
}

Step 6. Verify PIN and/or Biometrics on an action

The verification flow will automatically prompt for Biometric Verification if the user's device has an enrolled biometric. Otherwise, it will fallback to entering PIN. Starting the verification flow is exactly the same as starting the Enrollment Flow on step 5.

// initialization
let cotter = Cotter(...)

cotter.PinEnrollment.startTransaction(
  vc: <your-vc>,
  animated: true,
  cb: <your-callback>,
  hideClose: false, // hideClose param gives you the choice to show/hide the close button
  configuration: [:]
);

Example:

class SomeUIVC: UIViewController {
  var cotter: Cotter?

  override func viewDidLoad() {
      super.viewDidLoad()

      // cotter initialization here
      self.cotter = Cotter(
          apiSecretKey: "<your API_SECRET_KEY>",
          apiKeyID: "<your API_KEY_ID>",
          userID: "hello@example.com",
          cotterURL: "https://www.cotter.app/api/v0"
        );

      cotter.startTransaction(
        vc: self,
        animated: true,
        cb: { (token: String, err: Error?) in 
            if err != nil {
                // handle error
                return
            }
            // handle success
        },
        hideClose: false
      )
  }
}

🎉 You're done!

Additional Notes

The Callbacks

There are 2 types of callback:

1. HTTP Callbacks

HTTP Callbacks are the ones that you pass in to the start flow functions (startEnrollment, startTransaction, startUpdateProfile).

The callback form is as such:

// FinalCallbackAuth is the general callback function declaration
public typealias FinalAuthCallback = (_ token: String, _ error: Error?) -> Void

It takes in a token String and an optional Error object. Currently token String is not used in PIN or Biometric authentication. We're working on making the token useable.

Error types

For the FinalAuthCallback function, there are 3 types of CotterError that exist in the SDK. These include:

1. CotterError.biometricEnrollment

  • This error is produced when you fail to enroll your biometrics during the Enrollment flow in startEnrollment.

2. CotterError.biometricVerification

  • This error is produced when you fail to verify your biometrics during the Transaction flow in startTransaction.

3. CotterError.keychainError

  • This error is produced in all flows when the user's device is unable to attain its corresponding public/private keys.

However, you will almost always only encounter CotterError.biometricEnrollment and CotterError.biometricVerification errors in the resulting FinalAuthCallback function.

2. Authentication Callbacks

Authentication Callbacks are the ones that is passed in through the CotterAPIService. It uses the latest Result enum in Swift 5. The Authentication callback works similarly as the HTTP Callback, it can handle success and error cases as shown on the previous example.

The callback form is as such:

public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void

What this definition says is that it takes a Result of a type Value, which Value can be any of the pre defined Cotter classes (such as CotterUser, CotterEvent, etc), and returns nothing.

Error types

When using the CotterAPIService class to call Cotter's API endpoints, there are 5 types of Cotter errors that you might encounter:

1. CotterAPIError.encoding

  • An 'encoding' error refers to an error encoding the HTTP Request.

2. CotterAPIError.decoding

  • A 'decoding' error refers to an error decoding the HTTP Response.

3. CotterAPIError.status(code: Int)

  • A 'status' error refers to the response having an invalid HTTP Status Code - e.g. Status 400 (Bad Request Error)

4. CotterAPIError.server(message: String)

  • A 'server' error means that our API server has responded to the request with an error message.

5. CotterAPIError.network

  • A 'network' error means that network conditions are poor, which can be due to bad internet connection.

Last updated