File size: 2,150 Bytes
88bf46c
 
27e40c0
88bf46c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27e40c0
 
 
88bf46c
 
27e40c0
88bf46c
 
 
 
 
27e40c0
88bf46c
 
 
 
 
 
 
 
 
 
 
 
024b436
 
 
 
88bf46c
 
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
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {BehaviorSubject, catchError, Observable, shareReplay, tap, throwError} from "rxjs";
import {environment} from "../../../environments/environment";

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  private readonly apiUrl = environment.apiUrl;
  private token: string | null = this.getTokenFromLocalStorage();
  public $authStatus = new BehaviorSubject<string>(
    this.token !== null ? 'authenticated' : ''
  );


  constructor(
    private http: HttpClient
  ) {

  }

  private getTokenFromLocalStorage(): string | null {
    try {
      return localStorage.getItem('auth_token');
    } catch (e) {
      return null;
    }
  }

  public getAuthHeaders(): HttpHeaders {
    return new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: `Bearer ${this.token}`,
    });
  }

  public login(password: string): Observable<{ access_token: string; token_type: string }> {
    // Create the request payload
    const payload = new URLSearchParams();
    payload.set('username', 'admin'); // Username is not used in this case
    payload.set('password', password);
    let headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
    });
    // Send POST request to the backend
    return this.http.post<{ access_token: string; token_type: string }>
    (this.apiUrl + '/token', payload.toString(), { headers }).pipe(
      tap(response => {
        this.token = response.access_token;
        localStorage.setItem('auth_token', this.token);
        this.$authStatus.next('authenticated');
      }),
      shareReplay(1),
      catchError(error => {
        if (error.status === 401) {
          this.$authStatus.next('wrong password');
        } else {
          this.$authStatus.next('server error');
        }
        // Return an observable to continue the stream
        return throwError(() => error);
      })
    );
  }

  public logout(): void {
    this.token = null;
    localStorage.removeItem('auth_token');
    this.$authStatus.next('');
  }
}