Compare commits

...

2 Commits

Author SHA1 Message Date
1818fcfe88
Enhance file upload handling in FilesController
Added request and response handling for the file upload endpoint in FilesController. Implemented form data parsing, header validation, and admin-specific parameter management. These changes aim to improve error handling and prepare the logic needed for saving files and associated data.
2024-10-04 11:35:23 +02:00
db700241a8
Add InsertAdminState guard to check admin status
Introduces a new InsertAdminState guard to verify if the user is an admin by checking their authentication token and updating a custom header 'is_admin' accordingly. This guard fetches user details from the database and sets the 'is_admin' header to true or false based on the user's admin status.
2024-10-04 11:35:12 +02:00
2 changed files with 98 additions and 2 deletions

View File

@ -87,3 +87,41 @@ export class AdminGuard implements CanActivate {
return true;
}
}
@Injectable()
export class InsertAdminState implements CanActivate {
constructor(
@Inject(CredentialsService)
private readonly credentialService: CredentialsService,
@Inject(DbService) private readonly databaseService: DbService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request : Request = context.switchToHttp().getRequest();
const authHeader = request.headers.authorization;
if (!authHeader) {
request.headers.is_admin = false;
return true;
}
const token = authHeader.split(" ")[1];
const vToken = await this.credentialService.verifyAuthToken(token);
const user = await this.databaseService
.use()
.select()
.from(UsersTable)
.where(eq(UsersTable.uuid, vToken.payload.sub));
if (user.length !== 1)
throw new UnauthorizedException("No such user found.");
if (!user[0].isAdmin) {
request.headers.is_admin = false;
return true;
}
request.headers.is_admin = true
return true;
}
}

View File

@ -1,13 +1,71 @@
import { Controller, DefaultValuePipe, Get, Param, ParseIntPipe, Post, Query, StreamableFile } from '@nestjs/common';
import {
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
Post,
Query,
Req,
Res,
Request,
Response,
StreamableFile, HttpStatus, HttpCode, BadRequestException, UseGuards
} from '@nestjs/common';
import { FilesService } from "./files.service";
import { IncomingMessage } from 'node:http';
import { InsertAdminState } from '../auth/auth.guard';
@Controller("files")
export class FilesController {
constructor(private readonly filesService: FilesService) {}
@UseGuards(InsertAdminState)
@HttpCode(HttpStatus.OK)
@Post('new')
async saveFile() {
async saveFile(@Req() req: IncomingMessage, @Res() res: Response) {
let fileBuffer: Buffer = Buffer.from([]);
req.on('data', (chunk: Buffer) => {
fileBuffer = Buffer.concat([fileBuffer, chunk]);
});
req.on('end', async () => {
const _fileName = req.headers['file_name'] as string;
const _groupId = req.headers['group_id'] as string;
const _machineId = req.headers['machine_id'];
const _isDocumentation = req.headers['is_documentation'] as string;
const _isRestricted = req.headers['is_restricted'] as string;
const _isAdmin = Boolean(req.headers['is_admin'] as string | boolean);
// Vérifier que les en-têtes nécessaires sont présents
if (!_fileName || !_groupId || !_machineId) {
throw new BadRequestException("Header(s) manquant(s)");
}
const machineId = Array(..._machineId);
const Params = new Map()
.set("fileName", _fileName.toString())
.set("groupId", _groupId.toString())
.set("machinesId", Array(..._machineId))
//TODO Integrate a verification if the source is an admin, if that the case then it can define isDocumentation and isRestricted else throw in case of presence of those parameters.
if (_isAdmin) {
Params.set("isDocumentation", Boolean(_isDocumentation))
Params.set("isRestricted", Boolean(_isRestricted))
}
//TODO Implement the service
//await this.filesService.save(fileBuffer, Params);
// TODO logique de sauvegarde du fichier et des données
return { message: 'Fichier sauvegardé avec succès' }
});
req.on('error', (err) => {
throw new BadRequestException(err.message)
});
}
@Get('find')