fix(repository): Move backend code into subdirectory

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2022-10-02 20:10:32 +02:00 committed by David Mehren
parent 86584e705f
commit bf30cbcf48
272 changed files with 87 additions and 67 deletions

View file

@ -0,0 +1,253 @@
/*
* SPDX-FileCopyrightText: 2022 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import request from 'supertest';
import { AliasUpdateDto } from '../../src/notes/alias-update.dto';
import { TestSetup, TestSetupBuilder } from '../test-setup';
describe('Alias', () => {
let testSetup: TestSetup;
let forbiddenNoteId: string;
let testAlias: string;
let publicId: string;
beforeEach(async () => {
testSetup = await TestSetupBuilder.create().withUsers().withNotes().build();
forbiddenNoteId =
testSetup.configService.get('noteConfig').forbiddenNoteIds[0];
await testSetup.app.init();
testAlias = (await testSetup.ownedNotes[0].aliases)[0].name;
publicId = testSetup.ownedNotes[0].publicId;
});
afterEach(async () => {
await testSetup.app.close();
await testSetup.cleanup();
});
describe('POST /alias', () => {
it('create with normal alias', async () => {
const metadata = await request(testSetup.app.getHttpServer())
.post(`/api/v2/alias`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send({
noteIdOrAlias: testAlias,
newAlias: 'normalAlias',
})
.expect(201);
expect(metadata.body.name).toEqual('normalAlias');
expect(metadata.body.primaryAlias).toBeFalsy();
expect(metadata.body.noteId).toEqual(publicId);
const note = await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/normalAlias`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(200);
expect(note.body.metadata.aliases).toContainEqual({
name: 'normalAlias',
primaryAlias: false,
noteId: publicId,
});
expect(note.body.metadata.primaryAddress).toEqual(testAlias);
expect(note.body.metadata.id).toEqual(publicId);
});
describe('does not create an alias', () => {
it('because because it is already used', async () => {
await request(testSetup.app.getHttpServer())
.post(`/api/v2/alias`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send({
noteIdOrAlias: testAlias,
newAlias: 'testAlias1',
})
.expect(409);
});
it('because of a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.post(`/api/v2/alias`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send({
noteIdOrAlias: testAlias,
newAlias: forbiddenNoteId,
})
.expect(400);
});
it('because of a alias that is a public id', async () => {
await request(testSetup.app.getHttpServer())
.post(`/api/v2/alias`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send({
noteIdOrAlias: testAlias,
newAlias: publicId,
})
.expect(409);
});
it('because the user is not an owner', async () => {
await request(testSetup.app.getHttpServer())
.post(`/api/v2/alias`)
.set('Authorization', `Bearer ${testSetup.authTokens[1].secret}`)
.set('Content-Type', 'application/json')
.send({
noteIdOrAlias: testAlias,
newAlias: '',
})
.expect(401);
});
});
});
describe('PUT /alias/{alias}', () => {
const changeAliasDto: AliasUpdateDto = {
primaryAlias: true,
};
it('updates a note with a normal alias', async () => {
const metadata = await request(testSetup.app.getHttpServer())
.put(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send(changeAliasDto)
.expect(200);
expect(metadata.body.name).toEqual(testAlias);
expect(metadata.body.primaryAlias).toBeTruthy();
expect(metadata.body.noteId).toEqual(publicId);
const note = await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(200);
expect(note.body.metadata.aliases).toContainEqual({
name: testAlias,
primaryAlias: true,
noteId: publicId,
});
expect(note.body.metadata.primaryAddress).toEqual(testAlias);
expect(note.body.metadata.id).toEqual(publicId);
});
describe('does not update', () => {
it('a note with unknown alias', async () => {
await request(testSetup.app.getHttpServer())
.put(`/api/v2/alias/i_dont_exist`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send(changeAliasDto)
.expect(404);
});
it('a note with a forbidden id', async () => {
await request(testSetup.app.getHttpServer())
.put(`/api/v2/alias/${forbiddenNoteId}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send(changeAliasDto)
.expect(400);
});
it('if the user is not an owner', async () => {
await request(testSetup.app.getHttpServer())
.put(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[1].secret}`)
.set('Content-Type', 'application/json')
.send(changeAliasDto)
.expect(401);
});
it('if the property primaryAlias is false', async () => {
changeAliasDto.primaryAlias = false;
await request(testSetup.app.getHttpServer())
.put(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.set('Content-Type', 'application/json')
.send(changeAliasDto)
.expect(400);
});
});
});
describe('DELETE /alias/{alias}', () => {
const secondAlias = 'secondAlias';
it('deletes a normal alias', async () => {
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(204);
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(404);
});
it('does not delete an unknown alias', async () => {
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/i_dont_exist`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(404);
});
it('errors on forbidden notes', async () => {
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${forbiddenNoteId}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(400);
});
it('errors if the user is not the owner', async () => {
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[1].secret}`)
.expect(401);
});
it('does not delete a primary alias (if it is not the only one)', async () => {
// add another alias
await testSetup.aliasService.addAlias(
testSetup.ownedNotes[0],
secondAlias,
);
// try to delete the primary alias
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(400);
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${secondAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(200);
});
it('deletes a primary alias (if it is the only one)', async () => {
// add another alias
await testSetup.aliasService.addAlias(
testSetup.ownedNotes[0],
secondAlias,
);
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${secondAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(204);
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/alias/${testAlias}`)
.set('Authorization', `Bearer ${testSetup.authTokens[0].secret}`)
.expect(204);
});
});
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
SPDX-License-Identifier: CC0-1.0

Binary file not shown.

View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
SPDX-License-Identifier: CC0-1.0

View file

@ -0,0 +1,236 @@
/*
* SPDX-FileCopyrightText: 2022 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { promises as fs } from 'fs';
import { join } from 'path';
import request from 'supertest';
import { HistoryEntryUpdateDto } from '../../src/history/history-entry-update.dto';
import { HistoryEntryDto } from '../../src/history/history-entry.dto';
import { NoteMetadataDto } from '../../src/notes/note-metadata.dto';
import { User } from '../../src/users/user.entity';
import { TestSetup, TestSetupBuilder } from '../test-setup';
// TODO Tests have to be reworked using UserService functions
describe('Me', () => {
let testSetup: TestSetup;
let uploadPath: string;
let user: User;
beforeAll(async () => {
testSetup = await TestSetupBuilder.create().withMockAuth().build();
uploadPath =
testSetup.configService.get('mediaConfig').backend.filesystem.uploadPath;
user = await testSetup.userService.createUser('hardcoded', 'Testy');
await testSetup.app.init();
});
afterAll(async () => {
await testSetup.app.close();
await testSetup.cleanup();
});
it(`GET /me`, async () => {
const userInfo = testSetup.userService.toFullUserDto(user);
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/me')
.expect('Content-Type', /json/)
.expect(200);
expect(response.body).toEqual(userInfo);
});
it(`GET /me/history`, async () => {
const noteName = 'testGetNoteHistory1';
const note = await testSetup.notesService.createNote('', null, noteName);
const createdHistoryEntry =
await testSetup.historyService.updateHistoryEntryTimestamp(note, user);
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/me/history')
.expect('Content-Type', /json/)
.expect(200);
const history: HistoryEntryDto[] = response.body;
expect(history.length).toEqual(1);
const historyDto = await testSetup.historyService.toHistoryEntryDto(
createdHistoryEntry,
);
for (const historyEntry of history) {
expect(historyEntry.identifier).toEqual(historyDto.identifier);
expect(historyEntry.title).toEqual(historyDto.title);
expect(historyEntry.tags).toEqual(historyDto.tags);
expect(historyEntry.pinStatus).toEqual(historyDto.pinStatus);
expect(historyEntry.lastVisitedAt).toEqual(
historyDto.lastVisitedAt.toISOString(),
);
}
});
describe(`GET /me/history/{note}`, () => {
it('works with an existing note', async () => {
const noteName = 'testGetNoteHistory2';
const note = await testSetup.notesService.createNote('', null, noteName);
const createdHistoryEntry =
await testSetup.historyService.updateHistoryEntryTimestamp(note, user);
const response = await request(testSetup.app.getHttpServer())
.get(`/api/v2/me/history/${noteName}`)
.expect('Content-Type', /json/)
.expect(200);
const historyEntry: HistoryEntryDto = response.body;
const historyEntryDto = await testSetup.historyService.toHistoryEntryDto(
createdHistoryEntry,
);
expect(historyEntry.identifier).toEqual(historyEntryDto.identifier);
expect(historyEntry.title).toEqual(historyEntryDto.title);
expect(historyEntry.tags).toEqual(historyEntryDto.tags);
expect(historyEntry.pinStatus).toEqual(historyEntryDto.pinStatus);
expect(historyEntry.lastVisitedAt).toEqual(
historyEntryDto.lastVisitedAt.toISOString(),
);
});
it('fails with a non-existing note', async () => {
await request(testSetup.app.getHttpServer())
.get('/api/v2/me/history/i_dont_exist')
.expect('Content-Type', /json/)
.expect(404);
});
});
describe(`PUT /me/history/{note}`, () => {
it('works', async () => {
const noteName = 'testGetNoteHistory3';
const note = await testSetup.notesService.createNote('', null, noteName);
await testSetup.historyService.updateHistoryEntryTimestamp(note, user);
const historyEntryUpdateDto = new HistoryEntryUpdateDto();
historyEntryUpdateDto.pinStatus = true;
const response = await request(testSetup.app.getHttpServer())
.put('/api/v2/me/history/' + noteName)
.send(historyEntryUpdateDto)
.expect(200);
const history = await testSetup.historyService.getEntriesByUser(user);
const historyEntry: HistoryEntryDto = response.body;
expect(historyEntry.pinStatus).toEqual(true);
let theEntry: HistoryEntryDto;
for (const entry of history) {
if (
(await (await entry.note).aliases).find(
(element) => element.name === noteName,
)
) {
theEntry = await testSetup.historyService.toHistoryEntryDto(entry);
}
}
expect(theEntry.pinStatus).toEqual(true);
});
it('fails with a non-existing note', async () => {
await request(testSetup.app.getHttpServer())
.put('/api/v2/me/history/i_dont_exist')
.expect('Content-Type', /json/)
.expect(404);
});
});
describe(`DELETE /me/history/{note}`, () => {
it('works', async () => {
const noteName = 'testGetNoteHistory4';
const note = await testSetup.notesService.createNote('', null, noteName);
await testSetup.historyService.updateHistoryEntryTimestamp(note, user);
const response = await request(testSetup.app.getHttpServer())
.delete(`/api/v2/me/history/${noteName}`)
.expect(204);
expect(response.body).toEqual({});
const history = await testSetup.historyService.getEntriesByUser(user);
for (const entry of history) {
if (
(await (await entry.note).aliases).find(
(element) => element.name === noteName,
)
) {
throw new Error('Deleted history entry still in history');
}
}
});
describe('fails', () => {
it('with a non-existing note', async () => {
await request(testSetup.app.getHttpServer())
.delete('/api/v2/me/history/i_dont_exist')
.expect(404);
});
it('with a non-existing history entry', async () => {
const noteName = 'testGetNoteHistory5';
await testSetup.notesService.createNote('', null, noteName);
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/me/history/${noteName}`)
.expect(404);
});
});
});
it(`GET /me/notes/`, async () => {
const noteName = 'testNote';
await testSetup.notesService.createNote('', user, noteName);
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/me/notes/')
.expect('Content-Type', /json/)
.expect(200);
const noteMetaDtos = response.body as NoteMetadataDto[];
expect(noteMetaDtos).toHaveLength(1);
expect(noteMetaDtos[0].primaryAddress).toEqual(noteName);
expect(noteMetaDtos[0].updateUsername).toEqual(user.username);
});
it('GET /me/media', async () => {
const note1 = await testSetup.notesService.createNote(
'This is a test note.',
await testSetup.userService.getUserByUsername('hardcoded'),
'test8',
);
const note2 = await testSetup.notesService.createNote(
'This is a test note.',
await testSetup.userService.getUserByUsername('hardcoded'),
'test9',
);
const httpServer = testSetup.app.getHttpServer();
const response1 = await request(httpServer)
.get('/api/v2/me/media/')
.expect('Content-Type', /json/)
.expect(200);
expect(response1.body).toHaveLength(0);
const testImage = await fs.readFile('test/public-api/fixtures/test.png');
const imageUrls = [];
imageUrls.push(
(await testSetup.mediaService.saveFile(testImage, user, note1)).fileUrl,
);
imageUrls.push(
(await testSetup.mediaService.saveFile(testImage, user, note1)).fileUrl,
);
imageUrls.push(
(await testSetup.mediaService.saveFile(testImage, user, note2)).fileUrl,
);
imageUrls.push(
(await testSetup.mediaService.saveFile(testImage, user, note2)).fileUrl,
);
const response = await request(httpServer)
.get('/api/v2/me/media/')
.expect('Content-Type', /json/)
.expect(200);
expect(response.body).toHaveLength(4);
expect(imageUrls).toContain(response.body[0].url);
expect(imageUrls).toContain(response.body[1].url);
expect(imageUrls).toContain(response.body[2].url);
expect(imageUrls).toContain(response.body[3].url);
for (const fileUrl of imageUrls) {
const fileName = fileUrl.replace('/uploads/', '');
// delete the file afterwards
await fs.unlink(join(uploadPath, fileName));
}
await fs.rm(uploadPath, { recursive: true });
});
});

View file

@ -0,0 +1,121 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { promises as fs } from 'fs';
import { join } from 'path';
import request from 'supertest';
import { ConsoleLoggerService } from '../../src/logger/console-logger.service';
import { Note } from '../../src/notes/note.entity';
import { User } from '../../src/users/user.entity';
import { TestSetup, TestSetupBuilder } from '../test-setup';
import { ensureDeleted } from '../utils';
describe('Media', () => {
let testSetup: TestSetup;
let uploadPath: string;
let testNote: Note;
let user: User;
beforeAll(async () => {
testSetup = await TestSetupBuilder.create().withMockAuth().build();
uploadPath =
testSetup.configService.get('mediaConfig').backend.filesystem.uploadPath;
testSetup.app.useStaticAssets(uploadPath, {
prefix: '/uploads',
});
await testSetup.app.init();
const logger = await testSetup.app.resolve(ConsoleLoggerService);
logger.log('Switching logger', 'AppBootstrap');
testSetup.app.useLogger(logger);
user = await testSetup.userService.createUser('hardcoded', 'Testy');
testNote = await testSetup.notesService.createNote(
'test content',
null,
'test_upload_media',
);
});
afterAll(async () => {
// Delete the upload folder
await ensureDeleted(uploadPath);
await testSetup.app.close();
await testSetup.cleanup();
});
describe('POST /media', () => {
it('works', async () => {
const uploadResponse = await request(testSetup.app.getHttpServer())
.post('/api/v2/media')
.attach('file', 'test/public-api/fixtures/test.png')
.set('HedgeDoc-Note', 'test_upload_media')
.expect('Content-Type', /json/)
.expect(201);
const path: string = uploadResponse.body.url;
const testImage = await fs.readFile('test/public-api/fixtures/test.png');
const downloadResponse = await request(testSetup.app.getHttpServer()).get(
path,
);
expect(downloadResponse.body).toEqual(testImage);
// Remove /uploads/ from path as we just need the filename.
const fileName = path.replace('/uploads/', '');
// delete the file afterwards
await fs.unlink(join(uploadPath, fileName));
});
describe('fails:', () => {
beforeEach(async () => {
await ensureDeleted(uploadPath);
});
it('MIME type not supported', async () => {
await request(testSetup.app.getHttpServer())
.post('/api/v2/media')
.attach('file', 'test/public-api/fixtures/test.zip')
.set('HedgeDoc-Note', 'test_upload_media')
.expect(400);
await expect(fs.access(uploadPath)).rejects.toBeDefined();
});
it('note does not exist', async () => {
await request(testSetup.app.getHttpServer())
.post('/api/v2/media')
.attach('file', 'test/public-api/fixtures/test.zip')
.set('HedgeDoc-Note', 'i_dont_exist')
.expect(404);
await expect(fs.access(uploadPath)).rejects.toBeDefined();
});
it('mediaBackend error', async () => {
await fs.mkdir(uploadPath, {
mode: '444',
});
await request(testSetup.app.getHttpServer())
.post('/api/v2/media')
.attach('file', 'test/public-api/fixtures/test.png')
.set('HedgeDoc-Note', 'test_upload_media')
.expect('Content-Type', /json/)
.expect(500);
});
afterEach(async () => {
await ensureDeleted(uploadPath);
});
});
});
it('DELETE /media/{filename}', async () => {
const testImage = await fs.readFile('test/public-api/fixtures/test.png');
const upload = await testSetup.mediaService.saveFile(
testImage,
user,
testNote,
);
const filename = upload.fileUrl.split('/').pop() || '';
await request(testSetup.app.getHttpServer())
.delete('/api/v2/media/' + filename)
.expect(204);
});
});

View file

@ -0,0 +1,492 @@
/*
* SPDX-FileCopyrightText: 2022 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { promises as fs } from 'fs';
import { join } from 'path';
import request from 'supertest';
import { NotInDBError } from '../../src/errors/errors';
import { NotePermissionsUpdateDto } from '../../src/notes/note-permissions.dto';
import { User } from '../../src/users/user.entity';
import { TestSetup, TestSetupBuilder } from '../test-setup';
describe('Notes', () => {
let testSetup: TestSetup;
let user: User;
let user2: User;
let content: string;
let forbiddenNoteId: string;
let uploadPath: string;
let testImage: Buffer;
beforeAll(async () => {
testSetup = await TestSetupBuilder.create().withMockAuth().build();
forbiddenNoteId =
testSetup.configService.get('noteConfig').forbiddenNoteIds[0];
uploadPath =
testSetup.configService.get('mediaConfig').backend.filesystem.uploadPath;
await testSetup.app.init();
user = await testSetup.userService.createUser('hardcoded', 'Testy');
user2 = await testSetup.userService.createUser(
'hardcoded2',
'Max Mustermann',
);
content = 'This is a test note.';
testImage = await fs.readFile('test/public-api/fixtures/test.png');
});
afterAll(async () => {
await testSetup.app.close();
await testSetup.cleanup();
});
it('POST /notes', async () => {
const response = await request(testSetup.app.getHttpServer())
.post('/api/v2/notes')
.set('Content-Type', 'text/markdown')
.send(content)
.expect('Content-Type', /json/)
.expect(201);
expect(response.body.metadata?.id).toBeDefined();
expect(
await testSetup.notesService.getNoteContent(
await testSetup.notesService.getNoteByIdOrAlias(
response.body.metadata.id,
),
),
).toEqual(content);
});
describe('GET /notes/{note}', () => {
it('works with an existing note', async () => {
// check if we can succefully get a note that exists
await testSetup.notesService.createNote(content, user, 'test1');
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/test1')
.expect('Content-Type', /json/)
.expect(200);
expect(response.body.content).toEqual(content);
});
it('fails with an non-existing note', async () => {
// check if a missing note correctly returns 404
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/i_dont_exist')
.expect('Content-Type', /json/)
.expect(404);
});
it('fails with a forbidden note id', async () => {
// check if a forbidden note correctly returns 400
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/forbiddenNoteId')
.expect('Content-Type', /json/)
.expect(400);
});
});
describe('POST /notes/{note}', () => {
it('works with a non-existing alias', async () => {
const response = await request(testSetup.app.getHttpServer())
.post('/api/v2/notes/test2')
.set('Content-Type', 'text/markdown')
.send(content)
.expect('Content-Type', /json/)
.expect(201);
expect(response.body.metadata?.id).toBeDefined();
return expect(
await testSetup.notesService.getNoteContent(
await testSetup.notesService.getNoteByIdOrAlias(
response.body.metadata?.id,
),
),
).toEqual(content);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.post(`/api/v2/notes/${forbiddenNoteId}`)
.set('Content-Type', 'text/markdown')
.send(content)
.expect('Content-Type', /json/)
.expect(400);
});
it('fails with a existing alias', async () => {
await request(testSetup.app.getHttpServer())
.post('/api/v2/notes/test2')
.set('Content-Type', 'text/markdown')
.send(content)
.expect('Content-Type', /json/)
.expect(409);
});
it('fails with a content, that is too long', async () => {
const content = 'x'.repeat(
(testSetup.configService.get('noteConfig')
.maxDocumentLength as number) + 1,
);
await request(testSetup.app.getHttpServer())
.post('/api/v2/notes/test2')
.set('Content-Type', 'text/markdown')
.send(content)
.expect('Content-Type', /json/)
.expect(413);
});
});
describe('DELETE /notes/{note}', () => {
describe('works', () => {
it('with an existing alias and keepMedia false', async () => {
const noteId = 'test3';
const note = await testSetup.notesService.createNote(
content,
user,
noteId,
);
await testSetup.mediaService.saveFile(testImage, user, note);
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/notes/${noteId}`)
.set('Content-Type', 'application/json')
.send({
keepMedia: false,
})
.expect(204);
await expect(
testSetup.notesService.getNoteByIdOrAlias(noteId),
).rejects.toEqual(
new NotInDBError(`Note with id/alias '${noteId}' not found.`),
);
expect(
await testSetup.mediaService.listUploadsByUser(user),
).toHaveLength(0);
});
it('with an existing alias and keepMedia true', async () => {
const noteId = 'test3a';
const note = await testSetup.notesService.createNote(
content,
user,
noteId,
);
const upload = await testSetup.mediaService.saveFile(
testImage,
user,
note,
);
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/notes/${noteId}`)
.set('Content-Type', 'application/json')
.send({
keepMedia: true,
})
.expect(204);
await expect(
testSetup.notesService.getNoteByIdOrAlias(noteId),
).rejects.toEqual(
new NotInDBError(`Note with id/alias '${noteId}' not found.`),
);
expect(
await testSetup.mediaService.listUploadsByUser(user),
).toHaveLength(1);
// Remove /upload/ from path as we just need the filename.
const fileName = upload.fileUrl.replace('/uploads/', '');
// delete the file afterwards
await fs.unlink(join(uploadPath, fileName));
});
});
it('works with an existing alias with permissions', async () => {
const note = await testSetup.notesService.createNote(
content,
user,
'test3',
);
const updateNotePermission = new NotePermissionsUpdateDto();
updateNotePermission.sharedToUsers = [
{
username: user.username,
canEdit: true,
},
];
updateNotePermission.sharedToGroups = [];
await testSetup.permissionsService.updateNotePermissions(
note,
updateNotePermission,
);
const updatedNote = await testSetup.notesService.getNoteByIdOrAlias(
(await note.aliases).filter((alias) => alias.primary)[0].name,
);
expect(await updatedNote.userPermissions).toHaveLength(1);
expect((await updatedNote.userPermissions)[0].canEdit).toEqual(
updateNotePermission.sharedToUsers[0].canEdit,
);
expect(
(await (await updatedNote.userPermissions)[0].user).username,
).toEqual(user.username);
expect(await updatedNote.groupPermissions).toHaveLength(0);
await request(testSetup.app.getHttpServer())
.delete('/api/v2/notes/test3')
.send({ keepMedia: false })
.expect(204);
await expect(
testSetup.notesService.getNoteByIdOrAlias('test3'),
).rejects.toEqual(
new NotInDBError("Note with id/alias 'test3' not found."),
);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.delete(`/api/v2/notes/${forbiddenNoteId}`)
.expect(400);
});
it('fails with a non-existing alias', async () => {
await request(testSetup.app.getHttpServer())
.delete('/api/v2/notes/i_dont_exist')
.expect(404);
});
});
describe('PUT /notes/{note}', () => {
const changedContent = 'New note text';
it('works with existing alias', async () => {
await testSetup.notesService.createNote(content, user, 'test4');
const response = await request(testSetup.app.getHttpServer())
.put('/api/v2/notes/test4')
.set('Content-Type', 'text/markdown')
.send(changedContent)
.expect(200);
expect(
await testSetup.notesService.getNoteContent(
await testSetup.notesService.getNoteByIdOrAlias('test4'),
),
).toEqual(changedContent);
expect(response.body.content).toEqual(changedContent);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.put(`/api/v2/notes/${forbiddenNoteId}`)
.set('Content-Type', 'text/markdown')
.send(changedContent)
.expect(400);
});
it('fails with a non-existing alias', async () => {
await request(testSetup.app.getHttpServer())
.put('/api/v2/notes/i_dont_exist')
.set('Content-Type', 'text/markdown')
.expect('Content-Type', /json/)
.expect(404);
});
});
describe('GET /notes/{note}/metadata', () => {
it('returns complete metadata object', async () => {
await testSetup.notesService.createNote(content, user, 'test5');
const metadata = await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/test5/metadata')
.expect(200);
expect(typeof metadata.body.id).toEqual('string');
expect(metadata.body.aliases[0].name).toEqual('test5');
expect(metadata.body.primaryAddress).toEqual('test5');
expect(metadata.body.title).toEqual('');
expect(metadata.body.description).toEqual('');
expect(typeof metadata.body.createdAt).toEqual('string');
expect(metadata.body.editedBy).toEqual([]);
expect(metadata.body.permissions.owner).toEqual('hardcoded');
expect(metadata.body.permissions.sharedToUsers).toEqual([]);
expect(metadata.body.permissions.sharedToUsers).toEqual([]);
expect(metadata.body.tags).toEqual([]);
expect(typeof metadata.body.updatedAt).toEqual('string');
expect(typeof metadata.body.updateUsername).toEqual('string');
expect(typeof metadata.body.viewCount).toEqual('number');
expect(metadata.body.editedBy).toEqual([]);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${forbiddenNoteId}/metadata`)
.expect(400);
});
it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/i_dont_exist/metadata')
.expect('Content-Type', /json/)
.expect(404);
});
it('has the correct update/create dates', async () => {
// create a note
const note = await testSetup.notesService.createNote(
content,
user,
'test5a',
);
// save the creation time
const createDate = note.createdAt;
const revisions = await note.revisions;
const updatedDate = revisions[revisions.length - 1].createdAt;
// wait one second
await new Promise((r) => setTimeout(r, 1000));
// update the note
await testSetup.notesService.updateNote(note, 'More test content');
const metadata = await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/test5a/metadata')
.expect(200);
expect(metadata.body.createdAt).toEqual(createDate.toISOString());
expect(metadata.body.updatedAt).not.toEqual(updatedDate.toISOString());
});
});
describe('GET /notes/{note}/revisions', () => {
it('works with existing alias', async () => {
await testSetup.notesService.createNote(content, user, 'test6');
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/test6/revisions')
.expect('Content-Type', /json/)
.expect(200);
expect(response.body).toHaveLength(1);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${forbiddenNoteId}/revisions`)
.expect(400);
});
it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/i_dont_exist/revisions')
.expect('Content-Type', /json/)
.expect(404);
});
});
describe('GET /notes/{note}/revisions/{revision-id}', () => {
it('works with an existing alias', async () => {
const note = await testSetup.notesService.createNote(
content,
user,
'test7',
);
const revision = await testSetup.revisionsService.getLatestRevision(note);
const response = await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/test7/revisions/${revision.id}`)
.expect('Content-Type', /json/)
.expect(200);
expect(response.body.content).toEqual(content);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${forbiddenNoteId}/revisions/1`)
.expect(400);
});
it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/i_dont_exist/revisions/1')
.expect('Content-Type', /json/)
.expect(404);
});
});
describe('GET /notes/{note}/content', () => {
it('works with an existing alias', async () => {
await testSetup.notesService.createNote(content, user, 'test8');
const response = await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/test8/content')
.expect(200);
expect(response.text).toEqual(content);
});
it('fails with a forbidden alias', async () => {
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${forbiddenNoteId}/content`)
.expect(400);
});
it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404
await request(testSetup.app.getHttpServer())
.get('/api/v2/notes/i_dont_exist/content')
.expect(404);
});
});
describe('GET /notes/{note}/media', () => {
it('works', async () => {
const alias = 'test9';
const extraAlias = 'test10';
const note1 = await testSetup.notesService.createNote(
content,
user,
alias,
);
const note2 = await testSetup.notesService.createNote(
content,
user,
extraAlias,
);
const httpServer = testSetup.app.getHttpServer();
const response = await request(httpServer)
.get(`/api/v2/notes/${alias}/media/`)
.expect('Content-Type', /json/)
.expect(200);
expect(response.body).toHaveLength(0);
const testImage = await fs.readFile('test/public-api/fixtures/test.png');
const upload0 = await testSetup.mediaService.saveFile(
testImage,
user,
note1,
);
const upload1 = await testSetup.mediaService.saveFile(
testImage,
user,
note2,
);
const responseAfter = await request(httpServer)
.get(`/api/v2/notes/${alias}/media/`)
.expect('Content-Type', /json/)
.expect(200);
expect(responseAfter.body).toHaveLength(1);
expect(responseAfter.body[0].url).toEqual(upload0.fileUrl);
expect(responseAfter.body[0].url).not.toEqual(upload1.fileUrl);
for (const upload of [upload0, upload1]) {
const fileName = upload.fileUrl.replace('/uploads/', '');
// delete the file afterwards
await fs.unlink(join(uploadPath, fileName));
}
await fs.rm(uploadPath, { recursive: true });
});
it('fails, when note does not exist', async () => {
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/i_dont_exist/media/`)
.expect('Content-Type', /json/)
.expect(404);
});
it("fails, when user can't read note", async () => {
const alias = 'test11';
await testSetup.notesService.createNote(
'This is a test note.',
user2,
alias,
);
// Redact default read permissions
const note = await testSetup.notesService.getNoteByIdOrAlias(alias);
const everyone = await testSetup.groupService.getEveryoneGroup();
const loggedin = await testSetup.groupService.getLoggedInGroup();
await testSetup.permissionsService.removeGroupPermission(note, everyone);
await testSetup.permissionsService.removeGroupPermission(note, loggedin);
await request(testSetup.app.getHttpServer())
.get(`/api/v2/notes/${alias}/media/`)
.expect('Content-Type', /json/)
.expect(403);
});
});
});