1
|
import {Component, OnDestroy, OnInit} from '@angular/core';
|
2
|
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
|
3
|
import {switchMap} from 'rxjs/operators';
|
4
|
import {of, Subscription} from 'rxjs';
|
5
|
import {AuthService} from '../../auth/services/auth.service';
|
6
|
import {Router} from '@angular/router';
|
7
|
|
8
|
@Component({
|
9
|
selector: 'app-login',
|
10
|
templateUrl: './login.component.html',
|
11
|
styleUrls: ['./login.component.scss']
|
12
|
})
|
13
|
export class LoginComponent implements OnInit, OnDestroy {
|
14
|
|
15
|
loginForm: FormGroup;
|
16
|
subscription: Subscription[] = [];
|
17
|
|
18
|
constructor(
|
19
|
private formBuilder: FormBuilder,
|
20
|
private authService: AuthService,
|
21
|
private router: Router
|
22
|
) {
|
23
|
}
|
24
|
|
25
|
/**
|
26
|
* Unsubscribe after leaving
|
27
|
*/
|
28
|
ngOnDestroy(): void {
|
29
|
this.subscription.forEach(subs => subs.unsubscribe());
|
30
|
}
|
31
|
|
32
|
ngOnInit(): void {
|
33
|
this.loginForm = this.formBuilder.group({
|
34
|
username: ['', [Validators.required]],
|
35
|
password: ['', Validators.required]
|
36
|
});
|
37
|
this.userRedirect();
|
38
|
}
|
39
|
|
40
|
/**
|
41
|
* Process login
|
42
|
*/
|
43
|
doLogin(): void {
|
44
|
if (this.loginForm.valid) {
|
45
|
this.subscription[2] = this.authService.doLogin({
|
46
|
username: this.loginForm.controls.username.value,
|
47
|
password: this.loginForm.controls.password.value
|
48
|
})
|
49
|
.pipe(
|
50
|
switchMap(res => {
|
51
|
if (res) {
|
52
|
console.log('Login getUserState');
|
53
|
return this.authService.getUserState();
|
54
|
} else {
|
55
|
return of(false);
|
56
|
}
|
57
|
})
|
58
|
).subscribe(
|
59
|
res => {
|
60
|
if (res) {
|
61
|
this.subscription[2].unsubscribe();
|
62
|
this.router.navigate(['/dashboard'])
|
63
|
}
|
64
|
}
|
65
|
);
|
66
|
}
|
67
|
}
|
68
|
|
69
|
/**
|
70
|
* If user already logged with valid sessionId redirect to dashboard
|
71
|
*/
|
72
|
userRedirect(): void {
|
73
|
console.log('Login redirect');
|
74
|
if (this.authService.getUser()){
|
75
|
this.router.navigate(['/dashboard']);
|
76
|
}
|
77
|
}
|
78
|
}
|