Angularjs - 如何防止用户在没有登录的情况下进入内部页面以及如何在成功登录时存储会话

时间:2017-11-15 03:30:22

标签: angularjs angular-ui-router angularjs-rootscope

我正在使用angularjs和angularjs ui-route。我正在构建一个登录页面,我想阻止任何用户在没有登录的情况下转到内页。我发现了一个类似的问题,但它缺少信息。此外,我想在成功登录后存储会话。

这是我的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');        
                }
            });
        }
    }]);
  

这是我的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);

 ?>

这是我的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>

这是我的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>

我不熟悉在angularjs上使用.run()和$ rootScope。

2 个答案:

答案 0 :(得分:1)

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

        $rootScope.$on('$stateChangeStart', function (event, toState){

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

        });

此处会话是一项服务。它检查是否在会话存储中找到了访问令牌。如果未找到,则会阻止用户进入内页。

现在,在从登录页面调用登录API后,将响应中的访问令牌存储到会话存储中,并将状态更改为所需的主页。

注意:您可能更喜欢使用本地存储而不是会话存储来存储访问令牌。

答案 1 :(得分:0)

要使用PHP执行此操作,您需要将用户凭据(或登录状态)保存到$_SESSION,并在每次提供文件时验证它们。为了兼容性,您需要提供文件php扩展名。

  1. 设置index.php以在表单提交时调用自身。

  2. 使用用户名和密码进行调用时,请对其进行身份验证,并在真实登录时将$_SESSION['authenticated']变量设置为true

  3. 现在每次提供模板时都要检查此$_SESSION变量。

      <?PHP 
        if ($_SESSION['authenticated'] == false)
            die('Permission denied');
      ?>
    
  4. 然而,尽管它有效,但有很多新的和更安全的方法可以通过jwt等方法来处理这个问题。