add auth roles and guards 050220
This commit is contained in:
@@ -7,8 +7,13 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AttributeDefinitionEntity } from '../../entities/attribute-definition.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { AttributeDefinitionsService } from './attribute-definitions.service';
|
||||
import { CreateAttributeDefinitionDto } from './dto/create-attribute-definition.dto';
|
||||
import { UpdateAttributeDefinitionDto } from './dto/update-attribute-definition.dto';
|
||||
@@ -30,6 +35,8 @@ export class AttributeDefinitionsController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
create(
|
||||
@Body() payload: CreateAttributeDefinitionDto,
|
||||
): Promise<AttributeDefinitionEntity> {
|
||||
@@ -37,6 +44,8 @@ export class AttributeDefinitionsController {
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateAttributeDefinitionDto,
|
||||
@@ -45,6 +54,8 @@ export class AttributeDefinitionsController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
return { success: true };
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,15 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BookingEntity, BookingStatus } from '../../entities/booking.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { BookingsService } from './bookings.service';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
import { UpdateBookingDto } from './dto/update-booking.dto';
|
||||
@@ -18,33 +25,51 @@ export class BookingsController {
|
||||
constructor(private readonly service: BookingsService) {}
|
||||
|
||||
@Get()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER, UserRole.CUSTOMER)
|
||||
findAll(
|
||||
@Query('customerId') customerId?: string,
|
||||
@Query('businessId') businessId?: string,
|
||||
@Query('status') status?: BookingStatus,
|
||||
@CurrentUser() user?: AuthUser,
|
||||
): Promise<BookingEntity[]> {
|
||||
return this.service.findAll({ customerId, businessId, status });
|
||||
return this.service.findAll({ customerId, businessId, status }, user);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string): Promise<BookingEntity> {
|
||||
return this.service.findOne(id);
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER, UserRole.CUSTOMER)
|
||||
findOne(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BookingEntity> {
|
||||
return this.service.findOne(id, user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() payload: CreateBookingDto): Promise<BookingEntity> {
|
||||
return this.service.create(payload);
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.CUSTOMER)
|
||||
create(
|
||||
@Body() payload: CreateBookingDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BookingEntity> {
|
||||
return this.service.create(payload, user);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateBookingDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BookingEntity> {
|
||||
return this.service.update(id, payload);
|
||||
return this.service.update(id, payload, user);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
return { success: true };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -9,7 +10,8 @@ import { Repository } from 'typeorm';
|
||||
import { BookingEntity, BookingStatus } from '../../entities/booking.entity';
|
||||
import { BusinessServiceEntity } from '../../entities/business-service.entity';
|
||||
import { BusinessEntity } from '../../entities/business.entity';
|
||||
import { UserEntity } from '../../entities/user.entity';
|
||||
import { UserEntity, UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
import { UpdateBookingDto } from './dto/update-booking.dto';
|
||||
|
||||
@@ -39,7 +41,10 @@ export class BookingsService {
|
||||
this.minLeadMinutes = Number.isFinite(parsed) && parsed >= 0 ? parsed : 60;
|
||||
}
|
||||
|
||||
async findAll(filters: FindAllFilters): Promise<BookingEntity[]> {
|
||||
async findAll(
|
||||
filters: FindAllFilters,
|
||||
actor?: AuthUser,
|
||||
): Promise<BookingEntity[]> {
|
||||
const qb = this.repo
|
||||
.createQueryBuilder('b')
|
||||
.leftJoinAndSelect('b.customer', 'customer')
|
||||
@@ -48,7 +53,15 @@ export class BookingsService {
|
||||
.leftJoinAndSelect('businessService.serviceTemplate', 'template')
|
||||
.orderBy('b.scheduledAt', 'ASC');
|
||||
|
||||
if (filters.customerId) {
|
||||
if (actor?.role === UserRole.CUSTOMER) {
|
||||
qb.andWhere('b.customerId = :actorCustomerId', {
|
||||
actorCustomerId: actor.id,
|
||||
});
|
||||
} else if (actor?.role === UserRole.BUSINESS_OWNER) {
|
||||
qb.andWhere('business.ownerId = :actorOwnerId', {
|
||||
actorOwnerId: actor.id,
|
||||
});
|
||||
} else if (filters.customerId) {
|
||||
qb.andWhere('b.customerId = :customerId', {
|
||||
customerId: filters.customerId,
|
||||
});
|
||||
@@ -65,7 +78,7 @@ export class BookingsService {
|
||||
return qb.getMany();
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<BookingEntity> {
|
||||
async findOne(id: string, actor?: AuthUser): Promise<BookingEntity> {
|
||||
const row = await this.repo.findOne({
|
||||
where: { id },
|
||||
relations: {
|
||||
@@ -77,10 +90,18 @@ export class BookingsService {
|
||||
if (!row) {
|
||||
throw new NotFoundException('Booking not found');
|
||||
}
|
||||
this.assertCanViewBooking(row, actor);
|
||||
return row;
|
||||
}
|
||||
|
||||
async create(dto: CreateBookingDto): Promise<BookingEntity> {
|
||||
async create(dto: CreateBookingDto, actor?: AuthUser): Promise<BookingEntity> {
|
||||
if (
|
||||
actor?.role === UserRole.CUSTOMER &&
|
||||
dto.customerId !== actor.id
|
||||
) {
|
||||
throw new ForbiddenException('Customers can only book for themselves');
|
||||
}
|
||||
|
||||
const customer = await this.userRepo.findOne({
|
||||
where: { id: dto.customerId },
|
||||
});
|
||||
@@ -124,8 +145,13 @@ export class BookingsService {
|
||||
return this.repo.save(entity);
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateBookingDto): Promise<BookingEntity> {
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateBookingDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BookingEntity> {
|
||||
const row = await this.findOne(id);
|
||||
this.assertCanManageBooking(row, actor);
|
||||
|
||||
if (dto.scheduledAt !== undefined) {
|
||||
const scheduledAt = this.parseScheduledAt(dto.scheduledAt);
|
||||
@@ -168,4 +194,38 @@ export class BookingsService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private assertCanViewBooking(row: BookingEntity, actor?: AuthUser): void {
|
||||
if (!actor || actor.role === UserRole.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (actor.role === UserRole.CUSTOMER && row.customerId === actor.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
actor.role === UserRole.BUSINESS_OWNER &&
|
||||
row.business?.ownerId === actor.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new ForbiddenException('You cannot access this booking');
|
||||
}
|
||||
|
||||
private assertCanManageBooking(row: BookingEntity, actor?: AuthUser): void {
|
||||
if (!actor || actor.role === UserRole.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
actor.role === UserRole.BUSINESS_OWNER &&
|
||||
row.business?.ownerId === actor.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new ForbiddenException('You can only manage your own business bookings');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,15 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BusinessAttributeValueEntity } from '../../entities/business-attribute-value.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { BusinessAttributeValuesService } from './business-attribute-values.service';
|
||||
import { CreateBusinessAttributeValueDto } from './dto/create-business-attribute-value.dto';
|
||||
import { UpdateBusinessAttributeValueDto } from './dto/update-business-attribute-value.dto';
|
||||
@@ -30,23 +37,34 @@ export class BusinessAttributeValuesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
create(
|
||||
@Body() payload: CreateBusinessAttributeValueDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BusinessAttributeValueEntity> {
|
||||
return this.service.create(payload);
|
||||
return this.service.create(payload, user);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateBusinessAttributeValueDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BusinessAttributeValueEntity> {
|
||||
return this.service.update(id, payload);
|
||||
return this.service.update(id, payload, user);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
async remove(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<{ success: true }> {
|
||||
await this.service.remove(id, user);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -12,6 +13,8 @@ import {
|
||||
} from '../../entities/attribute-definition.entity';
|
||||
import { BusinessAttributeValueEntity } from '../../entities/business-attribute-value.entity';
|
||||
import { BusinessEntity } from '../../entities/business.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CreateBusinessAttributeValueDto } from './dto/create-business-attribute-value.dto';
|
||||
import { UpdateBusinessAttributeValueDto } from './dto/update-business-attribute-value.dto';
|
||||
|
||||
@@ -53,6 +56,7 @@ export class BusinessAttributeValuesService {
|
||||
|
||||
async create(
|
||||
dto: CreateBusinessAttributeValueDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BusinessAttributeValueEntity> {
|
||||
const business = await this.businessRepo.findOne({
|
||||
where: { id: dto.businessId },
|
||||
@@ -60,6 +64,7 @@ export class BusinessAttributeValuesService {
|
||||
if (!business) {
|
||||
throw new NotFoundException('Business not found');
|
||||
}
|
||||
this.assertCanManageBusiness(business, actor);
|
||||
|
||||
const def = await this.defRepo.findOne({
|
||||
where: { id: dto.attributeDefinitionId },
|
||||
@@ -100,8 +105,10 @@ export class BusinessAttributeValuesService {
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateBusinessAttributeValueDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BusinessAttributeValueEntity> {
|
||||
const row = await this.findOne(id);
|
||||
this.assertCanManageBusiness(row.business, actor);
|
||||
|
||||
const def =
|
||||
row.attributeDefinition ??
|
||||
@@ -120,7 +127,10 @@ export class BusinessAttributeValuesService {
|
||||
return this.repo.save(row);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
async remove(id: string, actor?: AuthUser): Promise<void> {
|
||||
const row = await this.findOne(id);
|
||||
this.assertCanManageBusiness(row.business, actor);
|
||||
|
||||
const result = await this.repo.delete(id);
|
||||
if (!result.affected) {
|
||||
throw new NotFoundException('Business attribute value not found');
|
||||
@@ -174,4 +184,20 @@ export class BusinessAttributeValuesService {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
private assertCanManageBusiness(
|
||||
business: BusinessEntity,
|
||||
actor?: AuthUser,
|
||||
): void {
|
||||
if (!actor || actor.role === UserRole.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
actor.role !== UserRole.BUSINESS_OWNER ||
|
||||
business.ownerId !== actor.id
|
||||
) {
|
||||
throw new ForbiddenException('You can only manage your own business');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,13 @@ import {
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { BusinessCategoriesService } from './business-categories.service';
|
||||
import { CreateBusinessCategoryDto } from './dto/create-business-category.dto';
|
||||
import { UpdateBusinessCategoryDto } from './dto/update-business-category.dto';
|
||||
@@ -27,6 +32,8 @@ export class BusinessCategoriesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
create(
|
||||
@Body() payload: CreateBusinessCategoryDto,
|
||||
): Promise<BusinessCategoryEntity> {
|
||||
@@ -34,6 +41,8 @@ export class BusinessCategoriesController {
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateBusinessCategoryDto,
|
||||
@@ -42,6 +51,8 @@ export class BusinessCategoriesController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
return { success: true };
|
||||
|
||||
@@ -7,8 +7,15 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BusinessServiceEntity } from '../../entities/business-service.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { BusinessServicesService } from './business-services.service';
|
||||
import { CreateBusinessServiceDto } from './dto/create-business-service.dto';
|
||||
import { UpdateBusinessServiceDto } from './dto/update-business-service.dto';
|
||||
@@ -39,23 +46,34 @@ export class BusinessServicesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
create(
|
||||
@Body() payload: CreateBusinessServiceDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BusinessServiceEntity> {
|
||||
return this.service.create(payload);
|
||||
return this.service.create(payload, user);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateBusinessServiceDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BusinessServiceEntity> {
|
||||
return this.service.update(id, payload);
|
||||
return this.service.update(id, payload, user);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
async remove(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<{ success: true }> {
|
||||
await this.service.remove(id, user);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -9,6 +10,8 @@ import { Repository } from 'typeorm';
|
||||
import { BusinessEntity } from '../../entities/business.entity';
|
||||
import { BusinessServiceEntity } from '../../entities/business-service.entity';
|
||||
import { ServiceTemplateEntity } from '../../entities/service-template.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CreateBusinessServiceDto } from './dto/create-business-service.dto';
|
||||
import { UpdateBusinessServiceDto } from './dto/update-business-service.dto';
|
||||
|
||||
@@ -73,13 +76,17 @@ export class BusinessServicesService {
|
||||
return row;
|
||||
}
|
||||
|
||||
async create(dto: CreateBusinessServiceDto): Promise<BusinessServiceEntity> {
|
||||
async create(
|
||||
dto: CreateBusinessServiceDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BusinessServiceEntity> {
|
||||
const business = await this.businessRepo.findOne({
|
||||
where: { id: dto.businessId },
|
||||
});
|
||||
if (!business) {
|
||||
throw new NotFoundException('Business not found');
|
||||
}
|
||||
this.assertCanManageBusiness(business, actor);
|
||||
|
||||
const template = await this.templateRepo.findOne({
|
||||
where: { id: dto.serviceTemplateId },
|
||||
@@ -123,6 +130,7 @@ export class BusinessServicesService {
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateBusinessServiceDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BusinessServiceEntity> {
|
||||
const row = await this.findOne(id);
|
||||
|
||||
@@ -137,6 +145,7 @@ export class BusinessServicesService {
|
||||
if (!business) {
|
||||
throw new NotFoundException('Business not found');
|
||||
}
|
||||
this.assertCanManageBusiness(business, actor);
|
||||
|
||||
const template = await this.templateRepo.findOne({
|
||||
where: { id: nextTemplateId },
|
||||
@@ -184,10 +193,35 @@ export class BusinessServicesService {
|
||||
return this.repo.save(row);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
async remove(id: string, actor?: AuthUser): Promise<void> {
|
||||
const row = await this.findOne(id);
|
||||
const business = await this.businessRepo.findOne({
|
||||
where: { id: row.businessId },
|
||||
});
|
||||
if (!business) {
|
||||
throw new NotFoundException('Business not found');
|
||||
}
|
||||
this.assertCanManageBusiness(business, actor);
|
||||
|
||||
const result = await this.repo.delete(id);
|
||||
if (!result.affected) {
|
||||
throw new NotFoundException('Business service not found');
|
||||
}
|
||||
}
|
||||
|
||||
private assertCanManageBusiness(
|
||||
business: BusinessEntity,
|
||||
actor?: AuthUser,
|
||||
): void {
|
||||
if (!actor || actor.role === UserRole.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
actor.role !== UserRole.BUSINESS_OWNER ||
|
||||
business.ownerId !== actor.id
|
||||
) {
|
||||
throw new ForbiddenException('You can only manage your own business');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,15 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BusinessEntity } from '../../entities/business.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { BusinessesService } from './businesses.service';
|
||||
import { CreateBusinessDto } from './dto/create-business.dto';
|
||||
import { UpdateBusinessDto } from './dto/update-business.dto';
|
||||
@@ -37,19 +44,26 @@ export class BusinessesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
create(@Body() payload: CreateBusinessDto): Promise<BusinessEntity> {
|
||||
return this.service.create(payload);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN, UserRole.BUSINESS_OWNER)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateBusinessDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
): Promise<BusinessEntity> {
|
||||
return this.service.update(id, payload);
|
||||
return this.service.update(id, payload, user);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
return { success: true };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -7,6 +8,8 @@ import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||
import { BusinessEntity } from '../../entities/business.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CreateBusinessDto } from './dto/create-business.dto';
|
||||
import { UpdateBusinessDto } from './dto/update-business.dto';
|
||||
|
||||
@@ -80,8 +83,13 @@ export class BusinessesService {
|
||||
return this.repo.save(entity);
|
||||
}
|
||||
|
||||
async update(id: string, payload: UpdateBusinessDto): Promise<BusinessEntity> {
|
||||
async update(
|
||||
id: string,
|
||||
payload: UpdateBusinessDto,
|
||||
actor?: AuthUser,
|
||||
): Promise<BusinessEntity> {
|
||||
const business = await this.findOne(id);
|
||||
this.assertCanUpdateBusiness(business, payload, actor);
|
||||
|
||||
if (payload.slug && payload.slug !== business.slug) {
|
||||
const slugTaken = await this.repo.findOne({ where: { slug: payload.slug } });
|
||||
@@ -111,4 +119,31 @@ export class BusinessesService {
|
||||
throw new NotFoundException('Business category not found');
|
||||
}
|
||||
}
|
||||
|
||||
private assertCanUpdateBusiness(
|
||||
business: BusinessEntity,
|
||||
payload: UpdateBusinessDto,
|
||||
actor?: AuthUser,
|
||||
): void {
|
||||
if (!actor || actor.role === UserRole.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
actor.role !== UserRole.BUSINESS_OWNER ||
|
||||
business.ownerId !== actor.id
|
||||
) {
|
||||
throw new ForbiddenException('You can only manage your own business');
|
||||
}
|
||||
|
||||
if (
|
||||
payload.ownerId !== undefined ||
|
||||
payload.categoryId !== undefined ||
|
||||
payload.isActive !== undefined
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Only the super admin can change owner, category, or active status',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,13 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ServiceTemplateEntity } from '../../entities/service-template.entity';
|
||||
import { UserRole } from '../../entities/user.entity';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { ServiceTemplatesService } from './service-templates.service';
|
||||
import { CreateServiceTemplateDto } from './dto/create-service-template.dto';
|
||||
import { UpdateServiceTemplateDto } from './dto/update-service-template.dto';
|
||||
@@ -37,6 +42,8 @@ export class ServiceTemplatesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
create(
|
||||
@Body() payload: CreateServiceTemplateDto,
|
||||
): Promise<ServiceTemplateEntity> {
|
||||
@@ -44,6 +51,8 @@ export class ServiceTemplatesController {
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateServiceTemplateDto,
|
||||
@@ -52,6 +61,8 @@ export class ServiceTemplatesController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
async remove(@Param('id') id: string): Promise<{ success: true }> {
|
||||
await this.service.remove(id);
|
||||
return { success: true };
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { UserRole } from '../../../entities/user.entity';
|
||||
|
||||
export class UpdateUserDto {
|
||||
fullName?: string | null;
|
||||
role?: UserRole;
|
||||
isActive?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserEntity, UserRole } from '../../entities/user.entity';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('users')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(UserRole.ADMIN)
|
||||
export class UsersController {
|
||||
constructor(private readonly service: UsersService) {}
|
||||
|
||||
@Get()
|
||||
findAll(): Promise<UserEntity[]> {
|
||||
return this.service.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string): Promise<UserEntity> {
|
||||
return this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() payload: UpdateUserDto,
|
||||
): Promise<UserEntity> {
|
||||
return this.service.update(id, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UserEntity } from '../../entities/user.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([UserEntity]), AuthModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UserEntity } from '../../entities/user.entity';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly repo: Repository<UserEntity>,
|
||||
) {}
|
||||
|
||||
findAll(): Promise<UserEntity[]> {
|
||||
return this.repo.find({ order: { createdAt: 'DESC' } });
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<UserEntity> {
|
||||
const user = await this.repo.findOne({ where: { id } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateUserDto): Promise<UserEntity> {
|
||||
const user = await this.findOne(id);
|
||||
|
||||
if (dto.fullName !== undefined) {
|
||||
user.fullName = dto.fullName;
|
||||
}
|
||||
if (dto.role !== undefined) {
|
||||
user.role = dto.role;
|
||||
}
|
||||
if (dto.isActive !== undefined) {
|
||||
user.isActive = dto.isActive;
|
||||
}
|
||||
|
||||
return this.repo.save(user);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user