All files / app/common/services auth.service.ts

100% Statements 71/71
100% Branches 26/26
100% Functions 28/28
100% Lines 63/63

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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 2253x 3x 3x 3x 3x 3x                                                               3x 34x     34x 34x       34x 34x     34x     34x 34x 30x 30x     34x 34x             16x             5x             11x 9x             7x     5x     2x 2x                 3x     1x     2x 2x                 3x 2x 2x   3x 3x             5x 5x 1x     4x       4x     2x 2x 1x       2x 2x 1x   2x                 5x 5x             2x             2x     1x 1x                 2x           1x 1x                 6x 5x 5x   6x             2x 1x        
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from '../../../environments/environment';
 
export interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  blocked?: boolean;
  confirmed?: boolean;
}
 
export interface AuthResponse {
  jwt: string;
  user: User;
}
 
export interface LoginCredentials {
  identifier: string; // email or username
  password: string;
}
 
export interface SignupData {
  username: string;
  email: string;
  password: string;
  role?: string;
}
 
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'http://localhost:1337/api'; // Auth API endpoint
  private currentUserSubject: BehaviorSubject<User | null>;
  public currentUser: Observable<User | null>;
  private tokenKey = 'auth_token';
  private userKey = 'auth_user';
  private isBrowser: boolean;
 
  constructor(
    private http: HttpClient,
    private router: Router,
    @Inject(PLATFORM_ID) platformId: Object
  ) {
    this.isBrowser = isPlatformBrowser(platformId);
 
    // Initialize user from localStorage only in browser
    let storedUser = null;
    if (this.isBrowser) {
      const userJson = localStorage.getItem(this.userKey);
      storedUser = userJson ? JSON.parse(userJson) : null;
    }
 
    this.currentUserSubject = new BehaviorSubject<User | null>(storedUser);
    this.currentUser = this.currentUserSubject.asObservable();
  }
 
  /**
   * Get current user value
   */
  public get currentUserValue(): User | null {
    return this.currentUserSubject.value;
  }
 
  /**
   * Check if user is authenticated
   */
  public get isAuthenticated(): boolean {
    return !!this.getToken() && !!this.currentUserValue;
  }
 
  /**
   * Get stored token
   */
  public getToken(): string | null {
    if (!this.isBrowser) return null;
    return localStorage.getItem(this.tokenKey);
  }
 
  /**
   * Login user
   */
  login(credentials: LoginCredentials): Observable<AuthResponse> {
    return this.http.post<AuthResponse>(`${this.apiUrl}/auth/local`, credentials)
      .pipe(
        tap(response => {
          this.setSession(response);
        }),
        catchError(error => {
          console.error('Login error:', error);
          return throwError(() => new Error(error.error?.error?.message || 'Login failed'));
        })
      );
  }
 
  /**
   * Register new user
   */
  signup(data: SignupData): Observable<AuthResponse> {
    return this.http.post<AuthResponse>(`${this.apiUrl}/auth/local/register`, data)
      .pipe(
        tap(response => {
          this.setSession(response);
        }),
        catchError(error => {
          console.error('Signup error:', error);
          return throwError(() => new Error(error.error?.error?.message || 'Registration failed'));
        })
      );
  }
 
  /**
   * Logout user
   */
  logout(): void {
    if (this.isBrowser) {
      localStorage.removeItem(this.tokenKey);
      localStorage.removeItem(this.userKey);
    }
    this.currentUserSubject.next(null);
    this.router.navigate(['/login']);
  }
 
  /**
   * Get user profile from backend
   */
  getProfile(): Observable<User> {
    const token = this.getToken();
    if (!token) {
      return throwError(() => new Error('No authentication token found'));
    }
 
    const headers = new HttpHeaders({
      'Authorization': `Bearer ${token}`
    });
 
    return this.http.get<User>(`${this.apiUrl}/users/me`, { headers })
      .pipe(
        tap(user => {
          this.currentUserSubject.next(user);
          if (this.isBrowser) {
            localStorage.setItem(this.userKey, JSON.stringify(user));
          }
        }),
        catchError(error => {
          console.error('Get profile error:', error);
          if (error.status === 401) {
            this.logout();
          }
          return throwError(() => new Error('Failed to fetch user profile'));
        })
      );
  }
 
  /**
   * Check if user has specific role
   */
  hasRole(role: string): boolean {
    const user = this.currentUserValue;
    return user?.role === role;
  }
 
  /**
   * Check if user is admin
   */
  isAdmin(): boolean {
    return this.hasRole('admin') || this.hasRole('administrator');
  }
 
  /**
   * Forgot password - send reset email
   */
  forgotPassword(email: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/auth/forgot-password`, { email })
      .pipe(
        catchError(error => {
          console.error('Forgot password error:', error);
          return throwError(() => new Error('Failed to send reset email'));
        })
      );
  }
 
  /**
   * Reset password with code
   */
  resetPassword(code: string, password: string, passwordConfirmation: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/auth/reset-password`, {
      code,
      password,
      passwordConfirmation
    }).pipe(
      catchError(error => {
        console.error('Reset password error:', error);
        return throwError(() => new Error('Failed to reset password'));
      })
    );
  }
 
  /**
   * Set authentication session
   */
  private setSession(authResult: AuthResponse): void {
    if (this.isBrowser) {
      localStorage.setItem(this.tokenKey, authResult.jwt);
      localStorage.setItem(this.userKey, JSON.stringify(authResult.user));
    }
    this.currentUserSubject.next(authResult.user);
  }
 
  /**
   * Refresh user data
   */
  refreshUser(): void {
    if (this.isAuthenticated) {
      this.getProfile().subscribe();
    }
  }
}