Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(players)!: extended player roles #953

Merged
merged 2 commits into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions migrations/1616694341420-extended-player-roles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable @typescript-eslint/no-var-requires */
'use strict'

//
// Remove Player.role, use Player.roles instead.
//

const { config } = require('dotenv');
const { MongoClient } = require('mongodb');

module.exports.up = next => {
config();

let credentials = '';
if (process.env.MONGODB_USERNAME) {
if (process.env.MONGODB_PASSWORD) {
credentials = `${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@`;
} else {
credentials = `${process.env.MONGODB_USERNAME}@`;
}
}

const uri = `mongodb://${credentials}${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DB}`;

MongoClient.connect(uri, { useUnifiedTopology: true })
.then(client => client.db())
.then(db => db.collection('players'))
.then(collection => Promise.all([collection, collection.updateMany(
{
role: 'super-user',
},
{
$set: { roles: ['admin', 'super user'] },
$unset: { role: 1 },
},
)]))
.then(([ collection ]) => Promise.all([collection, collection.updateMany(
{
role: 'admin',
},
{
$set: { roles: ['admin'] },
$unset: { role: 1 },
},
)]))
.then(([ collection ]) => collection.updateMany(
{
role: 'bot',
},
{
$set: { roles: ['bot'] },
$unset: { role: 1 },
},
))
.then(() => next());
}
20 changes: 11 additions & 9 deletions src/auth/guards/role.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { RoleGuard } from './role.guard';
import { TestingModule, Test } from '@nestjs/testing';
import { Reflector } from '@nestjs/core';
import { PlayerRole } from '@/players/models/player-role';
import { UnauthorizedException } from '@nestjs/common';

const context = {
getHandler: () => null,
switchToHttp: () => null,
switchToHttp: jest.fn(),
};

