Skip to main content
login bootstrap ui

Part 2 – Angularjs User Authentication Using Node JS JWT

This is the second part of nodejs user authentication using the JWT tutorial, We have created nodejs application for user authentication using JWT and the user registration process, That are basic tutorials and you will get how to work with jwt and nodejs.

This angularjs tutorial help to integrate nodejs jwt tutorial with angularjs. I Will create sign in and signup process of angularjs application using nodejs JWT.
Once user logged-in and token will get from nodejs application, we will redirect user to dashboard page.
Please dont be panic, I am not describing angularjs application configuration steps.I will shared full angularjs code at the end of this tutorial.

Dependencies are:

There are following files will participate into this application

  • app.controller.js : This is the main angularjs controller file
  • app.js : This is a file use to create app, routes and configuration application level app.
  • index.html: This is the main view file that will render on load of angularjs application. We will include all js and css library files
  • service/ : This folder will contain all factories and services.
  • modules/ : I am following a module-wise structure, so it will contain all modules of this application.
  • lib/ : This folder will contains all third party library files

Checkout Other NodeJS tutorials,

How to create a Session Service in AngularJS

The session is very important to store user information on the client side, like email, name etc. I will use the session to store token information to validate the user and route access. Please create sessionService.js file into service/ folder.

(function (window, angular, undefined) {
  'use strict';
  
  angular.module('myApp').service('Session', Session);

  Session.$inject = ['$cookies'];

  function Session($cookies) {

    this.put = function(key, value){
      $cookies.put(key, value);
    }

    this.get = function(key){
      return $cookies.get(key);
    };

    this.getToken = function(key){
      return $cookies.get('tokenId');
    };

    this.delete = function(key){
      $cookies.remove(key);
    }
    
    return this;  

  }

})(window, window.angular);

How to create AUTH Service in AngularJS

I will create authService.js file into service/ folder. This file handle all user authentication process and add method into this factory. We will use this service any where application where we need user information and token etc.

/*global angular:true, moment:true, _:true */
(function () {
  'use strict';

  angular.module('myApp').factory('AuthService', AuthService);

  AuthService.$inject = ['$http', '$q', 'Session'];

  function AuthService($http,  $q, Session) {

    var factory = {     
      isLoggedIn: isLoggedIn,
      logout: logout,
      getToken: getToken,
      getUser: getUser,
      setUser: setUser
    };

    return factory;

    function isLoggedIn(){
      
      if(Session.get('tokenId')){
       return true
     }
     else{
      return false
    }
  }

   function logout(){
    
    	Session.delete('tokenId');
    }  

    function getToken(){
      return Session.get('tokenId');
    } 

    function setUser(data){
      console.log(data);
      Session.put('tokenId', data.token);
      Session.put('f_name', data.user.first_name);     
      Session.put('l_name', data.user.last_name);
      Session.put('email', data.user.email);

    }

    function getUser(){
      return {
        'tokenId': Session.get('tokenId'),
        'name': Session.get('f_name')+' ' + Session.get('l_name'),
        'email': Session.get('email')
      };
    }

  }

})(window, window.angular);

How to create User Register

We will create user registration html page and route using angular controller method.Registration page contains dome HTML fields that need to filed by user, one register we will send login page and user enter his credentials what he has entered at the time of registration.

Step 1: We will create register routes into app.js file.

.when("/register", {
		templateUrl : "modules/login/register.html",
		controller : "registerCtrl"
	})

We have defined view file(modules/login/register.html) and controller file(registerCtrl).

Step 2: We will create register.html file into modules/login folder.

<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-body">
<div class="row">
<div class="col-lg-12"><form id="register-form" style="display: none;" role="form" action="#" method="post">
<h2>REGISTER</h2>
<div class="form-group"><input id="first_name" class="form-control" tabindex="1" name="first_name" required="" type="text" value="" placeholder="First Name"></div>
<div class="form-group"><input id="last_name" class="form-control" tabindex="1" name="last_name" required="" type="text" value="" placeholder="Last Name"></div>
<div class="form-group"><input id="email" class="form-control" tabindex="1" name="email" required="" type="email" value="" placeholder="Email Address"> <span class="error_message">{{message_error}}</span> <span class="success_message">{{message_success}}</span></div>
<div class="form-group"><input id="password" class="form-control" tabindex="2" name="password" required="" type="password" placeholder="Password"></div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3"><input id="register-submit" class="form-control btn btn-register" tabindex="4" name="register-submit" type="submit" value="Register Now"></div>
</div>
</div>
</form></div>
</div>
</div>
<div class="panel-heading">
<div class="row">
<div class="col-xs-6 tabs">
<div class="login">LOGIN</div>
</div>
<div class="col-xs-6 tabs">
<div class="register">REGISTER</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Step 3:We will have login.js file and create registerCtrl method into this file.

