Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Injectable()
- export class UserService {
- private currentUserSubject = new BehaviorSubject<User>({} as User);
- public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());
- private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
- public isAuthenticated = this.isAuthenticatedSubject.asObservable();
- constructor(
- @Inject(LOCAL_STORAGE) private localStorage: any,
- private apiService: ApiService,
- private jwtService: JwtService
- ) {
- this.populate();
- }
- // Verify JWT in localstorage with server & load user's info.
- // This runs once on application startup.
- private populate() {
- // If JWT detected, attempt to get & store user's info
- if (this.jwtService.getToken()) {
- this.apiService.get('Accounts/Info')
- .subscribe(
- data => this.setUser(data),
- err => this.purgeAuth()
- );
- } else {
- // Remove any potential remnants of previous auth states
- this.purgeAuth();
- }
- }
- setUser(user: User) {
- // console.log(user);
- // // Save JWT sent from server in localstorage
- // this.jwtService.saveToken(user.access_token);
- // Set current user data into observable
- this.currentUserSubject.next(user);
- // Set isAuthenticated to true
- this.isAuthenticatedSubject.next(true);
- }
- purgeAuth() {
- // Remove JWT from localstorage
- this.jwtService.destroyToken();
- // wipe all localstorage data
- this.localStorage.clear();
- // Set current user to an empty object
- this.currentUserSubject.next(null as User);
- // Set auth status to false
- this.isAuthenticatedSubject.next(false);
- }
- attemptRegister(credentials: IRegisterUser) {
- return this.apiService.post('Accounts/Register', credentials);
- }
- attemptAuth(credentials: ILoginUser): Observable<User> {
- // Convert json to form values instead
- const formValues = {
- grant_type: credentials.grant_type,
- username: credentials.Email,
- password: credentials.Password,
- };
- return this.apiService.post('Accounts/Login', formValues)
- .pipe(map(
- (data) => {
- this.jwtService.saveToken(data.access_token);
- this.isAuthenticatedSubject.next(true);
- this.populate();
- return data;
- }
- ));
- }
- getCurrentUser(): User {
- return this.currentUserSubject.value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement