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 {User} from '../models/user';
|
10
|
import {GlobalVariable} from '../../globals';
|
11
|
import {UserCookie} from '../../shared/api/endpoints/models/user-cookie';
|
12
|
|
13
|
@Injectable({
|
14
|
providedIn: 'root'
|
15
|
})
|
16
|
export class AuthService {
|
17
|
|
18
|
constructor(
|
19
|
private http: HttpClient,
|
20
|
private userState: UserState,
|
21
|
private router: Router,
|
22
|
private cookieService: CookieService,
|
23
|
private loginService: LoginService
|
24
|
) {
|
25
|
}
|
26
|
|
27
|
setFromCookie() {
|
28
|
const user: User = {
|
29
|
userCookie: {
|
30
|
rightsID: JSON.parse(localStorage.getItem(GlobalVariable.RIGHTS)),
|
31
|
language: this.cookieService.get(GlobalVariable.LANGUAGE),
|
32
|
audio: JSON.parse(this.cookieService.get(GlobalVariable.AUDIO)),
|
33
|
sessionid: this.cookieService.get(GlobalVariable.SESSION_ID)
|
34
|
},
|
35
|
isLoggedIn: true
|
36
|
}
|
37
|
this.userState.setUser(user);
|
38
|
}
|
39
|
|
40
|
getUser() {
|
41
|
console.log('Auth Service');
|
42
|
if (!this.userState.getUser() && this.cookieService.get(GlobalVariable.SESSION_ID)) {
|
43
|
console.log('Session in cookie!');
|
44
|
this.setFromCookie();
|
45
|
}
|
46
|
return this.userState.getUser();
|
47
|
}
|
48
|
|
49
|
getUserState(): Observable<User> {
|
50
|
return this.userState.getUser$();
|
51
|
}
|
52
|
|
53
|
doLogin(loginInput): Observable<boolean> {
|
54
|
return this.loginService.login$Response(loginInput)
|
55
|
.pipe(
|
56
|
tap((userCookie: HttpResponse<UserCookie>) => this.setUserFromResponse(userCookie.body, loginInput.username)),
|
57
|
mapTo(true),
|
58
|
catchError(() => {
|
59
|
return of<boolean>(false);
|
60
|
})
|
61
|
);
|
62
|
}
|
63
|
|
64
|
setUserFromResponse(userCookie: UserCookie, username): UserCookie {
|
65
|
console.log('Setting user from login!');
|
66
|
this.userState.setUser({
|
67
|
userCookie,
|
68
|
isLoggedIn: true
|
69
|
});
|
70
|
this.setSessionStorage(userCookie, username);
|
71
|
return userCookie;
|
72
|
}
|
73
|
|
74
|
doLogout() {
|
75
|
this.userState.setUser(null);
|
76
|
this.cookieService.deleteAll();
|
77
|
localStorage.clear();
|
78
|
this.router.navigate(['/login']);
|
79
|
this.cookieService.deleteAll();
|
80
|
}
|
81
|
|
82
|
setSessionStorage(userCookie: UserCookie, username) {
|
83
|
localStorage.setItem(GlobalVariable.USER_NAME, username)
|
84
|
localStorage.setItem(GlobalVariable.RIGHTS, userCookie.rightsID.toString());
|
85
|
}
|
86
|
}
|