如何在全球范围内实现身份验证与AngularJS,设计和UI路由器? [英] How to globally implement Authentication with AngularJS, Devise and UI Router?

查看:184
本文介绍了如何在全球范围内实现身份验证与AngularJS,设计和UI路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的角所以这可能是一个新手的问​​题。

我试图实现与Rails的一个简单的任务管理器(只是一个练习)作为后端和角作为前端。到目前为止,我也跟着教程和一切工作正常。

现在我想在全球范围内实现身份验证。这意味着:当用户未注册并登录,她应该看到启动页面或登录页面。

我不想做,在每一个角控制器,因为干燥。所以我想通了UI路由器可能是一个好地方。我有轻微的怀疑,也许$ httpProvider.interceptors可能是有用的。

这是我多远了。我可以检查用户是否加载身份验证和prevent的页面。但仅此而已。我怎么会何去何从?是否有良好的教程在那里我错过了吗?

#2这个问题去类似的方向,但并没有解决我的的问题,因为他们没有使用设计

谢谢!

  // app.js
VAR应用= angular.module(任务管理器,['ui.router','模板','设计'])
的.config([
    '$ stateProvider',
    '$ urlRouterProvider',
    功能($ stateProvider,$ urlRouterProvider){
        $ stateProvider
            .STATE('家',{
                网址:'/家,
                templateUrl:家/ _home.html',
                控制器:'MainCtrl',
                解析:{
                    projectPromise:['项目',函数(项目){
                        的console.log($ rootScope);
                        返回projects.getAll();
                    }]
                }
            })
            .STATE('项目',{
                网址:'/项目/ {ID}
                templateUrl:项目/ _projects.html',
                控制器:'ProjectsCtrl',
                解析:{
                    项目:['$ stateParams','项目',函数($ stateParams,项目){
                        返回projects.get($ stateParams.id);
                    }]
                }
            })
            .STATE('登陆',{
                网址:'/登录',
                templateUrl:'auth /中_login.html',
                控制器:'AuthCtrl',
                的OnEnter:['$状态','验证',函数($状态,验证){
                    Auth.currentUser()。然后(函数(){
                        $ state.go('家');
                    })
                }]
            })
            .STATE('注册',{
                网址:'/注册,
                templateUrl:'auth /中_register.html',
                控制器:'AuthCtrl',
                的OnEnter:['$状态','验证',函数($状态,验证){
                    Auth.currentUser()。然后(函数(){
                        $ state.go('家');
                    })
                }]
            });        $ urlRouterProvider.otherwise('家');
    }
]);
//运行块
app.run(函数($ rootScope,验证){
  //你可以在这里注入任何实例
  $ rootScope。在$('$ stateChangeStart',
    功能(事件,toState,toParams,fromState,fromParams){
        如果(!Auth.isAuthenticated()){
            //所以魔术应该可能在这里发生。但我怎么实现这个?
            //以及如何让用户访问/登录和/寄存器页?
            。事件preventDefault();
        }
  })
});


解决方案

我写的,基本上回答了这个问题(至少在高层次上)被称为的如何设置身份验证与angularJS和Ruby on Rails

如果您要检查用户是否在任何特定的路线进行身份验证,就可以(在角的标准路由器,虽然我不知道UI的路由器)使用决心。下面是我的一个旧项目一对夫妇路线:

 。当('/',{
        templateUrl:意见/ main.html中,
        控制器:'MainCtrl',
        isPublic:真
      })
      。当('/今天,{
        templateUrl:意见/ announcements.html',
        控制器:'AnnouncementsCtrl',
        解析:{
          AUTH:['$ AUTH',函数($ AUTH){
            返回$ auth.validateUser();
          }]
        }
      })

根路径是公开的,但 /今天需要验证。也许这给你足够的去对UI的路由器也是如此。附注:我真的应该更新我的文章来解释UI的路由器(或角的新路由器),因为我不认为很多人用普通的旧角路由器

修改:我记得这件事情从我的一个不同的项目。这是CoffeeScript的。无关code省略。

使用严格的

  angular.module(fooApp,[
  ngAnimate
  ngCookies
  ngResource
  ngRoute
  ngSanitize
  ngTouch
  ui.router
  NG-令牌身份验证
])
.RUN($ rootScope,$权威性,$位置) - >
  $ rootScope $的身份验证:登录不成功, - > $ location.path/
  $ rootScope $上的Auth:注销-成功。, - > $ location.path/签到
  $ rootScope $的$ stateChangeStart(事件,旁边) - GT。
    $ auth.validateUser(),然后( - >
      如果$ location.path()==/
        $ location.path/文件上传
    ), - >
      如果!next.isPublic
        $ location.path/签到

