angularjsangular-ui-routerangularjs-rootscope

Angularjs - How to prevent user from going to inner pages without logging in and how to store session upon successfull login


I am using angularjs and angularjs ui-route. I am building a login page and I want to prevent any user to go to inner pages without logging in. I have found a similar question but it lacks information. Also I want to store session upon successful login.

Here is my homeroute.js

    'use strict';

var application = angular.module('App', ['ui.router']);

    application.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        // For unmatched routes
        $urlRouterProvider.otherwise('/');

        // Application routes
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: './views/login.html',
                controller: 'logincontroller'
            })
            .state('/', {
                url: '/',
                templateUrl: './views/home.html'
            })
             .state('customerHome', {
                url: '/customerHome',
                templateUrl: './views/customerHomepage.html'
            })
            .state('signup', {
                url: '/signup',
                templateUrl: './views/register.html',
                controller: 'registercontroller' 
            });
    }
]);

        application.run(function($rootScope, $location) {
        var customerHome = ['/customerHome'];
        $rootScope.$on('$routeLogin', function() {
            if(customerHome.indexOf($location.path()) != -1 && sessionStorage.getItem('userLogin')) {
                $location.path('/login');
            }
        });
    });

    application.controller('registercontroller', ['$scope', '$http', function($scope, $http) {
                $scope.formData = {};
                $scope.userform = "";
                $scope.register = function() {
                    $http({
                        method: 'POST',
                        url: './services/loginsubmit.php',
                        data: $scope.formData
                    }).then(function(response) {
                        console.log(response);
                        if(response.data.empty == true) {
                            $scope.userform = "Please fill the form.";
                        } else if(response.data.emailError == true) {
                            $scope.userform = "Invalid Email.";
                        } else if(response.data.validation == true) {
                            $scope.userform = "Username already exists.";   
                        } else if(response.data.validateUsername == true) {
                            $scope.userform = "Username must be more than 5 characters.";
                        } else if(response.data.validatePassword == true) {
                            $scope.userform = "Password must be more than 5 characters.";
                        } else if(response.data.registerSuccess == false) {
                            $scope.userform = "Registration Successful.";
                            $scope.formData = {};
                        } else if(response.data.registerSuccess == true) {
                            $scope.userform = "Registration Failed";
                        }
                    });
                }
            }]);

    application.controller('logincontroller', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
        $scope.loginData = {};
        $scope.loginUser = "";
        $scope.login = function() {
            $http({
                method: 'POST',
                url: './services/loginservice.php',
                data: $scope.loginData
            }).then(function(response) {
                console.log(response);
                if(response.data.UsernameLogin == true) {
                    $scope.loginUser = "Invalid username or password.";
                } else {
                    sessionStorage.setItem('userLogin', response.data.usernameSession); 
                    $location.path('/customerHome');        
                }
            });
        }
    }]);

Here is my loginservice.php

    <?php 

    include '../connection/connect.php';

    $formLogin = json_decode(file_get_contents("php://input"));

    $data = array();
    $check_UsernameLogin = false;

    $username = $formLogin->username;
    $password = $formLogin->password;

    $login = mysqli_query($conn, "SELECT username FROM customer WHERE username='$username' AND customer_password='$password'");

    $check_username = mysqli_num_rows($login);

    if($check_username == 0) {
        $check_UsernameLogin = true;
    } else {
        $check_UsernameLogin = false;
    }

    $data["UsernameLogin"] = $check_UsernameLogin;
    $data["usernameSession"] = $login;

    echo json_encode($data);

 ?>

Here is my login.html

    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>

Here is my customerHomepage.html

    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>

I am new to using .run() and $rootScope on angularjs.


Solution

  • In the application.run() , you need to check for state change and prevent or allow state change based on whether the user is logged in or not.For ex:

            $rootScope.$on('$stateChangeStart', function (event, toState){
    
                if(toState.name === 'login'){
                    return;
                }
                else if (!session.getAccessToken()) {    
                    $state.go('login');
                    event.preventDefault();                 
                }
                else{
                    return;
                }
    
            });
    

    Here session is a service.It checks if the access token is found in the session storage.If not found then it prevents user from going to inner pages.

    Now,after making a call to login API from your login page,store the access token form the response into your session storage,and change the state to your desired home page.

    NOTE: You might prefer using local storage instead of session storage for storing the access token.