Hi,
I have a problem with my authentication.
I use storage for set and retrieve my auth-token.
My problem is that when i call isAuthenticated() I make
this.storage.get(TOKEN_KEY).then((result) => {
if (result) {
this.token=result;
}
});
if(this.token){
return true;
}else{
return false;
}
but my function return before the variable is set…how can i make
Try something like that:
Create a user provider, so you can use it from your login controller and save the token in the storage.
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
import { Storage } from '@ionic/storage';
import { Observable } from '../../../node_modules/rxjs/Observable';
@Injectable()
export class User {
constructor(
public api: Api,
public storage: Storage,
) {}
/**
* Send a POST request to our login endpoint with the data
* the user entered on the form.
*/
login(accountInfo: any) {
return Observable.create(observer => {
let seq = this.api.post('ibizapi/login', accountInfo).share();
seq.subscribe(
(res: any) => {
if ( res['access_token'] ) {
this.storage.set('access_token', res.access_token);
return seq;
}
}, (err) => {
observer.error(err);
},
()=>{
return true;
}
);
});
}
/**
* Log the user out, which forgets the session
*/
logout(): void {
userData.storage.remove('refresh_token');
};
public getToken() {
return this.storage.get('access_token');
}
}
Create an interceptor who allways add your token on all your http calls, this interceptor use use the User provider to get from the storage your token and make the call until the storage had responded.
import { Injectable, Injector} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { HttpEvent, HttpInterceptor, HttpErrorResponse, HttpHandler, HttpRequest} from '@angular/common/http';
import { User } from '../../providers';
import 'rxjs/add/operator/do';
@Injectable()
export class YourHttpInterceptor implements HttpInterceptor {
/*
* By using the YourHttpInterceptor interceptor we transform every
* request coming from the application adding the authorization header
* before it is actually submitted to the backend.
*/
private User;
constructor(
private injector: Injector,
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.User = this.injector.get(User);
return fromPromise(this.User.getToken())
.switchMap((token) =>
{
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
return next.handle(request).do(() => {}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401 && err.url && err.url.indexOf('yourapp.com') >= 0 && !this.User.loggingOut) {
this.User.logout();
}
}
});
}
);
}
}
Hope this hepl you, btw sorry for my bad english.