AngularJS-登录和认证在每个路线和控制器 [英] AngularJS- Login and Authentication in each route and controller

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

问题描述

我以自耕农,咕噜和亭子创建的应用程序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-饼干,但我不知道如何使用它们。

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个部分:用户的状态存储在服务,在运行方法,你看,当路由变化,你是否允许用户访问请求的页面,在你的主控制器你看,如果用户变化的状态。

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');
        }
    });
}]);

您应该创建一个服务(我将它命名为验证),这将处理用户对象和
必须知道,如果用户登录与否的方法。

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 应在登录页面用来处理登录。它应该只是与验证服务interract并设置用户登录作为与否。

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.

的LoginController

.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天全站免登陆