AngularJS-logowanie i uwierzytelnianie w każdej trasie i kontrolerze

Mam aplikację AngularJS stworzoną za pomocą yeoman, grunt i bower.

Mam stronę logowania, która ma kontroler sprawdzający autentyczność. Jeśli poświadczenia są poprawne, Przekierowuję na stronę główną.

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";
        }
    }
});

Na stronie głównej Mam

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

W loginController sprawdzam dane logowania i jeśli się powiedzie, ustawiam obiekt user W service factory. Nie wiem czy to zgadza się czy nie.

To czego potrzebuję to to, że gdy użytkownik jest zalogowany, ustawia jakąś wartość w obiekcie user, aby wszystkie inne strony mogły ją otrzymać.

Za każdym razem, gdy dochodzi do jakichkolwiek zmian trasy, Kontroler powinien sprawdzić, czy użytkownik jest zalogowany, czy nie. Jeśli nie, należy przekierować na stronę logowania. Ponadto, jeśli użytkownik jest już zalogowany i wraca do strony, powinien przejść do strony głównej. Kontroler powinien również sprawdzić poświadczenia na wszystkich trasach.

Słyszałem o ng-ciasteczka, ale nie wiem jak z nich korzystać.

Wiele z przykładów, które widziałem, nie było zbyt jasnych i używały jakiegoś rodzaju ról dostępu lub czegoś takiego. Nie chcę tego. Chcę tylko filtr logowania. Czy ktoś może mi podać jakieś pomysły?

Author: UnbrandedTech, 2014-01-07

10 answers

Moje rozwiązanie dzieli się na 3 części: stan użytkownika jest przechowywany w usłudze, w metodzie run obserwujesz, gdy zmienia się trasa i sprawdzasz, czy użytkownik ma dostęp do żądanej strony, w głównym kontrolerze obserwujesz, czy zmienia się stan użytkownika.

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

Należy utworzyć usługę (nazwę ją Auth), która będzie obsługiwać obiekt user i mieć metodę, aby wiedzieć, czy użytkownik jest zalogowany, czy nie.

Serwis :

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

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

Od twój app.run, powinieneś posłuchać $routeChangeStart wydarzenia. Gdy trasa się zmieni, sprawdzi czy użytkownik jest zalogowany (metoda isLoggedIn powinna się tym zająć). Nie załaduje żądanej trasy, jeśli użytkownik nie jest zalogowany i przekieruje użytkownika na właściwą stronę (w Twoim przypadku login).

loginController powinny być używane na stronie logowania do obsługi logowania. Powinien po prostu współdziałać z usługą Auth i ustawić użytkownika jako zalogowanego lub nie.

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

Z głównego kontrolera możesz nasłuchać, jeśli zmieni się stan użytkownika i zareagować przekierowaniem.

.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);
 177
Author: gab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-29 05:54:22

Oto inne możliwe rozwiązanie, używając atrybutu resolve $stateProvider lub $routeProvider. Przykład z $stateProvider:

.config(["$stateProvider", function ($stateProvider) {

  $stateProvider

  .state("forbidden", {
    /* ... */
  })

  .state("signIn", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAnonymous(); }],
    }
  })

  .state("home", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAuthenticated(); }],
    }
  })

  .state("admin", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
    }
  });

}])

Access rozwiązuje lub odrzuca obietnicę w zależności od bieżących praw użytkownika:

.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {

  var Access = {

    OK: 200,

    // "we don't know who you are, so we can't say if you're authorized to access
    // this resource or not yet, please sign in first"
    UNAUTHORIZED: 401,

    // "we know who you are, and your profile does not allow you to access this resource"
    FORBIDDEN: 403,

    hasRole: function (role) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasRole(role)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    hasAnyRole: function (roles) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasAnyRole(roles)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAnonymous: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAnonymous()) {
          return Access.OK;
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAuthenticated: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAuthenticated()) {
          return Access.OK;
        } else {
          return $q.reject(Access.UNAUTHORIZED);
        }
      });
    }

  };

  return Access;

}])

UserProfile kopiuje bieżące właściwości użytkownika i wdraża $hasRole, $hasAnyRole, $isAnonymous i $isAuthenticated logika metod (plus metoda $refresh, wyjaśniona później):

