All files / src/app/services login.service.ts

90.9% Statements 30/33
83.33% Branches 10/12
91.66% Functions 11/12
90.62% Lines 29/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96                          70x   35x     35x 35x     35x       739x                   7x 7x 7x 7x 7x         1x       91x 91x       39x 1x   38x       1x                 1x 1x       3x       39x         216x 216x 205x 205x 205x     11x 11x      
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
 
import { FormGroup } from '@angular/forms';
import { User } from '../models/users';
import { Token } from '../models/token';
import { jwtDecode } from "jwt-decode";
 
@Injectable({
  providedIn: 'root'
})
export class LoginService {
 
  apiUrl: string = environment['apiUrl'];
  loggedInUserReplaySubject: BehaviorSubject<boolean>;
 
  constructor(private http: HttpClient) {
    Iif(!this.apiUrl){
      this.apiUrl = window.location.protocol+"//"+window.location.hostname.toLowerCase()+':5001';
    }
    this.loggedInUserReplaySubject = new BehaviorSubject(this.isTokenValid());
  }
 
  getToken() {
    return localStorage.getItem("accessToken");
  }
 
  logout() {
    localStorage.removeItem('accessToken');
    this.loggedInUserReplaySubject.next(false);
  }
 
 
  login(loginForm: FormGroup): Observable<Token> {
    const body = new URLSearchParams();
    const options = { headers: new HttpHeaders().set('Content-type', 'application/x-www-form-urlencoded') };
    body.set('username', loginForm.get('email')?.value);
    body.set('password', loginForm.get('password')?.value);
    return this.http.post<Token>(this.apiUrl+'/token', body.toString(), options);
  }
 
 
  register(form_firstname: string, form_lastname: string, form_email: string, form_password: string) {
    return this.http.post(this.apiUrl+'/users', { "firstname": form_firstname, "lastname": form_lastname, "email": form_email, "password": form_password });
  }
 
  isAuthenticated() {
    this.loggedInUserReplaySubject.next(this.isTokenValid());
    return this.http.post(this.apiUrl+'/authenticated', {});
  }
 
  getProfile(userId?: string): Observable<User> {
    if(userId){
      return this.http.get<User>(this.apiUrl+'/users/'+userId, {});
    }
    return this.http.post<User>(this.apiUrl+'/users/me', {});
  }
 
  editProfile(profileForm: FormGroup, userId: string): Observable<User> {
    const data = {
      "id": userId,
      "firstname": profileForm.get('firstname')?.value,
      "lastname": profileForm.get('lastname')?.value,
      "email": profileForm.get('email')?.value,
      "password": profileForm.get('password')?.value,
      "is_active": profileForm.get('userBlocked')?.value,
      "is_admin": profileForm.get('userAdministrator')?.value
    };
    const options = { headers: new HttpHeaders().set('Content-type', 'application/x-www-form-urlencoded') };
    return this.http.patch<User>(this.apiUrl+'/users/'+userId, data, options);
  }
 
  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(`${this.apiUrl}/users`);
  }
 
  isAdmin(): Observable<boolean> {
    return this.http.get<boolean>(this.apiUrl+'/is_admin');
  }
 
 
  isTokenValid(): boolean {
    const token = localStorage.getItem("accessToken");
    if(token != null){
      const exp = jwtDecode(token).exp;
      Eif(exp != null && exp > (Date.now() / 1000)){  // Divide by 1000 to get same timestamp length
        return true;
      }
    }
    localStorage.removeItem('accessToken');
    return false;
  }
}