-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.service.ts
183 lines (161 loc) · 5.24 KB
/
auth.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/* eslint-disable @typescript-eslint/member-ordering */
import { Injectable, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import {
BehaviorSubject,
Observable,
ReplaySubject,
Subject,
throwError
} from 'rxjs';
import {
catchError,
distinctUntilChanged, mergeMap,
takeUntil, tap
} from 'rxjs/operators';
import { environment } from '@environments/environment';
import { User, UserResponse } from '@models';
import { ApiService } from './api.service';
import { SessionService } from './session.service';
import * as _ from 'lodash';
import { encodeUserData, parseUserData } from '@utils/user';
@Injectable({
providedIn: 'root',
})
export class AuthService implements OnDestroy {
private destroy$ = new Subject<void>();
private sessionExpired = this.sessionService.expired;
// currentUser can only be set via subject in this service
private currentUserSubject = new BehaviorSubject<User>(null);
public currentUser$ = this.currentUserSubject
.asObservable()
.pipe(distinctUntilChanged(), takeUntil(this.destroy$));
// Provide the currentUser as a Promise to adapt to existing functionality
public currentUserPromise = this.currentUser$.toPromise();
public notVerifiedMsg = 'E-mail is not verified.';
// authenticated state
private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
public isAuthenticated$ = this.isAuthenticatedSubject.asObservable();
constructor(
private sessionService: SessionService,
private apiService: ApiService,
private router: Router
) {
this.sessionExpired.subscribe(() => this.logout());
}
ngOnDestroy(): void {
this.destroy$.next(undefined);
}
/**
* Sets the current user
* Updates localstorage, and provides new values for the relevant subjects
*
* @param user User object, not response data
*/
private setAuth(user: User): void {
// TODO: reinstate localStorage with session information (if needed)
// localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
this.isAuthenticatedSubject.next(true);
}
/**
* Removes current user
*/
private purgeAuth(): void {
// localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
this.isAuthenticatedSubject.next(false);
}
public setInitialAuth(): void {
this.apiService
.getUser()
.pipe(takeUntil(this.destroy$))
.subscribe(
(result) => this.setAuth(parseUserData(result)),
() => this.purgeAuth()
);
}
public getCurrentUser(): User {
return this.currentUserSubject.value;
}
public getCurrentUserPromise(): Promise<User> {
const currentUser = this.currentUserSubject.value;
return Promise.resolve(currentUser);
}
checkUser(): Observable<UserResponse> {
return this.apiService.getUser();
}
/**
* Logs in, retrieves user response, transforms to User object
*/
public login(username: string, password: string): Observable<UserResponse> {
const loginRequest$ = this.apiService.login(username, password);
return loginRequest$.pipe(
mergeMap(() => this.checkUser()),
tap((res) => this.setAuth(parseUserData(res))),
catchError((error) => {
console.error(error);
return throwError(error);
})
);
}
public logout(redirectToLogin: boolean = false) {
const isSamlLogin = this.currentUserSubject.value.isSamlLogin;
this.purgeAuth();
if (isSamlLogin) {
window.location.href = environment.samlLogoutUrl;
}
return this.apiService.logout().pipe(
tap(() => {
if (redirectToLogin) {
this.showLogin();
}
})
);
}
public register(username, email, password1, password2) {
return this.apiService.register({
username,
email,
password1,
password2,
});
}
public verify(key: string) {
return this.apiService.verify(key);
}
public keyInfo(key: string) {
return this.apiService.keyInfo(key);
}
public showLogin(returnUrl?: string) {
this.router.navigate(
['/login'],
returnUrl ? { queryParams: { returnUrl } } : undefined
);
}
public requestResetPassword(email: string) {
return this.apiService.requestResetPassword(email);
}
public resetPassword(
uid: string,
token: string,
newPassword1: string,
newPassword2: string
) {
return this.apiService.resetPassword(
uid,
token,
newPassword1,
newPassword2
);
}
public updateSettings(update: Partial<User>) {
return this.apiService.updateUserSettings(encodeUserData(update)).pipe(
tap((res) => this.setAuth(parseUserData(res))),
catchError((error) => {
console.error(error);
return throwError(error);
})
);
}
}