.factory("UserProfile", ["Auth", function (Auth) {

  var userProfile = {};

  var clearUserProfile = function () {
    for (var prop in userProfile) {
      if (userProfile.hasOwnProperty(prop)) {
        delete userProfile[prop];
      }
    }
  };

  var fetchUserProfile = function () {
    return Auth.getProfile().then(function (response) {
      clearUserProfile();
      return angular.extend(userProfile, response.data, {

        $refresh: fetchUserProfile,

        $hasRole: function (role) {
          return userProfile.roles.indexOf(role) >= 0;
        },

        $hasAnyRole: function (roles) {
          return !!userProfile.roles.filter(function (role) {
            return roles.indexOf(role) >= 0;
          }).length;
        },

        $isAnonymous: function () {
          return userProfile.anonymous;
        },

        $isAuthenticated: function () {
          return !userProfile.anonymous;
        }

      });
    });
  };

  return fetchUserProfile();

}])

Auth jest odpowiedzialny za żądanie serwera, aby poznać użytkownika profil (powiązany np. z tokenem dostępowym dołączonym do żądania):

.service("Auth", ["$http", function ($http) {

  this.getProfile = function () {
    return $http.get("api/auth");
  };

}])
W związku z tym, że nie jest to możliwe, nie jest to możliwe.]}
{
  "name": "John Doe", // plus any other user information
  "roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
  "anonymous": false // or true
}

Wreszcie, gdy Access odrzuci obietnicę, jeśli użyjesz ui.router, Zdarzenie $stateChangeError zostanie wywołane:

.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {

  $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    switch (error) {

    case Access.UNAUTHORIZED:
      $state.go("signIn");
      break;

    case Access.FORBIDDEN:
      $state.go("forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

Jeśli użyjesz ngRoute, zostanie wywołane zdarzenie $routeChangeError:

.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {

  $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
    switch (rejection) {

    case Access.UNAUTHORIZED:
      $location.path("/signin");
      break;

    case Access.FORBIDDEN:
      $location.path("/forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

[[35]} do profilu użytkownika można również uzyskać dostęp w kontrolerach: [40]}
.state("home", {
  /* ... */
  controller: "HomeController",
  resolve: {
    userProfile: "UserProfile"
  }
})

UserProfile następnie zawiera zwrócone właściwości przez serwer przy żądaniu GET api/auth:

.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {

  $scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example

}])

UserProfile należy odświeżyć, gdy użytkownik loguje się lub wychodzi, aby Access mógł obsługiwać trasy z nowym profilem użytkownika. Możesz przeładować całą stronę lub wywołać UserProfile.$refresh(). Przykład przy logowaniu:

.service("Auth", ["$http", function ($http) {

  /* ... */

  this.signIn = function (credentials) {
    return $http.post("api/auth", credentials).then(function (response) {
      // authentication succeeded, store the response access token somewhere (if any)
    });
  };

}])
.state("signIn", {
  /* ... */
  controller: "SignInController",
  resolve: {
    /* ... */
    userProfile: "UserProfile"
  }
})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {

  $scope.signIn = function () {
    Auth.signIn($scope.credentials).then(function () {
      // user successfully authenticated, refresh UserProfile
      return userProfile.$refresh();
    }).then(function () {
      // UserProfile is refreshed, redirect user somewhere
      $state.go("home");
    });
  };

}])
 108
Author: sp00m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 09:18:47

Najprostszy sposób zdefiniowania niestandardowego zachowania dla poszczególnych tras byłby dość prosty:

1) routes.js: Utwórz nową właściwość (np. requireAuth) dla dowolnej pożądanej trasy

angular.module('yourApp').config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'templates/home.html',
            requireAuth: true
        })
        .when('/login', {
            templateUrl: 'templates/login.html',
        })
        .otherwise({
            redirectTo: '/home'
        });
}])

2) w kontrolerze najwyższego poziomu, który nie jest związany z elementem wewnątrz ng-view (Aby uniknąć konfliktu z angular $routeProvider), sprawdź, czy newUrl ma właściwość requireAuth i działaj zgodnie z

angular.module('YourApp').controller('YourController', ['$scope', 'session', '$location',
    function($scope, session, $location) {

        $scope.$on('$routeChangeStart', function(angularEvent, newUrl) {

            if (newUrl.requireAuth && !session.user) {
                // User isn’t authenticated
                $location.path("/login");
            }

        });
    }
]);
 18
