I have authentication set up in such a way that I want to prevent any route/state from loading until I know that the user is authorized to access the page. If they are, then the requested page should load, if not, then it should go to the login page.
My config function:
$stateProvider
.state('login', {
url: '/login',
templateUrl : 'login.html',
controller : 'loginController',
data: {
authorizedRoles: [USER_ROLES.guest]
}
})
.state('home', {
url: '/',
templateUrl : 'home.html',
controller : 'homeController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
})
.state('admin', {
url: '/admin',
templateUrl : 'admin.html',
controller : 'adminController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
});
$urlRouterProvider.otherwise('/login');
$locationProvider.html5Mode(true);
My run function:
$rootScope.$on('$stateChangeStart', function(event, next) {
event.preventDefault();
function checkAuthorization() {
if(!AuthService.isAuthorized(authRole)) {
$state.go('login');
} else {
$state.go(next.name);
}
}
if(AuthService.getRoleId() === undefined) {
// We'll have to send request to server to see if user is logged in
AuthService.checkLogin().then(function(response) {
checkAuthorization();
});
} else {
checkAuthorization();
}
})
If I keep the event.preventDefault() in my run function, then the app will be stuck in a loop always going to the requested state. If I remove the event.preventDefault() statement then the app will load the view (which will be visible for a second) before realizing the user should not be allowed to view it (and then go to the correct state).
How can I solve this problem?
You should use resolve and make request to the server to see if user is logged in the resolve
https://github.com/angular-ui/ui-router/wiki#resolve
.state('whatever',{
...
promiseObj: function($http){
// $http returns a promise for the url data
return $http({method: 'GET', url: '/someUrl'}).$promise;
},
...
}
OR
if you have make a call in the controller, make the call in resolve in state, in which your api should response with a 401 if user is not login in and redirect to the log in screen if you have an intercept service.
There is detailed explanation how to do this kind of resolve/wait stuff in this Q & A with working plunker.
An extracted version of the Auth service is:
.factory('userService', function ($timeout, $q) {
var user = undefined;
return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();
// later we can use this quick way -
// - once user is already loaded
if (user) {
return $q.when(user);
}
// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)
return deferred.promise;
},
// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};
})
where the most important parts are
var user = undefined; - "global" variable which is
containing user and can answer if he has rights
does not contain user (yet) and the answer is "not authorized" then
returned service function: isAuthenticated
That should solve the issue. check more details here
Related
I'm working on an AngularJS 1.5.3 project.
There is one page in my app that needs some server information before going to the page. It's kind of like a route guard. No other pages need this information before proceeding.
How can I get this to work in my route resolve? Is this a valid approach to this problem?
e.g.
.state('verifyCredentials', {
url: '/verifyCredentials',
templateUrl: 'verifyCredentials/verify-credentials.html',
controller: 'VerifyCredentialsController',
controllerAs: 'verifyCredentialsController',
resolve: {
//calls http request
authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
//$state.go('home);
} else {
//proceed to verify credentials
}
})
}
})
An AngularJS (1.x) resolve: block is an object on a state definition. Each key is the name of some data to load, and each value is a function which returns a promise for the data.
Resolve functions are injected using Angular’s injector.
An example can be found in the ui-router tutorial.
You are not providing a valid object to your resolve. The authentication should be a value to a key. Here is how your resolve should look.
.state('verifyCredentials', {
url: '/verifyCredentials',
templateUrl: 'verifyCredentials/verify-credentials.html',
controller: 'VerifyCredentialsController',
controllerAs: 'verifyCredentialsController',
resolve: {
authenticate: function(authentication, $state) { // you'll need to inject $state
and your authentication service here if you want to use them.
return authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
$state.go('home');
} else {
//proceed to verify credentials
}
});
}
})
Another possibility is to use the redirectTo method on the state object in order to redirect to a different state depending on the resolve.
Use the redirectTo with the resolve like so:
.state('verifyCredentials', {
resolve: {
authResolve: function(authenticate) {
return authentication.getInfo();
}
},
redirectTo: (trans) => {
// getAsync tells the resolve to load
let resolvePromise = trans.injector().getAsync('authResolve')
return resolvePromise.then(resolveData => {
return resolveData.loggedIn === true ? 'home' : null; // go to home if logged in, else stay on this route in order to continue with credentials flow.
)}
})
Here is how the doc recommend to handle resolves. They use component architecture.
.state('verifyCredentials', {
url: '/verifyCredentials',
component: 'verifyCredentialsComponent',
resolve: {
authenticateData: function(authentication, $state) { // you'll need to inject $state
and your authentication service here if you want to use them.
return authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
$state.go('home');
} else {
//proceed to verify credentials
}
});
}
})
// component
angular.module('app').component('verifyCredentialsComponent', {
bindings: {
authenticateData: '<'
},
template: '<div></div>'
controller: function() {
...
}
})
My angular application is divided into 4 modules and all modules require user details so I am calling getUser method from each of the module. So when my application loads all 4 modules hit the getUser API simultaneously resulting in 4 get requests on server. How can I prevent this ? I am using singleton pattern in my getUser method so once my user gets loaded it will simply serve the user from an object. But that does not solves the problem if all modules request for the user simultaneously.
My code looks like this
getUser() {
let defer = this.q.defer();
if (!this.user) {
this.http.get(`${this.config.apiHost}users`)
.success(result => {
this.user = result;
this.rootScope.$broadcast('userFound', this.user);
defer.resolve(this.user);
})
.error(err => defer.reject(err))
}
else {
defer.resolve(this.user);
this.rootScope.$broadcast('userFound', this.user);
}
return defer.promise;
}
By storing the current request in a variable the call to UserService.get will return the same request promise.
Then when the promise resolves, it will resolve to all your modules.
angular.module('app').service('UserService', function ($http) {
var self = this;
var getRequestCache;
/**
* Will get the current logged in user
* #return user
*/
this.get = function () {
if (getRequestCache) {
return getRequestCache;
}
getRequestCache = $http({
url: '/api/user',
method: 'GET',
cache: false
}).then(function (response) {
// clear request cache when request is done so that a new request can be called next time
getRequestCache = undefined;
return response.data;
});
return getRequestCache;
};
});
You are using ui-router for the routing. You can then use this to resolve the user when landing on the page.
In your routing config :
$stateProvider
.state('myPage', {
url: '/myPage',
templateUrl: 'myPage.html',
controller: 'myCtrl',
resolve: {
userDetails: ['UserService', function(UserService) {
return UserService.getUserDetails();
}],
}
})
In your controller
angular.module('myModule')
.controller('myCtrl', ['userDetails', function(userDetails) {
console.log(userDetails);
}];
This will load the user details while loading the page.
I solved this problem by using defer object as a global object so that it only gets initialised once.
In my app i want to resolve a few things before the front page loads. on my other pages its easy for me as i use this function in my resolve:
userAccount.$inject = ['userService','authService'];
function userAccount(userService, authService) {
return authService.firebaseAuthObject.$requireAuth()
.then(function(response) {
return userService.getAccount(response.uid).$loaded();
});
}
And it requires Authorisation, once promise is returned it gets the user data in firebase i saved elsewere. And if the promise is revoked it wont load that page.
But on the home page i want to check if user is logged in, If the user is logged in, grab the users data and goto the page. BUT if the user is not logged in, still go to the page just the user data will be empty.
I currently am using this to check Auth:
checkAuth.$inject = ['userService', 'authService'];
function checkAuth(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
}
Which works good, but i still want to resolve the users data before loading the page only IF the user is logged in.
I assumed that this was my answer:
checkAuth.$inject = ['userService','authService'];
function checkAuth(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
.then(function(response) {
return checkAuth.getAccount(response.uid).$loaded();
});
}
Which would wait for the promise then load in the users data, but unfortunately this doesnt work.
Any ideas on how i can retrieve the users data once the $waitforauth() function has run, the key is i want to resolve this data before the page loads.
Thanks guys
my state that also doesnt work:
.state('home', {
url: '/',
templateUrl: '/views/main.html',
controller: 'MainCtrl as vm',
resolve: {
checkAuth: checkAuth,
userAccount: function(checkAuth){
console.log(checkAuth);
if(checkAuth){
// grab user data
} else {
return false;
}
}
}
})
This got it done for me.
State:
.state('main', {
url: '/',
templateUrl: '/views/main.html',
controller: 'MainCtrl as vm',
resolve: {
userAccount: userAccountMain
}
})
Function:
userAccountMain.$inject = ['userService', 'authService'];
function userAccountMain(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
.then(function(response){
if(response){
return userService.getAccount(response.uid).$loaded();
} else {
return false;
}
});
}
I've made an AuthService that should help me take care of all authentication matters like logging in, registering, getting user data from server etc.
I am looking for a solution that runs only on login, on page refresh and when triggered to refresh get the user data from the service and make it available on the controllers that i include the service to. I would like to have something like vm.user = AuthService.getUserData() and this returns the session variable from the service. Something like this:
function getUserData(){
if (session) {
return session.user;
}
return null;
}
On $rootScope.$on('$stateChangeStart' i have :
AuthService.loadSessionData();
Which translates to:
function loadSessionData() {
$http({
url: API.URL+'auth/session-data',
method: 'GET'
})
.success(function(response)
{
session = response;
})
.error(function(err){
console.log(err);
});
};
One of the issues here are that i have to set a timeout on AuthService.getUserData() because when this executes, the call that retrieves the session data from the server is not finished yet, but this is a bad practice.
Here is the complete service code http://pastebin.com/QpHrKJmb
How about using resolve? If I understood correctly you wish to have this data in your controller anyway.
You can add this to your state definitions:
.state('bla', {
template: '...'
controller: 'BlaCtrl',
resolve: {
user: ['AuthService', function(AuthService) {
return AuthService.loadSessionData();
}
}
}
also, alter your loadSessionData function: (make sure to inject $q to AuthService)
function loadSessionData() {
return $q(function(resolve, reject) {
$http({
url: API.URL + 'auth/session-data',
method: 'GET'
})
.success(function(response)
{
if (response) {
resolve(response);
} else {
reject();
}
})
.error(function(err){
reject(err);
});
})
}
Lastly, add the user object from the resolve function to you controller:
app.contoller('BlaCtrl', ['$scope', 'user', function($scope, user) {
$scope.user = user;
}]);
What does this accomplish?
In case the user does not have a valid session or an error occurs, the state change is rejected and the event $stateChangeError is thrown. You can listen (like you did for $stateChangeStart for that event and respond with a modal, redirect to an error page, or whatever.
You only pull the session for states that needs it - not for every state change.
The state is not resolved until the user data is resolved as well (either by resolve or reject).
You should call loadSessionData() in getUserData()
function getUserData(){
loadSessionData()
.success(function(response)
{
if (response) {
return response.user;
}
})
return null;
}
and
function loadSessionData() {
return $http.get(API.URL+'auth/session-data');
};
I am trying to do some authentication with AngularUI Router. $urlRouter.sync() looks like exactly what I need. However, that's only available when I intercept $locationChangeSuccess. But when I do that, $state.current.name is empty, whereas I want it to be the current state.
Here's my code so far:
$rootScope.$on('$locationChangeSuccess', function(event, next, nextParams) {
event.preventDefault();
if ($state.current.name === 'login') {
return userService.isAuthenticated().then(function(response) {
var authenticated;
authenticated = response.authenticated;
return alert(authenticated);
});
}
});
Any pointers as to what I'm doing wrong?
I would suggest to go more "UI-Router way". We should use $rootScope.$on('$stateChangeStart' event where $state.current would be properly provided. Here is a working example
Let's observe simple (but not naive) solution, which could be extended to any degree later. Also if you will like this approach, here is much more comprehensive implementation: angular ui-router login authentication
Firstly, let's have our user service defined like this:
.factory('userService', function ($timeout, $q) {
var user = undefined;
return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();
// later we can use this quick way -
// - once user is already loaded
if (user) {
return $q.when(user);
}
// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)
return deferred.promise;
},
// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};
})
So, we use async (here $timeout) to load user object form a server. In our example it will have a property {isAuthenticated: false }, which will be used to check if is authenticated.
There is also sync method isAuthenticated() which, until user is loaded and allowed - always returns false.
And that would be our listener of the '$stateChangeStart' event:
.run(['$rootScope', '$state', 'userService',
function ($rootScope, $state, userService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams
, fromState, fromParams) {
// if already authenticated...
var isAuthenticated = userService.isAuthenticated();
// any public action is allowed
var isPublicAction = angular.isObject(toState.data)
&& toState.data.isPublic === true;
if (isPublicAction || isAuthenticated) {
return;
}
// stop state change
event.preventDefault();
// async load user
userService
.getAuthObject()
.then(function (user) {
var isAuthenticated = user.isAuthenticated === true;
if (isAuthenticated) {
// let's continue, use is allowed
$state.go(toState, toParams)
return;
}
// log on / sign in...
$state.go("login");
})
...
What we are checking first, is if user is already loaded and authenticated (var isAuthenticated = ...). Next we will give green to any public method. This is done with the data {} property of the state object definition (see Attach Custom Data to State Objects)
And that's it. In case of states defined like in a below snippet we can experience:
the 'public', 'home' are allowed to anybody
the 'private', 'private' will redirect to login if isAuthenticated === false
the 'login' in this example provides quick way how to switch isAuthenticated on/off
// States
$stateProvider
// public
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
data: { isPublic: true },
})
.state('public', {
url: "/public",
templateUrl: 'tpl.html',
data: { isPublic: true },
})
// private
.state('private', {
url: "/private",
templateUrl: 'tpl.html',
})
.state('private2', {
url: "/private2",
templateUrl: 'tpl.html',
})
// login
.state('login', {
url: "/login",
templateUrl: 'tpl.html',
data: { isPublic: true },
controller: 'loginCtrl',
})
Check that all here
Some other resources:
angular ui-router login authentication
Angular UI Router: nested states for home to differentiate logged in and logged out
other state data and authentication