I
I
Ivan Stroykin2017-01-24 17:06:12
Angular
Ivan Stroykin, 2017-01-24 17:06:12

How to correctly check authorization when initializing an application (Angular2)?

Good day,
During the initialization of the application, I make a request to the backend to get the navigation menu (different depending on the role)

providers: [
    provide: APP_INITIALIZER,
    useFactory: (service: GlobalService) => () => service.init(),
    deps: [GlobalService], multi: true,
]

init(): Promise<any> {
        var promise = this.http.get('/api/menu_navigation').map(res => res.json()).toPromise();
        promise.then(data => this.menuNavigation = data.menu_navigation);
        return promise;
    }

Everything is fine, but if the user is not authorized, the backend does not let him in (302). Here, either add a decorator to the method to skip unauthorized ones, but these are extra empty requests. Or do it right and check whether the user is authorized at the stage of application initialization. If not, then just redirect to /login ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2017-01-24
@StivinKing

Strange, apparently somewhere the first time he made a mistake.
In general, who will be interested or can help someone. In init, we simply write a condition, something like:
And then all the redirection work is done by routing, immediately after the application is fully initialized.
The isLoggedIn () method is a normal return of a private property, which is defined as follows:

set loggedIn(val: boolean) {
     if (typeof val == 'undefined') {
         val = !!this.cookie.getObject('loggedIn');
     } else {
         this.cookie.putObject('loggedIn', val);
     }
     this._loggedIn = val;
 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question