Author: DotBot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-31 16:34:12

Napisałem post kilka miesięcy temu, jak skonfigurować funkcję rejestracji użytkowników i logowania za pomocą Angular, możesz to sprawdzić na http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx

Sprawdzam czy użytkownik jest zalogowany w zdarzeniu $locationChangeStart, Oto moja główna aplikacja.js pokazuje to:

(function () {
    'use strict';
 
    angular
        .module('app', ['ngRoute', 'ngCookies'])
        .config(config)
        .run(run);
 
    config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                controller: 'HomeController',
                templateUrl: 'home/home.view.html',
                controllerAs: 'vm'
            })
 
            .when('/login', {
                controller: 'LoginController',
                templateUrl: 'login/login.view.html',
                controllerAs: 'vm'
            })
 
            .when('/register', {
                controller: 'RegisterController',
                templateUrl: 'register/register.view.html',
                controllerAs: 'vm'
            })
 
            .otherwise({ redirectTo: '/login' });
    }
 
    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
    function run($rootScope, $location, $cookieStore, $http) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }
 
        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in and trying to access a restricted page
            var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            var loggedIn = $rootScope.globals.currentUser;
            if (restrictedPage && !loggedIn) {
                $location.path('/login');
            }
        });
    }
 
})();
 6
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-02 10:51:09

Wydaje mi się, że ten sposób jest najłatwiejszy, ale może to tylko osobiste preferencje.

Po określeniu trasy logowania (i innych anonimowych tras; np. / register, / logout, / refreshToken, itp.), dodać:

allowAnonymous: true

Więc, coś takiego:

$stateProvider.state('login', {
    url: '/login',
    allowAnonymous: true, //if you move this, don't forget to update
                          //variable path in the force-page check.
    views: {
        root: {
            templateUrl: "app/auth/login/login.html",
            controller: 'LoginCtrl'
        }
    }
    //Any other config
}

Nigdy nie musisz określać "allowAnonymous: false", jeśli nie jest obecny, zakłada się, że false, w sprawdzaniu. W aplikacji, w której większość adresów URL jest wymuszona, jest to mniej pracy. I bezpieczniejsze; jeśli zapomnisz dodać go do nowego adresu URL, najgorsze, co może się zdarzyć, to anonimowy adres URL jest chroniony. Jeśli zrobisz to w inny sposób, określając "requireAuthentication: true" i zapomnisz dodać go do adresu URL, wyciekasz wrażliwa strona do publicznej wiadomości.

Następnie uruchom to tam, gdzie uważasz, że najlepiej pasuje do twojego projektu kodu.

//I put it right after the main app module config. I.e. This thing:
angular.module('app', [ /* your dependencies*/ ])
       .config(function (/* you injections */) { /* your config */ })

//Make sure there's no ';' ending the previous line. We're chaining. (or just use a variable)
//
//Then force the logon page
.run(function ($rootScope, $state, $location, User /* My custom session obj */) {
    $rootScope.$on('$stateChangeStart', function(event, newState) {
        if (!User.authenticated && newState.allowAnonymous != true) {
            //Don't use: $state.go('login');
            //Apparently you can't set the $state while in a $state event.
            //It doesn't work properly. So we use the other way.
            $location.path("/login");
        }
    });
});
 2
Author: Yurelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-04 19:47:03

App.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
  $routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
    $routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});


  $routeProvider.otherwise({redirectTo: '/login'});


}]);


app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    var salesnew=['/salesnew'];
    var salesview=['/salesview'];
    var users=['/users'];
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1
        || salesview.indexOf($location.path()) !=-1
        || salesnew.indexOf($location.path()) !=-1
        || users.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data)
                {
                    $location.path('/login');
                }

            });
        }
    });
});

LoginServices.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }          
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }                  
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

SessionServices.js

'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

LoginCtrl.js

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };

}]);
 1
Author: Jaydeep Gondaliya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-22 06:58:43

Na przykład aplikacja ma dwóch użytkowników o nazwie ap i auc. Przekazuję dodatkową właściwość do każdej trasy i obsługuję routing na podstawie danych, które dostaję w $routeChangeStart.

Spróbuj tego:

