AngularJS Authentication Blog

Angularjs login authentication example

What we are building ??

This example will aware you about basic process of authentication which covers all the basic requirements in authentication process.

The main workflow of this example covers following requirements.

  • What will happen when I am on welcome page and try to access login route.
  • How unprotected and protected route will handle.
  • What will happen when I try to access those route which require login.
  • What will happen if I logout and I tried to access those route.
Tool Needed
  • sublime text editor or any other editor.

Let the fun begins:

Sample file structure.

– app/

        
——- js /
         

———– LoginController.js

———– HomeController.js

———- app.js

——- html /

—————- login.html

—————- welcome.html

– index.html


Angularjs Dependency requirements.

  • angular.min.js
  • angular-ui-router.min.js
  • angular-cookies.min.js

Note : Git code link at the end of this block

How it will look on-fire

Let’s code it
> app.js 

First and foremost thing is to define our app.

var authApp = angular.module('authApp',['ui.router','ngCookies']);


our route config will look like this.

authApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/login');

    $stateProvider

        .state('login', {
            url: '/login',
            templateUrl: 'app/html/login.html',
            controller: 'loginController'        }).state('home', {
            url: '/home',
            templateUrl: 'app/html/welcome.html',
            controller:'homeController',
            secure:true
   });

});
Note : home is a secure url.

- We need to add some security in app.js but I will declare it in end of this blog.

> LoginController.js  
Lets define our login function in this controller.
- we have set 'isLogin' to 'true' which required to check that user is logged in or not after page refresh.   
- Currently I have put some test email and password value.
$scope.login = function(){

    if($scope.email === 'test@james.com' && $scope.password === "1234"){
        $cookies.put('isLogin', true);
        $cookies.put('email',$scope.email);
        $state.go('home');
    }
    else
        $scope.error = "wrong credential";
}; 
> HomeController.js
Now it's time to define the home controller. It just contain logout() function and get email value from $cookies. 
- I put value of user's email id in $cookies in loginController here I am assigning it to $scope.email.
$scope.email = $cookies.get('email');
- Our logout() function will look as below,
$scope.logout = function() {
    $cookies.remove('isLogin');
    $cookies.remove('email');
    $state.go('login');
}  
- Here we just remove isLogin and email value from cookies at the time of logout. 
> Now what will happen if you reload or refresh the page or try to access '/login' route once login.
- Here is the answer. 
- For this you have to define run configuration in your app. Which execute in every route change call.

- This will redirect you to welcome screen if you are logged in and refresh your page.
- This will redirect you to welcome screen if you try to access login link if you are logged in.

- This will allow only authenticate user to access welcome screen.

- Put this code in app.js.

authApp.run(['$location', '$rootScope','$cookies', '$state', '$stateParams',
    function($location, $rootScope, $cookies, $state, $stateParams) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;

           //fired when transition begins
           $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
            if (toState && toState.secure) {
                if($cookies.get('isLogin')){
                    //do nothing                }else{
                    $state.go("login");
                    event.preventDefault();
                }
            }

            if(toState.url == '/login' && $cookies.get('isLogin')) {
                $state.go("home");
                event.preventDefault();
            }

        });
}]);
- run config will monitor the state change and behave according to it.
We are at the end of this blog, let's take a look at a code of our html pages.
> index.html
- We always put index.html at the root scope of our app. 
<!DOCTYPE html>
<html>
<head lang="en">
    <title>Angularjs basic login authentication example</title>

    <script src="plugin/angular/angular.min.js"></script>
    <script src="plugin/angular-ui-router/angular-ui-router.min.js"></script>
    <script src="plugin/angular-cookies/angular-cookies.min.js"></script>
    <script src="app/js/app.js"></script>
    <script src="app/js/LoginController.js"></script>
    <script src="app/js/HomeController.js"></script>
    <script src="app/js/LoginService.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <style type="text/css">
        body{padding-top:20px;}
    </style>
</head>
<body ng-app="authApp">
    <div ui-view></div>
</body>
</html>
> login.html
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Please sign in</h3>
                </div>
                <div class="panel-body">
                    <form accept-charset="UTF-8" role="form">
                        <fieldset>
                            <div class="form-group">
                                <input class="form-control" placeholder="E-mail" name="email" type="text" ng-model="email">
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Password" name="password" type="password" value="" ng-model="password">
                            </div>
                            <input class="btn btn-lg btn-success btn-block" type="submit" value="Login" ng-click='login()'>
                        </fieldset>
                        <br>
                        <div align="center"><label style="color:red;">{{error}}</label></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div> 
> welcome.html
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="panel panel-default" style="background-color: beige;">
                <div class="panel-heading">
                    <h3 class="panel-title">Welcome</h3>
                </div>
                <div class="panel-body">This is welcome page. Hello {{email}}</div>
         
       <div align="center"><input class="btn btn-danger btn-small" type="submit" value="logout" ng-click='logout()'></div>
            </div>
        </div>
    </div>
</div>

This is how we define our angluar-basic-authentication-app.
I have create git repository for this. you can pull code from my git repository. 
Here is pull request.
https://github.com/jimmydave03/Angular-Login-Authentication.git
For view code in git click here.


AngularJS Authentication Blog

Leave a Reply

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

Feedback