DEV Community

Cover image for 🟢 Build a Demo of Face Recognition Authentication ✨
Random
Random

Posted on

🟢 Build a Demo of Face Recognition Authentication ✨

Hellooo Developers 👋 Welcome to my another blog post .

Face Recognition Authentication is the future of login and identity verification. In a world filled with passwords that are easily forgotten or stolen, facial biometrics provide a convenient and secure way for users to verify who they are.

In this blog post, I'll be showing a demo nextjs application with implements face authentication using the FACEIO API in a Next.js project.

The goal of the demo is to show developers how they can add Face Recognition Authentication to their own React/Next.js or any other apps.

Let's Start with a DEMO 👇 And Drop a "💖🤯🔥".


Click here for Demo 🟢

faceiodemo

Source Code 👆

The faceioAuth demo uses Faceio Api and @faceio/fiojs for Facial Authentication .

It allows users to enroll their face for authentication by capturing images during an enrollment process. Once enrolled, a user can log in by verifying their face against what was captured during enrollment.

FACEIO Documantation 📝

The core technology powering the face recognition is faceio. Faceio is an API and SDK that makes it easy to add facial authentication to websites and apps. Some key capabilities of FACEIO include:

  • Face detection - Detect and capture faces in real time camera.
  • Face enrollment - Capturing facial features to create a user profile.
  • Face verification - Comparing a new face image to an enrolled profile.
  • Web support - Can Works across different web frameworks .

Implement Faceio in your react/nextjs app 🤔

To Implement Faceio in your react/nextjs app is very simple there is a predefined function in FACEIO like enroll() & authenticate() :

1. Get your api key and public_id

facio console

  • After you compleated all the steps and create your application simply implement fio.js by running npm i @faceio/fiojs, its a facial recognition JavaScript library, and initialize the library with your application Public ID.

  • if your are facing any problem in integrating checkout their 👇.

Integration Guide 📖

2. Initialise your Public_id



  const initialiseFaceio = async () => {
    try {
      faceioRef.current = new faceIO('Faceio-Public-id');
      console.log("FaceIO initialized successfully");
    } catch (error) {
      console.log(error);
      handleError(error)
    }
  };
  useEffect(() => {
    initialiseFaceio();

  }, []);

Enter fullscreen mode Exit fullscreen mode

3. Create a Register user function


// HANDLE REGISTER 
  const handleRegister = async () => {
    try {
      if (!faceioRef.current) {
        console.error("FaceIO instance is not initialized");
        return;
      }

       await faceioRef.current?.enroll({
        userConsent: false,
        locale: "auto",
        payload: { email: `${email}` },
      });
     // here you add you cookie storing logic ...

      toast.success("Successfully Registered user.")

    } catch (error) {
      handleError(error);
      faceioRef.current?.restartSession();
    }
  };

Enter fullscreen mode Exit fullscreen mode

4. Create a Login user Function


// HANDLE LOGIN 
  const handleLogin = async () => {
    try {
      const authenticate = await faceioRef.current?.authenticate();
      console.log("User authenticated successfully:", authenticate);
      setUserLogin(authenticate.payload.email);
            // here you add you cookie storing logic ...

    } catch (error) {
      console.log(error);

      handleError(error);
    }
  };

Enter fullscreen mode Exit fullscreen mode

