AngularJS- 每个路由和控制器中的登录和身份验证 [英] AngularJS- Login and Authentication in each route and controller

查看:25
本文介绍了AngularJS- 每个路由和控制器中的登录和身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 yeoman、grunt 和 bower 创建的 AngularJS 应用程序.

I have an AngularJS application created by using yeoman, grunt and bower.

我有一个登录页面,其中有一个检查身份验证的控制器.如果凭据正确,我将重新路由到主页.

I have a login page that has a controller that checks for authentication. If the credentials are correct I reroute to home page.

app.js

'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
    .when('/forgotPassword', {
        templateUrl: 'forgotpassword.html',
        controller: 'forgotController'
      })
   .when('/home', {
       templateUrl: 'views/home.html',
       controller: 'homeController'
    })
    .otherwise({
       redirectTo: '/login'
    });
//    $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);

angular.module('myApp').factory("page", function($rootScope){
    var page={};
    var user={};
    page.setPage=function(title,bodyClass){
        $rootScope.pageTitle = title;
        $rootScope.bodylayout=bodyClass;
    };
    page.setUser=function(user){
        $rootScope.user=user;
    }
    return page;
});

LoginControler.js

'use strict';

angular.module('myApp').controller('LoginController', function($scope, $location, $window,page) {
    page.setPage("Login","login-layout");
    $scope.user = {};
    $scope.loginUser=function()
    {
        var username=$scope.user.name;
        var password=$scope.user.password;
        if(username=="admin" && password=="admin123")
        {
            page.setUser($scope.user);
            $location.path( "/home" );
        }
        else
        {
            $scope.message="Error";
            $scope.messagecolor="alert alert-danger";
        }
    }
});

在我的主页上

<span class="user-info">
    <small>Welcome,</small>
    {{user.name}}
</span>
<span class="logout"><a href="" ng-click="logoutUser()">Logout</a></span>

loginController 中,我检查登录信息,如果成功,则在服务工厂中设置用户对象.我不知道这是否正确.

In the loginController, I check the login info and if it's successful, I set the user object in the service factory. I don't know whether this is correct or not.

我需要的是,当用户登录时,它会在用户对象中设置一些值,以便所有其他页面都可以获取该值.

What I need is, When the user is logged in, It sets some value in the user object so that all other pages can get that value.

每当发生任何路由更改时,控制器都应检查用户是否已登录.如果没有,它应该重新路由到登录页面.此外,如果用户已经登录并返回该页面,则它应该转到主页.控制器还应检查所有路由上的凭据.

Whenever any route changes happen, the controller should check if the user is logged in or not. If not, it should reroute to the login page. Also, if the user is already logged in and come back to the page, it should go to home page. The controller should also check the credentials on all of the routes.

我听说过 ng-cookies,但我不知道如何使用它们.

I have heard about ng-cookies, but I don't know how to use them.

我看到的很多例子都不是很清楚,他们使用了某种访问角色或其他东西.我不想要那个.我只想要一个登录过滤器.有人可以给我一些想法吗?

Many of the examples I saw were not very clear and they use some kind of access roles or something. I don't want that. I only want a login filter. Can someone give me some ideas?

推荐答案

我的解决方案分为 3 部分:用户的状态存储在服务中,在你观察路由变化时的 run 方法中,并检查是否允许用户访问请求的页面,在您的主控制器中,您可以查看用户状态是否发生变化.

My solution breaks down in 3 parts: the state of the user is stored in a service, in the run method you watch when the route changes and you check if the user is allowed to access the requested page, in your main controller you watch if the state of the user change.

app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
    $rootScope.$on('$routeChangeStart', function (event) {

        if (!Auth.isLoggedIn()) {
            console.log('DENY');
            event.preventDefault();
            $location.path('/login');
        }
        else {
            console.log('ALLOW');
            $location.path('/home');
        }
    });
}]);

您应该创建一个服务(我将其命名为 Auth),它将处理用户对象并有一个方法来了解用户是否已登录.

You should create a service (I will name it Auth) which will handle the user object and have a method to know if the user is logged or not.

服务:

 .factory('Auth', function(){
var user;

return{
    setUser : function(aUser){
        user = aUser;
    },
    isLoggedIn : function(){
        return(user)? user : false;
    }
  }
})

在您的 app.run 中,您应该监听 $routeChangeStart 事件.当路由发生变化时,它会检查用户是否已登录(isLoggedIn 方法应该处理它).如果用户没有登录,它不会加载请求的路由,它会将用户重定向到正确的页面(在您的情况下登录).

From your app.run, you should listen the $routeChangeStart event. When the route will change, it will check if the user is logged (the isLoggedIn method should handle it). It won't load the requested route if the user is not logged and it will redirect the user to the right page (in your case login).

loginController 应该在您的登录页面中用于处理登录.它应该只是与 Auth 服务交互并将用户设置为已登录.

The loginController should be used in your login page to handle login. It should just interract with the Auth service and set the user as logged or not.

登录控制器:

.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
  //submit
  $scope.login = function () {
    // Ask to the server, do your job and THEN set the user

    Auth.setUser(user); //Update the state of the user in the app
  };
}])

从您的主控制器,您可以监听用户状态是否发生变化并响应重定向.

From your main controller, you could listen if the user state change and react with a redirection.

.controller('mainCtrl', ['$scope', 'Auth', '$location', function ($scope, Auth, $location) {

  $scope.$watch(Auth.isLoggedIn, function (value, oldValue) {

    if(!value && oldValue) {
      console.log("Disconnect");
      $location.path('/login');
    }

    if(value) {
      console.log("Connect");
      //Do something when the user is connected
    }

  }, true);

这篇关于AngularJS- 每个路由和控制器中的登录和身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