Reputation: 5565
My login action returns information about the logged in user if they are admin or not, say (isAdmin: true)
I can keep this information between the component until a browser refresh or similar action. But I lose this information after a browser refresh. I m confused how to retain this value.
I am using localStorage
and sessionStorage
to save some non-sensitive information. But this information is sensitive and the user should not be allowed to edit/view this value.
Is there any way to accomplish this using angular2?
Upvotes: 2
Views: 7930
Reputation: 1
I saved a user profile in localStorage and I subscribed to the router events. Then I logged the events and chose the start event of the route I was having issues with. When the event occurs I reset the user profile from localStorage which satisfies my AuthGuard checks. Now anytime I refresh, my data is still there and I don't get kicked out of guarded routes.
Upvotes: 0
Reputation: 3068
sessionStorage
and localStorage
should last page reloads by design
while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.
You should get the data from API and store it in a service since a service is a singleton it means that it will available for the duration of the app and won't be persisted.
import { Injectable } from '@angular/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class StorageService {
private _isAdmin = null;
constructor(private http: Http) {}
public get isAdmin() {
// If we need to fetch the data
if (_isAdmin === null) {
return this.http.get('https://myapi.myserver.com')
.map((response) => response.json().isAdmin)
.do(isAdmin: boolean) { this._isAdmin = isAdmin);
})
return Observable.of(this._isAdmin);
}
}
You can also use angular-redux
or another storage library if you need to store more then just this bit of data
Upvotes: 0
Reputation: 20005
I would make an API call to the server or where you have the user's information each time the App starts. So, when I refresh the App I get the information from first hand and I don't have to store it in sessions, I just store the data in an object and use it.
When you login generate a token and save it in session and send it along with the API call that I mentioned earlier.
That would be my approach:
Hope it helps or at least gives you some valuable ideas... Let us know how you solve your issue! :D
Upvotes: 13
Reputation: 1008
You can't trust the client. You could create an API Service that returns a boolean value if that user is an admin, and check it if the isAdmin value isn't set.
Upvotes: 0