File size: 6,681 Bytes
6ecce98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { tap, catchError, switchMap, finalize } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from '../../../environments/environment';

/**
 * Authentication service responsible for managing user authentication state
 * and handling login/logout operations with automatic token refresh.
 */
@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  private readonly API_BASE_URL = environment.apiBaseUrl;
  private readonly TOKEN_REFRESH_INTERVAL = 12 * 60 * 1000; // 12 minutes
  private readonly LOGIN_ENDPOINT = '/auth/login';
  private readonly LOGOUT_ENDPOINT = '/auth/logout';
  private readonly REFRESH_ENDPOINT = '/auth/refresh';
  private readonly CHECK_AUTH_ENDPOINT = '/auth/check-auth';

  private readonly loggedInSubject = new BehaviorSubject<boolean>(false);
  private refreshIntervalId: number | null = null;

  public readonly isLoggedIn$ = this.loggedInSubject.asObservable();

  constructor(
    private readonly http: HttpClient,
    private readonly router: Router
  ) {
    this.initializeAuthState();
  }

  /**
   * Initialize authentication state on service creation
   */
  private initializeAuthState(): void {
    const hasUserSession = this.hasValidSession();
    this.loggedInSubject.next(hasUserSession);
  }

  /**
   * Check if user has a valid session
   */
  private hasValidSession(): boolean {
    return typeof localStorage !== 'undefined' && !!localStorage.getItem('username');
  }

  /**
   * Get current authentication status
   */
  public isLoggedIn(): boolean {
    return this.loggedInSubject.value;
  }

  /**
   * Update authentication status
   */
  public setLoggedIn(status: boolean): void {
    this.loggedInSubject.next(status);
  }

  /**
   * Authenticate user with credentials
   */
  public login(credentials: { username: string; password: string }): Observable<any> {
    const loginData = {
      username: credentials.username,
      password: credentials.password
    };

    return this.http.post(`${this.API_BASE_URL}${this.LOGIN_ENDPOINT}`, loginData, {
      withCredentials: true
    }).pipe(
      tap(() => {
        this.setLoggedIn(true);
        this.startAutoRefresh();
        localStorage.setItem('username', credentials.username);
      }),
      catchError(this.handleAuthError.bind(this))
    );
  }

  /**
   * Log out current user
   */
  public logout(): Observable<any> {
    return this.http.post(`${this.API_BASE_URL}${this.LOGOUT_ENDPOINT}`, {}, {
      withCredentials: true
    }).pipe(
      tap(() => this.handleLogoutSuccess()),
      catchError((error) => {
        // Even if logout fails, clean up local state
        this.handleLogoutSuccess();
        return throwError(() => error);
      }),
      finalize(() => this.handleLogoutSuccess())
    );
  }

  /**
   * Check if current session is valid
   */
  public checkSession(): Observable<boolean> {
    return this.http.get(`${this.API_BASE_URL}${this.CHECK_AUTH_ENDPOINT}`, {
      withCredentials: true
    }).pipe(
      tap(() => {
        this.setLoggedIn(true);
        this.startAutoRefresh();
      }),
      switchMap(() => [true]),
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          return this.attemptTokenRefresh();
        }
        this.setLoggedIn(false);
        return [false];
      })
    );
  }

  /**
   * Start automatic token refresh
   */
  public startAutoRefresh(): void {
    if (this.refreshIntervalId) {
      return;
    }

    this.refreshIntervalId = window.setInterval(() => {
      this.refreshAccessToken().subscribe({
        error: () => this.handleRefreshError()
      });
    }, this.TOKEN_REFRESH_INTERVAL);
  }

  /**
   * Stop automatic token refresh
   */
  public clearAutoRefresh(): void {
    if (this.refreshIntervalId) {
      clearInterval(this.refreshIntervalId);
      this.refreshIntervalId = null;
    }
  }

  /**
   * Refresh access token
   */
  private refreshAccessToken(): Observable<any> {
    return this.http.post(`${this.API_BASE_URL}${this.REFRESH_ENDPOINT}`, {}, {
      withCredentials: true
    }).pipe(
      catchError(this.handleRefreshError.bind(this))
    );
  }

  /**
   * Attempt to refresh token when session check fails
   */
  private attemptTokenRefresh(): Observable<boolean> {
    return this.http.post(`${this.API_BASE_URL}${this.REFRESH_ENDPOINT}`, {}, {
      withCredentials: true
    }).pipe(
      tap(() => {
        this.setLoggedIn(true);
        this.startAutoRefresh();
      }),
      switchMap(() => [true]),
      catchError(() => {
        this.setLoggedIn(false);
        return [false];
      })
    );
  }

  /**
   * Handle authentication errors
   */
  private handleAuthError(error: HttpErrorResponse): Observable<never> {
    let errorMessage = 'Authentication failed';
    
    if (error.error?.message) {
      errorMessage = error.error.message;
    } else if (error.status === 401) {
      errorMessage = 'Invalid credentials';
    } else if (error.status === 0) {
      errorMessage = 'Network error - please check your connection';
    }

    return throwError(() => ({ message: errorMessage, status: error.status }));
  }

  /**
   * Handle refresh token errors
   */
  private handleRefreshError(): Observable<never> {
    this.clearTokens();
    this.setLoggedIn(false);
    this.router.navigate(['/login']);
    return throwError(() => new Error('Session expired'));
  }

  /**
   * Handle successful logout
   */
  private handleLogoutSuccess(): void {
    this.clearTokens();
    this.clearAutoRefresh();
    this.setLoggedIn(false);
    localStorage.removeItem('username');
  }

  /**
   * Clear authentication tokens
   */
  private clearTokens(): void {
    // Clear HTTP-only cookies by setting expired date
    document.cookie = 'access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure; samesite=strict';
    document.cookie = 'refresh_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure; samesite=strict';
  }

  /**
   * Get access token from cookies (for debugging purposes)
   */
  public getAccessToken(): string | null {
    if (typeof document === 'undefined') {
      return null;
    }

    const cookies = document.cookie.split('; ');
    const tokenCookie = cookies.find(cookie => cookie.startsWith('access_token='));
    return tokenCookie ? tokenCookie.split('=')[1] : null;
  }

  /**
   * Cleanup on service destruction
   */
  public ngOnDestroy(): void {
    this.clearAutoRefresh();
  }
}