AngjularJs current user solution - angularjs

I am new to AngularJs. My question is how to store current user data after user logged in?
I have come across lots of solutions recommending the use of service, and inject the service into controllers. Something like this:
customer.factory('service', function(){
var auth = {};
auth.currentUser = null;
auth.setCurrentUser = function(data){
auth.currentUser = data;
};
return auth;
})
This worked perfectly for me until I hit the refresh button of the browser, all information stored in Javascript variable are lost.
To solve this problem, do I have to use $cookieStore or something similar? I have seen few people mentioning ui-route, I can't quite get my head around it. Is ui-route relevant to this discussion? Also I would like to use the same solution to save authentication token for the logged in user.
What is your general opinion around this issue? Thank you so much in advance.

Ui-route
I think you mean AngularUI Router which is a routing framework for AngularJS. It has got nothing to do with persistent storage.
Services
Angular Services are singletons. It is used to organize and share code across your app. It is instantiated when a component such as a controller needs it. Once you close your app or reload it, the data in it is lost and it is re-instantiated when needed.
Then how to persist data?
Using $cookies
Get angular-cookies.js
Include the dependency in your app angular.module('app', ['ngCookies']);
Include $cookies dependency in you controller or service (where you want to access the cookies)
//Getting a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');`
See documentation.
Using HTML5 Local Storage
"With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per domain. All pages, from one domain, can store and access the same data." - via W3Schools
While you can use pure JS for local storage, ngStore is a library that you can use with AngularJS. It provides you with localStorage and sessionStorage .
$localStorage - stores data with no expiration date
$sessionStorage - stores data for one session (data is lost when the tab is closed)
Dependency for your app:
angular.module('app', ['ngStorage']);
Then
$localStorage.visitorCount = 500;

Related

Parsing Oauth 2.0 return parameters in angular-ui-router

I'm attempting to authenticate a user using Google's Oauth 2.0 API. When my app HREF's to the Google authentication page, it successfully passes information back to my AngularJS app. However, I'm not sure how best to handle the returned URL-encoded data.
This is the format it is returned as:
#access_token=...
&token_type=Bearer
&expires_in=3600
My main problem is that this string begins with # instead of ? as is traditionally done with URL encoded parameters.
In my stateProvider config, I've implemented the callback state as such:
.state 'auth.googlecallback',
url: '/googlecallback/#{accessToken}&token_type={tokenType}&expires_in={expiresIn}'
templateUrl: 'views/auth/googlecallback.html'
controller: 'GoogleCallbackCtrl as gVm'
The above URL is an example of what I have tried. When the url is simply /googlecallback/, the page loads successfully, even when navigated to using the Google Oauth link. But the moment I had the # symbol, the state breaks and I can't parse the state params for the data inside.
I've looked into using the angular-oauth library on GitHub, but it hasn't been updated in 2 years, and it doesn't appear to allow Oauth authentication for more than just Google (I want to use Facebook and Google).
What is the correct way to handle the the Oauth URL data in angular-ui-router?
To be frank, I don't think this will actually answer your question, but I was helping some friends with this earlier today. They were unable to handle the URI via the ui-router. Instead, they had to delegate parsing the parameters and making the appropriate request to their view controller. Using the Angular $location service and some remapping functions, we were able to get the parameters out of the # query syntax into a hash that he was able to push back to the server in his request. The code looked similarly to the following:
var paramsArray = $location.hash().split('&')
var payload = {};
angular.forEach(paramsArray, function (param) {
var arr = param.split('='),
key = param[0],
value = param[1];
payload[key] = value;
});
This could absolutely be simplified but this was what he was trying to accomplish for his strategy.
That all being said, I'm personally not a fan of trying to accomplish OAuth strategy on the client. You have private keys that usually need to get exchanged to complete the full handshake. If possible, it would be best if you did the following:
Redirect the client to the appropriate OAuth path
Have the redirect go to a server endpoint that can process the oauth request and complete the handshake.
Have the server endpoint that the oauth request redirected to, redirect to your success landing page with any additional response
objects required by your application.
Doing this would protect your private keys and most web frameworks have modules/packages/gems/plugins/etc. for implementing oauth for all the mainstream providers. Hope this helps you in the right direction.

How to retain data securely on browser refresh in angularja?

I have authorization data received after calling service. On browser refresh I want retain the data securely and avoid a service call. Please suggest.
Depends upon your requirements if you want to do with angularjs cookie you can go with it or if you can also use local storage.
You can use:
localStorage.setItem('data', data);
or
$window.localStorage.data = JSON.stringify(data);
It won't get deleted on page refresh. You can see data in local storage.
You can use cookies as well, those are used for authorization mostly, it is secure than local storage as well as they can be expired in some time.

Accessing Session values in Angular.js

I am unable to access the session values which is set by node.js in Angular.js controller. I am using the Express framework. How to resolve it? Here is my code.
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERTY',
cookie: { httpOnly: false }
}));
//setting the values
cookies.set('username',username);
req.session.username=username;
Presumably you want to do something like show the username in your angular app. As I mentioned in this answer, the hard part to Angular is not thinking about what data the server has, but thinking about data the server should provide to the browser via API.
My general model is to have the angular page start up without any data and have a low-level controller invoke a service (say AuthenticationService or IdentityService) that requests relevant data from the server, e.g. HTTP GET /api/identity. That will return a block of JSON that the page can then store in that low-level controller. Any deeper controller can then access the identity (or whatever) data loaded in that first request.

Appending Param to AngularJS REST Queries

I'm using AngularJS with UI-Router and am attempting to attach a query parameter to a url on all http requests across my site.
I have an OAuth system on the backend and was previously applying Authorization headers to all requests, however to preserve backwards compatibility - have discovered I will have to instead apply a url parameter with the user identification to the backend.
My issue is that, I cannot use $httpInterceptor in the config portion of the app, because at that point in the app I don't have the current User, and can't inject $http to resolve the current user because that creates a circular dependency.
I was trying to use $http.defaults.transformRequest in the run portion of the app, but that didn't seem to be able to append a parameter to the url.
Is there a way to do this short of hand writing it on every REST request across the app?
I had similar problem in my current project.
To solve the problem I manually request current user info before app bootstapping & store it in localStorage.
Then bootstrap the app & in the config section you will have accesss to current user info.
TIP: to get user info before app bootstrap you can still use $http service by manually injecting it:
angular.injector(['ng']).get('$http');

Angular JS: How to get values in Cookies in different pages once it is set after login

I am using Angular JS to develop a application. I want to maintain some useful data in cookies so that I can use it through whole application after user login. I have tried for $cookies and $cookieStore but not able to access the stored data in login to other pages, it is coming as undefined.
Can anyone please help me and let me know how I can access the cookies in different pages which set after login?
Thanks in advance.
-Sachin
Why using cookies ? Do you need that data on backend ?
If you just need that data on frontend, why not using a service ?
Like this :
angular.module('myApp').value('globalData', {data1:data1_value, data2:data2_value});
Services are singleton so you just have to inject your service when needed and clean it on logout.
Example on a controller :
angular.module('myApp')
.controller('myCtrl', function ($scope, globalData) {
$scope.data1 = globalData.data1;
});

Resources