我希望它是一种不言自明的是怎么回事那里。这个项目确实使用的用户界面的路由器,因为你可以告诉 $ stateChangeStart

I'm quite new to Angular so this might be a newbie question.

I'm trying to implement a simple task manager (just an exercise) with Rails as backend and Angular as frontend. So far I followed a tutorial and everything worked fine.

Now I want to globally implement Authentication. That means: When a user is not registered and logged in, she should see a splash page or the login page.

I don't want to do that in every single Angular controller, because DRY. So I figured the UI Router might be a good place. And I have a slight suspicion that maybe $httpProvider.interceptors might be useful.

This is how far I got. I can check if a user is authenticated and prevent the page from loading. But nothing more. How would I go from here? Are there any good tutorials out there I missed?

This question on Stackoverflow goes in a similar direction but doesn't solve my problem since they are not using Devise.

Thanks!

// app.js
var app = angular.module("TaskManager", ['ui.router', 'templates', 'Devise'])
.config([
    '$stateProvider',
    '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('home', {
                url: '/home',
                templateUrl: 'home/_home.html',
                controller: 'MainCtrl', 
                resolve: {
                    projectPromise: ['projects', function(projects) {
                        console.log($rootScope);
                        return projects.getAll();
                    }]
                }
            })
            .state('projects', {
                url: '/projects/{id}',
                templateUrl: 'projects/_projects.html',
                controller: 'ProjectsCtrl',
                resolve: {
                    project: ['$stateParams', 'projects', function($stateParams, projects) {
                        return projects.get($stateParams.id);
                    }]
                }
            })
            .state('login', {
                url: '/login',
                templateUrl: 'auth/_login.html',
                controller: 'AuthCtrl',
                onEnter: ['$state', 'Auth', function($state, Auth) {
                    Auth.currentUser().then(function() {
                        $state.go('home');
                    })
                }]
            })
            .state('register', {
                url: '/register',
                templateUrl: 'auth/_register.html',
                controller: 'AuthCtrl',
                onEnter: ['$state', 'Auth', function($state, Auth) {
                    Auth.currentUser().then(function() {
                        $state.go('home');
                    })
                }]
            });

        $urlRouterProvider.otherwise('home');
    }
]);
// run blocks
app.run(function($rootScope, Auth) {
  // you can inject any instance here
  $rootScope.$on('$stateChangeStart', 
    function(event, toState, toParams, fromState, fromParams){ 
        if(!Auth.isAuthenticated()) {
            // So the magic should probably happen here. But how do I implement this?
            // And how do I allow users to access the /login and /register page?
            event.preventDefault(); 
        }
  })
});

解决方案

I wrote an article that basically answers this question (at a high level at least) called How to Set Up Authentication with AngularJS and Ruby on Rails.

If you want to check whether the user is authenticated at any particular route, you can (in Angular's standard router, although I don't know about ui-router) use resolve. Here are a couple routes from an older project of mine:

      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        isPublic: true
      })
      .when('/today', {
        templateUrl: 'views/announcements.html',
        controller: 'AnnouncementsCtrl',
        resolve: {
          auth: ['$auth', function($auth) {
            return $auth.validateUser();
          }]
        }
      })

The root route is public but /today requires authentication. Maybe that gives you enough to go on for ui-router as well. Side note: I should really update my article to account for ui-router (or Angular's new router) since I don't think many people use the regular old Angular router.

Edit: I remembered this thing from a different project of mine. This is CoffeeScript. Irrelevant code omitted.

"use strict"

angular.module("fooApp", [
  "ngAnimate"
  "ngCookies"
  "ngResource"
  "ngRoute"
  "ngSanitize"
  "ngTouch"
  "ui.router"
  "ng-token-auth"
])
.run ($rootScope, $auth, $location) ->
  $rootScope.$on "auth:login-success", -> $location.path "/"
  $rootScope.$on "auth:logout-success", -> $location.path "/sign-in"
  $rootScope.$on "$stateChangeStart", (event, next) ->
    $auth.validateUser().then (->
      if $location.path() == "/"
        $location.path "/file-uploads"
    ), ->
      if !next.isPublic
        $location.path "/sign-in"

Hopefully it's kind of self-evident what's going on there. This project DOES use ui-router, as you can tell from the $stateChangeStart.

这篇关于如何在全球范围内实现身份验证与AngularJS,设计和UI路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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