angular.module("app").config(['$routeProvider',
function ($routeProvider) {

    $routeProvider.
            when('/ap', {
                templateUrl: 'template1.html',
                controller: 'template1',
                isAp: 'ap',
            }).
            when('/auc', {
                templateUrl: 'template2.html',
                controller: 'template2',
                isAp: 'common',
            }).
            when('/ic', {
                templateUrl: 'template3.html',
                controller: 'template3',
                isAp: 'auc',
            }).
            when('/mup', {
                templateUrl: 'template4.html',
                controller: 'template4',
                isAp: 'ap',
            }).

            when('/mnu', {
                templateUrl: 'template5.html',
                controller: 'template5',
                isAp: 'common',
            }).                               
            otherwise({
                redirectTo: '/ap',
            });
   }]);

App.js:

.run(['$rootScope', '$location', function ($rootScope, $location) {                
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        if (next.$$route.isAp != 'common') {
            if ($rootScope.userTypeGlobal == 1) {
                if (next.$$route.isAp != 'ap') {
                    $location.path("/ap");
                }
            }
            else {
                if (next.$$route.isAp != 'auc') {
                    $location.path("/auc");
                }                        
            }
        }

    });
}]);
 0
Author: suresh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-25 10:25:26

Wszyscy zaproponowali Duże rozwiązanie, dlaczego martwisz się o sesję po stronie klienta. Chodzi mi o to, gdy zmienia się stan/url, przypuszczam, że robisz wywołanie ajax, aby załadować dane dla tempelate.

Note :- To Save user's data you may use `resolve` feature of `ui-router`.
 Check cookie if it exist load template , if even cookies doesn't exist than 
there is no chance of logged in , simply redirect to login template/page.

Teraz dane ajax są zwracane przez serwer przy użyciu dowolnego api. Teraz punkt wszedł w grę , zwraca standardowe typy zwrotów za pomocą serwera zgodnie ze statusem zalogowanego użytkownika. Sprawdź te kody zwrotne i przetworz żądanie w kontrolerze. Uwaga: - dla kontrolera, który nie wymaga wywołania ajax natywnie, możesz wywołać puste żądanie na serwer w ten sposób server.location/api/checkSession.php i to jest checkSession.php

<?php/ANY_LANGUAGE
session_start();//You may use your language specific function if required
if(isset($_SESSION["logged_in"])){
set_header("200 OK");//this is not right syntax , it is just to hint
}
else{
set_header("-1 NOT LOGGED_IN");//you may set any code but compare that same       
//code on client side to check if user is logged in or not.
}
//thanks.....

Po stronie klienta wewnątrz kontrolera lub za pośrednictwem jakiejkolwiek usługi, jak pokazano w innych odpowiedziach

    $http.get(dataUrl)
    .success(function (data){
        $scope.templateData = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status);
if(status == CODE_CONFIGURED_ON_SERVER_SIDE_FOR_NON_LOGGED_IN){
//redirect to login
  });

Uwaga: - zaktualizuję więcej jutro lub w przyszłości

 0
Author: Ravinder Payal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 15:55:02

Możesz użyć resolve:

angular.module('app',[])
.config(function($routeProvider)
{
    $routeProvider
    .when('/', {
        templateUrl  : 'app/views/login.html',
        controller   : 'YourController',
        controllerAs : 'Your',
        resolve: {
            factory : checkLoginRedirect
        }
    })
}

I, funkcja rozwiązania:

function checkLoginRedirect($location){

    var user = firebase.auth().currentUser;

    if (user) {
        // User is signed in.
        if ($location.path() == "/"){
            $location.path('dash'); 
        }

        return true;
    }else{
        // No user is signed in.
        $location.path('/');
        return false;
    }   
}

Firebase ma również metodę, która pomaga zainstalować obserwatora, radzę zainstalować go wewnątrz .run:

.run(function(){

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            console.log('User is signed in.');
        } else {
            console.log('No user is signed in.');
        }
    });
  }
 0
Author: Diogo Machado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-23 19:12:08

Należy sprawdzić uwierzytelnianie użytkowników w dwóch głównych witrynach.

  • Gdy użytkownik zmienia stan, sprawdzanie go za pomocą '$routeChangeStart' callback
  • gdy żądanie $ http jest wysyłane z angular, za pomocą Interceptora.
 -1
Author: levi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-20 18:27:26