feat(auth): implement login page and authentication flow
Implement a complete authentication system including a new login page, updated authentication service, and conditional routing. - Add `LoginPage` component with animated UI and form validation - Update `AuthService` to handle user sessions, CSRF tokens, and enhanced user data structures - Implement conditional rendering in `App` component based on authentication state - Add `postRaw` and `getRaw` methods to `HttpService` for direct API interaction - Update routing to include login path and prepare for auth guards - Add rate limiting error handling (429) in `HttpService`
This commit is contained in:
@@ -1,65 +1,112 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable, BehaviorSubject, forkJoin, of } from 'rxjs';
|
||||
import { Observable, BehaviorSubject, forkJoin, of, throwError } from 'rxjs';
|
||||
import { tap, map, switchMap, catchError } from 'rxjs/operators';
|
||||
import { HttpService } from '../http-request/http.service';
|
||||
|
||||
interface ApiResult<T> {
|
||||
hasError: boolean;
|
||||
messages: string[];
|
||||
result: T;
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
auth: boolean;
|
||||
token: string;
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
role: string;
|
||||
organization_id: string;
|
||||
}
|
||||
|
||||
interface LoginResult extends ApiResult<LoginResponse> {
|
||||
licenseValid?: boolean;
|
||||
export interface LoginResponse {
|
||||
user: AuthUser;
|
||||
csrf_token: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export interface CurrentUserResponse {
|
||||
user: AuthUser;
|
||||
csrf_token: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
public currentUserSubject = new BehaviorSubject<string | null>(
|
||||
localStorage.getItem('username'),
|
||||
);
|
||||
public currentUserSubject = new BehaviorSubject<AuthUser | null>(null);
|
||||
private csrfToken: string | null = null;
|
||||
|
||||
constructor(
|
||||
private httpService: HttpService,
|
||||
) {
|
||||
let previousUser: string | null = this.currentUserSubject.value;
|
||||
this.currentUserSubject.subscribe((username) => {
|
||||
if (username !== previousUser) {
|
||||
previousUser = username;
|
||||
const savedUser = localStorage.getItem('current_user');
|
||||
const savedCsrf = localStorage.getItem('csrf_token');
|
||||
if (savedUser) {
|
||||
try {
|
||||
this.currentUserSubject.next(JSON.parse(savedUser));
|
||||
} catch {
|
||||
// ignore corrupt data
|
||||
}
|
||||
});
|
||||
}
|
||||
if (savedCsrf) {
|
||||
this.csrfToken = savedCsrf;
|
||||
}
|
||||
}
|
||||
|
||||
login(credentials: {
|
||||
username: string;
|
||||
password: string;
|
||||
rememberMe: boolean;
|
||||
}): Observable<LoginResult> {
|
||||
return this.httpService.post<LoginResponse>('users/login', credentials).pipe(
|
||||
tap((response: ApiResult<LoginResponse>) => {
|
||||
if (!response.hasError && response.result?.auth) {
|
||||
localStorage.setItem('access_token', response.result.token);
|
||||
localStorage.setItem('username', response.result.username);
|
||||
this.currentUserSubject.next(response.result.username);
|
||||
}
|
||||
}): Observable<LoginResponse> {
|
||||
return this.httpService.postRaw<LoginResponse>('v1/auth/login', credentials).pipe(
|
||||
tap((response) => {
|
||||
this.currentUserSubject.next(response.user);
|
||||
this.csrfToken = response.csrf_token;
|
||||
localStorage.setItem('current_user', JSON.stringify(response.user));
|
||||
localStorage.setItem('csrf_token', response.csrf_token);
|
||||
}),
|
||||
catchError((err) => {
|
||||
this.clearAuth();
|
||||
return throwError(() => err);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem('access_token');
|
||||
localStorage.removeItem('username');
|
||||
this.currentUserSubject.next(null);
|
||||
logout(): Observable<void> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (this.csrfToken) {
|
||||
headers['X-CSRF-Token'] = this.csrfToken;
|
||||
}
|
||||
return this.httpService.postRaw<void>('v1/auth/logout', {}, { headers }).pipe(
|
||||
tap(() => {
|
||||
this.clearAuth();
|
||||
}),
|
||||
catchError((err) => {
|
||||
this.clearAuth();
|
||||
return throwError(() => err);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getCurrentUser(): Observable<CurrentUserResponse> {
|
||||
return this.httpService.getRaw<CurrentUserResponse>('v1/me').pipe(
|
||||
tap((response) => {
|
||||
this.currentUserSubject.next(response.user);
|
||||
this.csrfToken = response.csrf_token;
|
||||
localStorage.setItem('current_user', JSON.stringify(response.user));
|
||||
localStorage.setItem('csrf_token', response.csrf_token);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
isAuthenticated(): boolean {
|
||||
return !!localStorage.getItem('access_token');
|
||||
return !!this.currentUserSubject.value;
|
||||
}
|
||||
|
||||
getCurrentUserValue(): AuthUser | null {
|
||||
return this.currentUserSubject.value;
|
||||
}
|
||||
|
||||
getCsrfToken(): string | null {
|
||||
return this.csrfToken;
|
||||
}
|
||||
|
||||
private clearAuth(): void {
|
||||
this.currentUserSubject.next(null);
|
||||
this.csrfToken = null;
|
||||
localStorage.removeItem('current_user');
|
||||
localStorage.removeItem('csrf_token');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,13 @@ export class HttpService {
|
||||
return throwError(() => new Error('Unauthorized'));
|
||||
}
|
||||
|
||||
if (error.status === 429 && !skipToast) {
|
||||
if (this.shouldDisplayMessage('تلاشهای بیش از حد مجاز. لطفاً بعداً تلاش کنید.')) {
|
||||
this.toast.warning('تلاشهای بیش از حد مجاز. لطفاً بعداً تلاش کنید.');
|
||||
}
|
||||
return throwError(() => new Error('RATE_LIMITED'));
|
||||
}
|
||||
|
||||
if (error.status === 422 && error.error && !skipToast) {
|
||||
try {
|
||||
const apiError = error.error as ApiResult<any>;
|
||||
@@ -254,6 +261,24 @@ export class HttpService {
|
||||
);
|
||||
}
|
||||
|
||||
postRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
return this.http.post<T>(url, data, {
|
||||
headers,
|
||||
params: options.params,
|
||||
});
|
||||
}
|
||||
|
||||
getRaw<T>(endpoint: string, options: HttpOptions = {}): Observable<T> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
return this.http.get<T>(url, {
|
||||
headers,
|
||||
params: options.params,
|
||||
});
|
||||
}
|
||||
|
||||
put<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
|
||||
Reference in New Issue
Block a user