2

My app has 2 pages: main.html and login.html. When not authenticated users go to /main they should be redirected to /login.

The problem is that main.html is rendered first, and after a second or so, when user authentication fails, login.html is rendered.

How could I prevent from main.html to be rendered until authentication succeeds?

Here is the relevant code (CoffeeScript):

angular.module('myApp', [...])
.config(['$routeProvider', ($routeProvider) ->
  $routeProvider.when '/login',
    templateUrl: 'html/login.html'
    controller: LoginController

  $routeProvider.otherwise
    templateUrl: 'html/main.html'
    controller: MainController
])
.run(['$rootScope', '$location', 'appService', ($rootScope, $location, app) ->
  $rootScope.$on '$locationChangeStart', (event, newValue, oldValue) ->
    return if newValue == '/login'

    $.when(app.authenticate()).fail ->
      $location.path '/login'
      $rootScope.$apply()
])

angular.module('myApp.services').factory 'appService' , () ->
  rootRef = new Firebase('https://myapp.firebaseio.com')

  user: null
  authenticate: ->
    deferred = $.Deferred()

    authClient = new FirebaseAuthClient rootRef, (error, user) =>
      if error
        # An error occurred while attempting login
        @user = null
        deferred.reject()
      else if user
        # User authenticated with Firebase
        @user = user
        deferred.resolve()
      else
        # User is logged out
        @user = null
        deferred.reject()

    deferred.promise()
4

3 回答 3

1

main.html好吧,在用户通过身份验证之前,我不会提供模板(在您的情况下)。我在服务器上有一个用于提供模板的自定义功能,它检查用户是否经过身份验证。如果在函数中我发现用户没有登录,它会返回带有 401 状态码的响应。然后在角度代码中,我将请求保留到身份验证,然后再次请求模板。

这篇文章启发了我这样做:http: //www.espeo.pl/2012/02/26/authentication-in-angularjs-application

于 2013-02-22T14:56:34.003 回答
0

一种选择是隐藏普通 DOM 并显示“Authenticating...”消息,可能带有微调器,让用户了解他/她为什么坐在那里等待某事发生。在 main.html 中,包括以下内容:

<spinner ng-hide="appService.wrapper.user"></spinner>
<!-- everything else ng-show="appService.wrapper.user" -->

where<spinner></spinner>是一个 Angular指令,它被您的自定义“Authenticating...”消息替换,并且user是您的 appService 可用于的变量MainController。请注意,您可能需要user在 appService 中包装一个对象,如下所示:

.service('appService', function() {

  var wrapper = {
    user: null
  };

  function authenticate() {
    // start the authentication and return the promise,
    // but modify wrapper.user instead of user
  }

  return wrapper;

});

您还需要将其中一个appService或存储appService.wrapper$scope您的MainController.

于 2013-02-26T20:48:23.250 回答
0

我对相同要求的解决方案是定义以下手表:

$rootScope.$watch(
    function() {
        return $location.path();
    },
    function(newValue, oldValue) {  
        if (newValue != '/login' && user is not logged in) {
            $location.path('/login');  
        }
    },
    true);

ng-view在与索引页面(即包含指令的页面)的主体元素关联的控制器中。

于 2013-02-22T16:59:59.847 回答