add permission checking for infractions

This commit is contained in:
Lea 2023-07-03 12:46:41 +02:00
parent 7ce22e23fe
commit 8d603b4de3
4 changed files with 48 additions and 1 deletions

View file

@ -8,6 +8,11 @@ import {
import { Request } from 'express';
import { AuthService } from './auth.service';
export class AuthenticationData {
user: string;
god: boolean;
}
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService) {}
@ -23,6 +28,10 @@ export class AuthGuard implements CanActivate {
if (!details.god)
throw new ForbiddenException("You don't have access to this resource");
(request as any)['auth_data'] = {
user: details.user,
god: details.god,
} as AuthenticationData;
return true;
}

View file

@ -0,0 +1,17 @@
import {
createParamDecorator,
ExecutionContext,
InternalServerErrorException,
} from '@nestjs/common';
import { AuthenticationData } from './auth.guard';
export const AuthData = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
if (!request.auth_data)
throw new InternalServerErrorException(
'Authentication data not present in request object',
);
return request.auth_data as AuthenticationData;
},
);

View file

@ -1,5 +1,6 @@
import {
Controller,
ForbiddenException,
Get,
HttpException,
HttpStatus,
@ -9,7 +10,8 @@ import {
import { DBInfraction } from 'lib';
import { InfractionsService } from './infractions.service';
import { ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AuthGuard } from 'src/auth/auth.guard';
import { AuthGuard, AuthenticationData } from 'src/auth/auth.guard';
import { AuthData } from 'src/auth/authdata.decorator';
@UseGuards(AuthGuard)
@ApiBearerAuth()
@ -22,9 +24,17 @@ export class InfractionsController {
async getInfraction(
@Param('server') server: string,
@Param('id') id: string,
@AuthData() auth: AuthenticationData,
): Promise<DBInfraction> {
const infraction = await this.infractions.get(server, id);
if (!infraction) throw new HttpException('Not found', HttpStatus.NOT_FOUND);
if (
!auth.god &&
!(await this.infractions.canAccessInfraction(auth.user, server, id))
)
throw new ForbiddenException("You don't have access to this infraction");
return infraction;
}
}

View file

@ -11,4 +11,15 @@ export class InfractionsService {
.getDb()
.infractions.findOne({ '_id.server': server, '_id.infraction': id });
}
async canAccessInfraction(
user: string,
server: string,
infraction: string,
): Promise<boolean> {
const serverConfig = await this.db.getDb().servers.findOne({ _id: server });
const accessLevel = serverConfig?.infraction_visibility || 'own';
if (accessLevel == 'all') return true;
return false;
}
}