Skip to content

Instantly share code, notes, and snippets.

@kudchikarsk
Created May 21, 2021 05:33
Show Gist options
  • Save kudchikarsk/80fc076765c7250588b63be84ed1d221 to your computer and use it in GitHub Desktop.
Save kudchikarsk/80fc076765c7250588b63be84ed1d221 to your computer and use it in GitHub Desktop.
authentication.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, switchMap, throwIfEmpty, tap, catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<any>;
public currentUser: Observable<any>;
private rolesSubject: BehaviorSubject<string[]> ;
public roles$ : Observable<any>;
constructor(private http: HttpClient, private userService:UserService) {
let user = JSON.parse(localStorage.getItem('currentUser'));
this.currentUserSubject = new BehaviorSubject<any>(user);
this.currentUser = this.currentUserSubject.asObservable();
let roles = JSON.parse(localStorage.getItem('roles'));
this.rolesSubject = new BehaviorSubject<string[]>(roles);
this.roles$ = this.rolesSubject.asObservable();
}
public get currentUserValue(){
return this.currentUserSubject.value;
}
login(username: string, password: string) {
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
body.set("grant_type", "password");
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
return this.http.post<any>(`${environment.apiUrl}/token`, body.toString(), options)
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.access_token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
//store roles
this.userService.getById(user.id).pipe(
map(u=>u.Roles),
catchError((e)=> of([])),
tap(roles=> localStorage.setItem('roles', JSON.stringify(roles)))
)
.subscribe(data=>this.rolesSubject.next(data));
}
return user;
}));
}
logout() {
// remove us er from local storage to log user out
localStorage.removeItem('currentUser');
localStorage.removeItem('roles');
this.currentUserSubject.next(null);
this.rolesSubject.next([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment