Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. @Injectable()
  2. export class UserService {
  3. private currentUserSubject = new BehaviorSubject<User>({} as User);
  4. public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());
  5.  
  6. private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
  7. public isAuthenticated = this.isAuthenticatedSubject.asObservable();
  8.  
  9. constructor(
  10. @Inject(LOCAL_STORAGE) private localStorage: any,
  11. private apiService: ApiService,
  12. private jwtService: JwtService
  13. ) {
  14. this.populate();
  15. }
  16.  
  17. // Verify JWT in localstorage with server & load user's info.
  18. // This runs once on application startup.
  19. private populate() {
  20. // If JWT detected, attempt to get & store user's info
  21. if (this.jwtService.getToken()) {
  22. this.apiService.get('Accounts/Info')
  23. .subscribe(
  24. data => this.setUser(data),
  25. err => this.purgeAuth()
  26. );
  27. } else {
  28. // Remove any potential remnants of previous auth states
  29. this.purgeAuth();
  30. }
  31. }
  32.  
  33. setUser(user: User) {
  34. // console.log(user);
  35. // // Save JWT sent from server in localstorage
  36. // this.jwtService.saveToken(user.access_token);
  37. // Set current user data into observable
  38. this.currentUserSubject.next(user);
  39. // Set isAuthenticated to true
  40. this.isAuthenticatedSubject.next(true);
  41. }
  42.  
  43. purgeAuth() {
  44. // Remove JWT from localstorage
  45. this.jwtService.destroyToken();
  46. // wipe all localstorage data
  47. this.localStorage.clear();
  48. // Set current user to an empty object
  49. this.currentUserSubject.next(null as User);
  50. // Set auth status to false
  51. this.isAuthenticatedSubject.next(false);
  52. }
  53.  
  54. attemptRegister(credentials: IRegisterUser) {
  55. return this.apiService.post('Accounts/Register', credentials);
  56. }
  57.  
  58. attemptAuth(credentials: ILoginUser): Observable<User> {
  59. // Convert json to form values instead
  60. const formValues = {
  61. grant_type: credentials.grant_type,
  62. username: credentials.Email,
  63. password: credentials.Password,
  64. };
  65.  
  66. return this.apiService.post('Accounts/Login', formValues)
  67. .pipe(map(
  68. (data) => {
  69. this.jwtService.saveToken(data.access_token);
  70. this.isAuthenticatedSubject.next(true);
  71. this.populate();
  72. return data;
  73. }
  74. ));
  75. }
  76.  
  77. getCurrentUser(): User {
  78. return this.currentUserSubject.value;
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement