Spaces:
Building
Building
File size: 10,024 Bytes
9f79da5 3b93905 |
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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
// auth.service.ts
// Path: /flare-ui/src/app/services/auth.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { BehaviorSubject, Observable, throwError, of } from 'rxjs';
import { tap, catchError, map, timeout, retry } from 'rxjs/operators';
interface LoginResponse {
token: string;
username: string;
expires_at?: string;
refresh_token?: string;
}
interface AuthError {
message: string;
code?: string;
details?: any;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private http = inject(HttpClient);
private router = inject(Router);
private tokenKey = 'flare_token';
private usernameKey = 'flare_username';
private refreshTokenKey = 'flare_refresh_token';
private tokenExpiryKey = 'flare_token_expiry';
private loggedInSubject = new BehaviorSubject<boolean>(this.hasValidToken());
public loggedIn$ = this.loggedInSubject.asObservable();
private readonly REQUEST_TIMEOUT = 30000; // 30 seconds
private tokenRefreshInProgress = false;
private tokenRefreshSubject = new BehaviorSubject<string | null>(null);
login(username: string, password: string): Observable<LoginResponse> {
// Validate input
if (!username || !password) {
return throwError(() => ({
message: 'Username and password are required',
code: 'VALIDATION_ERROR'
} as AuthError));
}
return this.http.post<LoginResponse>('/api/admin/login', { username, password })
.pipe(
timeout(this.REQUEST_TIMEOUT),
retry({ count: 2, delay: 1000 }),
tap(response => {
this.handleLoginSuccess(response);
}),
catchError(error => this.handleAuthError(error, 'login'))
);
}
logout(): void {
try {
// Clear all auth data
this.clearAuthData();
// Update logged in state
this.loggedInSubject.next(false);
// Optional: Call logout endpoint
this.http.post('/api/logout', {}).pipe(
catchError(() => of(null)) // Ignore logout errors
).subscribe();
// Navigate to login
this.router.navigate(['/login']);
console.log('β
User logged out successfully');
} catch (error) {
console.error('Error during logout:', error);
// Still navigate to login even if error occurs
this.router.navigate(['/login']);
}
}
refreshToken(): Observable<LoginResponse> {
const refreshToken = this.getRefreshToken();
if (!refreshToken) {
return throwError(() => ({
message: 'No refresh token available',
code: 'NO_REFRESH_TOKEN'
} as AuthError));
}
// Prevent multiple simultaneous refresh requests
if (this.tokenRefreshInProgress) {
return this.tokenRefreshSubject.asObservable().pipe(
map(token => {
if (token) {
return { token, username: this.getUsername() || '' } as LoginResponse;
}
throw new Error('Token refresh failed');
})
);
}
this.tokenRefreshInProgress = true;
return this.http.post<LoginResponse>('/api/refresh', { refresh_token: refreshToken })
.pipe(
timeout(this.REQUEST_TIMEOUT),
tap(response => {
this.handleLoginSuccess(response);
this.tokenRefreshSubject.next(response.token);
this.tokenRefreshInProgress = false;
}),
catchError(error => {
this.tokenRefreshInProgress = false;
this.tokenRefreshSubject.next(null);
// If refresh fails, logout user
if (error.status === 401 || error.status === 403) {
this.logout();
}
return this.handleAuthError(error, 'refresh');
})
);
}
getToken(): string | null {
try {
// Check if token is expired
if (this.isTokenExpired()) {
this.clearAuthData();
return null;
}
return localStorage.getItem(this.tokenKey);
} catch (error) {
console.error('Error getting token:', error);
return null;
}
}
getUsername(): string | null {
try {
return localStorage.getItem(this.usernameKey);
} catch (error) {
console.error('Error getting username:', error);
return null;
}
}
getRefreshToken(): string | null {
try {
return localStorage.getItem(this.refreshTokenKey);
} catch (error) {
console.error('Error getting refresh token:', error);
return null;
}
}
setToken(token: string): void {
try {
localStorage.setItem(this.tokenKey, token);
} catch (error) {
console.error('Error setting token:', error);
throw new Error('Failed to save authentication token');
}
}
setUsername(username: string): void {
try {
localStorage.setItem(this.usernameKey, username);
} catch (error) {
console.error('Error setting username:', error);
}
}
hasToken(): boolean {
return !!this.getToken();
}
hasValidToken(): boolean {
return this.hasToken() && !this.isTokenExpired();
}
isLoggedIn(): boolean {
return this.hasValidToken();
}
isTokenExpired(): boolean {
try {
const expiryStr = localStorage.getItem(this.tokenExpiryKey);
if (!expiryStr) {
return false; // No expiry means token doesn't expire
}
const expiry = new Date(expiryStr);
return expiry <= new Date();
} catch (error) {
console.error('Error checking token expiry:', error);
return true; // Assume expired on error
}
}
getTokenExpiry(): Date | null {
try {
const expiryStr = localStorage.getItem(this.tokenExpiryKey);
return expiryStr ? new Date(expiryStr) : null;
} catch (error) {
console.error('Error getting token expiry:', error);
return null;
}
}
private handleLoginSuccess(response: LoginResponse): void {
try {
// Save auth data
this.setToken(response.token);
this.setUsername(response.username);
if (response.refresh_token) {
localStorage.setItem(this.refreshTokenKey, response.refresh_token);
}
if (response.expires_at) {
localStorage.setItem(this.tokenExpiryKey, response.expires_at);
}
// Update logged in state
this.loggedInSubject.next(true);
console.log('β
Login successful for user:', response.username);
} catch (error) {
console.error('Error handling login success:', error);
throw new Error('Failed to save authentication data');
}
}
private clearAuthData(): void {
try {
localStorage.removeItem(this.tokenKey);
localStorage.removeItem(this.usernameKey);
localStorage.removeItem(this.refreshTokenKey);
localStorage.removeItem(this.tokenExpiryKey);
} catch (error) {
console.error('Error clearing auth data:', error);
}
}
private handleAuthError(error: HttpErrorResponse, operation: string): Observable<never> {
console.error(`Auth error during ${operation}:`, error);
let authError: AuthError;
// Handle different error types
if (error.status === 0) {
// Network error
authError = {
message: 'Network error. Please check your connection.',
code: 'NETWORK_ERROR'
};
} else if (error.status === 401) {
authError = {
message: error.error?.message || 'Invalid credentials',
code: 'UNAUTHORIZED'
};
} else if (error.status === 403) {
authError = {
message: error.error?.message || 'Access forbidden',
code: 'FORBIDDEN'
};
} else if (error.status === 409) {
// Race condition
authError = {
message: error.error?.message || 'Request conflict. Please try again.',
code: 'CONFLICT',
details: error.error?.details
};
} else if (error.status === 422) {
// Validation error
authError = {
message: error.error?.message || 'Validation error',
code: 'VALIDATION_ERROR',
details: error.error?.details
};
} else if (error.status >= 500) {
authError = {
message: 'Server error. Please try again later.',
code: 'SERVER_ERROR'
};
} else {
authError = {
message: error.error?.message || error.message || 'Authentication failed',
code: 'UNKNOWN_ERROR'
};
}
return throwError(() => authError);
}
// Validate current session
validateSession(): Observable<boolean> {
if (!this.hasToken()) {
return of(false);
}
return this.http.get<{ valid: boolean }>('/api/validate')
.pipe(
timeout(this.REQUEST_TIMEOUT),
map(response => response.valid),
catchError(error => {
if (error.status === 401) {
this.clearAuthData();
this.loggedInSubject.next(false);
}
return of(false);
})
);
}
// Get user profile
getUserProfile(): Observable<any> {
return this.http.get('/api/user/profile')
.pipe(
timeout(this.REQUEST_TIMEOUT),
catchError(error => this.handleAuthError(error, 'getUserProfile'))
);
}
// Update password
updatePassword(currentPassword: string, newPassword: string): Observable<any> {
return this.http.post('/api/user/password', {
current_password: currentPassword,
new_password: newPassword
}).pipe(
timeout(this.REQUEST_TIMEOUT),
catchError(error => this.handleAuthError(error, 'updatePassword'))
);
}
} |