forked from Yara724/api
Added expert field mirror flow
This commit is contained in:
21
src/common/auth/auth.controller.ts
Normal file
21
src/common/auth/auth.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
30
src/common/auth/auth.module.ts
Normal file
30
src/common/auth/auth.module.ts
Normal 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 {}
|
||||
31
src/common/auth/auth.service.ts
Normal file
31
src/common/auth/auth.service.ts
Normal 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
|
||||
}
|
||||
}
|
||||
2
src/common/auth/decorators/index.ts
Normal file
2
src/common/auth/decorators/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { IS_PUBLIC_KEY, Public } from "./public.decorator";
|
||||
export { ROLES_KEY, Roles } from "./roles.decorator";
|
||||
4
src/common/auth/decorators/public.decorator.ts
Normal file
4
src/common/auth/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from "@nestjs/common";
|
||||
|
||||
export const IS_PUBLIC_KEY = "isPublic";
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
5
src/common/auth/decorators/roles.decorator.ts
Normal file
5
src/common/auth/decorators/roles.decorator.ts
Normal 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);
|
||||
2
src/common/auth/dtos/index.ts
Normal file
2
src/common/auth/dtos/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { UserRegisterDto } from "./user-register.dto";
|
||||
export { UserLoginDto } from "./user-login.dto";
|
||||
10
src/common/auth/dtos/user-login.dto.ts
Normal file
10
src/common/auth/dtos/user-login.dto.ts
Normal 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;
|
||||
}
|
||||
7
src/common/auth/dtos/user-register.dto.ts
Normal file
7
src/common/auth/dtos/user-register.dto.ts
Normal 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;
|
||||
}
|
||||
1
src/common/auth/enums/index.ts
Normal file
1
src/common/auth/enums/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { Role } from "./roles.enum";
|
||||
9
src/common/auth/enums/roles.enum.ts
Normal file
9
src/common/auth/enums/roles.enum.ts
Normal 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",
|
||||
}
|
||||
35
src/common/auth/guards/auth.guard.ts
Normal file
35
src/common/auth/guards/auth.guard.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
2
src/common/auth/guards/index.ts
Normal file
2
src/common/auth/guards/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { AuthGuard } from "./auth.guard";
|
||||
export { RolesGuard } from "./role.guard";
|
||||
47
src/common/auth/guards/role.guard.ts
Normal file
47
src/common/auth/guards/role.guard.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
1
src/common/auth/types/index.ts
Normal file
1
src/common/auth/types/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { JwtPayload } from "./payload.types";
|
||||
7
src/common/auth/types/payload.types.ts
Normal file
7
src/common/auth/types/payload.types.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
role: string;
|
||||
clientId?: string;
|
||||
iat?: number;
|
||||
exp?: number;
|
||||
}
|
||||
Reference in New Issue
Block a user