Public API: Introduce RequestUser decorator

This introduces the `RequestUser` decorator
to extract the `User` from a request.

It reduces code duplication across the public API
and allows us to drop the override of the `Request` type from express.

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-08-28 19:03:15 +02:00
parent 1a6e525446
commit ba2e4b0e3a
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
5 changed files with 81 additions and 146 deletions

View file

@ -9,11 +9,9 @@ import {
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
InternalServerErrorException,
NotFoundException, NotFoundException,
Param, Param,
Put, Put,
Req,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { import {
@ -24,7 +22,6 @@ import {
ApiTags, ApiTags,
ApiUnauthorizedResponse, ApiUnauthorizedResponse,
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { Request } from 'express';
import { TokenAuthGuard } from '../../../auth/token-auth.guard'; import { TokenAuthGuard } from '../../../auth/token-auth.guard';
import { NotInDBError } from '../../../errors/errors'; import { NotInDBError } from '../../../errors/errors';
@ -37,12 +34,14 @@ import { MediaService } from '../../../media/media.service';
import { NoteMetadataDto } from '../../../notes/note-metadata.dto'; import { NoteMetadataDto } from '../../../notes/note-metadata.dto';
import { NotesService } from '../../../notes/notes.service'; import { NotesService } from '../../../notes/notes.service';
import { UserInfoDto } from '../../../users/user-info.dto'; import { UserInfoDto } from '../../../users/user-info.dto';
import { User } from '../../../users/user.entity';
import { UsersService } from '../../../users/users.service'; import { UsersService } from '../../../users/users.service';
import { import {
notFoundDescription, notFoundDescription,
successfullyDeletedDescription, successfullyDeletedDescription,
unauthorizedDescription, unauthorizedDescription,
} from '../../utils/descriptions'; } from '../../utils/descriptions';
import { RequestUser } from '../../utils/request-user.decorator';
@ApiTags('me') @ApiTags('me')
@ApiSecurity('token') @ApiSecurity('token')
@ -65,14 +64,8 @@ export class MeController {
type: UserInfoDto, type: UserInfoDto,
}) })
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
async getMe(@Req() req: Request): Promise<UserInfoDto> { getMe(@RequestUser() user: User): UserInfoDto {
if (!req.user) { return this.usersService.toUserDto(user);
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
return this.usersService.toUserDto(
await this.usersService.getUserByUsername(req.user.userName),
);
} }
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@ -83,12 +76,8 @@ export class MeController {
type: HistoryEntryDto, type: HistoryEntryDto,
}) })
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
async getUserHistory(@Req() req: Request): Promise<HistoryEntryDto[]> { async getUserHistory(@RequestUser() user: User): Promise<HistoryEntryDto[]> {
if (!req.user) { const foundEntries = await this.historyService.getEntriesByUser(user);
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
const foundEntries = await this.historyService.getEntriesByUser(req.user);
return await Promise.all( return await Promise.all(
foundEntries.map((entry) => this.historyService.toHistoryEntryDto(entry)), foundEntries.map((entry) => this.historyService.toHistoryEntryDto(entry)),
); );
@ -103,17 +92,13 @@ export class MeController {
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
@ApiNotFoundResponse({ description: notFoundDescription }) @ApiNotFoundResponse({ description: notFoundDescription })
async getHistoryEntry( async getHistoryEntry(
@Req() req: Request, @RequestUser() user: User,
@Param('note') note: string, @Param('note') note: string,
): Promise<HistoryEntryDto> { ): Promise<HistoryEntryDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const foundEntry = await this.historyService.getEntryByNoteIdOrAlias( const foundEntry = await this.historyService.getEntryByNoteIdOrAlias(
note, note,
req.user, user,
); );
return this.historyService.toHistoryEntryDto(foundEntry); return this.historyService.toHistoryEntryDto(foundEntry);
} catch (e) { } catch (e) {
@ -133,20 +118,16 @@ export class MeController {
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
@ApiNotFoundResponse({ description: notFoundDescription }) @ApiNotFoundResponse({ description: notFoundDescription })
async updateHistoryEntry( async updateHistoryEntry(
@Req() req: Request, @RequestUser() user: User,
@Param('note') note: string, @Param('note') note: string,
@Body() entryUpdateDto: HistoryEntryUpdateDto, @Body() entryUpdateDto: HistoryEntryUpdateDto,
): Promise<HistoryEntryDto> { ): Promise<HistoryEntryDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
// ToDo: Check if user is allowed to pin this history entry // ToDo: Check if user is allowed to pin this history entry
try { try {
return this.historyService.toHistoryEntryDto( return this.historyService.toHistoryEntryDto(
await this.historyService.updateHistoryEntry( await this.historyService.updateHistoryEntry(
note, note,
req.user, user,
entryUpdateDto, entryUpdateDto,
), ),
); );
@ -165,16 +146,12 @@ export class MeController {
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
@ApiNotFoundResponse({ description: notFoundDescription }) @ApiNotFoundResponse({ description: notFoundDescription })
async deleteHistoryEntry( async deleteHistoryEntry(
@Req() req: Request, @RequestUser() user: User,
@Param('note') note: string, @Param('note') note: string,
): Promise<void> { ): Promise<void> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
// ToDo: Check if user is allowed to delete note // ToDo: Check if user is allowed to delete note
try { try {
await this.historyService.deleteHistoryEntry(note, req.user); await this.historyService.deleteHistoryEntry(note, user);
} catch (e) { } catch (e) {
if (e instanceof NotInDBError) { if (e instanceof NotInDBError) {
throw new NotFoundException(e.message); throw new NotFoundException(e.message);
@ -191,12 +168,8 @@ export class MeController {
type: NoteMetadataDto, type: NoteMetadataDto,
}) })
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
async getMyNotes(@Req() req: Request): Promise<NoteMetadataDto[]> { async getMyNotes(@RequestUser() user: User): Promise<NoteMetadataDto[]> {
if (!req.user) { const notes = this.notesService.getUserNotes(user);
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
const notes = this.notesService.getUserNotes(req.user);
return await Promise.all( return await Promise.all(
(await notes).map((note) => this.notesService.toNoteMetadataDto(note)), (await notes).map((note) => this.notesService.toNoteMetadataDto(note)),
); );
@ -210,12 +183,8 @@ export class MeController {
type: MediaUploadDto, type: MediaUploadDto,
}) })
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
async getMyMedia(@Req() req: Request): Promise<MediaUploadDto[]> { async getMyMedia(@RequestUser() user: User): Promise<MediaUploadDto[]> {
if (!req.user) { const media = await this.mediaService.listUploadsByUser(user);
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
const media = await this.mediaService.listUploadsByUser(req.user);
return media.map((media) => this.mediaService.toMediaUploadDto(media)); return media.map((media) => this.mediaService.toMediaUploadDto(media));
} }
} }

View file

@ -13,7 +13,6 @@ import {
NotFoundException, NotFoundException,
Param, Param,
Post, Post,
Req,
UnauthorizedException, UnauthorizedException,
UploadedFile, UploadedFile,
UseGuards, UseGuards,
@ -31,7 +30,6 @@ import {
ApiTags, ApiTags,
ApiUnauthorizedResponse, ApiUnauthorizedResponse,
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { Request } from 'express';
import { TokenAuthGuard } from '../../../auth/token-auth.guard'; import { TokenAuthGuard } from '../../../auth/token-auth.guard';
import { import {
@ -44,12 +42,14 @@ import { ConsoleLoggerService } from '../../../logger/console-logger.service';
import { MediaUploadUrlDto } from '../../../media/media-upload-url.dto'; import { MediaUploadUrlDto } from '../../../media/media-upload-url.dto';
import { MediaService } from '../../../media/media.service'; import { MediaService } from '../../../media/media.service';
import { MulterFile } from '../../../media/multer-file.interface'; import { MulterFile } from '../../../media/multer-file.interface';
import { User } from '../../../users/user.entity';
import { import {
forbiddenDescription, forbiddenDescription,
successfullyDeletedDescription, successfullyDeletedDescription,
unauthorizedDescription, unauthorizedDescription,
} from '../../utils/descriptions'; } from '../../utils/descriptions';
import { FullApi } from '../../utils/fullapi-decorator'; import { FullApi } from '../../utils/fullapi-decorator';
import { RequestUser } from '../../utils/request-user.decorator';
@ApiTags('media') @ApiTags('media')
@ApiSecurity('token') @ApiSecurity('token')
@ -89,15 +89,11 @@ export class MediaController {
@UseInterceptors(FileInterceptor('file')) @UseInterceptors(FileInterceptor('file'))
@HttpCode(201) @HttpCode(201)
async uploadMedia( async uploadMedia(
@Req() req: Request, @RequestUser() user: User,
@UploadedFile() file: MulterFile, @UploadedFile() file: MulterFile,
@Headers('HedgeDoc-Note') noteId: string, @Headers('HedgeDoc-Note') noteId: string,
): Promise<MediaUploadUrlDto> { ): Promise<MediaUploadUrlDto> {
if (!req.user) { const username = user.userName;
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
const username = req.user.userName;
this.logger.debug( this.logger.debug(
`Recieved filename '${file.originalname}' for note '${noteId}' from user '${username}'`, `Recieved filename '${file.originalname}' for note '${noteId}' from user '${username}'`,
'uploadMedia', 'uploadMedia',
@ -128,14 +124,10 @@ export class MediaController {
@ApiNoContentResponse({ description: successfullyDeletedDescription }) @ApiNoContentResponse({ description: successfullyDeletedDescription })
@FullApi @FullApi
async deleteMedia( async deleteMedia(
@Req() req: Request, @RequestUser() user: User,
@Param('filename') filename: string, @Param('filename') filename: string,
): Promise<void> { ): Promise<void> {
if (!req.user) { const username = user.userName;
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
const username = req.user.userName;
try { try {
this.logger.debug( this.logger.debug(
`Deleting '${filename}' for user '${username}'`, `Deleting '${filename}' for user '${username}'`,

View file

@ -11,12 +11,10 @@ import {
Get, Get,
Header, Header,
HttpCode, HttpCode,
InternalServerErrorException,
NotFoundException, NotFoundException,
Param, Param,
Post, Post,
Put, Put,
Req,
UnauthorizedException, UnauthorizedException,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
@ -30,7 +28,6 @@ import {
ApiTags, ApiTags,
ApiUnauthorizedResponse, ApiUnauthorizedResponse,
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { Request } from 'express';
import { TokenAuthGuard } from '../../../auth/token-auth.guard'; import { TokenAuthGuard } from '../../../auth/token-auth.guard';
import { import {
@ -56,6 +53,7 @@ import { PermissionsService } from '../../../permissions/permissions.service';
import { RevisionMetadataDto } from '../../../revisions/revision-metadata.dto'; import { RevisionMetadataDto } from '../../../revisions/revision-metadata.dto';
import { RevisionDto } from '../../../revisions/revision.dto'; import { RevisionDto } from '../../../revisions/revision.dto';
import { RevisionsService } from '../../../revisions/revisions.service'; import { RevisionsService } from '../../../revisions/revisions.service';
import { User } from '../../../users/user.entity';
import { import {
forbiddenDescription, forbiddenDescription,
successfullyDeletedDescription, successfullyDeletedDescription,
@ -63,6 +61,7 @@ import {
} from '../../utils/descriptions'; } from '../../utils/descriptions';
import { FullApi } from '../../utils/fullapi-decorator'; import { FullApi } from '../../utils/fullapi-decorator';
import { MarkdownBody } from '../../utils/markdownbody-decorator'; import { MarkdownBody } from '../../utils/markdownbody-decorator';
import { RequestUser } from '../../utils/request-user.decorator';
@ApiTags('notes') @ApiTags('notes')
@ApiSecurity('token') @ApiSecurity('token')
@ -85,20 +84,16 @@ export class NotesController {
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
@ApiForbiddenResponse({ description: forbiddenDescription }) @ApiForbiddenResponse({ description: forbiddenDescription })
async createNote( async createNote(
@Req() req: Request, @RequestUser() user: User,
@MarkdownBody() text: string, @MarkdownBody() text: string,
): Promise<NoteDto> { ): Promise<NoteDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
// ToDo: provide user for createNoteDto // ToDo: provide user for createNoteDto
if (!this.permissionsService.mayCreate(req.user)) { if (!this.permissionsService.mayCreate(user)) {
throw new UnauthorizedException('Creating note denied!'); throw new UnauthorizedException('Creating note denied!');
} }
this.logger.debug('Got raw markdown:\n' + text); this.logger.debug('Got raw markdown:\n' + text);
return await this.noteService.toNoteDto( return await this.noteService.toNoteDto(
await this.noteService.createNote(text, undefined, req.user), await this.noteService.createNote(text, undefined, user),
); );
} }
@ -110,13 +105,9 @@ export class NotesController {
}) })
@FullApi @FullApi
async getNote( async getNote(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<NoteDto> { ): Promise<NoteDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
let note: Note; let note: Note;
try { try {
note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
@ -129,10 +120,10 @@ export class NotesController {
} }
throw e; throw e;
} }
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
await this.historyService.createOrUpdateHistoryEntry(note, req.user); await this.historyService.createOrUpdateHistoryEntry(note, user);
return await this.noteService.toNoteDto(note); return await this.noteService.toNoteDto(note);
} }
@ -146,21 +137,17 @@ export class NotesController {
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
@ApiForbiddenResponse({ description: forbiddenDescription }) @ApiForbiddenResponse({ description: forbiddenDescription })
async createNamedNote( async createNamedNote(
@Req() req: Request, @RequestUser() user: User,
@Param('noteAlias') noteAlias: string, @Param('noteAlias') noteAlias: string,
@MarkdownBody() text: string, @MarkdownBody() text: string,
): Promise<NoteDto> { ): Promise<NoteDto> {
if (!req.user) { if (!this.permissionsService.mayCreate(user)) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
if (!this.permissionsService.mayCreate(req.user)) {
throw new UnauthorizedException('Creating note denied!'); throw new UnauthorizedException('Creating note denied!');
} }
this.logger.debug('Got raw markdown:\n' + text, 'createNamedNote'); this.logger.debug('Got raw markdown:\n' + text, 'createNamedNote');
try { try {
return await this.noteService.toNoteDto( return await this.noteService.toNoteDto(
await this.noteService.createNote(text, noteAlias, req.user), await this.noteService.createNote(text, noteAlias, user),
); );
} catch (e) { } catch (e) {
if (e instanceof AlreadyInDBError) { if (e instanceof AlreadyInDBError) {
@ -179,17 +166,13 @@ export class NotesController {
@ApiNoContentResponse({ description: successfullyDeletedDescription }) @ApiNoContentResponse({ description: successfullyDeletedDescription })
@FullApi @FullApi
async deleteNote( async deleteNote(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
@Body() noteMediaDeletionDto: NoteMediaDeletionDto, @Body() noteMediaDeletionDto: NoteMediaDeletionDto,
): Promise<void> { ): Promise<void> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.isOwner(req.user, note)) { if (!this.permissionsService.isOwner(user, note)) {
throw new UnauthorizedException('Deleting note denied!'); throw new UnauthorizedException('Deleting note denied!');
} }
const mediaUploads = await this.mediaService.listUploadsByNote(note); const mediaUploads = await this.mediaService.listUploadsByNote(note);
@ -223,17 +206,13 @@ export class NotesController {
}) })
@FullApi @FullApi
async updateNote( async updateNote(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
@MarkdownBody() text: string, @MarkdownBody() text: string,
): Promise<NoteDto> { ): Promise<NoteDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayWrite(req.user, note)) { if (!this.permissionsService.mayWrite(user, note)) {
throw new UnauthorizedException('Updating note denied!'); throw new UnauthorizedException('Updating note denied!');
} }
this.logger.debug('Got raw markdown:\n' + text, 'updateNote'); this.logger.debug('Got raw markdown:\n' + text, 'updateNote');
@ -260,16 +239,12 @@ export class NotesController {
@FullApi @FullApi
@Header('content-type', 'text/markdown') @Header('content-type', 'text/markdown')
async getNoteContent( async getNoteContent(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<string> { ): Promise<string> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
return await this.noteService.getNoteContent(note); return await this.noteService.getNoteContent(note);
@ -292,16 +267,12 @@ export class NotesController {
}) })
@FullApi @FullApi
async getNoteMetadata( async getNoteMetadata(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<NoteMetadataDto> { ): Promise<NoteMetadataDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
return await this.noteService.toNoteMetadataDto(note); return await this.noteService.toNoteMetadataDto(note);
@ -327,17 +298,13 @@ export class NotesController {
}) })
@FullApi @FullApi
async updateNotePermissions( async updateNotePermissions(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
@Body() updateDto: NotePermissionsUpdateDto, @Body() updateDto: NotePermissionsUpdateDto,
): Promise<NotePermissionsDto> { ): Promise<NotePermissionsDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.isOwner(req.user, note)) { if (!this.permissionsService.isOwner(user, note)) {
throw new UnauthorizedException('Updating note denied!'); throw new UnauthorizedException('Updating note denied!');
} }
return this.noteService.toNotePermissionsDto( return this.noteService.toNotePermissionsDto(
@ -363,16 +330,12 @@ export class NotesController {
}) })
@FullApi @FullApi
async getNoteRevisions( async getNoteRevisions(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<RevisionMetadataDto[]> { ): Promise<RevisionMetadataDto[]> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
const revisions = await this.revisionsService.getAllRevisions(note); const revisions = await this.revisionsService.getAllRevisions(note);
@ -400,17 +363,13 @@ export class NotesController {
}) })
@FullApi @FullApi
async getNoteRevision( async getNoteRevision(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
@Param('revisionId') revisionId: number, @Param('revisionId') revisionId: number,
): Promise<RevisionDto> { ): Promise<RevisionDto> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
return this.revisionsService.toRevisionDto( return this.revisionsService.toRevisionDto(
@ -436,16 +395,12 @@ export class NotesController {
}) })
@ApiUnauthorizedResponse({ description: unauthorizedDescription }) @ApiUnauthorizedResponse({ description: unauthorizedDescription })
async getNotesMedia( async getNotesMedia(
@Req() req: Request, @RequestUser() user: User,
@Param('noteIdOrAlias') noteIdOrAlias: string, @Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<MediaUploadDto[]> { ): Promise<MediaUploadDto[]> {
if (!req.user) {
// We should never reach this, as the TokenAuthGuard handles missing user info
throw new InternalServerErrorException('Request did not specify user');
}
try { try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias); const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(req.user, note)) { if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!'); throw new UnauthorizedException('Reading note denied!');
} }
const media = await this.mediaService.listUploadsByNote(note); const media = await this.mediaService.listUploadsByNote(note);

View file

@ -0,0 +1,32 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import {
createParamDecorator,
ExecutionContext,
InternalServerErrorException,
} from '@nestjs/common';
import { Request } from 'express';
import { User } from '../../users/user.entity';
/**
* Extracts the {@link User} object from a request
*
* Will throw an {@link InternalServerErrorException} if no user is present
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export const RequestUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request: Request & { user: User } = ctx.switchToHttp().getRequest();
if (!request.user) {
// We should have a user here, otherwise something is wrong
throw new InternalServerErrorException(
'Request is missing a user object',
);
}
return request.user;
},
);

View file

@ -1,13 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { User} from '../../src/users/user.entity';
declare module 'express' {
export interface Request {
user?: User;
}
}