Skip to content

Instantly share code, notes, and snippets.

@AlexDaSoul
Created January 19, 2020 15:18
Show Gist options
  • Save AlexDaSoul/d7ae6bb13b147c474f8dae1953304f3d to your computer and use it in GitHub Desktop.
Save AlexDaSoul/d7ae6bb13b147c474f8dae1953304f3d to your computer and use it in GitHub Desktop.
nga-25
@Injectable({
providedIn: 'root',
})
export class AuthService {
private ngOnDestroy$ = new Subject<void>();
private loggedInSubject$ = new ReplaySubject<boolean>(1);
constructor(
private router: Router,
private logger: NGXLogger,
private authGrpcService: AuthGrpcService,
) {
}
public updateToken(): void {
const getToken = this.getToken().split('.')[1];
const jwt = JSON.parse(atob(getToken));
const now = Date.now() / 1000;
const period = Math.ceil(jwt.exp - now - environment.authDiff) * 1000;
interval(period)
.pipe(
switchMap(() => this.authGrpcService.updateAuth()),
takeUntil(this.ngOnDestroy$),
)
.subscribe(
res => localStorage.setItem(environment.token, res.token),
err => this.logger.warn(err.message));
}
public updateAuth(): Observable<AuthRes.AsObject> {
if (this.getToken()) {
return this.authGrpcService.updateAuth();
} else {
this.logout();
}
}
public isLoggedIn(): Observable<boolean> {
return this.loggedInSubject$.asObservable();
}
public loggedIn(token: string): void {
localStorage.setItem(environment.token, token);
this.loggedInSubject$.next(true);
this.updateToken();
}
public getToken(): string {
return localStorage.getItem(environment.token);
}
public logout(): void {
localStorage.removeItem(environment.token);
this.loggedInSubject$.next(false);
this.ngOnDestroy$.next();
this.router.navigateByUrl('/auth');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment