Feature/Fix: Auth service will check local storage during get user in case another window has refreshed the token

This commit is contained in:
2020-09-13 08:34:47 +05:30
parent 8b82cf8157
commit cb66700157
3 changed files with 19 additions and 8 deletions

View File

@ -16,28 +16,39 @@ export class AuthService {
public currentUser: Observable<User>;
constructor(private http: HttpClient) {
this.checkStorage();
this.currentUser = this.currentUserSubject.asObservable();
}
checkStorage(): User {
const existingToken: User = JSON.parse(localStorage.getItem(JWT_USER));
if (existingToken === null || Date.now() > existingToken.exp * 1000) {
localStorage.removeItem(JWT_USER);
this.currentUserSubject = new BehaviorSubject<User>(null);
return null;
} else {
this.currentUserSubject = new BehaviorSubject<User>(existingToken);
return existingToken;
}
this.currentUser = this.currentUserSubject.asObservable();
}
public get user(): User {
const val = this.currentUserSubject.value;
let val = this.currentUserSubject.value;
if (val == null) {
return val;
}
const expired = Date.now() > val.exp * 1000;
let expired = Date.now() > val.exp * 1000;
if (expired) {
val = this.checkStorage();
}
if (val == null) {
return null;
}
expired = Date.now() > val.exp * 1000;
if (expired) {
this.logout();
return null;
} else {
return this.currentUserSubject.value;
}
return this.currentUserSubject.value;
}
login(username: string, password: string, otp: string) {