简体   繁体   English

Angular.js-如何防止用户不登录就进入内页以及如何在成功登录后存储会话

[英]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. 我正在使用angularjs和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 这是我的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 这是我的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 这是我的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 这是我的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. 我是刚开始在angularjs上使用.run()和$ rootScope。

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: 在application.run()中,您需要根据用户是否登录来检查状态更改并阻止或允许状态更改。例如:

        $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. 现在,在从登录页面调用登录API之后,将来自响应的访问令牌存储到会话存储中,并将状态更改为所需的主页。

NOTE: You might prefer using local storage instead of session storage for storing the access token. 注意:您可能更喜欢使用本地存储而不是会话存储来存储访问令牌。

To do this with PHP, you need to save user credentials (or login status) to $_SESSION and verify them everytime you serve a file. 要使用PHP做到这一点,您需要将用户凭据(或登录状态)保存到$_SESSION ,并在每次提供文件时进行验证。 You need to give your files php extension for compatibility. 您需要为文件提供php扩展名以实现兼容性。

  1. Set you index.php to call itself on form submission. 将您设置为index.php以在表单提交时自行调用。

  2. When called with the user name and password, authenticate them, and set the $_SESSION['authenticated'] variable to true in case of authentic login. 使用用户名和密码进行调用时,请对其进行身份验证,然后将$_SESSION['authenticated']变量设置为true以进行可靠登录。

  3. Now check this $_SESSION variable everytime you serve your templates. 现在,每次您提供模板时$_SESSION检查此$_SESSION变量。

      <?PHP if ($_SESSION['authenticated'] == false) die('Permission denied'); ?> 

However, although it works, there are lot of new and more secure ways to handle this via methods such as jwt . 但是,尽管它可以工作,但是有许多新的和更安全的方法可以通过诸如jwt之类的方法来处理此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM