1
|
import {Injectable} from '@angular/core';
|
2
|
import {HttpClient, HttpResponse} from '@angular/common/http';
|
3
|
import {Observable, of} from 'rxjs';
|
4
|
import {catchError, mapTo, tap} from 'rxjs/operators';
|
5
|
import {Router} from '@angular/router';
|
6
|
import {CookieService} from 'ngx-cookie-service';
|
7
|
import {UserState} from '../states/user.state';
|
8
|
import {LoginService} from '../../shared/api/endpoints/services/login.service';
|
9
|
import {UserInfo} from '../../shared/api/endpoints/models/user-info';
|
10
|
|
11
|
@Injectable({
|
12
|
providedIn: 'root'
|
13
|
})
|
14
|
export class AuthService {
|
15
|
|
16
|
constructor(
|
17
|
private http: HttpClient,
|
18
|
private userState: UserState,
|
19
|
private router: Router,
|
20
|
private cookieService: CookieService,
|
21
|
private loginService: LoginService
|
22
|
) {
|
23
|
}
|
24
|
|
25
|
doLogin(loginInput): Observable<boolean> {
|
26
|
return this.loginService.login$Response(loginInput)
|
27
|
.pipe(
|
28
|
tap((userInfo: HttpResponse<UserInfo>) => this.setUserFromResponse(userInfo.body)),
|
29
|
mapTo(true),
|
30
|
catchError(() => {
|
31
|
return of<boolean>(false);
|
32
|
})
|
33
|
);
|
34
|
}
|
35
|
|
36
|
getUserState(): Observable<UserInfo> {
|
37
|
return this.userState.getUser$();
|
38
|
}
|
39
|
|
40
|
setUserFromResponse(userInfo: UserInfo): UserInfo {
|
41
|
this.userState.setUser(userInfo);
|
42
|
this.userState.setLoggedIn(true);
|
43
|
return userInfo;
|
44
|
}
|
45
|
|
46
|
doLogout() {
|
47
|
this.cookieService.deleteAll();
|
48
|
}
|
49
|
}
|