add auth roles and guards 050220

This commit is contained in:
2026-05-11 12:40:42 +03:30
parent 03ac02bee9
commit 3e5543a548
29 changed files with 924 additions and 30 deletions
+7
View File
@@ -0,0 +1,7 @@
import { UserRole } from '../../../entities/user.entity';
export class UpdateUserDto {
fullName?: string | null;
role?: UserRole;
isActive?: boolean;
}
+39
View File
@@ -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);
}
}
+13
View File
@@ -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 {}
+41
View File
@@ -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);
}
}