auth
This commit is contained in:
+8
-1
@@ -1,13 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CustomersModule } from './customers/customers.module';
|
||||
import configuration from './config/configuration';
|
||||
import { SalonsModule } from './salons/salons.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
load: [configuration],
|
||||
}),
|
||||
TypeOrmModule.forRoot({
|
||||
type: 'postgres',
|
||||
host: process.env.DB_HOST,
|
||||
@@ -17,7 +22,9 @@ import { UsersModule } from './users/users.module';
|
||||
database: process.env.DB_NAME,
|
||||
autoLoadEntities: true,
|
||||
entities: [__dirname + '/**/*.entity.{js,ts}'],
|
||||
synchronize: process.env.NODE_ENV !== 'production',
|
||||
}),
|
||||
AuthModule,
|
||||
UsersModule,
|
||||
SalonsModule,
|
||||
CustomersModule,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PermissionsGuard } from './guards/permissions.guard';
|
||||
import { RolesGuard } from './guards/roles.guard';
|
||||
|
||||
@Module({
|
||||
providers: [RolesGuard, PermissionsGuard],
|
||||
exports: [RolesGuard, PermissionsGuard],
|
||||
})
|
||||
export class AuthGuardsModule {}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CurrentUser } from './decorators/current-user.decorator';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
import { RefreshTokenDto } from './dto/refresh-token.dto';
|
||||
import { RequestOtpDto } from './dto/request-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { AuthUser } from './interfaces/auth-user.interface';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Public()
|
||||
@Post('otp/request')
|
||||
requestOtp(@Body() dto: RequestOtpDto) {
|
||||
return this.authService.requestOtp(dto.mobile);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('otp/verify')
|
||||
verifyOtp(@Body() dto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtp(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('refresh')
|
||||
refresh(@Body() dto: RefreshTokenDto) {
|
||||
return this.authService.refresh(dto.refreshToken);
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
logout(@CurrentUser() user: AuthUser, @Body() dto: RefreshTokenDto) {
|
||||
return this.authService.logout(user.id, dto.refreshToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthorizationModule } from '../authorization/authorization.module';
|
||||
import { Customer } from '../customers/entities/customer.entity';
|
||||
import { SmsModule } from '../sms/sms.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { Otp } from './entities/otp.entity';
|
||||
import { RefreshToken } from './entities/refresh-token.entity';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Otp, RefreshToken, Customer]),
|
||||
PassportModule.register({ defaultStrategy: 'jwt' }),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.getOrThrow<string>('JWT_ACCESS_SECRET'),
|
||||
signOptions: {
|
||||
expiresIn: (configService.get<string>('JWT_ACCESS_EXPIRES_IN') ??
|
||||
'15m') as `${number}m`,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
UsersModule,
|
||||
SmsModule,
|
||||
AuthorizationModule,
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtStrategy,
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtAuthGuard,
|
||||
},
|
||||
],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,296 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { Repository, IsNull } from 'typeorm';
|
||||
import { Customer } from '../customers/entities/customer.entity';
|
||||
import { SmsService } from '../sms/sms.service';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { User } from '../users/entities/user.entity';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { Otp } from './entities/otp.entity';
|
||||
import { RefreshToken } from './entities/refresh-token.entity';
|
||||
import { JwtPayload } from './interfaces/jwt-payload.interface';
|
||||
|
||||
export interface AuthTokensResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
user: {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mobile: string;
|
||||
role: UserRole;
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
private readonly otpLength: number;
|
||||
private readonly otpExpiresInMinutes: number;
|
||||
private readonly otpMaxAttempts: number;
|
||||
private readonly otpCooldownSeconds: number;
|
||||
private readonly otpDebug: boolean;
|
||||
private readonly refreshExpiresIn: string;
|
||||
|
||||
constructor(
|
||||
@InjectRepository(Otp)
|
||||
private readonly otpRepository: Repository<Otp>,
|
||||
@InjectRepository(RefreshToken)
|
||||
private readonly refreshTokenRepository: Repository<RefreshToken>,
|
||||
@InjectRepository(Customer)
|
||||
private readonly customersRepository: Repository<Customer>,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
this.otpLength = parseInt(
|
||||
this.configService.get<string>('OTP_LENGTH') ?? '5',
|
||||
10,
|
||||
);
|
||||
this.otpExpiresInMinutes = parseInt(
|
||||
this.configService.get<string>('OTP_EXPIRES_IN_MINUTES') ?? '5',
|
||||
10,
|
||||
);
|
||||
this.otpMaxAttempts = parseInt(
|
||||
this.configService.get<string>('OTP_MAX_ATTEMPTS') ?? '5',
|
||||
10,
|
||||
);
|
||||
this.otpCooldownSeconds = parseInt(
|
||||
this.configService.get<string>('OTP_COOLDOWN_SECONDS') ?? '60',
|
||||
10,
|
||||
);
|
||||
this.otpDebug = this.configService.get<string>('OTP_DEBUG') === 'true';
|
||||
this.refreshExpiresIn =
|
||||
this.configService.get<string>('JWT_REFRESH_EXPIRES_IN') ?? '7d';
|
||||
}
|
||||
|
||||
async requestOtp(mobile: string): Promise<{ message: string }> {
|
||||
const recentOtp = await this.otpRepository.findOne({
|
||||
where: { mobile, verified: false },
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
|
||||
if (recentOtp) {
|
||||
const cooldownEnd =
|
||||
recentOtp.createdAt.getTime() + this.otpCooldownSeconds * 1000;
|
||||
if (Date.now() < cooldownEnd) {
|
||||
throw new HttpException(
|
||||
'Please wait before requesting a new OTP',
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await this.otpRepository.delete({ mobile, verified: false });
|
||||
|
||||
const code = this.generateOtpCode();
|
||||
const hashedCode = await bcrypt.hash(code, 10);
|
||||
const expiresAt = new Date(
|
||||
Date.now() + this.otpExpiresInMinutes * 60 * 1000,
|
||||
);
|
||||
|
||||
await this.otpRepository.save({
|
||||
mobile,
|
||||
code: hashedCode,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
const sent = await this.smsService.sendSms(mobile, `کد ورود: ${code}`);
|
||||
|
||||
if (!sent) {
|
||||
throw new BadRequestException('Failed to send OTP');
|
||||
}
|
||||
|
||||
if (
|
||||
this.otpDebug &&
|
||||
this.configService.get<string>('NODE_ENV') === 'development'
|
||||
) {
|
||||
this.logger.debug(`OTP for ${mobile}: ${code}`);
|
||||
}
|
||||
|
||||
return { message: 'OTP sent' };
|
||||
}
|
||||
|
||||
async verifyOtp(dto: VerifyOtpDto): Promise<AuthTokensResponse> {
|
||||
const otp = await this.otpRepository.findOne({
|
||||
where: { mobile: dto.mobile, verified: false },
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
|
||||
if (!otp) {
|
||||
throw new UnauthorizedException('Invalid or expired OTP');
|
||||
}
|
||||
|
||||
if (otp.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException('Invalid or expired OTP');
|
||||
}
|
||||
|
||||
if (otp.attempts >= this.otpMaxAttempts) {
|
||||
throw new UnauthorizedException('Too many failed attempts');
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(dto.code, otp.code);
|
||||
if (!isValid) {
|
||||
otp.attempts += 1;
|
||||
await this.otpRepository.save(otp);
|
||||
throw new UnauthorizedException('Invalid or expired OTP');
|
||||
}
|
||||
|
||||
otp.verified = true;
|
||||
await this.otpRepository.save(otp);
|
||||
|
||||
const user = await this.resolveUserForLogin(dto);
|
||||
return this.issueTokens(user);
|
||||
}
|
||||
|
||||
async refresh(refreshToken: string): Promise<AuthTokensResponse> {
|
||||
const storedTokens = await this.refreshTokenRepository.find({
|
||||
where: { revokedAt: IsNull() },
|
||||
relations: { user: true },
|
||||
});
|
||||
|
||||
let matchedToken: RefreshToken | null = null;
|
||||
for (const stored of storedTokens) {
|
||||
if (await bcrypt.compare(refreshToken, stored.tokenHash)) {
|
||||
if (stored.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException('Invalid refresh token');
|
||||
}
|
||||
matchedToken = stored;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchedToken) {
|
||||
throw new UnauthorizedException('Invalid refresh token');
|
||||
}
|
||||
|
||||
matchedToken.revokedAt = new Date();
|
||||
await this.refreshTokenRepository.save(matchedToken);
|
||||
|
||||
return this.issueTokens(matchedToken.user);
|
||||
}
|
||||
|
||||
async logout(userId: string, refreshToken: string): Promise<void> {
|
||||
const storedTokens = await this.refreshTokenRepository.find({
|
||||
where: { userId, revokedAt: IsNull() },
|
||||
});
|
||||
|
||||
for (const stored of storedTokens) {
|
||||
if (await bcrypt.compare(refreshToken, stored.tokenHash)) {
|
||||
stored.revokedAt = new Date();
|
||||
await this.refreshTokenRepository.save(stored);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new UnauthorizedException('Invalid refresh token');
|
||||
}
|
||||
|
||||
private async resolveUserForLogin(dto: VerifyOtpDto): Promise<User> {
|
||||
const existingUser = await this.usersService.findByMobile(dto.mobile);
|
||||
|
||||
if (existingUser) {
|
||||
return existingUser;
|
||||
}
|
||||
|
||||
return this.createCustomerUser(dto);
|
||||
}
|
||||
|
||||
private async createCustomerUser(dto: VerifyOtpDto): Promise<User> {
|
||||
const firstName = dto.firstName ?? 'کاربر';
|
||||
const lastName = dto.lastName ?? dto.mobile.slice(-4);
|
||||
const dateOfBirth = dto.dateOfBirth ?? '2000-01-01';
|
||||
const address = dto.address ?? '-';
|
||||
|
||||
const user = await this.usersService.create({
|
||||
firstName,
|
||||
lastName,
|
||||
mobile: dto.mobile,
|
||||
role: UserRole.CUSTOMER,
|
||||
});
|
||||
|
||||
await this.customersRepository.save({
|
||||
userId: user.id,
|
||||
dateOfBirth,
|
||||
address,
|
||||
});
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private async issueTokens(user: User): Promise<AuthTokensResponse> {
|
||||
const payload: JwtPayload = { sub: user.id, role: user.role };
|
||||
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
const refreshToken = await this.createRefreshToken(user.id);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
mobile: user.mobile,
|
||||
role: user.role,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async createRefreshToken(userId: string): Promise<string> {
|
||||
const refreshToken = this.jwtService.sign(
|
||||
{ sub: userId },
|
||||
{
|
||||
secret: this.configService.getOrThrow<string>('JWT_REFRESH_SECRET'),
|
||||
expiresIn: this.refreshExpiresIn as `${number}d`,
|
||||
},
|
||||
);
|
||||
|
||||
const tokenHash = await bcrypt.hash(refreshToken, 10);
|
||||
const expiresAt = this.parseExpiresIn(this.refreshExpiresIn);
|
||||
|
||||
await this.refreshTokenRepository.save({
|
||||
userId,
|
||||
tokenHash,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
private generateOtpCode(): string {
|
||||
const max = Math.pow(10, this.otpLength);
|
||||
const min = Math.pow(10, this.otpLength - 1);
|
||||
return String(Math.floor(min + Math.random() * (max - min)));
|
||||
}
|
||||
|
||||
private parseExpiresIn(expiresIn: string): Date {
|
||||
const match = expiresIn.match(/^(\d+)([dhms])$/);
|
||||
if (!match) {
|
||||
return new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
const value = parseInt(match[1], 10);
|
||||
const unit = match[2];
|
||||
const multipliers: Record<string, number> = {
|
||||
s: 1000,
|
||||
m: 60 * 1000,
|
||||
h: 60 * 60 * 1000,
|
||||
d: 24 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
return new Date(Date.now() + value * multipliers[unit]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthUser } from '../interfaces/auth-user.interface';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): AuthUser => {
|
||||
const request = ctx.switchToHttp().getRequest<{ user: AuthUser }>();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthUser } from '../interfaces/auth-user.interface';
|
||||
|
||||
export const OptionalCurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): AuthUser | undefined => {
|
||||
const request = ctx.switchToHttp().getRequest<{ user?: AuthUser }>();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { PermissionCode } from '../../authorization/enums/permission-code.enum';
|
||||
|
||||
export const PERMISSIONS_KEY = 'permissions';
|
||||
export const Permissions = (...permissions: PermissionCode[]) =>
|
||||
SetMetadata(PERMISSIONS_KEY, permissions);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,7 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Matches } from 'class-validator';
|
||||
|
||||
export class RequestOtpDto {
|
||||
@Matches(/^09\d{9}$/)
|
||||
mobile: string;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
IsDateString,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Length,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
|
||||
export class VerifyOtpDto {
|
||||
@Matches(/^09\d{9}$/)
|
||||
mobile: string;
|
||||
|
||||
@IsString()
|
||||
@Length(4, 6)
|
||||
code: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Length(1, 100)
|
||||
firstName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Length(1, 100)
|
||||
lastName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
dateOfBirth?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Length(1, 500)
|
||||
address?: string;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('otps')
|
||||
export class Otp {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Index()
|
||||
@Column({ length: 11 })
|
||||
mobile: string;
|
||||
|
||||
@Column()
|
||||
code: string;
|
||||
|
||||
@Column({ type: 'timestamp' })
|
||||
expiresAt: Date;
|
||||
|
||||
@Column({ default: 0 })
|
||||
attempts: number;
|
||||
|
||||
@Column({ default: false })
|
||||
verified: boolean;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
import { User } from '../../users/entities/user.entity';
|
||||
|
||||
@Entity('refresh_tokens')
|
||||
export class RefreshToken {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
userId: string;
|
||||
|
||||
@Column()
|
||||
tokenHash: string;
|
||||
|
||||
@Column({ type: 'timestamp' })
|
||||
expiresAt: Date;
|
||||
|
||||
@Column({ type: 'timestamp', nullable: true })
|
||||
revokedAt: Date | null;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'userId' })
|
||||
user: User;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor(private readonly reflector: Reflector) {
|
||||
super();
|
||||
}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.canActivate(context);
|
||||
}
|
||||
|
||||
handleRequest<T>(err: Error | null, user: T): T {
|
||||
if (err || !user) {
|
||||
throw err ?? new UnauthorizedException();
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { PermissionCode } from '../../authorization/enums/permission-code.enum';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
import { PERMISSIONS_KEY } from '../decorators/permissions.decorator';
|
||||
import { AuthUser } from '../interfaces/auth-user.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredPermissions = this.reflector.getAllAndOverride<
|
||||
PermissionCode[]
|
||||
>(PERMISSIONS_KEY, [context.getHandler(), context.getClass()]);
|
||||
|
||||
if (!requiredPermissions?.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { user } = context.switchToHttp().getRequest<{ user: AuthUser }>();
|
||||
|
||||
if (user.role !== UserRole.ADMIN) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
if (user.permissions.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasAllPermissions = requiredPermissions.every((permission) =>
|
||||
user.permissions.includes(permission),
|
||||
);
|
||||
|
||||
if (!hasAllPermissions) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import { AuthUser } from '../interfaces/auth-user.interface';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
|
||||
@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?.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { user } = context.switchToHttp().getRequest<{ user: AuthUser }>();
|
||||
|
||||
if (!requiredRoles.includes(user.role)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
|
||||
export class AuthUser {
|
||||
id: string;
|
||||
role: UserRole;
|
||||
mobile: string;
|
||||
permissions: string[];
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
role: UserRole;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { AuthorizationService } from '../../authorization/authorization.service';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
import { UsersService } from '../../users/users.service';
|
||||
import { AuthUser } from '../interfaces/auth-user.interface';
|
||||
import { JwtPayload } from '../interfaces/jwt-payload.interface';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(
|
||||
configService: ConfigService,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly authorizationService: AuthorizationService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.getOrThrow<string>('JWT_ACCESS_SECRET'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload): Promise<AuthUser> {
|
||||
const user = await this.usersService.findOne(payload.sub);
|
||||
|
||||
const permissions =
|
||||
user.role === UserRole.ADMIN
|
||||
? await this.authorizationService.loadPermissions(user.id)
|
||||
: [];
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
role: user.role,
|
||||
mobile: user.mobile,
|
||||
permissions,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthorizationService } from './authorization.service';
|
||||
import { Permission } from './entities/permission.entity';
|
||||
import { UserPermission } from './entities/user-permission.entity';
|
||||
import { CustomerPolicy } from './policies/customer.policy';
|
||||
import { SalonPolicy } from './policies/salon.policy';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Permission, UserPermission])],
|
||||
providers: [AuthorizationService, SalonPolicy, CustomerPolicy],
|
||||
exports: [AuthorizationService, SalonPolicy, CustomerPolicy],
|
||||
})
|
||||
export class AuthorizationModule {}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserPermission } from './entities/user-permission.entity';
|
||||
|
||||
@Injectable()
|
||||
export class AuthorizationService {
|
||||
constructor(
|
||||
@InjectRepository(UserPermission)
|
||||
private readonly userPermissionsRepository: Repository<UserPermission>,
|
||||
) {}
|
||||
|
||||
async loadPermissions(userId: string): Promise<string[]> {
|
||||
const userPermissions = await this.userPermissionsRepository.find({
|
||||
where: { userId },
|
||||
relations: { permission: true },
|
||||
});
|
||||
|
||||
return userPermissions.map((up) => up.permission.code);
|
||||
}
|
||||
|
||||
hasPermission(user: AuthUser, code: string): boolean {
|
||||
return user.permissions.includes(code);
|
||||
}
|
||||
|
||||
isAdmin(user: AuthUser): boolean {
|
||||
return user.role === UserRole.ADMIN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
||||
|
||||
@Entity('permissions')
|
||||
export class Permission {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ unique: true })
|
||||
code: string;
|
||||
|
||||
@Column()
|
||||
description: string;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
import { User } from '../../users/entities/user.entity';
|
||||
import { Permission } from './permission.entity';
|
||||
|
||||
@Entity('user_permissions')
|
||||
@Unique(['userId', 'permissionId'])
|
||||
export class UserPermission {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
userId: string;
|
||||
|
||||
@Column()
|
||||
permissionId: string;
|
||||
|
||||
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'userId' })
|
||||
user: User;
|
||||
|
||||
@ManyToOne(() => Permission, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'permissionId' })
|
||||
permission: Permission;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export enum PermissionCode {
|
||||
USERS_READ = 'users:read',
|
||||
USERS_WRITE = 'users:write',
|
||||
USERS_DELETE = 'users:delete',
|
||||
SALONS_READ = 'salons:read',
|
||||
SALONS_WRITE = 'salons:write',
|
||||
SALONS_DELETE = 'salons:delete',
|
||||
CUSTOMERS_READ = 'customers:read',
|
||||
CUSTOMERS_WRITE = 'customers:write',
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthUser } from '../../auth/interfaces/auth-user.interface';
|
||||
import { Customer } from '../../customers/entities/customer.entity';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
import { AuthorizationService } from '../authorization.service';
|
||||
|
||||
@Injectable()
|
||||
export class CustomerPolicy {
|
||||
constructor(private readonly authorizationService: AuthorizationService) {}
|
||||
|
||||
canRead(user: AuthUser, customer: Customer): boolean {
|
||||
if (this.authorizationService.isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (user.role === UserRole.CUSTOMER) {
|
||||
return customer.userId === user.id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
canUpdate(user: AuthUser, customer: Customer): boolean {
|
||||
if (this.authorizationService.isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (user.role === UserRole.CUSTOMER) {
|
||||
return customer.userId === user.id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthUser } from '../../auth/interfaces/auth-user.interface';
|
||||
import { Salon } from '../../salons/entities/salon.entity';
|
||||
import { UserRole } from '../../users/enums/user-role.enum';
|
||||
import { AuthorizationService } from '../authorization.service';
|
||||
|
||||
@Injectable()
|
||||
export class SalonPolicy {
|
||||
constructor(private readonly authorizationService: AuthorizationService) {}
|
||||
|
||||
canRead(user: AuthUser, salon: Salon): boolean {
|
||||
if (this.authorizationService.isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (user.role === UserRole.SALON) {
|
||||
return salon.ownerId === user.id;
|
||||
}
|
||||
if (user.role === UserRole.CUSTOMER) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
canUpdate(user: AuthUser, salon: Salon): boolean {
|
||||
if (this.authorizationService.isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (user.role === UserRole.SALON) {
|
||||
return salon.ownerId === user.id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
canDelete(user: AuthUser, salon: Salon): boolean {
|
||||
if (this.authorizationService.isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (user.role === UserRole.SALON) {
|
||||
return salon.ownerId === user.id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export default () => {
|
||||
const isDev = process.env.NODE_ENV !== 'production';
|
||||
|
||||
return {
|
||||
JWT_ACCESS_SECRET:
|
||||
process.env.JWT_ACCESS_SECRET ??
|
||||
(isDev ? 'dev-jwt-access-secret-change-me' : undefined),
|
||||
JWT_REFRESH_SECRET:
|
||||
process.env.JWT_REFRESH_SECRET ??
|
||||
(isDev ? 'dev-jwt-refresh-secret-change-me' : undefined),
|
||||
JWT_ACCESS_EXPIRES_IN: process.env.JWT_ACCESS_EXPIRES_IN ?? '15m',
|
||||
JWT_REFRESH_EXPIRES_IN: process.env.JWT_REFRESH_EXPIRES_IN ?? '7d',
|
||||
SMS_API_KEY: process.env.SMS_API_KEY ?? '',
|
||||
SMS_SENDER: process.env.SMS_SENDER ?? '',
|
||||
SMS_API_BASE_URL:
|
||||
process.env.SMS_API_BASE_URL ??
|
||||
'https://api.sms-webservice.com/api/V3',
|
||||
OTP_LENGTH: process.env.OTP_LENGTH ?? '5',
|
||||
OTP_EXPIRES_IN_MINUTES: process.env.OTP_EXPIRES_IN_MINUTES ?? '5',
|
||||
OTP_MAX_ATTEMPTS: process.env.OTP_MAX_ATTEMPTS ?? '5',
|
||||
OTP_COOLDOWN_SECONDS: process.env.OTP_COOLDOWN_SECONDS ?? '60',
|
||||
OTP_DEBUG: process.env.OTP_DEBUG ?? 'false',
|
||||
};
|
||||
};
|
||||
@@ -6,39 +6,49 @@ import {
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { PermissionCode } from '../authorization/enums/permission-code.enum';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Permissions } from '../auth/decorators/permissions.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { PermissionsGuard } from '../auth/guards/permissions.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { CustomersService } from './customers.service';
|
||||
import { CreateCustomerDto } from './dto/create-customer.dto';
|
||||
import { UpdateCustomerDto } from './dto/update-customer.dto';
|
||||
|
||||
@Controller('customers')
|
||||
@UseGuards(RolesGuard, PermissionsGuard)
|
||||
export class CustomersController {
|
||||
constructor(private readonly customersService: CustomersService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createCustomerDto: CreateCustomerDto) {
|
||||
return this.customersService.create(createCustomerDto);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN)
|
||||
@Permissions(PermissionCode.CUSTOMERS_READ)
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.customersService.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.customersService.findOne(id);
|
||||
findOne(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.customersService.findOne(id, user);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() updateCustomerDto: UpdateCustomerDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.customersService.update(id, updateCustomerDto);
|
||||
return this.customersService.update(id, updateCustomerDto, user);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN)
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.customersService.remove(id);
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthGuardsModule } from '../auth/auth-guards.module';
|
||||
import { AuthorizationModule } from '../authorization/authorization.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { CustomersController } from './customers.controller';
|
||||
import { CustomersService } from './customers.service';
|
||||
import { Customer } from './entities/customer.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Customer]), UsersModule],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Customer]),
|
||||
UsersModule,
|
||||
AuthorizationModule,
|
||||
AuthGuardsModule,
|
||||
],
|
||||
controllers: [CustomersController],
|
||||
providers: [CustomersService],
|
||||
exports: [CustomersService],
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CustomerPolicy } from '../authorization/policies/customer.policy';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { CreateCustomerDto } from './dto/create-customer.dto';
|
||||
@@ -13,6 +19,7 @@ export class CustomersService {
|
||||
@InjectRepository(Customer)
|
||||
private readonly customersRepository: Repository<Customer>,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly customerPolicy: CustomerPolicy,
|
||||
) {}
|
||||
|
||||
async create(createCustomerDto: CreateCustomerDto): Promise<Customer> {
|
||||
@@ -37,7 +44,7 @@ export class CustomersService {
|
||||
return this.customersRepository.find({ relations: { user: true } });
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<Customer> {
|
||||
async findOne(id: string, user?: AuthUser): Promise<Customer> {
|
||||
const customer = await this.customersRepository.findOne({
|
||||
where: { id },
|
||||
relations: { user: true },
|
||||
@@ -45,14 +52,24 @@ export class CustomersService {
|
||||
if (!customer) {
|
||||
throw new NotFoundException(`Customer #${id} not found`);
|
||||
}
|
||||
|
||||
if (user && !this.customerPolicy.canRead(user, customer)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
return customer;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
updateCustomerDto: UpdateCustomerDto,
|
||||
user: AuthUser,
|
||||
): Promise<Customer> {
|
||||
const customer = await this.findOne(id);
|
||||
if (!this.customerPolicy.canUpdate(user, customer)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
const { firstName, lastName, mobile, dateOfBirth, address } =
|
||||
updateCustomerDto;
|
||||
|
||||
@@ -76,7 +93,7 @@ export class CustomersService {
|
||||
}
|
||||
|
||||
await this.customersRepository.save(customer);
|
||||
return this.findOne(customer.id);
|
||||
return this.findOne(customer.id, user);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
|
||||
@@ -25,6 +25,7 @@ export class CreateSalonDto {
|
||||
@Matches(/^09\d{9}$/)
|
||||
phone: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
ownerId: string;
|
||||
ownerId?: string;
|
||||
}
|
||||
|
||||
@@ -7,40 +7,61 @@ import {
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { OptionalCurrentUser } from '../auth/decorators/optional-current-user.decorator';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { CreateSalonDto } from './dto/create-salon.dto';
|
||||
import { UpdateSalonDto } from './dto/update-salon.dto';
|
||||
import { SalonsService } from './salons.service';
|
||||
|
||||
@Controller('salons')
|
||||
@UseGuards(RolesGuard)
|
||||
export class SalonsController {
|
||||
constructor(private readonly salonsService: SalonsService) {}
|
||||
|
||||
@Roles(UserRole.ADMIN, UserRole.SALON)
|
||||
@Post()
|
||||
create(@Body() createSalonDto: CreateSalonDto) {
|
||||
return this.salonsService.create(createSalonDto);
|
||||
create(
|
||||
@Body() createSalonDto: CreateSalonDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.salonsService.create(createSalonDto, user);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.salonsService.findAll();
|
||||
findAll(@OptionalCurrentUser() user?: AuthUser) {
|
||||
return this.salonsService.findAll(user);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.salonsService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN, UserRole.SALON)
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() updateSalonDto: UpdateSalonDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.salonsService.update(id, updateSalonDto);
|
||||
return this.salonsService.update(id, updateSalonDto, user);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN, UserRole.SALON)
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.salonsService.remove(id);
|
||||
remove(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.salonsService.remove(id, user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthGuardsModule } from '../auth/auth-guards.module';
|
||||
import { AuthorizationModule } from '../authorization/authorization.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { Salon } from './entities/salon.entity';
|
||||
import { SalonsController } from './salons.controller';
|
||||
import { SalonsService } from './salons.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Salon]), UsersModule],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Salon]),
|
||||
UsersModule,
|
||||
AuthorizationModule,
|
||||
AuthGuardsModule,
|
||||
],
|
||||
controllers: [SalonsController],
|
||||
providers: [SalonsService],
|
||||
exports: [SalonsService],
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { SalonPolicy } from '../authorization/policies/salon.policy';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { CreateSalonDto } from './dto/create-salon.dto';
|
||||
@@ -17,15 +20,28 @@ export class SalonsService {
|
||||
@InjectRepository(Salon)
|
||||
private readonly salonsRepository: Repository<Salon>,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly salonPolicy: SalonPolicy,
|
||||
) {}
|
||||
|
||||
async create(createSalonDto: CreateSalonDto): Promise<Salon> {
|
||||
await this.ensureOwnerIsSalonOwner(createSalonDto.ownerId);
|
||||
const salon = this.salonsRepository.create(createSalonDto);
|
||||
async create(createSalonDto: CreateSalonDto, user: AuthUser): Promise<Salon> {
|
||||
const ownerId = this.resolveOwnerId(createSalonDto, user);
|
||||
await this.ensureOwnerIsSalonOwner(ownerId);
|
||||
|
||||
const salon = this.salonsRepository.create({
|
||||
...createSalonDto,
|
||||
ownerId,
|
||||
});
|
||||
return this.salonsRepository.save(salon);
|
||||
}
|
||||
|
||||
findAll(): Promise<Salon[]> {
|
||||
findAll(user?: AuthUser): Promise<Salon[]> {
|
||||
if (user?.role === UserRole.SALON) {
|
||||
return this.salonsRepository.find({
|
||||
where: { ownerId: user.id },
|
||||
relations: { owner: true },
|
||||
});
|
||||
}
|
||||
|
||||
return this.salonsRepository.find({ relations: { owner: true } });
|
||||
}
|
||||
|
||||
@@ -40,17 +56,42 @@ export class SalonsService {
|
||||
return salon;
|
||||
}
|
||||
|
||||
async update(id: string, updateSalonDto: UpdateSalonDto): Promise<Salon> {
|
||||
async update(
|
||||
id: string,
|
||||
updateSalonDto: UpdateSalonDto,
|
||||
user: AuthUser,
|
||||
): Promise<Salon> {
|
||||
const salon = await this.findOne(id);
|
||||
if (!this.salonPolicy.canUpdate(user, salon)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
Object.assign(salon, updateSalonDto);
|
||||
return this.salonsRepository.save(salon);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
async remove(id: string, user: AuthUser): Promise<void> {
|
||||
const salon = await this.findOne(id);
|
||||
if (!this.salonPolicy.canDelete(user, salon)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
await this.salonsRepository.remove(salon);
|
||||
}
|
||||
|
||||
private resolveOwnerId(
|
||||
createSalonDto: CreateSalonDto,
|
||||
user: AuthUser,
|
||||
): string {
|
||||
if (user.role === UserRole.SALON) {
|
||||
return user.id;
|
||||
}
|
||||
|
||||
if (!createSalonDto.ownerId) {
|
||||
throw new BadRequestException('ownerId is required for admin');
|
||||
}
|
||||
|
||||
return createSalonDto.ownerId;
|
||||
}
|
||||
|
||||
private async ensureOwnerIsSalonOwner(ownerId: string): Promise<void> {
|
||||
const owner = await this.usersService.findOne(ownerId);
|
||||
if (owner.role !== UserRole.SALON) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { HttpModule } from '@nestjs/axios';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SmsService } from './sms.service';
|
||||
|
||||
@Module({
|
||||
imports: [HttpModule],
|
||||
providers: [SmsService],
|
||||
exports: [SmsService],
|
||||
})
|
||||
export class SmsModule {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { HttpService } from '@nestjs/axios';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private readonly logger = new Logger(SmsService.name);
|
||||
private readonly apiKey: string;
|
||||
private readonly sender: string;
|
||||
private readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
private readonly httpService: HttpService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
this.apiKey = this.configService.get<string>('SMS_API_KEY', '');
|
||||
this.sender = this.configService.get<string>('SMS_SENDER', '');
|
||||
this.baseUrl =
|
||||
this.configService.get<string>('SMS_API_BASE_URL') ??
|
||||
'https://api.sms-webservice.com/api/V3';
|
||||
}
|
||||
|
||||
async sendSms(mobile: string, message: string): Promise<boolean> {
|
||||
if (!this.apiKey || !this.sender) {
|
||||
this.logger.error('SMS_API_KEY or SMS_SENDER is not configured');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const url = new URL(`${this.baseUrl}/Send`);
|
||||
url.searchParams.append('ApiKey', this.apiKey);
|
||||
url.searchParams.append('Sender', this.sender);
|
||||
url.searchParams.append('Recipients', mobile);
|
||||
url.searchParams.append('Text', message);
|
||||
|
||||
await firstValueFrom(this.httpService.get(url.toString()));
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to send SMS to ${mobile}`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMultipleSms(
|
||||
recipients: Array<{ mobile: string; message: string }>,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await firstValueFrom(
|
||||
this.httpService.post(`${this.baseUrl}/SendMultiple`, {
|
||||
ApiKey: this.apiKey,
|
||||
Recipients: recipients,
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to send multiple SMS', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { IsOptional, IsString, Length, Matches } from 'class-validator';
|
||||
import { IsEnum, IsOptional, IsString, Length, Matches } from 'class-validator';
|
||||
import { UserRole } from '../enums/user-role.enum';
|
||||
|
||||
export class UpdateUserDto {
|
||||
@IsOptional()
|
||||
@@ -14,4 +15,8 @@ export class UpdateUserDto {
|
||||
@IsOptional()
|
||||
@Matches(/^09\d{9}$/)
|
||||
mobile?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(UserRole)
|
||||
role?: UserRole;
|
||||
}
|
||||
|
||||
@@ -2,32 +2,53 @@ import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { PermissionCode } from '../authorization/enums/permission-code.enum';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Permissions } from '../auth/decorators/permissions.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { PermissionsGuard } from '../auth/guards/permissions.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { UserRole } from './enums/user-role.enum';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('users')
|
||||
@UseGuards(RolesGuard, PermissionsGuard)
|
||||
export class UsersController {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
@Roles(UserRole.ADMIN)
|
||||
@Permissions(PermissionCode.USERS_WRITE)
|
||||
@Post()
|
||||
create(@Body() createUserDto: CreateUserDto) {
|
||||
return this.usersService.create(createUserDto);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN)
|
||||
@Permissions(PermissionCode.USERS_READ)
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.usersService.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseUUIDPipe) id: string) {
|
||||
findOne(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
if (user.role !== UserRole.ADMIN && user.id !== id) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
return this.usersService.findOne(id);
|
||||
}
|
||||
|
||||
@@ -35,10 +56,16 @@ export class UsersController {
|
||||
update(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() updateUserDto: UpdateUserDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.usersService.update(id, updateUserDto);
|
||||
if (user.role !== UserRole.ADMIN && user.id !== id) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
return this.usersService.update(id, updateUserDto, user);
|
||||
}
|
||||
|
||||
@Roles(UserRole.ADMIN)
|
||||
@Permissions(PermissionCode.USERS_DELETE)
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.usersService.remove(id);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthGuardsModule } from '../auth/auth-guards.module';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User])],
|
||||
imports: [TypeOrmModule.forFeature([User]), AuthGuardsModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { AuthUser } from '../auth/interfaces/auth-user.interface';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRole } from './enums/user-role.enum';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
@@ -34,11 +37,25 @@ export class UsersService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async update(id: string, updateUserDto: UpdateUserDto): Promise<User> {
|
||||
async findByMobile(mobile: string): Promise<User | null> {
|
||||
return this.usersRepository.findOneBy({ mobile });
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
updateUserDto: UpdateUserDto,
|
||||
currentUser?: AuthUser,
|
||||
): Promise<User> {
|
||||
const user = await this.findOne(id);
|
||||
if (updateUserDto.mobile) {
|
||||
await this.ensureMobileIsUnique(updateUserDto.mobile, id);
|
||||
}
|
||||
if (
|
||||
updateUserDto.role !== undefined &&
|
||||
currentUser?.role !== UserRole.ADMIN
|
||||
) {
|
||||
throw new ForbiddenException('Only admin can change user role');
|
||||
}
|
||||
Object.assign(user, updateUserDto);
|
||||
return this.usersRepository.save(user);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user