1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import { Body, Controller, ForbiddenException, Get, GoneException, Param, Post } from '@nestjs/common';
import { SessionService } from '../../session/service/session.service';
import { SessionTokenDto } from '../dto/session-key.dto';
import { CreateFileDto } from '../dto/create-file.dto';
import { FileService } from '../service/file.service';
@Controller('file')
export class FileController {
constructor(
private readonly sessionService: SessionService,
private readonly fileService: FileService,
) {}
@Post('retrieve-keys')
async use(@Body() sessionTokenDto: SessionTokenDto) {
const sessionMarkedAsUsed = await this.sessionService.markSessionAsUsed(sessionTokenDto.token);
if (!sessionMarkedAsUsed) {
throw new ForbiddenException();
}
const files = await this.fileService.findManyValid(sessionTokenDto.token);
return {
files: files.map((file) => ({
key: file.key,
purpose: file.purpose?.name,
validUntil: file.validUntil,
})),
};
}
@Post('create')
async create(@Body() createFileDto: CreateFileDto) {
const session = await this.sessionService.findValid(createFileDto.token);
if (!session) {
throw new ForbiddenException();
}
const data = JSON.stringify(createFileDto.data);
const b64EncodedData = Buffer.from(data).toString('base64');
const validTo = new Date(Date.now() + 1000 * 60 * 30);
const file = await this.fileService.createFile(b64EncodedData, createFileDto.purpose, validTo, session);
return {
creationDate: file.creationDate,
validUntil: file.validUntil,
purpose: file.purpose,
session: {
validUntil: file.session.validUntil,
},
};
}
@Get('retrieve-file/:key')
async retrieve(@Param('key') key: string) {
const fileMarkedAsUsed = await this.fileService.markFileAsUsed(key);
if (!fileMarkedAsUsed) {
throw new ForbiddenException();
}
const fileData = await this.fileService.fetchFileContents(key);
if (!fileData) {
throw new GoneException('This file has been deleted');
}
const json = JSON.parse(Buffer.from(fileData, 'base64').toString('utf8'));
return {
data: json,
};
}
}
|