5. Define the handleError() Function


 // HANDLing ERRORs 
  function handleError(errCode: any) {
    const fioErrs = faceioRef.current?.fetchAllErrorCodes()!;
    switch (errCode) {
      case fioErrs.PERMISSION_REFUSED:
        toast.info("Access to the Camera stream was denied by the end user");
        break;
      case fioErrs.NO_FACES_DETECTED:
        toast.info(
          "No faces were detected during the enroll or authentication process"
        );
        break;
      case fioErrs.UNRECOGNIZED_FACE:
        toast.info("Unrecognized face on this application's Facial Index");
        break;
      case fioErrs.MANY_FACES:
        toast.info("Two or more faces were detected during the scan process");
        break;
      case fioErrs.FACE_DUPLICATION:
        toast.info(
          "User enrolled previously (facial features already recorded). Cannot enroll again!"
        );
        break;
      case fioErrs.MINORS_NOT_ALLOWED:
        toast.info("Minors are not allowed to enroll on this application!");
        break;
      case fioErrs.PAD_ATTACK:
        toast.info(
          "Presentation (Spoof) Attack (PAD) detected during the scan process"
        );
        break;
      case fioErrs.FACE_MISMATCH:
        toast.info(
          "Calculated Facial Vectors of the user being enrolled do not matches"
        );
        break;
      case fioErrs.WRONG_PIN_CODE:
        toast.info("Wrong PIN code supplied by the user being authenticated");
        break;
      case fioErrs.PROCESSING_ERR:
        toast.info("Server side error");
        break;
      case fioErrs.UNAUTHORIZED:
        toast.info(
          "Your application is not allowed to perform the requested operation (eg. Invalid ID, Blocked, Paused, etc.). Refer to the FACEIO Console for additional information"
        );
        break;
      case fioErrs.TERMS_NOT_ACCEPTED:
        toast.info(
          "Terms & Conditions set out by FACEIO/host application rejected by the end user"
        );
        break;
      case fioErrs.UI_NOT_READY:
        toast.info(
          "The FACEIO Widget could not be (or is being) injected onto the client DOM"
        );
        break;
      case fioErrs.SESSION_EXPIRED:
        toast.info(
          "Client session expired. The first promise was already fulfilled but the host application failed to act accordingly"
        );
        break;
      case fioErrs.TIMEOUT:
        toast.info(
          "Ongoing operation timed out (eg, Camera access permission, ToS accept delay, Face not yet detected, Server Reply, etc.)"
        );
        break;
      case fioErrs.TOO_MANY_REQUESTS:
        toast.info(
          "Widget instantiation requests exceeded for freemium applications. Does not apply for upgraded applications"
        );
        break;
      case fioErrs.EMPTY_ORIGIN:
        toast.info("Origin or Referer HTTP request header is empty or missing");
        break;
      case fioErrs.FORBIDDDEN_ORIGIN:
        toast.info("Domain origin is forbidden from instantiating fio.js");
        break;
      case fioErrs.FORBIDDDEN_COUNTRY:
        toast.info(
          "Country ISO-3166-1 Code is forbidden from instantiating fio.js"
        );
        break;
      case fioErrs.SESSION_IN_PROGRESS:
        toast.info(
          "Another authentication or enrollment session is in progress"
        );
        break;
      case fioErrs.NETWORK_IO:
      default:
        toast.info(
          "Error while establishing network connection with the target FACEIO processing node"
        );
        break;
    }
  }

Enter fullscreen mode Exit fullscreen mode

⚙ If your are facing any problem then check out my faceiodemo github repo 👉 https://github.com/taqui-786/faceioAuth .


Community Contribuition Tutorials🙌

More about implementing FACIO in your web application using your favorite JavaScript framework whether it is React, Vue, Angular, Next, React or Vanilla JavaScript.

Checkout More Tutorials ⭐


That's it 🙏

Comment your thoughts on this Face Recognition Authentication and my demo app built with Next.js and FaceIO.

Thanks for reading till here!

Happy Coding 👋

github

twitter

portfolio

buymeacoffee

Top comments (13)

Collapse
 
disane profile image
Marco

In this hot topic you should consider to mention explicitly that your data (your biometric face and the image) is processed on a third party server. So your most personal data (biometric features) is saved somewhere in the internet.

Collapse
 
devluc profile image
Devluc

Great guide Taqui. Thanks for sharing it

Collapse
 
random_ti profile image
Random

Thank you so much Lucian for your feedback 🙏

Collapse
 
framemuse profile image
Valery Zinchenko

I mean all cool, but it's not that interesting when you're just connecting to third-party API to achieve it.

Collapse
 
random_ti profile image
Random

I understand Valery, Thank you for your feedback 💖

Collapse
 
sonu123 profile image
Sonu

Awesome Demo .. but FACEIO Ui is like old style ... Btw cool 😎

Collapse
 
random_ti profile image
Random

Thanks for your feedback 🙏

Collapse
 
john90 profile image
John bobby

Cool 😎

Collapse
 
random_ti profile image
Random

Thanks John🤝

Collapse
 
john90 profile image
John bobby

Your welcome 😃

Collapse
 
friendz_me_12 profile image
friendz

its cool 🤔 but i don't prefer to use 3rd party api for authentication.

Collapse
 
sona21 profile image
Sona1

I will try once 👍 Nice Demo .

Collapse
 
random_ti profile image
Random

🙌