How do you load data asynchronously when loading an angular module? - angularjs

In my angular app I need to read some data from the server before I allow the rest of my application to run. For example, I need the user authenticated so I can verify their permission before I allow them access to anything. Since I need to do this on app start and I don't know what controller will be loaded first, I can't use the resolve feature of the $routeProvider.when method because I do not know which controller will be hit first, and it only occurs once on app start.
I keep steering towards doing something in the module.run method, but I can't find a way to prevent it from continuing until get the data back from the server. I found this but it suffers from the same problem: AngularJS : Initialize service with asynchronous data.
I can also do manual bootstrapping, but I can't find any good examples of how to do this. Any help you can provide would be appreciated.

The easiest way i can think of here would be to have a separate page for login. Once the user is authenticated then only allow him access to the main app (angular app).
Also you need to secure you service resources against unauthorized request. This would safeguard against your controller \ views loading unauthorized data.

Like the other answer already mentioned, you should take care of the security of your app.
Possible solutions are:
Check if the user is authenticated
Implement a authentication in your API. You can check if the user is logged in with a responseInterceptor:
.config(['$routeProvider','$httpProvider', function($routeProvider,$httpProvider) {
//setup your routes here...
var authChecker = ['$location', '$q', function($location, $q) {
//redirects the user to /login page if he's not authorized (401)
function success(response) {
return response;
}
function error(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
return function(promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(authChecker);
}])
See $http docs for more details.
Workaround: run scope
Does not solve the security issues, but is working, too:
Get your data in the run block like this:
.run(function($http,$location,$rootScope) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if($rootScope.gotData) {
$location.path(next.path);
} else {
$location.path('/loading');
}
});
$http.get('path/to/data').success(function() {
$rootScope.gotData = true;
$location.path('/home');
}).error(function() {
$location.path('/404');
})
})
see docs for further information.

Related

Angular-permission define permissions retrieved via API

I am trying to use angular-permission to implement permission-based authentication but I don't know where to define those permissions which are retrieved from my back-end via API which requires token-based access.
First, let me give a bit background about how my app looks like. On my back-end, my system portal, I define permissions to allow different APIs to be called. Permissions won't change all the time. Only when I add new features(APIs), new permissions will be added. For example.
permission1: api1,api2,api3
permission2:api4,api5,api6
permission3:api7,api8,api9
On the front-end, customers login the front-end web portal and create customized roles themselves which group some permissions together, for example:
admin: permission1,permission2,permission3
auditor:permission 3
The angular-permission doc says (https://github.com/Narzerus/angular-permission/blob/development/docs/1-manging-permissions.md#multiple-permissions) I can use PermissionStore.defineManyPermissions to define permissions which are retrieved from API after user login. That's all clear.
So I have two modules. One is the Authentication module which handles user login. The other one is the Permission module which handles the permission validation. On the Permission module .run() phase, I define the permissions like this:
var getPermissions = function () {
var deferred = $q.defer();
system.permissions.get(
function () {
return deferred.resolve(system.permissions._permissions);
},
function (error) {
console.log("error if can't load permissions");
console.log(error);
}
);
return deferred.promise;
};
var loadPermissions = function () {
var promise = getPermissions();
promise.then(function (permissions) {
var arrayPermissions = formatPermissionArray(permissions);
//var arrayPermissions=['viewSeed','viewAuthentication'];
PermissionStore.defineManyPermissions(arrayPermissions, checkPermission);
console.log("from permission run service");
console.log(arrayPermissions);
}, function (reason) {
console.log('Failed: ' + reason);
}, function (update) {
console.log('Got notification: ' + update);
});
};
loadPermissions();
var formatPermissionArray = function (sourceData) {
var formatedPermissionArray = [];
for (var i = 0; i < sourceData.length; i++) {
formatedPermissionArray.push(sourceData[i].permissionId);
};
return formatedPermissionArray;
};
But during the bootstrap of the app, this module already loaded and the arrayPermissions will be empty since user hasn't logged in yet.
I tried to use oclazyload to load the Permission module from the login controller of the Authentication module, that actually works but if user refresh/reload their page, the Permission module won't be loaded anymore.
I am new to web development and also new to AngularJs. Just a few months experience. I don't know if I am doing it in a complete wrong way.
My questions are:
The API for retrieving a permission list should require authentication? Since I will need to put those authentication on the UI-router routes. Anyone can see it anyway. If I should not protect that API, then my problem is solved.
If I should keep my api protected, how should I address the issues I described above and that is where to define the permissions for angular-permission and how to use API to retrieve the permissions.
I hope I have managed to describe my issues clearly. Any help or guidance are greatly appreciated.
Regards,
Lola
I'm using angular-permission with angular-satellizer. PermRoleStore or PermPermissionStore needs to be in run block. You can add data to JSON WEB TOKEN add use it at the run block like I did.
$auth.getPayload()This function returns payload from JWT in localStorage. And in that payload it has data with role key which I saved in backend. I hope this helps your issue.
.run(function (PermRoleStore, $auth, Yollar) {
PermRoleStore
.defineRole('ADMIN', function () {
if($auth.getPayload()) {
if ($auth.getPayload().data.role === 'ADMIN') {
return true;
}
else {
return false;
}
}
else {
return false;
}
});
PermRoleStore
.defineRole('MODERATOR', function () {
if($auth.getPayload()) {
if ($auth.getPayload().data.role === 'MODERATOR') {
return true;
}
else {
return false;
}
}
else {
return false;
}
});
})

AngularJs watch for change in variable inside a service

I have a service named loginManager which stores objects called is_logged_in & api_token along with few others. My various controllers make ajax calls using $http using the api_token.
If the api_token is reset/expired on server, response is sent as auth_error, at this point I set is_logged_in = false
What i want to achieve is, whenever is_logged_in is changed, the service redirects to /login using $location.path('/login'), i.e. to say, I want to watch the object inside the service, and invoke callback on change from service itself.
I just want the service to take care of login and corresponding routing, without any controller worrying about weather user is logged in or not.
I believe Pankaj Pakar's answer could work but you should use angular's interceptors for that. They intercept all messages. You could add hook for response or responseError and when you recieve auth_error you do any action you like. For example $location.path('/login'), display error to user, etc.
If you want to separate logic you could inject your service with all code inside and just call some method on it.
I'd suggest you to put that watcher in run phase on the angular application which will be there at a single place, by which you could check the value is_logged_in flag of service & if user is not login then redirect him/her to login page directily.
Code
app.run(function($rootScope, loginManager, $location){
$rootScope.$watch(function(){
return loginManager.is_logged_in;
}, function(newValue){
if(angular.isDefine(newValue) && !newValue)
$location.path('/login');
//$state.go('login'); //if you are using ui.router
})
})
Edit
Really curious part of your question is, from where you are changing is_logged_in flag of your service as #JBNizet asked? If any code is there is JavaScript then you should directly redirect to login page from there.
I feel the need to answer something more, Mior is quite right, but his answer needs more meat.
Here I show you how I managed to handle ALL server XHR requests with response 401 unauthorized.
First of all you need a service:
'use strict';
angular.module('theModule')
.factory('interceptorService', ['$q', '$location', function ($q, $location) {
return {
response: function (response) {
return response || $q.when(response);
},
responseError: function (rejection) {
var returnTo = $location.path().replace(/^\/|\/$/g, '');
if (returnTo === 'login') {
return;
}
if (rejection.status === 401) {
console.log('Unauthorized');
$location.path('/login').search('returnTo', returnTo);
}
return $q.reject(rejection);
}
};
}]);
This will be used to intercept all XHR calls and to change the location every time a 401 error is found.
I've also added an improvement that is the "returnTo" parameter, you will be able to use it after login to return to the previous page.
To bind it to each request you have to call the config method, this is my main javascript.
'use strict';
/**
* #author Gianmarco Laggia
*
* Main module of the application an configurations.
*/
angular
.module('theModule', [])
.config(['$httpProvider', function ($httpProvider) {
//Http Interceptor to check auth failures for xhr requests
$httpProvider.interceptors.push('interceptorService');
}]);
This is pretty much what you need to intercept every request, working on the rejection.status you can also intercept events such as server down (status is -1), internal server error (500+), success status (in the response part, status 200+) etc.

Handling session/cookie with Sails.JS and AngularJS

I'm doing a simple SPA where I am using Sails.JS for a REST API and AngularJS for my frontend.
I'm currently having some struggles with figuring out how I should handle the sessions when combining these two.
Feel free to give me some pointers if I'm going about this the wrong way.
--
Here is part of my login function. When a successfull login happens I return the user object along with a session to my client.
User.js
if(user) {
bcrypt.compare(userObj.password, user.encryptedPassword, function(err, match) {
if(err) {
res.json({rspMessage: 'Server error'}, 500);
}
if(match) {
req.session.user = user;
res.json(req.session.user); // return user data and session.
/* This returns something like this
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
user: {
username: 'admin',
id: '549f2ad213c64d3b2f3b9777'}
}
*/
}
});
}
loginService
Here is my loginService which doesn't really do much right now. I figured this is the place to keep track of the session. I'm just not sure how to go about this... There aren't many tutorials about combining Sails + AngularJS.
MyApp.factory('loginService', ['$cookieStore', '$http', '$rootScope', function($cookieStore, $http, $rootScope){
var _user = {};
return {
login: function(credentials) {
return $http.post('/user/login', credentials)
.then(function(result) {
return result.data;
});
}
}
}])
I want to check the session against my backend somehow and see if its valid or if it has expired. If the session is still valid, the user will be kept logged in even if the user closes his browser/refresh.
Suggestions, links.. anything helpful is appreciated.
Here's some tips I can give you :
Since Sails v0.10, you can use custom responses (doc page) which is a better practice than using
res.status(...);
res.json(...);
The session cookie you are creating with Sails is saved server-side. Maybe you can create a url (e.g. GET /me) to know if this session is still valid. Your Angular app would make a request to this url each time the page is loaded (in a run block I would suggest) to know if the user is still logged in server-side.
Do not hesitate if you need more precision.

How can I redirect a user to the login page using angularjs and laravel

I am working on a project using laravel and angularjs. I am using only Laravel to authenticate the users and when their logged in, then angularjs ui veiw will handle the navigation. when doing this I realized a problem, when the session has expire the user should be redirected to the logged in page based on the auth filter that is set on the route. Additionally when I checked the browser dev tool network tab, I see that the sign in page is send as a response. I am wondering how can I make my project redirect the user to the logged in page when the session has expire. how can I solve this problem and Thanks in advance for the assistance.
You can do that with $httpInterceptor, here is demo code:
var myApp = angular.module("MyApp", []);
myApp.config(function ($httpProvider, $provide) {
$provide.factory('myHttpInterceptor', function ($q, $location) {
return {
'response': function (response) {
//you can handle you sucess response here.
return response;
},
'responseError': function (rejection) {
console.log(rejection);
//if(rejection.data.xxx==="xxx")
if(rejection.status === 408){//session expired code
alert('logout!');
// clear your local data here...
$location.url("/login")
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
});
myApp.controller("MainController", function ($scope, $http) {
$scope.response = {};
$scope.triggerGet = function () {
$http.get("/my/json").success(function (data) {
$scope.response = data;
});
};
});
When your server side response is session expired, you can handle the response.status or you can handle the other data with response.data.
Here is $httpInterceptor document.(In the middle of the page)
To redirect the user client-side in JavaScript use location. https://developer.mozilla.org/en-US/docs/Web/API/Location
For this case I think you want to look at location.assign() specifically.

How to get logged user with Angular?

Maybe I am missing something very trivial, but I can't find an answer.
I am implementing a webapp based on nodejs, express and angular for the client side.
I handle my signup and sessions through passport.js. Therefore, server-side, I can access the logged user through request.user.
Now, I have a logged user which goes on its profile page, displayed through an angular view.
Here is the issue: In order to show them user information now I am thinking to send an $http request to the server, which takes the user from request and sends it back to the client where it is displayed. However, this sounds weird to me.
So here is my question: Is there any way to access the user in the session thruogh angular? If so, what user information is actually stored in the client?
Thanks in advance, and apologies if this is something too trivial to be asked:/
You will need to create a service in Angular that requests the current user, and stores the result so you can retrieve it for use in your controllers. There is nothing built in to Angular for this; you will have to create it your self. However, it's fairly straight forward.
myapp // assume was previously defined using var myapp = angular.module('myapp', []);
.factory('principal', ['$http', '$q', function($http, $q) {
var _identity = undefined;
return {
// this function returns the current _identity if defined; otherwise, it retrieves it from the HTTP endpoint
identity: function(setIdentity) {
if (setIdentity) {
_identity = setIdentity;
return;
}
var deferred = $q.defer();
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
$http.get('/path/to/endpoint')
.success(function(result) {
_identity = result;
deferred.resolve(_identity);
})
.error(function() {
_identity = undefined;
deferred.reject();
});
return deferred.promise;
}
};
}]);
This principal service has one method at the moment, identity(). This method returns a promise. If the identity has already been retrieved, it will resolve with that value immediately. If not, it will attempt to get it from an HTTP endpoint. If the HTTP call succeeds, it will memoize the result to _identity and resolve the promise. If the call fails, the promise will be rejected. identity has a secondary use. If you supply it with a single parameter, it will set that value as the identity and return nothing. This is useful if you already have the identity and want to set it right away, for example, after they successfully sign-in.
You could manage the sign-in page like this:
myapp.controller('SignInCtrl', ['$scope', 'principal', '$http', function($scope, principal, $http) {
// these two values will be bound to textboxes in the view
$scope.username = '';
$scope.password = '';
// this function will be called when the sign in form is submitted
$scope.submit = function() {
$http.post('/path/to/signin', {username: $scope.username, password: $scope.password })
.success(function(identity) {
// assumes /path/to/signin returns a JSON representation of the signed-in user upon successful authentication
// presumably the endpoint also sets a cookie representing an auth token or something of that nature. the browser will store this automatically for you
principal.identity(identity); // set the identity immediately
// do whatever else on successful login, like redirect to another route
});
}
}]);
And a controller somewhere else that needs the current identity could do something like this:
myapp.controller('MyCtrl', ['$scope', 'principal', function($scope, principal) {
// retrieve the identity. when it resolves, set user on the scope
principal.identity().then(function(identity) {
// after this, you can use user in your view or later in your controller
$scope.user = identity;
});
}]);
Now you have a way of storing the identity immediately after sign-in. I do make an assumption that your code that signs the user in sets a cookie to represent an auth token or whatever in your signin endpoint. The good thing about this is that if the user refreshes their browser, or the cookie is stored for a period of time, the user can just visit your app and the identity will resolve it using that token cookie automatically.
This plunk is a working demo of a more elaborate set up. Some of it may not apply to you (for example, it uses ui-router instead of regular routing), but it should be a reasonable reference point.

Resources