init
This commit is contained in:
@@ -7,20 +7,20 @@
|
||||
class="flex flex-col items-center justify-center px-12 py-10 h-auto bg-surface-card border border-surface-border rounded-lg shadow w-full max-w-md"
|
||||
>
|
||||
<div class="flex flex-col gap-4 text-center mb-10 items-center justify-center">
|
||||
<img [src]="logo" alt="صندوق فروشگاهی" class="w-20 h-auto" />
|
||||
<span class="text-lg font-bold"> به پنل صندوق فروشگاهی خوش آمدید. </span>
|
||||
<img [src]="logo" alt="مدیریت کسبوکار" class="w-20 h-auto" />
|
||||
<span class="text-lg font-bold"> به پنل مدیریت کسبوکار خوش آمدید. </span>
|
||||
</div>
|
||||
|
||||
@if (activeStep() === "login") {
|
||||
<app-login
|
||||
[redirectUrl]="redirectUrl"
|
||||
[loginApiUrl]="loginApiUrl"
|
||||
[defaultRole]="role"
|
||||
class="w-full"
|
||||
(onSuccessfullySubmit)="onLoggedIn($event)"
|
||||
(onToSignup)="toSignUp()"
|
||||
/>
|
||||
} @else if (activeStep() === "signup") {
|
||||
<!-- @if (activeStep() === "login") { -->
|
||||
<app-login
|
||||
[redirectUrl]="redirectUrl"
|
||||
[loginApiUrl]="loginApiUrl"
|
||||
[defaultRole]="role"
|
||||
class="w-full"
|
||||
(onSuccessfullySubmit)="onLoggedIn($event)"
|
||||
(onToSignup)="toSignUp()"
|
||||
/>
|
||||
<!-- } @else if (activeStep() === "signup") {
|
||||
<auth-signup role="TEACHER" class="w-full" />
|
||||
} @else if (activeStep() === "otp") {
|
||||
<app-otp class="w-full" />
|
||||
@@ -31,7 +31,7 @@
|
||||
(onSubmit)="onModifyLoginInfo()"
|
||||
class="w-full"
|
||||
/>
|
||||
}
|
||||
} -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,16 +4,13 @@ import { Component, EventEmitter, inject, Input, Output, signal } from '@angular
|
||||
import { Router } from '@angular/router';
|
||||
import images from 'src/assets/images';
|
||||
import { LoginComponent } from './login/login.component';
|
||||
import { ModifyLoginInfoComponent } from './modifyLoginInfo/modify-login-info.component';
|
||||
import { OTPComponent } from './otp/otp.component';
|
||||
import { SignupComponent } from './signup/signup.component';
|
||||
|
||||
type TSteps = 'login' | 'otp' | 'modifyLoginInfo' | 'signup';
|
||||
|
||||
@Component({
|
||||
selector: 'app-auth',
|
||||
templateUrl: './auth.component.html',
|
||||
imports: [LoginComponent, OTPComponent, ModifyLoginInfoComponent, SignupComponent],
|
||||
imports: [LoginComponent],
|
||||
})
|
||||
export class AuthComponent {
|
||||
@Input() redirectUrl!: string;
|
||||
@@ -39,11 +36,11 @@ export class AuthComponent {
|
||||
|
||||
onLoggedIn = (data: IAuthResponse) => {
|
||||
this.toastService.success({ text: 'شما با موفقیت وارد شدید.' });
|
||||
this.selectedRole.set(data.role.toUpperCase() as TRoles);
|
||||
if (data.mustChangePassword) {
|
||||
this.activeStep.set('modifyLoginInfo');
|
||||
return;
|
||||
}
|
||||
this.selectedRole.set(data.account.type.toUpperCase() as TRoles);
|
||||
// if (data.mustChangePassword) {
|
||||
// this.activeStep.set('modifyLoginInfo');
|
||||
// return;
|
||||
// }
|
||||
|
||||
if (this.submit.observed) {
|
||||
return this.submit.emit(Promise.resolve(true));
|
||||
@@ -63,17 +60,17 @@ export class AuthComponent {
|
||||
|
||||
if (!redirectUrl) {
|
||||
switch (this.selectedRole()) {
|
||||
case 'SCHOOL':
|
||||
redirectUrl = '/schools';
|
||||
case 'SUPERADMIN':
|
||||
redirectUrl = '/super_admin';
|
||||
break;
|
||||
case 'ADMIN':
|
||||
redirectUrl = '/admin';
|
||||
break;
|
||||
case 'TEACHER':
|
||||
redirectUrl = '/teachers';
|
||||
case 'POS':
|
||||
redirectUrl = '/poss';
|
||||
break;
|
||||
case 'STUDENTS':
|
||||
redirectUrl = '/students';
|
||||
case 'PARTNER':
|
||||
redirectUrl = '/partner';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,12 +46,12 @@
|
||||
</span>
|
||||
</div> -->
|
||||
<div class="mb-6 flex flex-col items-center gap-4 w-[16rem] mx-auto">
|
||||
<div
|
||||
class="relative bg-surface-ground rounded-xl overflow-hidden shadow shrink-0 border border-[var(--p-inputtext-border-color)] w-full aspect-[2]"
|
||||
<!-- <div
|
||||
class="relative bg-surface-ground rounded-xl overflow-hidden shadow shrink-0 border border-(--p-inputtext-border-color) w-full aspect-[2]"
|
||||
>
|
||||
<img p-image id="captchaImage" [src]="captchaImageSrc()" class="w-full object-contain" />
|
||||
@if (isCaptchaLoading()) {
|
||||
<div class="!absolute inset-0 bg-surface-hover/50 flex items-center justify-center">
|
||||
<div class="absolute! inset-0 bg-surface-hover/50 flex items-center justify-center">
|
||||
<p-progress-spinner
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
@@ -61,14 +61,14 @@
|
||||
</div>
|
||||
} @else if (isCaptchaExpired()) {
|
||||
<div
|
||||
class="!absolute inset-0 bg-surface-hover/70 flex items-center justify-center text-center p-2 text-sm font-medium cursor-pointer"
|
||||
class="absolute! inset-0 bg-surface-hover/70 flex items-center justify-center text-center p-2 text-sm font-medium cursor-pointer"
|
||||
(click)="onRefreshCaptcha()"
|
||||
>
|
||||
<i class="pi pi-refresh !text-3xl text-gray-500"></i>
|
||||
<i class="pi pi-refresh text-3xl! text-gray-500"></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<p-inputgroup>
|
||||
</div> -->
|
||||
<!-- <p-inputgroup>
|
||||
<input
|
||||
pInputText
|
||||
id="captcha"
|
||||
@@ -81,14 +81,14 @@
|
||||
<p-inputgroup-addon>
|
||||
<p-button icon="pi pi-refresh" severity="secondary" variant="text" (click)="onRefreshCaptchaImage()" />
|
||||
</p-inputgroup-addon>
|
||||
</p-inputgroup>
|
||||
</p-inputgroup> -->
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-3">
|
||||
@if (loginForm.controls.role.value === "TEACHER") {
|
||||
<!-- @if (loginForm.controls.role.value === "TEACHER") {
|
||||
<span class="w-full text-center text-sm select-none">
|
||||
برای ثبت نام در سامانه <a class="text-primary cursor-pointer" (click)="toSignup()">اینجا</a> کلیک کنید.
|
||||
</span>
|
||||
}
|
||||
} -->
|
||||
<p-button label="ورود" styleClass="w-full" size="large" [loading]="isLoading()" type="submit"></p-button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -14,7 +14,6 @@ import { InputText } from 'primeng/inputtext';
|
||||
import { Password } from 'primeng/password';
|
||||
import { ProgressSpinnerModule } from 'primeng/progressspinner';
|
||||
import { RadioButtonModule } from 'primeng/radiobutton';
|
||||
import { CaptchaService } from 'src/app/core/services/captcha.service';
|
||||
// import { CENTRAL_AUTH_ROLES } from '../../constants/central-auth-roles.const';
|
||||
|
||||
@Component({
|
||||
@@ -45,48 +44,47 @@ export class LoginComponent {
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly fb = inject(FormBuilder);
|
||||
private readonly captchaService = inject(CaptchaService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
|
||||
readonly isLoading = computed(() => this.authService.isLoading());
|
||||
readonly errorMessage = signal<string>('');
|
||||
readonly hidePassword = signal<boolean>(true);
|
||||
readonly isCaptchaExpired = this.captchaService.captchaIsExpired;
|
||||
readonly isCaptchaLoading = this.captchaService.loading;
|
||||
readonly captchaImageSrc = this.captchaService.captchaImageSrc;
|
||||
// readonly isCaptchaExpired = this.captchaService.captchaIsExpired;
|
||||
// readonly isCaptchaLoading = this.captchaService.loading;
|
||||
// readonly captchaImageSrc = this.captchaService.captchaImageSrc;
|
||||
// readonly centralAuthRoles = CENTRAL_AUTH_ROLES;
|
||||
|
||||
readonly loginForm = this.fb.group({
|
||||
username: ['', [Validators.required]],
|
||||
password: ['', [Validators.required]],
|
||||
rememberMe: [false],
|
||||
captcha: ['', [Validators.required]],
|
||||
role: [this.defaultRole, [Validators.required]],
|
||||
// captcha: ['', [Validators.required]],
|
||||
// role: [this.defaultRole, [Validators.required]],
|
||||
});
|
||||
|
||||
selectedRole = signal<TRoles>('SCHOOL');
|
||||
selectedRole = signal<TRoles>('SUPERADMIN');
|
||||
ngOnInit() {
|
||||
this.captchaService.requestNewCaptcha();
|
||||
// this.captchaService.requestNewCaptcha();
|
||||
}
|
||||
|
||||
togglePasswordVisibility(): void {
|
||||
this.hidePassword.set(!this.hidePassword());
|
||||
}
|
||||
|
||||
resetCaptcha(): void {
|
||||
this.fb.control('captcha').setValue('');
|
||||
this.captchaService.renewCaptcha();
|
||||
}
|
||||
// resetCaptcha(): void {
|
||||
// this.fb.control('captcha').setValue('');
|
||||
// this.captchaService.renewCaptcha();
|
||||
// }
|
||||
|
||||
onRefreshCaptcha(): void {
|
||||
this.resetCaptcha();
|
||||
}
|
||||
onRefreshCaptchaImage(): void {
|
||||
this.resetCaptcha();
|
||||
// document
|
||||
// .getElementById('captchaImage')
|
||||
// ?.setAttribute('src', this.captchaService.captchaImageSrc()! + `&${new Date().getTime()}`);
|
||||
}
|
||||
// onRefreshCaptcha(): void {
|
||||
// this.resetCaptcha();
|
||||
// }
|
||||
// onRefreshCaptchaImage(): void {
|
||||
// this.resetCaptcha();
|
||||
// // document
|
||||
// // .getElementById('captchaImage')
|
||||
// // ?.setAttribute('src', this.captchaService.captchaImageSrc()! + `&${new Date().getTime()}`);
|
||||
// }
|
||||
|
||||
toSignup() {
|
||||
this.onToSignup.emit();
|
||||
@@ -95,27 +93,25 @@ export class LoginComponent {
|
||||
submit(): void {
|
||||
this.loginForm.markAllAsTouched();
|
||||
if (this.loginForm.invalid) return;
|
||||
if (!this.captchaService.captchaId()) {
|
||||
this.toastService.error({ text: 'مقدار کپچا را وارد کنید' });
|
||||
}
|
||||
// if (!this.captchaService.captchaId()) {
|
||||
// this.toastService.error({ text: 'مقدار کپچا را وارد کنید' });
|
||||
// }
|
||||
const credentials: LoginCredentials = this.loginForm.value as LoginCredentials;
|
||||
|
||||
this.authService
|
||||
.login(credentials, (this.defaultRole || this.loginForm.value.role)!)
|
||||
.subscribe({
|
||||
next: (data) => {
|
||||
this.errorMessage.set('');
|
||||
if (this.redirectUrl) {
|
||||
this.router.navigateByUrl(this.redirectUrl.replace(/\/[^/]*$/, ''));
|
||||
} else {
|
||||
this.onSuccessfullySubmit.emit(data);
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
this.resetCaptcha();
|
||||
this.errorMessage.set('نام کاربری یا رمز عبور اشتباه است');
|
||||
console.error('Login failed:', error);
|
||||
},
|
||||
});
|
||||
this.authService.login(credentials).subscribe({
|
||||
next: (data) => {
|
||||
this.errorMessage.set('');
|
||||
if (this.redirectUrl) {
|
||||
this.router.navigateByUrl(this.redirectUrl.replace(/\/[^/]*$/, ''));
|
||||
} else {
|
||||
this.onSuccessfullySubmit.emit(data);
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
// this.resetCaptcha();
|
||||
this.errorMessage.set('نام کاربری یا رمز عبور اشتباه است');
|
||||
console.error('Login failed:', error);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<form [formGroup]="form" class="w-full flex flex-col gap-4" (ngSubmit)="submit()">
|
||||
<app-input label="نام" name="firstName" size="large" [control]="form.controls.firstName" />
|
||||
<app-input label="نام خانوادگی" name="lastName" size="large" [control]="form.controls.lastName" />
|
||||
<app-gender-select [control]="form.controls.gender" size="large" />
|
||||
<!-- <app-gender-select [control]="form.controls.gender" size="large" /> -->
|
||||
<app-input
|
||||
label="شماره تلفن همراه"
|
||||
name="mobile"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ISignupRequestPayload, IUserLoginInfo, Maybe, TRoles } from '@/core/mod
|
||||
import { ToastService } from '@/core/services/toast.service';
|
||||
import { mobileValidator, MustMatch } from '@/core/validators';
|
||||
import { password } from '@/core/validators/password.validator';
|
||||
import { GenderSelectComponent } from '@/shared/catalog';
|
||||
// import { GenderSelectComponent } from '@/shared/catalog';
|
||||
import { InputComponent } from '@/shared/components';
|
||||
import { UikitFieldComponent } from '@/uikit/uikit-field.component';
|
||||
import { CommonModule } from '@angular/common';
|
||||
@@ -33,7 +33,7 @@ import { RadioButtonModule } from 'primeng/radiobutton';
|
||||
InputGroupAddonModule,
|
||||
UikitFieldComponent,
|
||||
InputComponent,
|
||||
GenderSelectComponent,
|
||||
// GenderSelectComponent,
|
||||
],
|
||||
})
|
||||
export class SignupComponent {
|
||||
|
||||
@@ -1,406 +0,0 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { computed, inject, Injectable } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, of, tap } from 'rxjs';
|
||||
import { LOCAL_STORAGE_KEYS, ROLES } from 'src/assets/constants';
|
||||
import { IAuthResponse, LoginCredentials, Maybe, TRoles, User } from '../../../core/models';
|
||||
import { BaseState, BaseStore } from '../../../core/state/base-store';
|
||||
|
||||
/**
|
||||
* Authentication state
|
||||
*/
|
||||
export interface AuthState extends BaseState {
|
||||
user: Maybe<User>;
|
||||
token: Maybe<string>;
|
||||
refreshToken: Maybe<string>;
|
||||
isAuthenticated: boolean;
|
||||
permissions: string[];
|
||||
loginAttempts: number;
|
||||
lastLoginTime: Maybe<number>;
|
||||
sessionExpiry: Maybe<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login state for UI feedback
|
||||
*/
|
||||
export interface LoginState {
|
||||
isLoggingIn: boolean;
|
||||
isRefreshing: boolean;
|
||||
loginError: Maybe<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication state store
|
||||
*/
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthStore extends BaseStore<AuthState> {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
// Login-specific state
|
||||
private readonly _loginState = {
|
||||
isLoggingIn: false,
|
||||
isRefreshing: false,
|
||||
loginError: null as Maybe<string>,
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super({
|
||||
initialized: false,
|
||||
loading: false,
|
||||
error: null,
|
||||
user: null,
|
||||
token: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
permissions: [],
|
||||
loginAttempts: 0,
|
||||
lastLoginTime: null,
|
||||
sessionExpiry: null,
|
||||
});
|
||||
|
||||
this.initializeAuth();
|
||||
}
|
||||
|
||||
// Computed selectors
|
||||
readonly user = computed(() => this._state().user);
|
||||
readonly token = computed(() => this._state().token);
|
||||
readonly refreshToken = computed(() => this._state().refreshToken);
|
||||
readonly isAuthenticated = computed(() => this._state().isAuthenticated);
|
||||
readonly userRole = computed(() => this._state().user?.role);
|
||||
readonly permissions = computed(() => this._state().permissions);
|
||||
readonly loginAttempts = computed(() => this._state().loginAttempts);
|
||||
readonly lastLoginTime = computed(() => this._state().lastLoginTime);
|
||||
readonly sessionExpiry = computed(() => this._state().sessionExpiry);
|
||||
|
||||
// Login state selectors
|
||||
readonly isLoggingIn = computed(() => this._loginState.isLoggingIn);
|
||||
readonly isRefreshing = computed(() => this._loginState.isRefreshing);
|
||||
readonly loginError = computed(() => this._loginState.loginError);
|
||||
|
||||
/**
|
||||
* Initialize authentication from stored data
|
||||
*/
|
||||
private initializeAuth(): void {
|
||||
const token = localStorage.getItem(LOCAL_STORAGE_KEYS.AUTH_TOKEN);
|
||||
const refreshToken = localStorage.getItem(LOCAL_STORAGE_KEYS.REFRESH_TOKEN);
|
||||
const userData = localStorage.getItem(LOCAL_STORAGE_KEYS.USER_DATA);
|
||||
const loginAttempts = parseInt(localStorage.getItem(LOCAL_STORAGE_KEYS.LOGIN_ATTEMPTS) || '0');
|
||||
const lastLoginTime = parseInt(localStorage.getItem(LOCAL_STORAGE_KEYS.LAST_LOGIN_TIME) || '0');
|
||||
|
||||
if (token && refreshToken && userData) {
|
||||
try {
|
||||
const user = JSON.parse(userData) as User;
|
||||
const sessionExpiry = this.getTokenExpiry(token);
|
||||
|
||||
this.patchState({
|
||||
user,
|
||||
token,
|
||||
refreshToken,
|
||||
isAuthenticated: true,
|
||||
permissions: [],
|
||||
// permissions: user.permissions?.map((p) => `${p.resource}:${p.action}`) || [],
|
||||
loginAttempts,
|
||||
lastLoginTime: lastLoginTime || null,
|
||||
sessionExpiry,
|
||||
});
|
||||
|
||||
// Check if token is expired
|
||||
if (this.isTokenExpired()) {
|
||||
this.refreshAuthToken().subscribe();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing stored user data:', error);
|
||||
this.logout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Login with credentials
|
||||
*/
|
||||
login(credentials: LoginCredentials) {
|
||||
this._loginState.isLoggingIn = true;
|
||||
this._loginState.loginError = null;
|
||||
this.setLoading(true);
|
||||
|
||||
return this.http.post<IAuthResponse>('/api/auth/login', credentials).pipe(
|
||||
tap((response) => {
|
||||
this.handleAuthSuccess(response);
|
||||
this._loginState.isLoggingIn = false;
|
||||
}),
|
||||
catchError((error) => {
|
||||
this.handleAuthError(error);
|
||||
return of(null);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
*/
|
||||
logout(): void {
|
||||
// Clear stored data
|
||||
localStorage.removeItem(LOCAL_STORAGE_KEYS.AUTH_TOKEN);
|
||||
localStorage.removeItem(LOCAL_STORAGE_KEYS.REFRESH_TOKEN);
|
||||
localStorage.removeItem(LOCAL_STORAGE_KEYS.USER_DATA);
|
||||
localStorage.removeItem(LOCAL_STORAGE_KEYS.LAST_LOGIN_TIME);
|
||||
|
||||
// Reset state
|
||||
this.patchState({
|
||||
user: null,
|
||||
token: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
permissions: [],
|
||||
lastLoginTime: null,
|
||||
sessionExpiry: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// Reset login state
|
||||
this._loginState.isLoggingIn = false;
|
||||
this._loginState.isRefreshing = false;
|
||||
this._loginState.loginError = null;
|
||||
|
||||
// Navigate to login
|
||||
this.router.navigate(['/auth']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh authentication token
|
||||
*/
|
||||
refreshAuthToken() {
|
||||
const refreshToken = this._state().refreshToken;
|
||||
if (!refreshToken) {
|
||||
this.logout();
|
||||
return of(null);
|
||||
}
|
||||
|
||||
this._loginState.isRefreshing = true;
|
||||
this.setLoading(true);
|
||||
|
||||
return this.http.post<IAuthResponse>('/api/auth/refresh', { refreshToken }).pipe(
|
||||
tap((response) => {
|
||||
this.handleAuthSuccess(response);
|
||||
this._loginState.isRefreshing = false;
|
||||
}),
|
||||
catchError((error) => {
|
||||
console.error('Token refresh failed:', error);
|
||||
this.logout();
|
||||
return of(null);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has specific role
|
||||
*/
|
||||
hasRole(role: TRoles): boolean {
|
||||
return this._state().user?.role === role;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has any of the specified roles
|
||||
*/
|
||||
hasAnyRole(roles: TRoles[]): boolean {
|
||||
const userRole = this._state().user?.role;
|
||||
return userRole ? roles.includes(userRole) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has specific permission
|
||||
*/
|
||||
hasPermission(permission: string): boolean {
|
||||
const permissions = this._state().permissions;
|
||||
return permissions.includes(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has all specified permissions
|
||||
*/
|
||||
hasAllPermissions(permissions: string[]): boolean {
|
||||
const userPermissions = this._state().permissions;
|
||||
return permissions.every((permission) => userPermissions.includes(permission));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has any of the specified permissions
|
||||
*/
|
||||
hasAnyPermission(permissions: string[]): boolean {
|
||||
const userPermissions = this._state().permissions;
|
||||
return permissions.some((permission) => userPermissions.includes(permission));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user can access resource
|
||||
*/
|
||||
canAccess(requiredRoles?: TRoles[], requiredPermissions?: string[]): boolean {
|
||||
if (!this._state().isAuthenticated) return false;
|
||||
|
||||
if (requiredRoles && !this.hasAnyRole(requiredRoles)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requiredPermissions && !this.hasAllPermissions(requiredPermissions)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current access token
|
||||
*/
|
||||
getToken(): string | null {
|
||||
return this._state().token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current refresh token
|
||||
*/
|
||||
getRefreshToken(): string | null {
|
||||
return this._state().refreshToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if token is expired
|
||||
*/
|
||||
isTokenExpired(): boolean {
|
||||
const sessionExpiry = this._state().sessionExpiry;
|
||||
if (!sessionExpiry) return true;
|
||||
|
||||
return Date.now() > sessionExpiry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get time until token expires (in minutes)
|
||||
*/
|
||||
getTimeUntilExpiry(): number {
|
||||
const sessionExpiry = this._state().sessionExpiry;
|
||||
if (!sessionExpiry) return 0;
|
||||
|
||||
return Math.max(0, Math.floor((sessionExpiry - Date.now()) / 60000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user profile
|
||||
*/
|
||||
updateUserProfile(updates: Partial<User>): void {
|
||||
const currentUser = this._state().user;
|
||||
if (!currentUser) return;
|
||||
|
||||
const updatedUser = { ...currentUser, ...updates };
|
||||
|
||||
this.patchState({ user: updatedUser });
|
||||
localStorage.setItem(LOCAL_STORAGE_KEYS.USER_DATA, JSON.stringify(updatedUser));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle successful authentication
|
||||
*/
|
||||
private handleAuthSuccess(response: IAuthResponse): void {
|
||||
const sessionExpiry = this.getTokenExpiry(response.token);
|
||||
const currentTime = Date.now();
|
||||
|
||||
// Store in localStorage
|
||||
localStorage.setItem(LOCAL_STORAGE_KEYS.AUTH_TOKEN, response.token);
|
||||
localStorage.setItem(LOCAL_STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken);
|
||||
// localStorage.setItem(LOCAL_STORAGE_KEYS.USER_DATA, JSON.stringify(response.user));
|
||||
localStorage.setItem(LOCAL_STORAGE_KEYS.LAST_LOGIN_TIME, currentTime.toString());
|
||||
|
||||
// Update state
|
||||
this.patchState({
|
||||
user: { fullName: response.fullName, role: response.role as TRoles },
|
||||
token: response.token,
|
||||
refreshToken: response.refreshToken,
|
||||
isAuthenticated: true,
|
||||
// permissions: response.user.permissions?.map((p) => `${p.resource}:${p.action}`) || [],
|
||||
lastLoginTime: currentTime,
|
||||
sessionExpiry,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// Reset login attempts on successful login
|
||||
localStorage.removeItem(LOCAL_STORAGE_KEYS.LOGIN_ATTEMPTS);
|
||||
|
||||
// Navigate based on user role
|
||||
// this.navigateByRole(response.user.role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle authentication error
|
||||
*/
|
||||
private handleAuthError(error: any): void {
|
||||
console.error('Authentication error:', error);
|
||||
|
||||
// Increment login attempts
|
||||
const attempts = this._state().loginAttempts + 1;
|
||||
this.patchState({ loginAttempts: attempts });
|
||||
localStorage.setItem(LOCAL_STORAGE_KEYS.LOGIN_ATTEMPTS, attempts.toString());
|
||||
|
||||
// Set login error
|
||||
this._loginState.isLoggingIn = false;
|
||||
this._loginState.loginError = error.error?.message || 'خطا در ورود به سیستم';
|
||||
|
||||
if (this._loginState.loginError) {
|
||||
this.setError(this._loginState.loginError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate user based on their role
|
||||
*/
|
||||
private navigateByRole(role: TRoles): void {
|
||||
const roleRoutes = {
|
||||
[ROLES.ADMIN]: '/admin',
|
||||
[ROLES.SCHOOL]: '/schools',
|
||||
[ROLES.TEACHER]: '/teachers',
|
||||
[ROLES.STUDENTS]: '/students',
|
||||
[ROLES.GRADER]: '/grader',
|
||||
[ROLES.SUPERADMIN]: '/superadmin',
|
||||
};
|
||||
|
||||
this.router.navigate([roleRoutes[role]]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract token expiry from JWT
|
||||
*/
|
||||
private getTokenExpiry(token: string): number | null {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return payload.exp * 1000; // Convert to milliseconds
|
||||
} catch (error) {
|
||||
console.error('Error parsing token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset state to initial values
|
||||
*/
|
||||
reset(): void {
|
||||
this.setState({
|
||||
initialized: false,
|
||||
loading: false,
|
||||
error: null,
|
||||
user: null,
|
||||
token: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
permissions: [],
|
||||
loginAttempts: 0,
|
||||
lastLoginTime: null,
|
||||
sessionExpiry: null,
|
||||
});
|
||||
|
||||
this._loginState.isLoggingIn = false;
|
||||
this._loginState.isRefreshing = false;
|
||||
this._loginState.loginError = null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Authentication state management
|
||||
export * from './auth.store';
|
||||
|
||||
// Types
|
||||
export type { AuthState, LoginState } from './auth.store';
|
||||
Reference in New Issue
Block a user