PrivateAPI: Add notes controller

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-03-24 00:12:54 +01:00
parent 374f675353
commit b60fa155dd
3 changed files with 334 additions and 1 deletions

View file

@ -0,0 +1,102 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Test, TestingModule } from '@nestjs/testing';
import { NotesController } from './notes.controller';
import { NotesService } from '../../../notes/notes.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Note } from '../../../notes/note.entity';
import { Tag } from '../../../notes/tag.entity';
import { RevisionsModule } from '../../../revisions/revisions.module';
import { UsersModule } from '../../../users/users.module';
import { GroupsModule } from '../../../groups/groups.module';
import { LoggerModule } from '../../../logger/logger.module';
import { PermissionsModule } from '../../../permissions/permissions.module';
import { HistoryModule } from '../../../history/history.module';
import { MediaModule } from '../../../media/media.module';
import { ConfigModule } from '@nestjs/config';
import appConfigMock from '../../../config/mock/app.config.mock';
import mediaConfigMock from '../../../config/mock/media.config.mock';
import { Revision } from '../../../revisions/revision.entity';
import { Authorship } from '../../../revisions/authorship.entity';
import { AuthorColor } from '../../../notes/author-color.entity';
import { User } from '../../../users/user.entity';
import { AuthToken } from '../../../auth/auth-token.entity';
import { Identity } from '../../../users/identity.entity';
import { HistoryEntry } from '../../../history/history-entry.entity';
import { NoteGroupPermission } from '../../../permissions/note-group-permission.entity';
import { NoteUserPermission } from '../../../permissions/note-user-permission.entity';
import { Group } from '../../../groups/group.entity';
import { MediaUpload } from '../../../media/media-upload.entity';
describe('NotesController', () => {
let controller: NotesController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [NotesController],
providers: [
NotesService,
{
provide: getRepositoryToken(Note),
useValue: {},
},
{
provide: getRepositoryToken(Tag),
useValue: {},
},
],
imports: [
RevisionsModule,
UsersModule,
GroupsModule,
LoggerModule,
PermissionsModule,
HistoryModule,
MediaModule,
ConfigModule.forRoot({
isGlobal: true,
load: [appConfigMock, mediaConfigMock],
}),
],
})
.overrideProvider(getRepositoryToken(Note))
.useValue({})
.overrideProvider(getRepositoryToken(Revision))
.useValue({})
.overrideProvider(getRepositoryToken(Authorship))
.useValue({})
.overrideProvider(getRepositoryToken(AuthorColor))
.useValue({})
.overrideProvider(getRepositoryToken(User))
.useValue({})
.overrideProvider(getRepositoryToken(AuthToken))
.useValue({})
.overrideProvider(getRepositoryToken(Identity))
.useValue({})
.overrideProvider(getRepositoryToken(Note))
.useValue({})
.overrideProvider(getRepositoryToken(Tag))
.useValue({})
.overrideProvider(getRepositoryToken(HistoryEntry))
.useValue({})
.overrideProvider(getRepositoryToken(NoteGroupPermission))
.useValue({})
.overrideProvider(getRepositoryToken(NoteUserPermission))
.useValue({})
.overrideProvider(getRepositoryToken(Group))
.useValue({})
.overrideProvider(getRepositoryToken(MediaUpload))
.useValue({})
.compile();
controller = module.get<NotesController>(NotesController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View file

@ -0,0 +1,219 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import {
BadRequestException,
Controller,
Delete,
Get,
HttpCode,
NotFoundException,
Param,
Post,
UnauthorizedException,
} from '@nestjs/common';
import { Note } from '../../../notes/note.entity';
import {
AlreadyInDBError,
ForbiddenIdError,
NotInDBError,
} from '../../../errors/errors';
import { NoteDto } from '../../../notes/note.dto';
import { ConsoleLoggerService } from '../../../logger/console-logger.service';
import { NotesService } from '../../../notes/notes.service';
import { PermissionsService } from '../../../permissions/permissions.service';
import { HistoryService } from '../../../history/history.service';
import { UsersService } from '../../../users/users.service';
import { MediaUploadDto } from '../../../media/media-upload.dto';
import { MediaService } from '../../../media/media.service';
import { RevisionMetadataDto } from '../../../revisions/revision-metadata.dto';
import { RevisionDto } from '../../../revisions/revision.dto';
import { RevisionsService } from '../../../revisions/revisions.service';
import { MarkdownBody } from '../../utils/markdownbody-decorator';
@Controller('notes')
export class NotesController {
constructor(
private readonly logger: ConsoleLoggerService,
private noteService: NotesService,
private permissionsService: PermissionsService,
private historyService: HistoryService,
private userService: UsersService,
private mediaService: MediaService,
private revisionsService: RevisionsService,
) {
this.logger.setContext(NotesController.name);
}
@Get(':noteIdOrAlias')
async getNote(
@Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<NoteDto> {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
let note: Note;
try {
note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
if (e instanceof ForbiddenIdError) {
throw new BadRequestException(e.message);
}
throw e;
}
if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!');
}
await this.historyService.createOrUpdateHistoryEntry(note, user);
return await this.noteService.toNoteDto(note);
}
@Get(':noteIdOrAlias/media')
async getNotesMedia(
@Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<MediaUploadDto[]> {
try {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!');
}
const media = await this.mediaService.listUploadsByNote(note);
return media.map((media) => this.mediaService.toMediaUploadDto(media));
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
throw e;
}
}
@Post()
@HttpCode(201)
async createNote(@MarkdownBody() text: string): Promise<NoteDto> {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
// ToDo: provide user for createNoteDto
if (!this.permissionsService.mayCreate(user)) {
throw new UnauthorizedException('Creating note denied!');
}
this.logger.debug('Got raw markdown:\n' + text);
return await this.noteService.toNoteDto(
await this.noteService.createNote(text, undefined, user),
);
}
@Post(':noteAlias')
@HttpCode(201)
async createNamedNote(
@Param('noteAlias') noteAlias: string,
@MarkdownBody() text: string,
): Promise<NoteDto> {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
if (!this.permissionsService.mayCreate(user)) {
throw new UnauthorizedException('Creating note denied!');
}
this.logger.debug('Got raw markdown:\n' + text, 'createNamedNote');
try {
return await this.noteService.toNoteDto(
await this.noteService.createNote(text, noteAlias, user),
);
} catch (e) {
if (e instanceof AlreadyInDBError) {
throw new BadRequestException(e.message);
}
if (e instanceof ForbiddenIdError) {
throw new BadRequestException(e.message);
}
throw e;
}
}
@Delete(':noteIdOrAlias')
@HttpCode(204)
async deleteNote(
@Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<void> {
try {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.isOwner(user, note)) {
throw new UnauthorizedException('Deleting note denied!');
}
this.logger.debug('Deleting note: ' + noteIdOrAlias, 'deleteNote');
await this.noteService.deleteNote(note);
this.logger.debug('Successfully deleted ' + noteIdOrAlias, 'deleteNote');
return;
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
if (e instanceof ForbiddenIdError) {
throw new BadRequestException(e.message);
}
throw e;
}
}
@Get(':noteIdOrAlias/revisions')
async getNoteRevisions(
@Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<RevisionMetadataDto[]> {
try {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!');
}
const revisions = await this.revisionsService.getAllRevisions(note);
return await Promise.all(
revisions.map((revision) =>
this.revisionsService.toRevisionMetadataDto(revision),
),
);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
if (e instanceof ForbiddenIdError) {
throw new BadRequestException(e.message);
}
throw e;
}
}
@Get(':noteIdOrAlias/revisions/:revisionId')
async getNoteRevision(
@Param('noteIdOrAlias') noteIdOrAlias: string,
@Param('revisionId') revisionId: number,
): Promise<RevisionDto> {
try {
// ToDo: use actual user here
const user = await this.userService.getUserByUsername('hardcoded');
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
if (!this.permissionsService.mayRead(user, note)) {
throw new UnauthorizedException('Reading note denied!');
}
return this.revisionsService.toRevisionDto(
await this.revisionsService.getRevision(note, revisionId),
);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
if (e instanceof ForbiddenIdError) {
throw new BadRequestException(e.message);
}
throw e;
}
}
}

View file

@ -14,6 +14,10 @@ import { FrontendConfigModule } from '../../frontend-config/frontend-config.modu
import { HistoryController } from './me/history/history.controller';
import { HistoryModule } from '../../history/history.module';
import { NotesModule } from '../../notes/notes.module';
import { NotesController } from './notes/notes.controller';
import { PermissionsModule } from '../../permissions/permissions.module';
import { MediaModule } from '../../media/media.module';
import { RevisionsModule } from '../../revisions/revisions.module';
@Module({
imports: [
@ -23,7 +27,15 @@ import { NotesModule } from '../../notes/notes.module';
FrontendConfigModule,
HistoryModule,
NotesModule,
PermissionsModule,
MediaModule,
RevisionsModule,
],
controllers: [
TokensController,
ConfigController,
HistoryController,
NotesController,
],
controllers: [TokensController, ConfigController, HistoryController],
})
export class PrivateApiModule {}