1 | import { Component, OnInit, OnDestroy } from '@angular/core';
|
---|
2 | import { FormGroup, FormControl, Validators } from '@angular/forms';
|
---|
3 | import { Router, ActivatedRoute } from '@angular/router';
|
---|
4 | import { Subscription } from 'rxjs';
|
---|
5 | import { first } from 'rxjs/operators';
|
---|
6 | import { AuthService } from '../shared/services/auth.service';
|
---|
7 | import { finalize } from 'rxjs/operators';
|
---|
8 |
|
---|
9 | @Component({
|
---|
10 | selector: 'app-login',
|
---|
11 | templateUrl: './login.component.html',
|
---|
12 | styleUrls: ['./login.component.css']
|
---|
13 | })
|
---|
14 | export class LoginComponent implements OnInit, OnDestroy {
|
---|
15 | busy = false;
|
---|
16 | loginForm: FormGroup;
|
---|
17 | username = '';
|
---|
18 | password = '';
|
---|
19 | loginError = false;
|
---|
20 | expanded = false;
|
---|
21 | private subscription: Subscription;
|
---|
22 |
|
---|
23 | constructor(private authService: AuthService,private router: Router, private route: ActivatedRoute) {
|
---|
24 | this.loginForm = new FormGroup({
|
---|
25 | username: new FormControl('', [Validators.required, Validators.email]),
|
---|
26 | password: new FormControl('', [Validators.required])
|
---|
27 | });
|
---|
28 | }
|
---|
29 | ngOnDestroy(): void {
|
---|
30 | this.subscription?.unsubscribe();
|
---|
31 | }
|
---|
32 |
|
---|
33 | ngOnInit(): void {
|
---|
34 | this.subscription = this.authService.user$.subscribe((x) => {
|
---|
35 | if (this.route.snapshot.url[0].path === 'login') {
|
---|
36 | const accessToken = localStorage.getItem('access_token');
|
---|
37 | const refreshToken = localStorage.getItem('refresh_token');
|
---|
38 | if (x && accessToken && refreshToken) {
|
---|
39 | const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '';
|
---|
40 | this.router.navigate([returnUrl]);
|
---|
41 | }
|
---|
42 | }
|
---|
43 | });
|
---|
44 | }
|
---|
45 |
|
---|
46 | loginPharmacyHead() {
|
---|
47 | if (!this.username || !this.password) {
|
---|
48 | return;
|
---|
49 | }
|
---|
50 | this.busy = true;
|
---|
51 | const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '';
|
---|
52 | this.authService
|
---|
53 | .login(this.username, this.password)
|
---|
54 | .pipe(finalize(() => (this.busy = false)))
|
---|
55 | .subscribe(
|
---|
56 | (data) => {
|
---|
57 | if(data.role === 'Admin') {
|
---|
58 | this.router.navigate(['/admin']);
|
---|
59 | }
|
---|
60 | else {
|
---|
61 | this.router.navigate(['/dashboard']);
|
---|
62 | }
|
---|
63 | },
|
---|
64 | () => {
|
---|
65 | this.loginError = true;
|
---|
66 | }
|
---|
67 | );
|
---|
68 | this.loginForm.reset();
|
---|
69 | }
|
---|
70 |
|
---|
71 | expandRegistration() {
|
---|
72 | this.expanded = !this.expanded;
|
---|
73 | }
|
---|
74 | }
|
---|