From bb4400dcc807c0265a351d6dfc3cdfde0725a615 Mon Sep 17 00:00:00 2001
From: L4168 <L4168@student.jamk.fi>
Date: Tue, 18 Jun 2019 13:15:27 +0300
Subject: [PATCH] implemented guard logic for editing games

---
 src/game/game.controller.ts |  3 +--
 src/shared/roles.guard.ts   | 17 ++++++-----------
 2 files changed, 7 insertions(+), 13 deletions(-)

diff --git a/src/game/game.controller.ts b/src/game/game.controller.ts
index 6c44c7e..92ca90d 100644
--- a/src/game/game.controller.ts
+++ b/src/game/game.controller.ts
@@ -23,14 +23,13 @@ export class GameController {
 
   @Post('new')
   @UseGuards(new AuthGuard())
-  //@UsePipes(new ValidationPipe())
+  @UsePipes(new ValidationPipe())
   async newGame(@User('id') person, @Body() body: GameDTO) {
     return this.gameservice.createNewGame(person, body);
   }
 
   @Put(':id')
   @Roles('admin')
-  @UseGuards(new AuthGuard())
   @UsePipes(new ValidationPipe())
   async editGame(@Param('id') id: string, @Body() body: GameDTO) {
     return this.gameservice.editGame(id, body);
diff --git a/src/shared/roles.guard.ts b/src/shared/roles.guard.ts
index 03e9ecc..fcb7ae8 100644
--- a/src/shared/roles.guard.ts
+++ b/src/shared/roles.guard.ts
@@ -13,19 +13,15 @@ import * as jwt from 'jsonwebtoken';
 @Injectable()
 export class RolesGuard implements CanActivate {
   constructor(private readonly reflector: Reflector) {}
-  canActivate(
-    context: ExecutionContext,
-  ): boolean | Promise<boolean> | Observable<boolean> {
+
+  async canActivate(context: ExecutionContext): Promise<boolean> {
     const roles = this.reflector.get<string[]>('roles', context.getHandler());
     if (!roles) {
       return true;
     }
-
     const request = context.switchToHttp().getRequest();
-    const user = request.user;
-    const role = this.checkRole(request.headers.authorization);
-    const hasRole = () => user.roles.some(role => roles.includes(role));
-    return user && role && hasRole();
+    const role = await this.checkRole(request.headers.authorization);
+    return roles.includes(role['role'])
   }
 
   async checkRole(auth: string) {
@@ -36,9 +32,8 @@ export class RolesGuard implements CanActivate {
     // get the token
     const token = auth.split(' ')[1];
     try {
-      const decoded = await jwt.decode(token);
-      console.log(decoded);
-      return decoded;
+      console.log(jwt.verify(token, process.env.SECRET))
+      return await jwt.verify(token, process.env.SECRET)
     } catch (err) {
       const message = `Token error: ${err.message || err.name}`;
       throw new HttpException(message, HttpStatus.FORBIDDEN);
-- 
GitLab