first commit
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
|
||||
import { authGuard } from './auth.guard';
|
||||
|
||||
describe('authGuard', () => {
|
||||
const executeGuard: CanActivateFn = (...guardParameters) =>
|
||||
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(executeGuard).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
|
||||
export const authGuard: CanActivateFn = () => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
if (authService.isAuthenticated()) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(AuthService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable, BehaviorSubject, forkJoin, of } 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;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface LoginResult extends ApiResult<LoginResponse> {
|
||||
licenseValid?: boolean;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
public currentUserSubject = new BehaviorSubject<string | null>(
|
||||
localStorage.getItem('username'),
|
||||
);
|
||||
constructor(
|
||||
private httpService: HttpService,
|
||||
) {
|
||||
let previousUser: string | null = this.currentUserSubject.value;
|
||||
this.currentUserSubject.subscribe((username) => {
|
||||
if (username !== previousUser) {
|
||||
previousUser = username;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem('access_token');
|
||||
localStorage.removeItem('username');
|
||||
this.currentUserSubject.next(null);
|
||||
}
|
||||
|
||||
isAuthenticated(): boolean {
|
||||
return !!localStorage.getItem('access_token');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { HttpService } from './http.service';
|
||||
|
||||
describe('HttpService', () => {
|
||||
let service: HttpService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(HttpService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, Observable, throwError, map } from 'rxjs';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { ToastrService } from 'ngx-toastr';
|
||||
|
||||
export interface ApiResult<T> {
|
||||
hasError: boolean;
|
||||
messages: string[];
|
||||
result: T;
|
||||
}
|
||||
|
||||
export interface ApiResultArray<T> {
|
||||
hasError: boolean;
|
||||
messages: string[];
|
||||
result: {
|
||||
data: T[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface HttpOptions {
|
||||
params?: any;
|
||||
skipToast?: boolean;
|
||||
cooldownMs?: number;
|
||||
skipHasErrorCheck?: boolean;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const EVENT_STREAM_HEADERS = {
|
||||
Accept: 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
};
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HttpService {
|
||||
private readonly baseUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
public readonly backendUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
public readonly apiUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
public readonly imagesUrl = `${window.location.protocol}//${window.location.hostname}`;
|
||||
|
||||
constructor(
|
||||
private readonly http: HttpClient,
|
||||
private readonly router: Router,
|
||||
private readonly toast: ToastrService,
|
||||
private readonly modal: NgbModal,
|
||||
) {
|
||||
this.messageCooldowns = new Map();
|
||||
this.DEFAULT_COOLDOWN_MS = 30000;
|
||||
}
|
||||
|
||||
private readonly messageCooldowns: Map<string, number>;
|
||||
private readonly DEFAULT_COOLDOWN_MS: number;
|
||||
|
||||
private getToken(): string | null {
|
||||
return localStorage.getItem('access_token');
|
||||
}
|
||||
private getHeaders(): HttpHeaders {
|
||||
const token = this.getToken();
|
||||
let headers = new HttpHeaders();
|
||||
if (token) {
|
||||
headers = headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
private shouldDisplayMessage(message: string, customCooldown?: number): boolean {
|
||||
const cooldown = customCooldown ?? this.DEFAULT_COOLDOWN_MS;
|
||||
const now = Date.now();
|
||||
const lastShown = this.messageCooldowns.get(message);
|
||||
|
||||
if (lastShown !== undefined && now - lastShown < cooldown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.messageCooldowns.set(message, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
private handleUnauthorized(): void {
|
||||
this.toast.clear();
|
||||
localStorage.removeItem('access_token');
|
||||
this.modal.dismissAll();
|
||||
this.toast.error('جلسه منقضی شده است. لطفاً دوباره وارد شوید.');
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
private handleError(error: HttpErrorResponse, skipToast = false): Observable<never> {
|
||||
if (error.status === 401) {
|
||||
this.handleUnauthorized();
|
||||
return throwError(() => new Error('Unauthorized'));
|
||||
}
|
||||
|
||||
if (error.status === 422 && error.error && !skipToast) {
|
||||
try {
|
||||
const apiError = error.error as ApiResult<any>;
|
||||
if (apiError?.hasError && Array.isArray(apiError.messages)) {
|
||||
apiError.messages.forEach((msg) => {
|
||||
if (this.shouldDisplayMessage(msg)) {
|
||||
this.toast.error(msg);
|
||||
}
|
||||
});
|
||||
return throwError(() => new Error(apiError.messages.join('; ')));
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.shouldDisplayMessage('خطای نامشخص در پردازش پاسخ سرور.')) {
|
||||
this.toast.error('خطای نامشخص در پردازش پاسخ سرور.');
|
||||
}
|
||||
return throwError(() => new Error('Invalid server response'));
|
||||
}
|
||||
}
|
||||
return throwError(() => error);
|
||||
}
|
||||
|
||||
private processResponse<T>(response: ApiResult<T>, options?: HttpOptions): ApiResult<T> {
|
||||
if (!response || !Array.isArray(response.messages)) {
|
||||
if (
|
||||
!options?.skipToast &&
|
||||
this.shouldDisplayMessage('پاسخ سرور نامعتبر است.', options?.cooldownMs)
|
||||
) {
|
||||
this.toast.error('پاسخ سرور نامعتبر است.');
|
||||
}
|
||||
throw new Error('Invalid server response');
|
||||
}
|
||||
|
||||
if (!options?.skipToast) {
|
||||
response.messages.forEach((message) => {
|
||||
if (!this.shouldDisplayMessage(message, options?.cooldownMs)) {
|
||||
return;
|
||||
}
|
||||
response.hasError ? this.toast.error(message) : this.toast.success(message);
|
||||
});
|
||||
}
|
||||
|
||||
if (response.hasError && !options?.skipHasErrorCheck) {
|
||||
throw new Error(response.messages.join('; '));
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
get<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = this.mergeHeaders(options.headers);
|
||||
return this.http
|
||||
.get<ApiResult<T>>(url, {
|
||||
headers,
|
||||
params: options.params,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
catchError((err) => this.handleError(err, options.skipToast)),
|
||||
);
|
||||
}
|
||||
|
||||
private getAuthHeaderObject(): Record<string, string> {
|
||||
const token = this.getToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
private mergeHeaders(extra?: Record<string, string>): HttpHeaders {
|
||||
let headers = this.getHeaders();
|
||||
if (extra) {
|
||||
Object.entries(extra).forEach(([key, value]) => {
|
||||
headers = headers.set(key, value as string);
|
||||
});
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
getStream<T = any>(endpoint: string, headers: Record<string, string> = {}): Observable<T> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
|
||||
return new Observable<T>((observer) => {
|
||||
const controller = new AbortController();
|
||||
|
||||
fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
...EVENT_STREAM_HEADERS,
|
||||
...this.getAuthHeaderObject(),
|
||||
...headers,
|
||||
},
|
||||
signal: controller.signal,
|
||||
credentials: 'omit',
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`Stream request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
const pump = (): void => {
|
||||
reader
|
||||
.read()
|
||||
.then(({ done, value }) => {
|
||||
if (done) {
|
||||
observer.complete();
|
||||
return;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
const frames = buffer.split('\n\n');
|
||||
buffer = frames.pop() ?? '';
|
||||
|
||||
for (const frame of frames) {
|
||||
const dataLines = frame
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('data:'))
|
||||
.map((line) => line.slice(5).trim());
|
||||
|
||||
if (dataLines.length === 0) continue;
|
||||
|
||||
const payload = dataLines.join('\n');
|
||||
try {
|
||||
observer.next(JSON.parse(payload) as T);
|
||||
} catch {
|
||||
observer.next(payload as unknown as T);
|
||||
}
|
||||
}
|
||||
|
||||
pump();
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!controller.signal.aborted) observer.error(err);
|
||||
});
|
||||
};
|
||||
|
||||
pump();
|
||||
})
|
||||
.catch((err) => observer.error(err));
|
||||
|
||||
return () => controller.abort();
|
||||
});
|
||||
}
|
||||
|
||||
post<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
.post<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
catchError((err) => this.handleError(err, options.skipToast)),
|
||||
);
|
||||
}
|
||||
|
||||
put<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
.put<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
catchError((err) => this.handleError(err, options.skipToast)),
|
||||
);
|
||||
}
|
||||
|
||||
patch<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
.patch<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
catchError((err) => this.handleError(err, options.skipToast)),
|
||||
);
|
||||
}
|
||||
|
||||
delete<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
.delete<ApiResult<T>>(url, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
catchError((err) => this.handleError(err, options.skipToast)),
|
||||
);
|
||||
}
|
||||
downloadFile(endpoint: string): Observable<Blob> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
return this.http
|
||||
.get(url, {
|
||||
headers: this.getHeaders(),
|
||||
responseType: 'blob',
|
||||
})
|
||||
.pipe(catchError((err) => this.handleError(err, false)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { ThemeService } from './theme.service';
|
||||
|
||||
describe('ThemeService', () => {
|
||||
let service: ThemeService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(ThemeService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { signal } from '@angular/core';
|
||||
import { HttpService } from '../http-request/http.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ThemeService {
|
||||
private readonly _isDarkMode = signal<boolean>(false);
|
||||
readonly isDarkMode = this._isDarkMode.asReadonly();
|
||||
|
||||
constructor(private httpService: HttpService) {
|
||||
this.initTheme();
|
||||
}
|
||||
|
||||
initTheme(): void {
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
if (savedTheme) {
|
||||
this.applyTheme(savedTheme);
|
||||
} else {
|
||||
this.applyTheme('light');
|
||||
}
|
||||
|
||||
this.httpService.get('users/get-dark-mode').subscribe({
|
||||
next: (res: any) => {
|
||||
const isBackendDark = res.result.dark_mode;
|
||||
const trueTheme = isBackendDark ? 'dark' : 'light';
|
||||
|
||||
if (savedTheme !== trueTheme) {
|
||||
this.applyTheme(trueTheme);
|
||||
localStorage.setItem('theme', trueTheme);
|
||||
}
|
||||
},
|
||||
error: () => {}
|
||||
});
|
||||
}
|
||||
|
||||
toggleDarkMode(): void {
|
||||
const isDark = !this._isDarkMode();
|
||||
const theme = isDark ? 'dark' : 'light';
|
||||
|
||||
const payload = { dark_mode: isDark };
|
||||
|
||||
this.httpService.post('users/update-dark-mode', payload).subscribe({
|
||||
next: () => {},
|
||||
error: () => {}
|
||||
});
|
||||
|
||||
this.applyTheme(theme);
|
||||
localStorage.setItem('theme', theme);
|
||||
}
|
||||
|
||||
private applyTheme(theme: string): void {
|
||||
document.documentElement.setAttribute('data-bs-theme', theme);
|
||||
this._isDarkMode.set(theme === 'dark');
|
||||
}
|
||||
|
||||
get isDarkModeSync(): boolean {
|
||||
return this._isDarkMode();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user