Skip to content

Instantly share code, notes, and snippets.

@davestacey
Created February 21, 2020 15:41
Show Gist options
  • Save davestacey/bf9c80bb3dbb24a0690f367b9f927529 to your computer and use it in GitHub Desktop.
Save davestacey/bf9c80bb3dbb24a0690f367b9f927529 to your computer and use it in GitHub Desktop.
Authentication Service
/*
posts the users credentials to the api and checks the response for a JWT token, if there is one it means authentication was successful so the user details including the token are added to local storage.
The currentUser observable can be used when you want a component to reactively update when a user logs in or out
The currentUserValue property can be used when you just want to get the current value of the logged in user,checking if the user is currently logged in.
https://jasonwatmore.com/post/2019/06/10/angular-8-user-registration-and-login-example-tutorial
*/
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '@/_models';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(username, password) {
return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username, password })
.pipe(map(user => {
// 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);
return user;
}));
}
logout() {
// remove user from local storage and set current user to null
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment