add auth roles and guards 050220
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthUser } from './auth.types';
|
||||
import { CurrentUser } from './decorators/current-user.decorator';
|
||||
import { RequestOtpDto } from './dto/request-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
@Post('request-otp')
|
||||
requestOtp(@Body() payload: RequestOtpDto) {
|
||||
return this.auth.requestOtp(payload);
|
||||
}
|
||||
|
||||
@Post('verify-otp')
|
||||
verifyOtp(@Body() payload: VerifyOtpDto) {
|
||||
return this.auth.verifyOtp(payload);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
me(@CurrentUser() user: AuthUser) {
|
||||
return this.auth.me(user.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthOtpEntity } from '../../entities/auth-otp.entity';
|
||||
import { UserEntity } from '../../entities/user.entity';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { RolesGuard } from './guards/roles.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([AuthOtpEntity, UserEntity]),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get<string>('JWT_SECRET') ?? 'montime-dev-secret-change-me',
|
||||
signOptions: {
|
||||
expiresIn: config.get<string>('JWT_EXPIRES_IN') ?? '30d',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard, RolesGuard],
|
||||
exports: [JwtAuthGuard, RolesGuard, JwtModule],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,196 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { createHash, randomInt } from 'crypto';
|
||||
import { IsNull, MoreThan, Repository } from 'typeorm';
|
||||
import { AuthOtpEntity } from '../../entities/auth-otp.entity';
|
||||
import { UserEntity, UserRole } from '../../entities/user.entity';
|
||||
import { JwtPayload } from './auth.types';
|
||||
import { RequestOtpDto } from './dto/request-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
|
||||
type RequestOtpResponse = {
|
||||
expiresInSeconds: number;
|
||||
otpCode?: string;
|
||||
};
|
||||
|
||||
type VerifyOtpResponse = {
|
||||
accessToken: string;
|
||||
user: Pick<UserEntity, 'id' | 'mobile' | 'fullName' | 'role' | 'isActive'>;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly otpTtlSeconds: number;
|
||||
private readonly maxAttempts: number;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly jwt: JwtService,
|
||||
@InjectRepository(AuthOtpEntity)
|
||||
private readonly otps: Repository<AuthOtpEntity>,
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly users: Repository<UserEntity>,
|
||||
) {
|
||||
this.otpTtlSeconds = this.readPositiveInt('OTP_TTL_SECONDS', 120);
|
||||
this.maxAttempts = this.readPositiveInt('OTP_MAX_ATTEMPTS', 5);
|
||||
}
|
||||
|
||||
async requestOtp(dto: RequestOtpDto): Promise<RequestOtpResponse> {
|
||||
const mobile = this.normalizeMobile(dto.mobile);
|
||||
const code = this.generateOtpCode();
|
||||
const expiresAt = new Date(Date.now() + this.otpTtlSeconds * 1000);
|
||||
|
||||
await this.otps.update(
|
||||
{ mobile, consumedAt: IsNull() },
|
||||
{ consumedAt: new Date() },
|
||||
);
|
||||
|
||||
await this.otps.save(
|
||||
this.otps.create({
|
||||
mobile,
|
||||
codeHash: this.hashOtp(mobile, code),
|
||||
expiresAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const response: RequestOtpResponse = {
|
||||
expiresInSeconds: this.otpTtlSeconds,
|
||||
};
|
||||
|
||||
if (this.config.get<string>('AUTH_RETURN_OTP') === 'true') {
|
||||
response.otpCode = code;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async verifyOtp(dto: VerifyOtpDto): Promise<VerifyOtpResponse> {
|
||||
const mobile = this.normalizeMobile(dto.mobile);
|
||||
const code = String(dto.code ?? '').trim();
|
||||
|
||||
if (!/^\d{4,8}$/.test(code)) {
|
||||
throw new BadRequestException('Invalid OTP code');
|
||||
}
|
||||
|
||||
const otp = await this.otps.findOne({
|
||||
where: {
|
||||
mobile,
|
||||
consumedAt: IsNull(),
|
||||
expiresAt: MoreThan(new Date()),
|
||||
},
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
|
||||
if (!otp) {
|
||||
throw new UnauthorizedException('OTP expired or not requested');
|
||||
}
|
||||
|
||||
if (otp.attempts >= this.maxAttempts) {
|
||||
throw new UnauthorizedException('Too many OTP attempts');
|
||||
}
|
||||
|
||||
if (otp.codeHash !== this.hashOtp(mobile, code)) {
|
||||
otp.attempts += 1;
|
||||
await this.otps.save(otp);
|
||||
throw new UnauthorizedException('Invalid OTP code');
|
||||
}
|
||||
|
||||
otp.consumedAt = new Date();
|
||||
await this.otps.save(otp);
|
||||
|
||||
const user = await this.findOrCreateCustomer(mobile);
|
||||
const payload: JwtPayload = {
|
||||
sub: user.id,
|
||||
mobile: user.mobile,
|
||||
role: user.role,
|
||||
};
|
||||
|
||||
return {
|
||||
accessToken: await this.jwt.signAsync(payload),
|
||||
user: this.serializeUser(user),
|
||||
};
|
||||
}
|
||||
|
||||
async me(userId: string) {
|
||||
const user = await this.users.findOne({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
return this.serializeUser(user);
|
||||
}
|
||||
|
||||
private async findOrCreateCustomer(mobile: string): Promise<UserEntity> {
|
||||
const existing = await this.users.findOne({ where: { mobile } });
|
||||
if (existing) {
|
||||
if (!existing.isActive) {
|
||||
throw new UnauthorizedException('User is inactive');
|
||||
}
|
||||
if (this.isConfiguredSuperAdminMobile(mobile) && existing.role !== UserRole.ADMIN) {
|
||||
existing.role = UserRole.ADMIN;
|
||||
return this.users.save(existing);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
return this.users.save(
|
||||
this.users.create({
|
||||
mobile,
|
||||
fullName: null,
|
||||
role: this.isConfiguredSuperAdminMobile(mobile)
|
||||
? UserRole.ADMIN
|
||||
: UserRole.CUSTOMER,
|
||||
isActive: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private serializeUser(user: UserEntity) {
|
||||
return {
|
||||
id: user.id,
|
||||
mobile: user.mobile,
|
||||
fullName: user.fullName,
|
||||
role: user.role,
|
||||
isActive: user.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeMobile(mobile: string): string {
|
||||
const normalized = String(mobile ?? '').trim();
|
||||
if (!/^(\+?\d{10,15}|09\d{9})$/.test(normalized)) {
|
||||
throw new BadRequestException('Invalid mobile number');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private generateOtpCode(): string {
|
||||
return String(randomInt(100000, 1000000));
|
||||
}
|
||||
|
||||
private hashOtp(mobile: string, code: string): string {
|
||||
const pepper =
|
||||
this.config.get<string>('OTP_HASH_SECRET') ??
|
||||
this.config.get<string>('JWT_SECRET') ??
|
||||
'montime-dev-secret-change-me';
|
||||
|
||||
return createHash('sha256')
|
||||
.update(`${mobile}:${code}:${pepper}`)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
private isConfiguredSuperAdminMobile(mobile: string): boolean {
|
||||
const configured = this.config.get<string>('SUPER_ADMIN_MOBILE');
|
||||
return configured ? this.normalizeMobile(configured) === mobile : false;
|
||||
}
|
||||
|
||||
private readPositiveInt(key: string, fallback: number): number {
|
||||
const raw = this.config.get<string>(key);
|
||||
const parsed = raw ? Number.parseInt(raw, 10) : NaN;
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
mobile: string;
|
||||
role: UserRole;
|
||||
};
|
||||
|
||||
export type JwtPayload = {
|
||||
sub: string;
|
||||
mobile: string;
|
||||
role: UserRole;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthUser } from '../auth.types';
|
||||
|
||||
type RequestWithUser = Request & {
|
||||
user?: AuthUser;
|
||||
};
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, context: ExecutionContext): AuthUser | undefined => {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { UserRole } from '../../../entities/user.entity';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
|
||||
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,3 @@
|
||||
export class RequestOtpDto {
|
||||
mobile!: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export class VerifyOtpDto {
|
||||
mobile!: string;
|
||||
code!: string;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UserEntity } from '../../../entities/user.entity';
|
||||
import { AuthUser, JwtPayload } from '../auth.types';
|
||||
|
||||
type RequestWithUser = Request & {
|
||||
headers: {
|
||||
authorization?: string;
|
||||
};
|
||||
user?: AuthUser;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwt: JwtService,
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly users: Repository<UserEntity>,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const token = this.extractBearerToken(request.headers.authorization);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Missing bearer token');
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwt.verifyAsync<JwtPayload>(token);
|
||||
const user = await this.users.findOne({
|
||||
where: { id: payload.sub, isActive: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User is inactive or not found');
|
||||
}
|
||||
|
||||
request.user = {
|
||||
id: user.id,
|
||||
mobile: user.mobile,
|
||||
role: user.role,
|
||||
};
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid bearer token');
|
||||
}
|
||||
}
|
||||
|
||||
private extractBearerToken(header?: string): string | null {
|
||||
if (!header) {
|
||||
return null;
|
||||
}
|
||||
const [type, token] = header.split(' ');
|
||||
return type === 'Bearer' && token ? token : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { UserRole } from '../../../entities/user.entity';
|
||||
import { AuthUser } from '../auth.types';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
type RequestWithUser = Request & {
|
||||
user?: AuthUser;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(
|
||||
ROLES_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
|
||||
if (!user || !requiredRoles.includes(user.role)) {
|
||||
throw new ForbiddenException('Insufficient role');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user