describe('RoleGuard', () => {
Expand All @@ -27,26 +29,26 @@ describe('RoleGuard', () => {
});

it('should allow when the user has the required role', () => {
jest.spyOn(reflector, 'get').mockImplementation(() => ['super-user']);
jest.spyOn(context, 'switchToHttp').mockImplementation(() => ({
jest.spyOn(reflector, 'get').mockImplementation(() => [ PlayerRole.superUser ]);
context.switchToHttp.mockImplementation(() => ({
getRequest: () => ({
user: {
role: 'super-user',
roles: [ PlayerRole.superUser ]
},
}),
}));
expect(guard.canActivate(context as any)).toBe(true);
});

it('should dany when the user does not have the required role', () => {
jest.spyOn(reflector, 'get').mockImplementation(() => ['super-user']);
jest.spyOn(context, 'switchToHttp').mockImplementation(() => ({
it('should deny when the user does not have the required role', () => {
jest.spyOn(reflector, 'get').mockImplementation(() => [ PlayerRole.superUser ]);
context.switchToHttp.mockImplementation(() => ({
getRequest: () => ({
user: {
role: 'admin',
roles: [ PlayerRole.admin ],
},
}),
}));
expect(() => guard.canActivate(context as any)).toThrow(/*new UnauthorizedException()*/);
expect(() => guard.canActivate(context as any)).toThrow(UnauthorizedException);
});
});
8 changes: 5 additions & 3 deletions src/auth/guards/role.guard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PlayerRole } from '@/players/models/player-role';
import { Player } from '@/players/models/player';

@Injectable()
export class RoleGuard implements CanActivate {
Expand All @@ -11,10 +12,11 @@ export class RoleGuard implements CanActivate {

canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<PlayerRole[]>('roles', context.getHandler());
if (roles && roles.length) {
if (roles?.length) {
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!(user && user.role && roles.includes(user.role))) {
const user = request.user as Player;

if (!user || !roles.some(r => user.roles.includes(r))) {
throw new UnauthorizedException();
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/configuration/controllers/configuration.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Auth } from '@/auth/decorators/auth.decorator';
import { PlayerRole } from '@/players/models/player-role';
import { Body, ClassSerializerInterceptor, Controller, Get, Put, UseInterceptors, ValidationPipe } from '@nestjs/common';
import { DefaultPlayerSkill } from '../dto/default-player-skill';
import { WhitelistId } from '../dto/whitelist-id';
Expand All @@ -18,7 +19,7 @@ export class ConfigurationController {
}

@Put('default-player-skill')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UseInterceptors(ClassSerializerInterceptor)
async setDefaultPlayerSkill(
@Body(new ValidationPipe({ transform: true })) { value }: DefaultPlayerSkill,
Expand All @@ -33,7 +34,7 @@ export class ConfigurationController {
}

@Put('whitelist-id')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UseInterceptors(ClassSerializerInterceptor)
async setWhitelistId(@Body(new ValidationPipe()) { value }: WhitelistId) {
return new WhitelistId(await this.configurationService.setWhitelistId(value));
Expand Down
3 changes: 2 additions & 1 deletion src/documents/controllers/documents.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Auth } from '@/auth/decorators/auth.decorator';
import { PlayerRole } from '@/players/models/player-role';
import { DocumentNotFoundFilter } from '@/shared/filters/document-not-found.filter';
import { Body, ClassSerializerInterceptor, Controller, DefaultValuePipe, Get, Param, Put, Query, UseFilters, UseInterceptors, UsePipes, ValidationPipe } from '@nestjs/common';
import { Document } from '../models/document';
Expand All @@ -24,7 +25,7 @@ export class DocumentsController {
@Put(':name')
@UseInterceptors(ClassSerializerInterceptor)
@UsePipes(ValidationPipe)
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
async saveDocument(
@Param('name') name: string,
@Query('language', new DefaultValuePipe('en')) language: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Auth } from '@/auth/decorators/auth.decorator';
import { PlayerRole } from '@/players/models/player-role';
import { DocumentNotFoundFilter } from '@/shared/filters/document-not-found.filter';
import { ObjectIdValidationPipe } from '@/shared/pipes/object-id-validation.pipe';
import { ClassSerializerInterceptor, Controller, Get, Param, UseFilters, UseInterceptors } from '@nestjs/common';
import { GameServerDiagnosticRun } from '../models/game-server-diagnostic-run';
import { GameServerDiagnosticsService } from '../services/game-server-diagnostics.service';

@Auth('super-user')
@Controller('game-server-diagnostics')
export class GameServerDiagnosticsController {

Expand All @@ -14,7 +14,7 @@ export class GameServerDiagnosticsController {
) { }

@Get(':id')
@Auth('super-user')
@Auth(PlayerRole.superUser)
@UseInterceptors(ClassSerializerInterceptor)
@UseFilters(DocumentNotFoundFilter)
async getDiagnosticRun(@Param('id', ObjectIdValidationPipe) id: string): Promise<GameServerDiagnosticRun> {
Expand Down
7 changes: 4 additions & 3 deletions src/game-servers/controllers/game-servers.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { GameServerDiagnosticsService } from '../services/game-server-diagnostic
import { Environment } from '@/environment/environment';
import { User } from '@/auth/decorators/user.decorator';
import { Player } from '@/players/models/player';
import { PlayerRole } from '@/players/models/player-role';

@Controller('game-servers')
export class GameServersController {
Expand All @@ -33,21 +34,21 @@ export class GameServersController {
}

@Post()
@Auth('super-user')
@Auth(PlayerRole.superUser)
@UsePipes(ValidationPipe)
@UseInterceptors(ClassSerializerInterceptor)
async addGameServer(@Body() gameServer: AddGameServer, @User() admin: Player) {
return this.gameServersService.addGameServer(gameServer, admin.id);
}

@Delete(':id')
@Auth('super-user')
@Auth(PlayerRole.superUser)
async removeGameServer(@Param('id', ObjectIdValidationPipe) gameServerId: string, @User() admin: Player) {
await this.gameServersService.removeGameServer(gameServerId, admin.id);
}

@Post(':id/diagnostics')
@Auth('super-user')
@Auth(PlayerRole.superUser)
@HttpCode(202)
async runDiagnostics(@Param('id', ObjectIdValidationPipe) gameServerId: string) {
const id = await this.gameServerDiagnosticsService.runDiagnostics(gameServerId);
Expand Down
5 changes: 3 additions & 2 deletions src/games/controllers/games.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { IsOneOfPipe } from '@/shared/pipes/is-one-of.pipe';
import { Game } from '../models/game';
import { User } from '@/auth/decorators/user.decorator';
import { Player } from '@/players/models/player';
import { PlayerRole } from '@/players/models/player-role';

const sortOptions: string[] = [
'launched_at',
Expand Down Expand Up @@ -74,7 +75,7 @@ export class GamesController {
}

@Get(':id/skills')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
async getGameSkills(@Param('id', ObjectIdValidationPipe) gameId: string) {
const game = await this.gamesService.getById(gameId);
if (game) {
Expand All @@ -85,7 +86,7 @@ export class GamesController {
}

@Post(':id')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@HttpCode(200)
async takeAdminAction(
@Param('id', ObjectIdValidationPipe) gameId: string,
Expand Down
21 changes: 11 additions & 10 deletions src/players/controllers/players.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Tf2ClassName } from '@/shared/models/tf2-class-name';
import { DocumentNotFoundFilter } from '@/shared/filters/document-not-found.filter';
import { PlayerStats } from '../dto/player-stats';
import { ForceCreatePlayer } from '../dto/force-create-player';
import { PlayerRole } from '../models/player-role';

@Controller('players')
@UseInterceptors(CacheInterceptor)
Expand All @@ -39,18 +40,18 @@ export class PlayersController {
}

@Post()
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UsePipes(ValidationPipe)
@UseInterceptors(ClassSerializerInterceptor)
async forceCreatePlayer(@Body() player: ForceCreatePlayer) {
return await this.playersService.forceCreatePlayer(player);
}

@Patch(':id')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UseInterceptors(ClassSerializerInterceptor)
async updatePlayer(@Param('id', ObjectIdValidationPipe) playerId: string, @Body() player: Partial<Player>, @User() user: Player) {
return await this.playersService.updatePlayer(playerId, player, user.id);
async updatePlayer(@Param('id', ObjectIdValidationPipe) playerId: string, @Body() player: Partial<Player>, @User() admin: Player) {
return await this.playersService.updatePlayer(playerId, player, admin.id);
}

@Get(':id/games')
Expand Down Expand Up @@ -89,13 +90,13 @@ export class PlayersController {
}

@Get('/all/skill')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
async getAllPlayerSkills() {
return await this.playerSkillService.getAll();
}

@Get(':id/skill')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
async getPlayerSkill(@Param('id', ObjectIdValidationPipe) playerId: string) {
const skill = await this.playerSkillService.getPlayerSkill(playerId);
if (skill) {
Expand All @@ -106,7 +107,7 @@ export class PlayersController {
}

@Put(':id/skill')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
// todo validate skill
async setPlayerSkill(
@Param('id', ObjectIdValidationPipe) playerId: string,
Expand All @@ -118,14 +119,14 @@ export class PlayersController {
}

@Get(':id/bans')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UseInterceptors(ClassSerializerInterceptor)
async getPlayerBans(@Param('id', ObjectIdValidationPipe) playerId: string) {
return await this.playerBansService.getPlayerBans(playerId);
}

@Post(':id/bans')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UsePipes(ValidationPipe)
@UseInterceptors(ClassSerializerInterceptor)
async addPlayerBan(@Body() playerBan: PlayerBan, @User() user: Player) {
Expand All @@ -136,7 +137,7 @@ export class PlayersController {
}

@Post(':playerId/bans/:banId')
@Auth('admin', 'super-user')
@Auth(PlayerRole.admin)
@UseInterceptors(ClassSerializerInterceptor)
@HttpCode(200)
async updatePlayerBan(@Param('playerId', ObjectIdValidationPipe) playerId: string, @Param('banId', ObjectIdValidationPipe) banId: string,
Expand Down
7 changes: 6 additions & 1 deletion src/players/models/player-role.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export type PlayerRole = 'admin' | 'super-user' | 'bot';
export enum PlayerRole {
superUser = 'super user',
admin = 'admin',
bot = 'bot',
}

4 changes: 2 additions & 2 deletions src/players/models/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export class Player extends MongooseDocument {
@prop()
avatar?: PlayerAvatar;

@prop()
role?: PlayerRole;
@prop({ type: () => [String], enum: PlayerRole, default: [] })
roles?: PlayerRole[];

@Exclude({ toPlainOnly: true })
@prop({ default: false })
Expand Down
Loading