From e4b5f00febc53d08c4d9d1bf6decb9e32cfeb6a1 Mon Sep 17 00:00:00 2001
From: L4168 <L4168@student.jamk.fi>
Date: Wed, 19 Jun 2019 09:35:56 +0300
Subject: [PATCH] user validation from db

---
 src/game/game.entity.ts   | 25 --------------
 src/game/game.service.ts  | 68 +++++++++++++++++++--------------------
 src/shared/roles.guard.ts | 17 +++++++---
 3 files changed, 47 insertions(+), 63 deletions(-)

diff --git a/src/game/game.entity.ts b/src/game/game.entity.ts
index 12106af..f4d5e24 100644
--- a/src/game/game.entity.ts
+++ b/src/game/game.entity.ts
@@ -61,29 +61,4 @@ export class Game_PersonEntity {
     person_role: PersonRoleEntity;
     @ManyToMany(type => CoordinateEntity, game_person_coordinates => game_person_coordinates.game_persons)
     game_person_coordinates: CoordinateEntity[]; */
-
-  async checkPlayerRole(userId: PersonEntity, gameId: GameEntity) {
-    try {
-      return userId;
-    } catch (error) {
-      return error.message;
-    }
-  }
-
-  public tokenObject() {
-    const { gametoken } = this;
-    return gametoken;
-  }
-  private get gametoken() {
-    const { gamepersonId, game, role } = this;
-    return jwt.sign(
-      {
-        gamepersonId,
-        game,
-        role,
-      },
-      process.env.SECRET,
-      { expiresIn: '7d' },
-    );
-  }
 }
diff --git a/src/game/game.service.ts b/src/game/game.service.ts
index fa31ebf..dd22aa0 100644
--- a/src/game/game.service.ts
+++ b/src/game/game.service.ts
@@ -1,6 +1,6 @@
 import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
 import { InjectRepository } from '@nestjs/typeorm';
-import { Repository, In, QueryBuilder } from 'typeorm';
+import { Repository, In, QueryBuilder, Not } from 'typeorm';
 
 import { GameEntity, FactionEntity, Game_PersonEntity } from './game.entity';
 import { GameDTO } from './game.dto';
@@ -42,7 +42,6 @@ export class GameService {
       await this.game_PersonRepository.insert(gamePerson);
       return {
         message: 'New game added',
-        gametoken: gamePerson.tokenObject(),
       };
     } catch (error) {
       return error.message;
@@ -51,41 +50,42 @@ export class GameService {
 
   // edit already created game
   async editGame(id: string, gameData: GameDTO) {
-    try {
-      // update game entry in db
-      const updatedGame = await this.gameRepository.create({
-        ...gameData,
-        factions: gameData.factions,
-      });
-      updatedGame['id'] = id;
-      const gameId = await this.gameRepository.save(updatedGame);
-
-      // get all the factions that are associated with the game to deny duplicate entries
-      const factions = await this.factionRepository.find({
-        select: ['name'],
-        where: { game: gameId },
-      });
-      const factionNames = factions.map(({ name }) => name);
+    // checks if a game with the same name exists already
+    const { name } = gameData;
+    if (await this.gameRepository.findOne({ name: name, id: Not(id) })) {
+      throw new HttpException('Game already exists', HttpStatus.BAD_REQUEST);
+    }
+    // update game entry in db
+    const updatedGame = await this.gameRepository.create({
+      ...gameData,
+      factions: gameData.factions,
+    });
+    updatedGame['id'] = id;
+    const gameId = await this.gameRepository.save(updatedGame);
 
-      // add the factions to db
-      if (gameData.factions) {
-        gameData.factions.map(async faction => {
-          if (!Object.values(factionNames).includes(faction.name)) {
-            let name = await this.factionRepository.create({
-              ...faction,
-              game: gameId,
-            });
-            await this.factionRepository.insert(name);
-          }
-        });
-      }
+    // get all the factions that are associated with the game to deny duplicate entries
+    const factions = await this.factionRepository.find({
+      select: ['name'],
+      where: { game: gameId },
+    });
+    const factionNames = factions.map(({ name }) => name);
 
-      return {
-        message: 'Game updated',
-      };
-    } catch (error) {
-      console.log(error);
+    // add the factions to db
+    if (gameData.factions) {
+      gameData.factions.map(async faction => {
+        if (!Object.values(factionNames).includes(faction.name)) {
+          let name = await this.factionRepository.create({
+            ...faction,
+            game: gameId,
+          });
+          await this.factionRepository.insert(name);
+        }
+      });
     }
+
+    return {
+      message: 'Game updated',
+    };
   }
 
   // checks the password, creates an entry in GamePerson table with associated role&faction
diff --git a/src/shared/roles.guard.ts b/src/shared/roles.guard.ts
index 2397ac3..1f05fc9 100644
--- a/src/shared/roles.guard.ts
+++ b/src/shared/roles.guard.ts
@@ -7,10 +7,18 @@ import {
 } from '@nestjs/common';
 import { Reflector } from '@nestjs/core';
 import * as jwt from 'jsonwebtoken';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+
+import { Game_PersonEntity } from '../game/game.entity';
 
 @Injectable()
 export class RolesGuard implements CanActivate {
-  constructor(private readonly reflector: Reflector) {}
+  constructor(
+    private readonly reflector: Reflector,
+    @InjectRepository(Game_PersonEntity)
+    private game_PersonRepository: Repository<Game_PersonEntity>,
+    ) {}
 
   async canActivate(context: ExecutionContext): Promise<boolean> {
     // get roles that are allowed access, identified by @Roles('role') decorators in controllers
@@ -20,12 +28,13 @@ export class RolesGuard implements CanActivate {
     }
     const request = context.switchToHttp().getRequest();
     const gameId = request.params.id
-    const role = await this.checkRole(request.headers.authorization);
+    const user = await this.getUserObject(request.headers.authorization);
+    const role = await this.game_PersonRepository.findOne({person: user['id'], game: gameId})
     // check that the role matches the criteria and that token is valid for this game
-    return roles.includes(role['role']) && role['game']['id'] === gameId;
+    return role && roles.includes(role['role']);
   }
 
-  async checkRole(auth: string) {
+  async getUserObject(auth: string) {
     // check if header contains Bearer
     if (auth.split(' ')[0] !== 'Bearer') {
       throw new HttpException('Invalid token', HttpStatus.FORBIDDEN);
-- 
GitLab