paint-brush
How to Implement Face Recognition in Vue.JS with FaceIOby@houssein
8,915 reads
8,915 reads

How to Implement Face Recognition in Vue.JS with FaceIO

by HousseinSeptember 4th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Facial recognition authentication can be used on the Web with vanilla JavaScript or any modern Web framework. In this blog I will be introducing you to Faceio’s facial recognition authentication which is an amazing way to login users to your system as well we will be building a simple app to showcase the way to integrate this technology in a vue.js application. FaceIO is one of the most secure ways to authenticate your users. The technology makes user's life much easier so they don't have to remember passwords or else although we can add another layer of verification for user protection.

Company Mentioned

Mention Thumbnail
featured image - How to Implement Face Recognition in Vue.JS with FaceIO
Houssein HackerNoon profile picture


Nowadays the Web has become a platform where you can run all kinds of applications from e-learning, financial services, booking websites, and anything you could imagine.


Because of that authenticating users on the Web is a must. Actually, there are many ways to authenticate users one of which is using the traditional email and password authentication. Another way to do this is simply using a third-party authentication provider like Facebook for example.


But thanks to artificial intelligence facial recognition has become possible and It can be used on the Web with vanilla JavaScript or any modern Web framework. In this blog, I will be introducing you to Faceio’s Facial recognition authentication which is an amazing way to log in users to your system as well we will be building a simple app to showcase the way to integrate this mind-blowing technology in a vue.js application. So be ready, there will be a lot to cover.


Do we even need face recognition?

In the first place, you should consider face recognition for your project because AI-powered technologies are still mysterious which makes them more attractive. In fact, I wouldn't believe face recognition exists before making my own application that uses it. Just the fact that your website uses face recognition will make users want to visit your website to try out this new technology.


In the second place, face recognition is easy to integrate into your application. And to showcase this, we will be building a vue.js application with FaceIO’s facial recognition using the fio.js library which takes all the heavy lifting for us so we can easily use face recognition.


Finally, this technology makes user's life much easier so they don't have to remember passwords, or else we can add another layer of verification for user protection which can be a pin which is the case withFaceIO. So you as a user just have to let the camera scan your face and you're authenticated.


The first question that will come to your mind is, is it secure?

This era is known as the big data era, so companies consider data as a treasure, so they will try their best to protect their customer's data at any cost.


Also from a user standpoint having his data secure is something expected from companies he consumes their products. Also authenticating users is an extremely important feature of any web app. So security is a critical factor Also FaceIO is one of the most secure ways to authenticate your users. Why? Actually for many reasons which I will be naming a few :


The first reason is Faceio's compliance with broadly applicable privacy laws such as the GDPR, CCPA, and other privacy standards. Such laws may charge businesses up to 4% of their annual revenues for violating their rules concerning users’ privacy. Also, FaceIO never stores your image it just stores a hashed key of the image so you're photos are not getting anywhere.


The second one is the high accuracy of the model which FaceIO uses which scores almost 100% in the accuracy metrics which is an insane number that requires an insane amount of high-quality data that costs lots of money.


Making a registration app with FaceIO

We've talked enough and now it's time to build our simple application. The UI is very simple, typically 3 buttons one for signing in another one for registering, and one for logout.


The app works in a simple way you first register and then log in, at this point the logout button that was originally hidden shows and the other two will disappear. This is what the project will look like after we’re done :




First, you need to register on the FaceIO website if you don't have an account it's an easy thing to do, I'll be waiting for you to sign in so we can continue building this app. Once done you'll have a Public ID associated with your application that looks something like fio9362. We'll need this Public ID to connect with our application.


So first we need to set up a vue.js project. You need to first create a folder then use a command shell to navigate to the folder location and run the command shown below.


vue create faceRecognition


Now let’s add fio.js to our project. Now go to the HTML file and add a div with the id faceio-modal and the fio.js cdn to the end of the body:


<div class="faceio-modal"></div>
<script src="https://cdn.faceio.net/fio.js"></script>
<script type="text/javascript">
 const faceio = new faceIO('Your app id goes here')
 window.faceio=faceio
