diff --git a/src/structures/structures.controller.ts b/src/structures/structures.controller.ts index 2e17206da2b470367934fb5d1d252f43ed00cc26..94a6dca7760be4679d2376414728abdc21033e80 100644 --- a/src/structures/structures.controller.ts +++ b/src/structures/structures.controller.ts @@ -1,4 +1,7 @@ -import { Body, Controller, Get, Param, ParseIntPipe, Post, Put, Query } from '@nestjs/common'; +import { Body, Controller, Get, Param, ParseIntPipe, Post, Put, Query, UseGuards } from '@nestjs/common'; +import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; +import { Roles } from '../users/decorators/roles.decorator'; +import { IsStructureOwnerGuard } from '../users/guards/isStructureOwner.guard'; import { User } from '../users/schemas/user.schema'; import { UsersService } from '../users/users.service'; import { CreateStructureDto } from './dto/create-structure.dto'; @@ -22,7 +25,8 @@ export class StructuresController { } @Put(':id') - //TODO: protect, only structure owner can edit it + @UseGuards(JwtAuthGuard, IsStructureOwnerGuard) + @Roles('admin') public async update(@Param('id') id: string, @Body() body: structureDto): Promise<Structure> { return this.structureService.update(id, body); } diff --git a/src/users/guards/isStructureOwner.guard.ts b/src/users/guards/isStructureOwner.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c1de520b86f92083ac3eadc89c755e5c91bcb58 --- /dev/null +++ b/src/users/guards/isStructureOwner.guard.ts @@ -0,0 +1,21 @@ +import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import { User } from '../schemas/user.schema'; +import { RolesGuard } from './roles.guard'; + +@Injectable() +export class IsStructureOwnerGuard extends RolesGuard implements CanActivate { + constructor(protected readonly reflector: Reflector) { + super(reflector); + } + + canActivate(context: ExecutionContext): boolean { + const req = context.switchToHttp().getRequest(); + const user: User = req.user; + const idStructure = req.params.id; + if (user.structuresLink.includes(idStructure)) { + return true; + } + return super.canActivate(context); + } +} diff --git a/src/users/guards/roles.guard.ts b/src/users/guards/roles.guard.ts index 2ad8873575a0458ca5f15ffa6568f6af8767cbdd..fc06b77adf1253eb6efaf51fedfcc1c71a106882 100644 --- a/src/users/guards/roles.guard.ts +++ b/src/users/guards/roles.guard.ts @@ -4,7 +4,7 @@ import { UserRole } from '../enum/user-role.enum'; @Injectable() export class RolesGuard implements CanActivate { - constructor(private reflector: Reflector) {} + constructor(protected reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const roles = this.reflector.get<string[]>('roles', context.getHandler());