From 15b1d368a3d636facb3fd4a70967a82c528d852a Mon Sep 17 00:00:00 2001 From: Samuli Virtapohja <l4721@student.jamk.fi> Date: Fri, 7 Jun 2019 15:30:35 +0300 Subject: [PATCH] start of RolesGuard --- src/mapmarkers/mapmarker.entity.ts | 2 +- src/mapmarkers/mapmarker.service.ts | 2 +- src/mapmarkers/mapmarkers.controller.ts | 20 +++++++++++++++++--- src/mapmarkers/mapmarkers.module.ts | 2 +- src/shared/auth.guard.ts | 24 ++++++++++++++++++++++++ src/user/user.controller.ts | 4 ++-- src/user/user.entity.ts | 2 +- src/user/user.service.ts | 20 ++++++++++++-------- 8 files changed, 59 insertions(+), 17 deletions(-) diff --git a/src/mapmarkers/mapmarker.entity.ts b/src/mapmarkers/mapmarker.entity.ts index 41a955d..bc6d331 100644 --- a/src/mapmarkers/mapmarker.entity.ts +++ b/src/mapmarkers/mapmarker.entity.ts @@ -1,6 +1,6 @@ import { Entity, Column, PrimaryGeneratedColumn, Timestamp, ManyToOne } from 'typeorm'; -import { PersonEntity } from 'src/user/user.entity' +import { PersonEntity } from '../user/user.entity' /* Entity: MapMarker diff --git a/src/mapmarkers/mapmarker.service.ts b/src/mapmarkers/mapmarker.service.ts index c47ddf0..b0abf86 100644 --- a/src/mapmarkers/mapmarker.service.ts +++ b/src/mapmarkers/mapmarker.service.ts @@ -4,7 +4,7 @@ import { InjectRepository } from "@nestjs/typeorm"; import { MapMarkerEntity } from './mapmarker.entity'; import { MapMarkerDTO } from './mapmarker.dto'; -import { PersonEntity } from 'dist/user/user.entity'; +import { PersonEntity } from '../user/user.entity'; import { userInfo } from 'os'; @Injectable() diff --git a/src/mapmarkers/mapmarkers.controller.ts b/src/mapmarkers/mapmarkers.controller.ts index 6aa89c9..d2336b7 100644 --- a/src/mapmarkers/mapmarkers.controller.ts +++ b/src/mapmarkers/mapmarkers.controller.ts @@ -2,8 +2,8 @@ import { Controller, Body, Get, Put, UseGuards } from '@nestjs/common'; import { MapMarkerService } from './mapmarker.service'; import { MapMarkerDTO } from './mapmarker.dto'; -import { AuthGuard } from 'dist/shared/auth.guard'; -import { User } from 'src/user/user.decorator'; +import { AuthGuard, RolesGuard } from '../shared/auth.guard'; +import { User } from '../user/user.decorator'; @Controller('mapmarkers') export class MapMarkersController { @@ -23,6 +23,20 @@ export class MapMarkersController { // return all markers through service @Get('getall') async getAll(){ - return this.mapmarkerservice.getAllMarkers(); + try{ + return this.mapmarkerservice.getAllMarkers(); + }catch(error){ + return error.message; + } + } + + @Get('test') + @UseGuards(new RolesGuard()) + async test(){ + try { + + } catch (error) { + return error.message; + } } } diff --git a/src/mapmarkers/mapmarkers.module.ts b/src/mapmarkers/mapmarkers.module.ts index 06c45c2..9fda8c9 100644 --- a/src/mapmarkers/mapmarkers.module.ts +++ b/src/mapmarkers/mapmarkers.module.ts @@ -4,7 +4,7 @@ import { TypeOrmModule } from '@nestjs/typeorm'; import { MapMarkersController } from './mapmarkers.controller'; import { MapMarkerService } from './mapmarker.service'; import { MapMarkerEntity } from './mapmarker.entity'; -import { PersonEntity } from 'src/user/user.entity'; +import { PersonEntity } from '../user/user.entity'; @Module({ imports: [TypeOrmModule.forFeature([MapMarkerEntity, PersonEntity])], diff --git a/src/shared/auth.guard.ts b/src/shared/auth.guard.ts index 78d66f8..43fb6f0 100644 --- a/src/shared/auth.guard.ts +++ b/src/shared/auth.guard.ts @@ -4,27 +4,51 @@ import * as jwt from 'jsonwebtoken'; @Injectable() export class AuthGuard implements CanActivate { + // check for logged in user async canActivate(context: ExecutionContext): Promise<boolean> { + // get request const request = context.switchToHttp().getRequest(); + // check for authorization header if (!request.headers.authorization) { return false; } + // validate token request.user = await this.validateToken(request.headers.authorization); return true; } + // validate token async validateToken(auth: string) { + // check if header contains Bearer if (auth.split(" ")[0] !== 'Bearer') { throw new HttpException('Invalid token', HttpStatus.FORBIDDEN); } + // get the token const token = auth.split(" ")[1]; try { + // return token. return await jwt.verify(token, process.env.SECRET); } catch (err) { const message = `Token error: ${err.message || err.name}` throw new HttpException(message, HttpStatus.FORBIDDEN); } } +} + +export class RolesGuard implements CanActivate{ + // check for logged in user + async canActivate(context: ExecutionContext): Promise<boolean> { + // get request + const request = context.switchToHttp().getRequest(); + // check for authorization header + if (!request.headers.authorization) { + return false; + } + + // check for role + + return true; + } } \ No newline at end of file diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts index 363e894..2910ed9 100644 --- a/src/user/user.controller.ts +++ b/src/user/user.controller.ts @@ -2,8 +2,8 @@ import { Controller, Post, Body, UsePipes, Get, UseGuards } from '@nestjs/common import { UserService } from './user.service'; import { UserDTO } from './user.dto'; -import { AuthGuard } from 'src/shared/auth.guard'; -import { ValidationPipe } from 'src/shared/validation.pipe'; +import { AuthGuard } from '../shared/auth.guard'; +import { ValidationPipe } from '../shared/validation.pipe'; @Controller('user') export class UserController { diff --git a/src/user/user.entity.ts b/src/user/user.entity.ts index e718ce4..616da00 100644 --- a/src/user/user.entity.ts +++ b/src/user/user.entity.ts @@ -1,7 +1,7 @@ import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert, OneToMany } from 'typeorm'; import * as bcrypt from 'bcryptjs'; import * as jwt from 'jsonwebtoken'; -import { MapMarkerEntity } from 'src/mapmarkers/mapmarker.entity'; +import { MapMarkerEntity } from '../mapmarkers/mapmarker.entity'; @Entity('Person') export class PersonEntity { diff --git a/src/user/user.service.ts b/src/user/user.service.ts index 0b42bf9..eb9985a 100644 --- a/src/user/user.service.ts +++ b/src/user/user.service.ts @@ -21,14 +21,18 @@ export class UserService { } async login(data: UserDTO) { - const { name, password } = data; - const user = await this.userRepository.findOne({ where: { name }}); - if (!user || !(await user.comparePassword(password))) { - throw new HttpException( - 'Invalid username/password', - HttpStatus.BAD_REQUEST, - ); + try{ + const { name, password } = data; + const user = await this.userRepository.findOne({ where: { name }}); + if (!user || !(await user.comparePassword(password))) { + throw new HttpException( + 'Invalid username/password', + HttpStatus.BAD_REQUEST, + ); + } + return user.tokenObject(); + }catch(error){ + return error.message; } - return user.tokenObject(); } } -- GitLab