Skip to content

Commit

Permalink
[backend] Implement UserGuard and add it to UserController
Browse files Browse the repository at this point in the history
  • Loading branch information
usatie committed Nov 8, 2023
1 parent 1545b39 commit 7ffbca2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 4 additions & 0 deletions backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from '@nestjs/swagger';
import { UserEntity } from './entities/user.entity';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { UserGuard } from './user.guard';

@Controller('user')
@ApiTags('user')
Expand All @@ -44,6 +45,7 @@ export class UserController {
}

@Get(':id')
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOkResponse({ type: UserEntity })
Expand All @@ -52,6 +54,7 @@ export class UserController {
}

@Patch(':id')
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOkResponse({ type: UserEntity })
Expand All @@ -64,6 +67,7 @@ export class UserController {

@Delete(':id')
@HttpCode(204)
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiNoContentResponse()
Expand Down
15 changes: 14 additions & 1 deletion backend/src/user/user.guard.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { UserService } from './user.service';

@Injectable()
export class UserGuard implements CanActivate {
constructor(private readonly userService: UserService) {}

canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
return true;
const req = context.switchToHttp().getRequest();
// https://docs.nestjs.com/recipes/passport
// Passport automatically creates a user object, based on the value we return from the validate() method, and assigns it to the Request object as req.user.
const { params, user } = req;

if (params?.id == null) {
return true; // this request isn't scoped to a single existing todo
}

// user.id is a number, params.id is a string
return user.id === Number(params.id);
}
}

0 comments on commit 7ffbca2

Please sign in to comment.