(function (window, angular, undefined) {
  'use strict';

  angular.module('myApp').controller('registerCtrl', registerCtrl)
  registerCtrl.$inject = ['$scope', '$http', '$location', 'Session'];
  function registerCtrl($scope, $http, $location, Session) {
	$scope.signup = function() {
       var pass = $scope.newuser.password;
       var enc_pass = window.btoa(pass);
       $scope.newuser.password = enc_pass;
       $http({
            method  : 'POST',
            url     : 'http://localhost:3000/signup/',
            data    : $scope.newuser, //forms user object
         })
            .success(function(data) {
             console.log("done");
            });
    }
}

We have created a registerCtrl controller and inject dependencies, Also created signup method to register using nodejs service.

How to Check User Is already Exist OR Username Un-Available

We have also created nodejs rest service to check username is exist or not at the time user registration.I will fire this method on blur event of username field.

We will create a check user name method in login.js file under registerCtrl controller method.

$scope.check_user=function(){
      $scope.test_user={};
      var check_user=$scope.newuser.email;
      $scope.test_user.check_user=check_user;
      if($scope.test_user.check_user  != null){
        $http({
            method  : 'POST',
            url     : 'http://localhost:3000/check_user/',
            data    : $scope.test_user, //forms user object
         }).success(function(data) {
             console.log(data.results.status);
             $scope.status=data.results.status;
             if(data.results.status == "false"){
                 $scope.message_success="";
                $scope.message_error="User of Same Name Already Exists";
             }
             else if(data.results.status == "true"){
                 $scope.message_error="";
                 $scope.message_success="Valid User Name";
             }
            
          });
      } else if($scope.test_user.check_user  == null){
           $scope.message_error="";
           $scope.message_success="";
       }
    }

How to create User Sign In/Login

We have register user and now we will add user sign-in process with in this angularjs application.We will create login form and integrate using nodejs service to validate user is exist and credentials correct, if credential validate then generate token(nodejs app) and return into response, Otherwise send error message.

Step 1: We will create sign-in routes into app.js file.

.when("/login", {
	templateUrl : "modules/login/login.html",
	controller : "loginCtrl"
})

We have defined view file(modules/login/login.html) and controller file(loginCtrl).

Step 2: We will create loginCtrl.html file into modules/login folder.

<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div class="alert alert-danger" role="alert">{{errorMessage}}</div>
<form id="login-form" style="display: block;" role="form" name="login_form">
<h2>LOGIN</h2>
<div class="form-group"><input id="username" class="form-control" tabindex="1" name="username" required="" type="text" value="" placeholder="Username"></div>
<div class="form-group"><input id="password" class="form-control" tabindex="2" name="password" required="" type="password" placeholder="Password"></div>
<div class="col-xs-6 form-group pull-right"><input id="login-submit" class="form-control btn btn-login" tabindex="4" name="login-submit" type="submit" value="Log In"></div>
</form></div>
</div>
</div>
<div class="panel-heading">
<div class="row">
<div class="col-xs-6 tabs">
<div class="register">REGISTER</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Step 3: We will loginCtrl file into login.js file.

function loginCtrl($scope, $http, $location, Session, AuthService) {
    $scope.user={};
    $scope.newuser={};
    $scope.error = false;
    
    $scope.signin = function() {
      var pass=$scope.user.password;
      var enc_pass= window.btoa(pass);

      $http({
          method  : 'POST',
          url     : 'http://localhost:3000/signin/',
          data    : {email : $scope.user.email, password: enc_pass} //forms user object
       }).success(function(response) {
          var data = response.results;
          if(data.status) {
            AuthService.setUser(data);
          } else {
            $scope.error = true;
            $scope.errorMessage = data.msg;
          }

          console.log(Session.get('tokenId'));
          $location.path('/dashboard');
        });

    }
  }

Angularjs Dashboard page

We have created register user and sign-in user features into this angular application, Now I will create a dashboard page that will use when the user successfully logged-in and is redirected to this /dashboard route.

Here user can see his profile information and be able to logged-out from this angularjs application.
Step 1: We will create dashboard routes into app.js file.

.when("/dashboard",{
		templateUrl: "modules/dashboard/dashboard.html",
		controller : "dashboardCtrl"
	 })

We have defined view file(modules/dashboard/dashboard.html) and controller file(dashboardCtrl), lets create,

Step 2: We will create dashboard.html file into modules/dashboard folder.

<div class="username">
<h2>{{user_name}} <small><i class="fa fa-map-marker"></i> US </small></h2>
<i class="fa fa-briefcase"></i> Web Design and Development. <a class="btn-o" href="#" target="_blank" rel="noopener"> <i class="fa fa-user-plus"></i> Add Friend </a> <a class="btn-o" href="#" target="_blank" rel="noopener"> <i class="fa fa-plus"></i> Follow </a>
<ul class="dropdown-menu pull-right">
<li><a href="#">Video Call <i class="fa fa-video-camera"></i></a></li>
<li><a href="#">Poke <i class="fa fa-hand-o-right"></i></a></li>
<li><a href="#">Report <i class="fa fa-bug"></i></a></li>
<li><a href="#">Block <i class="fa fa-lock"></i></a></li>
</ul>
</div>

Step 3:We will dashboardCtrl file into /modules/dashboard/ folder.

function dashboardCtrl($rootScope, $scope, AuthService,$location) {
		var user = AuthService.getUser();
		$rootScope.user_name = user.name;
		$scope.logout = function () {
			AuthService.logout();
			$location.path("#/login");
		}
	}

We have created logout() method to log out users from the angular js application.

You can download the source code from the below link.

a class=”btn btn-default download-button” title=”User Authentication using JWT (JSON Web Token) with angularjs and nodejs” href=”https://github.com/jstutorials/angular_js_with_nodejs_jwt” target=”_blank” rel=”nofollow noopener”> Download Source Code

Conclusion:

We have created register ,login and dashboard controller and inject dependencies, Also created method to register user/login using nodejs service.We will store user information into session using setUser() and display information into user dashboard page.

Leave a Reply

Your email address will not be published. Required fields are marked *