Added expert field mirror flow

This commit is contained in:
SepehrYahyaee
2026-06-15 11:24:41 +03:30
parent 048398d653
commit 41f81a2f76
39 changed files with 2310 additions and 182 deletions

View File

@@ -0,0 +1,21 @@
import { Body, Controller, Post } from "@nestjs/common";
import { Public } from "./decorators";
import { UserLoginDto, UserRegisterDto } from "./dtos";
import { AuthService } from "./auth.service";
@Controller("auth")
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Public()
@Post("user/register")
async register(@Body() userRegisterDto: UserRegisterDto) {
return await this.authService.registerUser(userRegisterDto);
}
@Public()
@Post("user/login")
async login(@Body() userLoginDto: UserLoginDto) {
return await this.authService.loginUser(userLoginDto);
}
}

View File

@@ -0,0 +1,30 @@
import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { APP_GUARD } from "@nestjs/core";
import { JwtModule } from "@nestjs/jwt";
import { StringValue } from "ms";
import { AuthGuard, RolesGuard } from "./guards";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
@Module({
imports: [
JwtModule.registerAsync({
global: true,
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>("JWT_SECRET"),
signOptions: {
expiresIn: configService.get<StringValue>("JWT_EXPIRY"),
},
}),
}),
],
controllers: [AuthController],
providers: [
{ provide: APP_GUARD, useClass: AuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
AuthService,
],
})
export class AuthModule {}

View File

@@ -0,0 +1,31 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { UserRepository } from "src/features/user/repositories";
import { UserLoginDto, UserRegisterDto } from "./dtos";
@Injectable()
export class AuthService {
constructor(private readonly userRepo: UserRepository) {}
async registerUser(userRegisterDto: UserRegisterDto) {
const user = await this.userRepo.retrieveByCellPhoneNumber(
userRegisterDto.cellphoneNumber,
);
if (!user) {
// Create user + Send OTP and update database
}
// Send OTP to the cellphone number of user and update database
// TODO: Create a mock otp for once we got no otp senders or development phase
}
async loginUser(userLoginDto: UserLoginDto) {
const user = await this.userRepo.retrieveByCellPhoneNumber(
userLoginDto.cellphoneNumber,
);
if (!user) throw new BadRequestException("User does not exist");
// Generate token (access + refresh) and save inside the database, return them to the user
}
}

View File

@@ -0,0 +1,2 @@
export { IS_PUBLIC_KEY, Public } from "./public.decorator";
export { ROLES_KEY, Roles } from "./roles.decorator";

View File

@@ -0,0 +1,4 @@
import { SetMetadata } from "@nestjs/common";
export const IS_PUBLIC_KEY = "isPublic";
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

View File

@@ -0,0 +1,5 @@
import { SetMetadata } from "@nestjs/common";
import { Role } from "../enums/roles.enum";
export const ROLES_KEY = "roles";
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

View File

@@ -0,0 +1,2 @@
export { UserRegisterDto } from "./user-register.dto";
export { UserLoginDto } from "./user-login.dto";

View File

@@ -0,0 +1,10 @@
import { IsMobilePhone, IsNumberString, IsString } from "class-validator";
export class UserLoginDto {
@IsString({ message: "Cellphone number must be string" })
@IsMobilePhone("fa-IR")
cellphoneNumber: string;
@IsNumberString()
otp: string;
}

View File

@@ -0,0 +1,7 @@
import { IsMobilePhone, IsNumberString, IsString } from "class-validator";
export class UserRegisterDto {
@IsString({ message: "Cellphone number must be string" })
@IsMobilePhone("fa-IR")
cellphoneNumber: string;
}

View File

@@ -0,0 +1 @@
export { Role } from "./roles.enum";

View File

@@ -0,0 +1,9 @@
export enum Role {
SUPER_ADMIN = "super_admin",
INSURER = "insurer",
ACCIDENT_EXPERT = "accident_expert",
CLAIM_EXPERT = "claim_expert",
FIELD_EXPERT = "field_expert",
REGISTRAR = "registrar",
USER = "user",
}

View File

@@ -0,0 +1,35 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { JwtPayload } from "../types/payload.types";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException("No token provided");
}
try {
const payload: JwtPayload =
await this.jwtService.verifyAsync<JwtPayload>(token);
request["user"] = payload;
} catch {
throw new UnauthorizedException("Invalid or expired token");
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(" ") ?? [];
return type === "Bearer" ? token : undefined;
}
}

View File

@@ -0,0 +1,2 @@
export { AuthGuard } from "./auth.guard";
export { RolesGuard } from "./role.guard";

View File

@@ -0,0 +1,47 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";
import { IS_PUBLIC_KEY, ROLES_KEY } from "../decorators";
import { Role } from "../enums";
import { JwtPayload } from "../types";
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles || requiredRoles.length === 0) return true;
const request = context.switchToHttp().getRequest<Request>();
const user: JwtPayload = request["user"] as JwtPayload | undefined;
if (!user?.role) {
throw new ForbiddenException("No role found in token");
}
const hasRole = requiredRoles.includes(user.role as Role);
if (!hasRole) {
throw new ForbiddenException(
`Access denied. Required: [${requiredRoles.join(", ")}]. Your role: ${user.role}`,
);
}
return true;
}
}

View File

@@ -0,0 +1 @@
export { JwtPayload } from "./payload.types";

View File

@@ -0,0 +1,7 @@
export interface JwtPayload {
sub: string;
role: string;
clientId?: string;
iat?: number;
exp?: number;
}