I have some pages in my app that should only be accessible after the user logged in. If the API indicates he uses auth, he should be shown the login page again. What are the best practices to implement this?
I know @rapropos wrote about this somewhere, but I can’t find it now
Use ionViewCanEnter. This is a nice tutorial explaining the concept.
Note that currently there might be an issue if you try to redirect to a login page within ionViewCanEnter.
Imagine I have an app with 2 tabs. The app starts on tab A where user can read and go to subpages. Tab B should be clickable, but show a register/login form when you are not logged in. Only when you are logged in tab B should load and show its content and subpages.
(I am probably just confused about the rootpage stuff…)
I found the following tutorial about how to extend the http class:
In the interceptor your could do then something like following (for each route which should be guarded…post/get/delete/put/request):
// 1. Declare observable
private requestInterceptedSource: Subject<number> = new Subject<number>();
requestIntercepted:Observable<number> = this.requestInterceptedSource.asObservable();
// Override get/post/delete/put/request like
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return super.get(url,options).catch((errorResponse:Response) => {
// If you rather like to only forward to login page on 400, just check errorResponse.status == 400 for example
this.mySource.next(errorResponse.status);
return Observable.empty();
});
}
And finally in your app.component subscribe to the observable of the http-interceptor. If something is emitted, set the root navigation to the root page aka redirect to login page if user was not authenticated to execute the http post/get/put/etc.
@Injectable()
class JWTInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}).catch(err => {
if (err instanceof HttpErrorResponse {
if (err.status === 401) {
// JWT expired, go to login
// Observable.throw(err);
}
}
})
}
}
P.S.: In the link I displayed they use next.handle(req).map( according my test that doesn’t work and should be changed with next.handle(req).do( but except that it works fine