</script>


Another way to approach this is assigning window.faceio to the faceIO object and then creating an instance in the vue.js JavaScript code while storing the app id in a .env file.


Now going to the App.vue file update the HelloWorld component to be an AuthenticationComponent and add the CSS code below. The App.vue component should look like this :


<template>
<div class='app'>
  <AuthenticationComponent />
 </div> 
</template>

<script>
import AuthenticationComponent from './components/Authentication.vue'

export default {
  name: 'App',
  components: {
    AuthenticationComponent
  }
}
</script>

<style>
body{
  display:flex;
  justify-content:center;
  align-items:center;
  height:100vh
}

</style>


Now going to the Authentication.vue file that was previously the HelloWorld component, we will first start with clearing the template, then adding three buttons one for login, another one for registering, and one for logout. We need to create a user state a set its value to an empty string.


Now using the v-ifattribute we can make the login and registration buttons show only where the user is not set and the logout button only show when the user is logged in also we will add for each button its corresponding click event. We will be creating these 3 functions in a minute. The template will look as shown below, I added very basic CSS nothing crazy :

<template>
  <div class="Authentication">
    <h1>Face recognition with FaceIO</h1>
    <div class='container'>
    <div v-on:click='login' class='btn' v-if="user === ''">Sign in</div>
    <div class='btn' v-on:click='register' v-if="user === ''">Register</div>
    <div class='btn' v-on:click='logout'  v-if="user != ''">Log out</div>
    </div>
  </div>
</template>

<style scoped>
.container{
  width:90%;
  margin:20px auto;
  display:flex;
  justify-content:space-around;
  align-items:center;
  padding:1em;
}
.btn{
  border:1px solid black;
  border-radius:5px;
  padding:1em 2em;
}
.btn:hover{
  background:#000;
  color:#fff
}
</style>


Now for the JavaScript part, we need to first create a state for tracking users as shown below:


data(){
   return {
    user:''
   }
  },


Now let’s create the login, register, and logout functions :


The logout button just sets the user to an empty string It’s easy to implement but for the registration function we will use the method provided by fio.js which can be accessed from the window object. That function accepts a payload object which is data that will be returned when the same user logs in, the code is fairly simple as shown below.


 register(){
  window.faceio.enroll({
    "locale": "auto", 
    "payload": {
        "whoami": 123456,
        "email": "[email protected]"
        }
    }).then(userInfo => {
        // User Successfully Enrolled! 
        alert(
            `User Successfully Enrolled! Details:
           Unique Facial ID: ${userInfo.facialId}
           Enrollment Date: ${userInfo.timestamp}
           Gender: ${userInfo.details.gender}
           Age Approximation: ${userInfo.details.age}`
        );
       console.log(userInfo);
       // handle success, save the facial ID (userInfo.facialId), redirect to the dashboard...
    }).catch(errCode => {
       // Something went wrong during enrollment, log the failure
       console.log(errCode);
    })
   },
  logout(){
   this.user=''
   }


The documentation for the fio.js library can be found here.


Now for the login function, fio.js provides a function for user login that returns data that we passed as an argument for the enroll function when the user registered, here is how it works :


   login(){
    window.faceio.authenticate({
        "locale": "auto" // Default user locale
    }).then(userData => {
        console.log("Success, user identified")
        console.log("Linked facial Id: " + userData.facialId)
        console.log("Payload: " + JSON.stringify(userData.payload)) // {"whoami": 123456, "email": "[email protected]"} from the enroll() example above
        this.user=userData.payload.whoami
    }).catch(errCode => {
        console.log(errCode)
    })
   }


For a bigger project, you can set cookies and adjust the function for your needs.


And now we are finally done hopefully you enjoyed this project 😁


Conclusion

Ai is reshaping the web so fast, so be quick and add face recognition to your web application it will make a great difference.


Thanks for reading my article, I really appreciate this 🙂


You can follow me on LinkedIn for more great articles like this 😆

https://linkedin/in/housseinbadra