From 3a95396b773c3bfb5f8a407e256f98d926297002 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Tue, 10 Apr 2018 18:18:12 +0100 Subject: WIP: Add support for raw and meta views --- src/FileRouter.ts | 33 ++++------ src/app.ts | 37 +++++------ src/db/model/File.ts | 54 +++++++++++++++- src/files.ts | 172 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/logger.ts | 167 +++++++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 407 insertions(+), 56 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4d6eb16..ee10662 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,7 +8,7 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { files } from './files'; +import { View, files, views } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -268,7 +268,7 @@ const getUserProperties: Middleware = */ const getUsername: Middleware = (req: Request, res: Response, next: NextFunction): void => { - if (res.locals.user === null) { + if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; } @@ -473,36 +473,29 @@ const getProjectProperties: Middleware = /** * GET a File. */ -const getFilePath: Middleware = async( +const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { const file: File | null = res.locals.file; - const project: Project | null = res.locals.project; if (file == null) { return next(new RequestError(404, 'file_not_found')); - } else if (project == null) { - return next(new RequestError(404, 'project_not_found')); } - res.locals.function = res.sendFile; - res.locals.data = - `${BASE_FILE_STORAGE}/${res.locals.project.name}/${file.uuid}`; + const project: Project = res.locals.project; + const view: View = views[req.query.view || 'meta']; + res.locals.function = view.getResponseFunction(req, res); + res.locals.data = view.getResponseData(file, project, req.query); next(); }; /** * GET a File. */ -const getFileId: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - const file: File | null = res.locals.file; - if (file === null) { - next(new RequestError(404, 'file_not_found')); - return; - } - res.locals.function = res.sendFile; - res.locals.data = files.path(req.params.id, res.locals.project.name); - next(); -}; +const getFilePath: Middleware = getFile; + +/** + * GET a File. + */ +const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc diff --git a/src/app.ts b/src/app.ts index c627027..8207aa6 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,6 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; import * as expressJwt from 'express-jwt'; -import * as logger from 'morgan'; import * as passport from 'passport'; import { default as authRouter, unauthorisedErr } from './auth'; @@ -24,7 +23,7 @@ import { default as UserGroup } from './db/model/UserGroup'; */ class App { /** - * The Express app used throught the server. + * The Express app used throughout the server. */ public express: ex.Express; @@ -42,16 +41,23 @@ class App { public constructor(enableLog: boolean) { this.logEnabled = enableLog; this.express = ex(); + this.express.use(( + req: ex.Request, res: ex.Response, next: ex.NextFunction + ): void => { console.log(req.url); next(); }); this.precondition(); this.middleware(); this.mountRoutes(); this.express.use( async(req: ex.Request, res: ex.Response, next: ex.NextFunction): Promise => { - res.json({ - status: 'success', - data: await res.locals.data - }); + if (res.locals.function) { + res.locals.function.bind(res)(res.locals.data); + } else { + res.json({ + status: 'success', + data: await res.locals.data + }); + } } ); this.errorware(); @@ -83,9 +89,6 @@ class App { } next(); }); - if (this.logEnabled) { - this.express.use(logger('combined')); - } this.express.use(bodyParser.json()); this.express.use(bodyParser.urlencoded({ extended: false })); } @@ -143,7 +146,7 @@ class App { username: name } }); - if (user === null) { + if (user == null) { return next(new RequestError(404, 'user_not_found')); } else { res.locals.user = user; @@ -177,9 +180,8 @@ class App { ): Promise => { const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; - if (project === null) { - next(new RequestError(404, 'project_not_found')); - return; + if (project == null) { + return next(new RequestError(404, 'project_not_found')); } let file: File = project.rootFolder; // TODO Rewrite using sub-queries instead of repeated queries. @@ -190,7 +192,7 @@ class App { parentFolder: file } }); - if (fileOrNull === null) { + if (fileOrNull == null) { return next(); } else { file = fileOrNull; @@ -206,7 +208,7 @@ class App { name: fileNames[0] } }); - if (parentFolder === null) { + if (parentFolder == null) { return next(); } res.locals.parentFolder = parentFolder; @@ -231,9 +233,8 @@ class App { uuid: fileId } }); - if (file === null) { - next(new RequestError(404, 'file_not_found')); - return; + if (file == null) { + return next(new RequestError(404, 'file_not_found')); } else { res.locals.file = file; } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 33043f0..4026b85 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -3,18 +3,27 @@ import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany, HasOne, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; import { default as User } from './User'; +import { FileTypeName, mimes } from '../../files'; + @Table export default class File extends Model { @AllowNull @Column - public name!: string; + private nameInternal!: string; + + @AllowNull + @Column + private fullPathInternal!: string; @PrimaryKey @Column public uuid!: string; + @Column(DataType.TEXT) + public type!: FileTypeName; + @Column - public mimetype!: string; + public size!: number; @ForeignKey(() => File) @AllowNull @@ -46,6 +55,35 @@ export default class File extends Model { @Column(DataType.DATE) public modifyDate!: Date; + @Column + public status!: string; + + @Column + private metadataInternal!: string; + + public get name(): string { + return this.nameInternal; + } + + public set name(name: string) { + this.nameInternal = name; + this.fullPathInternal = this.fullPathInternal.substring( + 0, + this.fullPathInternal.lastIndexOf('/') + 1 + ) + this.name; + } + + public get fullPath(): string { + return this.fullPathInternal; + } + + public set fullPath(path: string) { + this.fullPathInternal = path; + this.nameInternal = this.fullPath.substring( + this.fullPathInternal.lastIndexOf('/') + 1 + ); + } + public get containedFiles(): File[] { if (this.containedFilesInternal === undefined) { throw new Error('containedFiles is undefined'); @@ -56,4 +94,16 @@ export default class File extends Model { public set containedFiles(files: File[]) { this.containedFilesInternal = files; } + + public get metadata(): object { + return JSON.parse(this.metadataInternal); + } + + public set metadata(metadata: object) { + this.metadataInternal = JSON.stringify(metadata); + } + + public set mimetype(mime: string) { + this.type = mimes.get(mime) || 'generic'; + } } diff --git a/src/files.ts b/src/files.ts index 644d24e..8ad7236 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,5 +1,9 @@ +import { Request, Response } from 'express'; import * as fs from 'fs'; +import { default as File } from './db/model/File'; +import { default as Project } from './db/model/Project'; + const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; @@ -8,12 +12,38 @@ const path: (filename: string, projectName: string) => string return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; }; -const writableStream: - (filename: string, projectName: string) => fs.WriteStream = - (filename: string, projectName: string): fs.WriteStream => { +const writableStream: ( + filename: string, projectName: string +) => fs.WriteStream = ( + filename: string, projectName: string +): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; +interface RawSize { + offset: number; + length: number; +} + +const readableStream: ( + filename: string, projectName: string, + { offset, length }?: Partial +) => fs.ReadStream = ( + filename: string, projectName: string, + { offset, length }: Partial = + { offset: undefined, length: undefined } +): fs.ReadStream => { + const options: object = { + start: offset + ? offset + : 0, + end: offset && length + ? offset + length + : undefined + }; + return fs.createReadStream(path(filename, projectName), options); +}; + const logPath: (type: string, projectName?: string) => string = ( type: string, projectName?: string @@ -32,3 +62,139 @@ export const files: { writableStream, logPath }; + +export type ViewName = 'raw' | 'meta'; + +interface Query extends Partial { + children?: boolean; +} + +export interface View { + getContents: (file: File) => object; + getResponseData: (file: File, project: Project, query: Query) => + Promise; + getResponseFunction: (req: Request, res: Response) => Function | null; +} + +interface MetaResponseData { + file_path: string; + file_name: string; + id: string; + type: FileTypeName; + metadata: object; + status: string; + supported_views: { + [key: string]: object | undefined; + }; + children?: MetaResponseData[]; +} + +const metaGetResponseData: ( + file: File, project: Project, query: Query +) => Promise = async( + file: File, project: Project, query: Query +): Promise => { + const data: MetaResponseData = { + file_path: file.fullPath, + file_name: file.name, + id: file.id, + type: file.type, + metadata: file.metadata, + status: file.status, + supported_views: {} + }; + for (const view of fileTypes[file.type].supportedViews) { + data.supported_views[view] = + views[view].getContents(file); + } + if (query.children) { + data.children = []; + const children: File[] | null = await File.findAll({ + where: { + parentFolder: file + } + }); + if (children != null) { + for (const child of children) { + data.children.push(await metaGetResponseData( + file, + project, + { + ...query, + children: undefined + } + )); + } + } + } + return data; +}; + +export const views: { + [view: string]: View; +} = { + raw: { + getContents: (file: File): object => { + return { + size: file.size + }; + }, + getResponseData: async( + file: File, project: Project, query: Query + ): Promise => { + return readableStream(file.name, project.name, query); + }, + getResponseFunction: (req: Request, res: Response): Function | null => { + return res.send; + } + }, + meta: { + getContents: (file: File): object => { + return {}; + }, + getResponseData: metaGetResponseData, + getResponseFunction: (req: Request, res: Response): Function | null => { + return null; + } + } +}; + +export type FileTypeName = 'generic' | 'directory'; + +export interface FileType { + supportedViews: ViewName[]; +} + +const fileTypes: { + [type: string]: FileType; +} = { + generic: { + supportedViews: [ + 'raw', 'meta' + ] + }, + directory: { + supportedViews: [ + 'meta' + ] + } +}; + +class MimeTypeMap extends Map { + public constructor(pairs: [string, FileTypeName][]) { + super(pairs); + } + + public get(mime: string): FileTypeName { + const ret: string | undefined = super.get(mime); + if (ret) { + return ret as FileTypeName; + } else { + return 'generic'; + } + } +} + +export const mimes: MimeTypeMap = new MimeTypeMap([ + [ 'inode/directory', 'directory' ] +]); diff --git a/src/logger.ts b/src/logger.ts index bbb0a73..069cdf5 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -5,26 +5,105 @@ import * as winston from 'winston'; import { files } from './files'; -type LogLevel = 'critical' | 'error' | 'warning' | 'security' | 'info'; +type Colour = (s: string) => string; + +type LogLevel = + | '7' + | 'debug' + | 'minor' + | 'silly' + | 'testing' + | 'verbose' + | '6' + | 'information' + | 'inform' + | 'info' + | '5' + | 'note' + | 'notice' + | 'notify' + | 'success' + | 'security' + | '4' + | 'warn' + | 'warning' + | '3' + | 'err' + | 'failure' + | 'fail' + | 'error' + | '2' + | 'crit' + | 'severe' + | 'critical' + | '1' + | 'alert' + | 'breach' + | '0' + | 'fatal' + | 'emerg' + | 'emergency' + | 'shutdown'; const LOG_LEVELS: winston.LoggerOptions = { - info: 4, - security: 3, - warning: 2, - error: 1, - critical: 0 + 7: 7, + debug: 7, + minor: 7, + silly: 7, + testing: 7, + verbose: 7, + 6: 6, + information: 6, + inform: 6, + info: 6, + 5: 5, + note: 5, + notice: 5, + notify: 5, + success: 5, + security: 5, + 4: 4, + warn: 4, + warning: 4, + 3: 3, + err: 3, + failure: 3, + fail: 3, + error: 3, + 2: 2, + crit: 2, + severe: 2, + critical: 2, + 1: 1, + alert: 1, + breach: 1, + 0: 0, + fatal: 0, + emerg: 0, + emergency: 0, + shutdown: 0 }; -const LOG_LEVEL_COLOURS: { - [key: string]: (s: string) => string; +const LEVEL_COLOURS: { + [key: number]: Colour; } = { - info: colors.cyan, - security: colors.blue, - warning: colors.yellow, - error: colors.red, - critical: colors.red + 7: colors.cyan, + 6: colors.blue, + 5: colors.green, + 4: colors.yellow, + 3: colors.red, + 2: colors.magenta, + 1: colors.black, + 0: colors.white }; +const LOG_LEVEL_COLOURS: { + [key: string]: Colour; +} = {}; +Object.keys(LOG_LEVELS).forEach((k: string): void => { + LOG_LEVEL_COLOURS[k] = LEVEL_COLOURS[LOG_LEVELS[k]]; +}); + interface LoggingMetadata { component?: string; user?: string; @@ -217,20 +296,82 @@ const fetchLogs: (level: LogLevel, params?: FetchParams) => LogItem[] = ( }; export const logger: { + 7: LogFunction; + debug: LogFunction; + minor: LogFunction; + silly: LogFunction; + testing: LogFunction; + verbose: LogFunction; + 6: LogFunction; + information: LogFunction; + inform: LogFunction; info: LogFunction; + 5: LogFunction; + note: LogFunction; + notice: LogFunction; + notify: LogFunction; + success: LogFunction; security: LogFunction; + 4: LogFunction; + warn: LogFunction; warning: LogFunction; + 3: LogFunction; + err: LogFunction; + failure: LogFunction; + fail: LogFunction; error: LogFunction; + 2: LogFunction; + crit: LogFunction; + severe: LogFunction; critical: LogFunction; + 1: LogFunction; + alert: LogFunction; + breach: LogFunction; + 0: LogFunction; + fatal: LogFunction; + emerg: LogFunction; + emergency: LogFunction; + shutdown: LogFunction; isEnabled: () => boolean; forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void; fetch: (level: LogLevel, params?: FetchParams) => LogItem[]; } = { + 7: makeLogFunction('7'), + debug: makeLogFunction('debug'), + minor: makeLogFunction('minor'), + silly: makeLogFunction('silly'), + testing: makeLogFunction('testing'), + verbose: makeLogFunction('verbose'), + 6: makeLogFunction('6'), + information: makeLogFunction('information'), + inform: makeLogFunction('inform'), info: makeLogFunction('info'), + 5: makeLogFunction('5'), + note: makeLogFunction('note'), + notice: makeLogFunction('notice'), + notify: makeLogFunction('notify'), + success: makeLogFunction('success'), security: makeLogFunction('security'), + 4: makeLogFunction('4'), + warn: makeLogFunction('warn'), warning: makeLogFunction('warning'), + 3: makeLogFunction('3'), + err: makeLogFunction('err'), + failure: makeLogFunction('failure'), + fail: makeLogFunction('fail'), error: makeLogFunction('error'), + 2: makeLogFunction('2'), + crit: makeLogFunction('crit'), + severe: makeLogFunction('severe'), critical: makeLogFunction('critical'), + 1: makeLogFunction('1'), + alert: makeLogFunction('alert'), + breach: makeLogFunction('breach'), + 0: makeLogFunction('0'), + fatal: makeLogFunction('fatal'), + emerg: makeLogFunction('emerg'), + emergency: makeLogFunction('emergency'), + shutdown: makeLogFunction('shutdown'), isEnabled: (): boolean => !basicFileTransport.silent, forward: basicLogger.log, fetch: fetchLogs -- cgit v1.2.1 From 56b06b5ee36ed83fc44d0775b6218aa8fed85b5e Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 10 Apr 2018 21:29:15 +0100 Subject: fixed auth tests --- src/app.ts | 4 +++- src/auth.ts | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/app.ts b/src/app.ts index c627027..91b8f95 100644 --- a/src/app.ts +++ b/src/app.ts @@ -101,7 +101,8 @@ class App { important: 'Endpoints start from /cs3099group-be-4/' }); }); - defRouter.get('/*', (req: ex.Request, res: ex.Response): void => { + const errRouter: ex.Router = ex.Router(); + errRouter.get('/*', (req: ex.Request, res: ex.Response): void => { res.status(404) .json({ status: 'error', @@ -112,6 +113,7 @@ class App { this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); this.express.use('/', defRouter); + this.express.use('/XX*', errRouter); } /** diff --git a/src/auth.ts b/src/auth.ts index 8a6b248..14e1170 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -193,8 +193,8 @@ export const unauthorisedErr: Errorware = if (isUnauthorizedError(err)) { return next(new RequestError( err.status, - err.code, - err.message + 'not_authorised', + 'user does not have correct authorisation for task' )); } next(err); @@ -210,7 +210,8 @@ export const unauthorisedErr: Errorware = */ export const isAdmin: Middleware = (req: Request, res: Response, next: NextFunction): void => { - const admin: boolean = req.user.object.userGroups + // tslint:disable-next-line:no-non-null-assertion + const admin: boolean = req!.user!.object!.userGroups! .some((x: UserGroup): boolean => x.name === 'admin'); if (!admin) { -- cgit v1.2.1 From ff1034dc6f427238b19f895b052e33fc181f0829 Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 10 Apr 2018 21:37:42 +0100 Subject: progress on testing --- test/integration/protocol.routes.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 18ee1e3..9467f13 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -111,7 +111,7 @@ describe('routes : protocol', () => { required: array(types.string) }), 200], ['get', '/log', types.array({ - component: types.string, + //component: types.string, level: alternative([ 'info', 'security', -- cgit v1.2.1 From f7220be4e1b80cdba0fbaf41f7382cbf18561e2b Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 10 Apr 2018 23:30:51 +0100 Subject: sth works maybe --- src/FileRouter.ts | 6 ++++-- src/app.ts | 1 + src/logger.ts | 15 ++++++++----- test/integration/protocol.routes.test.ts | 36 +++++++++++++++++++------------- test/test-db.ts | 23 ++++++++++++++++++++ 5 files changed, 60 insertions(+), 21 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4d6eb16..4d68b6d 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -63,7 +63,7 @@ const getProtocols: Middleware = const postLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { if (!req.user.hasPrivilege('logging')) { - next(new RequestError(400, 'invalid_privilege')); + next(new RequestError(401, 'invalid_privilege')); return; } else if (!logger.isEnabled()) { next(new RequestError(501, 'logging_not_enabled')); @@ -103,7 +103,7 @@ const postLog: Middleware = const getLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { if (!req.user.hasPrivilege('admin')) { - next(new RequestError(400, 'invalid_privilege')); + next(new RequestError(401, 'invalid_privilege')); } res.locals.data = logger.fetch( req.params.level, { @@ -416,9 +416,11 @@ const getProjectName: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { const project: Project | null = res.locals.project; if (project == null) { + console.log("was null") return next(new RequestError(404, 'project_not_found')); } else { res.locals.data = project.fullInfo; + console.log("wasnt " + res.locals.data) next(); } }; diff --git a/src/app.ts b/src/app.ts index 91b8f95..1378177 100644 --- a/src/app.ts +++ b/src/app.ts @@ -161,6 +161,7 @@ class App { req: ex.Request, res: ex.Response, next: ex.NextFunction, project: string ): Promise => { + console.log("## as " + project) res.locals.project = await Project.findOne({ where: { name: project diff --git a/src/logger.ts b/src/logger.ts index bbb0a73..4bcb267 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -186,12 +186,17 @@ interface LogItem { timestamp: string; } -const fetchLogs: (level: LogLevel, params?: FetchParams) => LogItem[] = ( - level: LogLevel, params: FetchParams = {} +const fetchLogs: (level?: LogLevel, params?: FetchParams) => LogItem[] = ( + level?: LogLevel, params: FetchParams = {} ): LogItem[] => { - const matches: (log: any, level: LogLevel, params?: FetchParams) => boolean = ( - log: any, minLevel: LogLevel, fetchParams: FetchParams = {} + const matches: (log: any, level?: LogLevel, params?: FetchParams) + => boolean = ( + log: any, minLevel?: LogLevel, fetchParams: FetchParams = {} ): boolean => { + if (!minLevel) { + // tslint:disable-next-line:no-parameter-reassignment + minLevel = 'info'; + } const time: Date = new Date(log.timestamp); if (params.before && params.before < time) { return false; @@ -205,7 +210,7 @@ const fetchLogs: (level: LogLevel, params?: FetchParams) => LogItem[] = ( basicLogger.stream({ level }).on('log', (log: any): void => { if (matches(log, level, params)) { out.push({ - component: log.meta.component, + component: log.component, level: log.level, value: log.message, username: log.user, diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 9467f13..e23fd60 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -7,7 +7,8 @@ import * as chai from 'chai'; const expect: Chai.ExpectStatic = chai.expect; -import { Credentials, Database, addUser, initDB, resetDB } from '../test-db'; +import { Credentials, Database, addUser, initDB, resetDB, + Projec, addProjec } from '../test-db'; import { default as User } from '../../src/db/model/User'; // Chai-http must be imported this way: @@ -28,6 +29,7 @@ const app = App.TestApp(); let database: Database; let mockUser: Credentials; let token: string; +let mockProj: Projec; const initDatabase = async() => { database = initDB(); @@ -37,6 +39,7 @@ const initDatabase = async() => { const populateDatabase = async() => { await resetDB(database); mockUser = await addUser(database, true); + mockProj = await addProjec(database, mockUser); }; const getToken = async() => { @@ -111,7 +114,7 @@ describe('routes : protocol', () => { required: array(types.string) }), 200], ['get', '/log', types.array({ - //component: types.string, + component: types.string, level: alternative([ 'info', 'security', @@ -122,8 +125,12 @@ describe('routes : protocol', () => { value: types.anything, username: types.string, timestamp: types.string - }), 500], - ['post', '/log', null, 500], + }), 200], + ['post', '/log', [{ + component: 'tesssst', + level: 'info', + value: 'sdasdasdasdasdasd' + }], 200], ['get', '/properties', types.array({ id: types.string, display: optional(match({ @@ -163,7 +170,7 @@ describe('routes : protocol', () => { private_admin_metadata: types.anything }), 401], // TODO types.metadata - ['get', '/users/:username', { + ['get', '/users/mock_user', { username: types.string, privileges: array(types.string), projects: array({ @@ -175,8 +182,8 @@ describe('routes : protocol', () => { public_admin_metadata: types.anything, private_admin_metadata: types.anything }, 401], - ['post', '/users/:username', null, 401], - ['get', '/users/:username/properties', { + ['post', '/users/mock_user', null, 401], + ['get', '/users/mock_user/properties', { data: optional(types.anything) }, 401], ['get', '/current_user', { @@ -207,7 +214,7 @@ describe('routes : protocol', () => { private_metadata: optional(types.anything), admin_metadata: optional(types.anything) }), 200], - ['get', '/projects/:project_name', { + ['get', '/projects/mocky', { project_name: types.string, users: array({ username: types.string, @@ -217,13 +224,13 @@ describe('routes : protocol', () => { private_metadata: types.anything, admin_metadata: optional(types.anything) }, 200], - ['post', '/projects/:project_name', null, 200], - ['get', '/projects/:project_name/properties', { + ['post', '/projects/mocky', null, 200], + ['get', '/projects/mocky/properties', { data: optional(types.anything) }, 200], - ['get', '/projects/:project_name/files/:path', null, 200], - ['post', '/projects/:project_name/files/:id', null, 200], - ['get', '/projects/:project_name/files_by_id/:id', null, 200] + ['get', '/projects/mocky/files/:path', null, 200], + ['post', '/projects/mocky/files/:id', null, 200], + ['get', '/projects/mocky/files_by_id/:id', null, 200] ]; /* tslint:enable:align */ @@ -238,7 +245,8 @@ describe('routes : protocol', () => { (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) - : chai.request(app).post(base + path); + : chai.request(app).post(base + path) + .set('content-type', 'application/json').send(temp); request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { expect(res.type).to.equal('application/json'); diff --git a/test/test-db.ts b/test/test-db.ts index f20608a..fa62ad7 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -1,3 +1,4 @@ +import { default as Project } from '../src/db/model/Project'; import { default as User } from '../src/db/model/User'; import { default as UserGroup } from '../src/db/model/UserGroup'; @@ -29,6 +30,13 @@ export interface Credentials { usergroups: UserGroup[]; } +export interface Projec { + name: string; + contributors: Credentials[]; + creationDate: Date; + lastActivity: Date; +} + export const addUser: (database?: Database, admin?: boolean) => Promise = async( database?: Database, admin?: boolean @@ -55,3 +63,18 @@ export const addUser: (database?: Database, admin?: boolean) => await new User(mockUser).save(); return mockUser; }; + +export const addProjec: (database: Database, user: Credentials) => + Promise = async( + database: Database, user: Credentials +): Promise => { + const mockProject: Projec = { + name: 'mocky', + contributors: [user], + creationDate: new Date(), + lastActivity: new Date() + }; + + await new Project(mockProject).save(); + return mockProject; +}; -- cgit v1.2.1 From 59d2c5c4b1dbc929f4f22192b781c0acd35eb78e Mon Sep 17 00:00:00 2001 From: jw255 Date: Wed, 11 Apr 2018 00:06:25 +0100 Subject: oh god --- src/FileRouter.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4d68b6d..630f64f 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -444,8 +444,10 @@ const postProjectName: Middleware = let promise: PromiseLike | null = null; if (project == null) { const file: File = new File({ + uuid: uuid.generate(), mimetype: 'inode/directory' }); + console.log(req.params.project_name) promise = file.save(); project = new Project({ name: req.params.project_name, @@ -454,8 +456,11 @@ const postProjectName: Middleware = } project.metadata = req.body; // tslint:disable-next-line:await-promise + console.log("anything prequel") await promise; + console.log("anything") await project.save(); + console.log("anything part 2") next(); }; -- cgit v1.2.1 From 3a02f5b8c7f3ae40072f41466c214a984885c2ac Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 12 Apr 2018 14:57:47 +0100 Subject: fixed precondition --- src/FileRouter.ts | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/app.ts | 122 +----------------------------------------------------- 2 files changed, 122 insertions(+), 121 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index d922023..f01e1a0 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -532,11 +532,132 @@ export class FileRouter { this.init(); } + /** + * Introduces variable-preconditioning middleware to the Express app. + * + * These middleware functions pre-process Express' matching variables + * in routes (e.g. `:project_name`). + * If an entity cannot be found in the database, the corresponding + * value is set to `null` instead. + */ + private precondition(): void { + // Fetch a user from their name: + this.router.param( + 'username', + async( + req: Request, res: Response, next: NextFunction, + name: string + ): Promise => { + const user: User | null = await User.findOne({ + where: { + username: name + } + }); + if (user == null) { + return next(new RequestError(404, 'user_not_found')); + } else { + res.locals.user = user; + } + next(); + } + ); + + // Fetch a project from its name: + this.router.param( + 'project_name', + async( + req: Request, res: Response, next: NextFunction, + project: string + ): Promise => { + console.log("## as " + project) + res.locals.project = await Project.findOne({ + where: { + name: project + } + }); + next(); + } + ); + + // Fetch a file from its path: + this.router.param( + 'file', + async( + req: Request, res: Response, next: NextFunction, + filename: string + ): Promise => { + const fileNames: string[] = req.params.path.split('/'); + const project: Project | null = res.locals.project; + if (project == null) { + return next(new RequestError(404, 'project_not_found')); + } + let file: File = project.rootFolder; + // TODO Rewrite using sub-queries instead of repeated queries. + while (fileNames.length > 2) { + const fileOrNull: File | null = await File.findOne({ + where: { + name: fileNames[0], + parentFolder: file + } + }); + if (fileOrNull == null) { + return next(); + } else { + file = fileOrNull; + } + fileNames.splice(0, 1); + } + const parentFolder: File | null = await File.findOne({ + include: [ + { model: File, as: 'containedFiles' } + ], + where: { + parentFolder: file, + name: fileNames[0] + } + }); + if (parentFolder == null) { + return next(); + } + res.locals.parentFolder = parentFolder; + const tFile: File | undefined = parentFolder.containedFiles.find( + (f: File): boolean => f.name === fileNames[1] + ); + res.locals.file = tFile; + res.locals.filename = fileNames[1]; + next(); + } + ); + + // Fetch a file from its UUID: + this.router.param( + 'id', + async( + req: Request, res: Response, next: NextFunction, + fileId: string + ): Promise => { + const file: File | null = await File.findOne({ + where: { + uuid: fileId + } + }); + if (file == null) { + return next(new RequestError(404, 'file_not_found')); + } else { + res.locals.file = file; + } + next(); + } + ); + } + /** * Take each handler, and attach to one of the Express.Router's * endpoints. */ public init(): void { + this.precondition(); + // General this.router.get ('/_supported_protocols_', getProtocols); this.router.get ('/log', getLog); diff --git a/src/app.ts b/src/app.ts index c51c574..d8dfe5d 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,8 +43,7 @@ class App { this.express = ex(); this.express.use(( req: ex.Request, res: ex.Response, next: ex.NextFunction - ): void => { console.log(req.url); next(); }); - this.precondition(); + ): void => { console.log(req.url); next(); }); this.middleware(); this.mountRoutes(); this.express.use( @@ -126,125 +125,6 @@ class App { this.express.use(unauthorisedErr); this.express.use(errorHandler); } - - /** - * Introduces variable-preconditioning middleware to the Express app. - * - * These middleware functions pre-process Express' matching variables - * in routes (e.g. `:project_name`). - * If an entity cannot be found in the database, the corresponding - * value is set to `null` instead. - */ - private precondition(): void { - // Fetch a user from their name: - this.express.param( - 'username', - async( - req: ex.Request, res: ex.Response, next: ex.NextFunction, - name: string - ): Promise => { - const user: User | null = await User.findOne({ - where: { - username: name - } - }); - if (user == null) { - return next(new RequestError(404, 'user_not_found')); - } else { - res.locals.user = user; - } - next(); - } - ); - - // Fetch a project from its name: - this.express.param( - 'project_name', - async( - req: ex.Request, res: ex.Response, next: ex.NextFunction, - project: string - ): Promise => { - console.log("## as " + project) - res.locals.project = await Project.findOne({ - where: { - name: project - } - }); - next(); - } - ); - - // Fetch a file from its path: - this.express.param( - 'file', - async( - req: ex.Request, res: ex.Response, next: ex.NextFunction, - filename: string - ): Promise => { - const fileNames: string[] = req.params.path.split('/'); - const project: Project | null = res.locals.project; - if (project == null) { - return next(new RequestError(404, 'project_not_found')); - } - let file: File = project.rootFolder; - // TODO Rewrite using sub-queries instead of repeated queries. - while (fileNames.length > 2) { - const fileOrNull: File | null = await File.findOne({ - where: { - name: fileNames[0], - parentFolder: file - } - }); - if (fileOrNull == null) { - return next(); - } else { - file = fileOrNull; - } - fileNames.splice(0, 1); - } - const parentFolder: File | null = await File.findOne({ - include: [ - { model: File, as: 'containedFiles' } - ], - where: { - parentFolder: file, - name: fileNames[0] - } - }); - if (parentFolder == null) { - return next(); - } - res.locals.parentFolder = parentFolder; - const tFile: File | undefined = parentFolder.containedFiles.find( - (f: File): boolean => f.name === fileNames[1] - ); - res.locals.file = tFile; - res.locals.filename = fileNames[1]; - next(); - } - ); - - // Fetch a file from its UUID: - this.express.param( - 'id', - async( - req: ex.Request, res: ex.Response, next: ex.NextFunction, - fileId: string - ): Promise => { - const file: File | null = await File.findOne({ - where: { - uuid: fileId - } - }); - if (file == null) { - return next(new RequestError(404, 'file_not_found')); - } else { - res.locals.file = file; - } - next(); - } - ); - } } export default new App(true).express; -- cgit v1.2.1 From 22efa1b090df7a427bfc1990d705624ae53d6231 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 12 Apr 2018 15:30:34 +0100 Subject: not much progress tbh --- src/FileRouter.ts | 5 +++-- test/integration/protocol.routes.test.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index f01e1a0..d6d49da 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -419,6 +419,7 @@ const getProjectName: Middleware = console.log("was null") return next(new RequestError(404, 'project_not_found')); } else { + console.log(project.contributors); res.locals.data = project.fullInfo; console.log("wasnt " + res.locals.data) next(); @@ -568,13 +569,13 @@ export class FileRouter { async( req: Request, res: Response, next: NextFunction, project: string - ): Promise => { - console.log("## as " + project) + ): Promise => { res.locals.project = await Project.findOne({ where: { name: project } }); + console.log("## as " + res.locals.project); next(); } ); diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index e23fd60..6a08278 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -240,7 +240,7 @@ describe('routes : protocol', () => { beforeEach(getToken); describe('Access all valid routes', () => { - forEach(completeProtocol).it( + forEach(completeProtocol).it.only( '%s %s should be json', (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' -- cgit v1.2.1 From 4430d61b381d0b3dce4831fea1a9faa78d9efdf6 Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 14:25:42 +0100 Subject: changed 2 debug msgs --- src/FileRouter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index f01e1a0..ddcb3d5 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -569,7 +569,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, project: string ): Promise => { - console.log("## as " + project) + logger.debug('Retrieving project \'${project}\''); res.locals.project = await Project.findOne({ where: { name: project -- cgit v1.2.1 From 01f3bde6fc51c398a36b42215c4056990821991b Mon Sep 17 00:00:00 2001 From: Hafeez Date: Fri, 13 Apr 2018 14:44:22 +0100 Subject: datebase retrieves all properties --- src/FileRouter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index aa13872..619be9e 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -572,6 +572,7 @@ export class FileRouter { ): Promise => { logger.debug('Retrieving project \'${project}\''); res.locals.project = await Project.findOne({ + include: [{all: true}], where: { name: project } -- cgit v1.2.1 From 8f013438e4e4c96594b7ed567e7a58dfc1b7ce5a Mon Sep 17 00:00:00 2001 From: Hafeez Date: Fri, 13 Apr 2018 15:53:10 +0100 Subject: fixed mock file tests --- src/FileRouter.ts | 10 ++++------ test/integration/protocol.routes.test.ts | 10 ++++++---- test/test-db.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 619be9e..b76dea7 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -415,13 +415,10 @@ const getProjects: Middleware = const getProjectName: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { const project: Project | null = res.locals.project; - if (project == null) { - console.log("was null") + if (project == null) { return next(new RequestError(404, 'project_not_found')); - } else { - console.log(project.contributors); - res.locals.data = project.fullInfo; - console.log("wasnt " + res.locals.data) + } else { + res.locals.data = project.fullInfo; next(); } }; @@ -639,6 +636,7 @@ export class FileRouter { fileId: string ): Promise => { const file: File | null = await File.findOne({ + include: [{all: true}], where: { uuid: fileId } diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 6a08278..7554f0e 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -8,7 +8,7 @@ import * as chai from 'chai'; const expect: Chai.ExpectStatic = chai.expect; import { Credentials, Database, addUser, initDB, resetDB, - Projec, addProjec } from '../test-db'; + Projec, addProjec, Filee, addFilee } from '../test-db'; import { default as User } from '../../src/db/model/User'; // Chai-http must be imported this way: @@ -30,6 +30,7 @@ let database: Database; let mockUser: Credentials; let token: string; let mockProj: Projec; +let mockFile: Filee; const initDatabase = async() => { database = initDB(); @@ -40,6 +41,7 @@ const populateDatabase = async() => { await resetDB(database); mockUser = await addUser(database, true); mockProj = await addProjec(database, mockUser); + mockFile = await addFilee(database, mockUser); }; const getToken = async() => { @@ -228,9 +230,9 @@ describe('routes : protocol', () => { ['get', '/projects/mocky/properties', { data: optional(types.anything) }, 200], - ['get', '/projects/mocky/files/:path', null, 200], - ['post', '/projects/mocky/files/:id', null, 200], - ['get', '/projects/mocky/files_by_id/:id', null, 200] + ['get', '/projects/mocky/files/example/path', null, 200], + ['post', '/projects/mocky/files/mockyfile2', null, 200], + ['get', '/projects/mocky/files_by_id/file1', null, 200] ]; /* tslint:enable:align */ diff --git a/test/test-db.ts b/test/test-db.ts index fa62ad7..32f2f0b 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -1,6 +1,8 @@ import { default as Project } from '../src/db/model/Project'; import { default as User } from '../src/db/model/User'; import { default as UserGroup } from '../src/db/model/UserGroup'; +import { default as File } from '../src/db/model/File'; +import { FileTypeName } from '../src/files'; import { Sequelize } from 'sequelize-typescript'; import * as sqlite from 'sqlite3'; @@ -37,6 +39,14 @@ export interface Projec { lastActivity: Date; } +export interface Filee { + name: string, + path: string, + uuid: string, + creator: Credentials, + type: FileTypeName +} + export const addUser: (database?: Database, admin?: boolean) => Promise = async( database?: Database, admin?: boolean @@ -78,3 +88,19 @@ export const addProjec: (database: Database, user: Credentials) => await new Project(mockProject).save(); return mockProject; }; + +export const addFilee: (database: Database, user: Credentials) => + Promise = async( + database: Database, user: Credentials +): Promise => { + const mockFile: Filee = { + name: 'mockyFile', + path: 'example/path', + uuid: 'file1', + creator: user, + type: "generic" + }; + + await new File(mockFile).save(); + return mockFile; +}; \ No newline at end of file -- cgit v1.2.1 From deab81f8ef469c4119838d72b56683b8dd4cbcfe Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 16:10:32 +0100 Subject: fixed some privs --- src/FileRouter.ts | 1 + src/app.ts | 1 + src/db/model/UserGroup.ts | 3 +++ src/index.ts | 20 ++++++++++++++++++-- test/integration/protocol.routes.test.ts | 16 +++++++++++++++- test/test-db.ts | 1 + 6 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 619be9e..7db7eb2 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -550,6 +550,7 @@ export class FileRouter { name: string ): Promise => { const user: User | null = await User.findOne({ + include: [{all: true}], where: { username: name } diff --git a/src/app.ts b/src/app.ts index d8dfe5d..f71ecf3 100644 --- a/src/app.ts +++ b/src/app.ts @@ -68,6 +68,7 @@ class App { private middleware(): void { this.express.use(expressJwt({secret: 'Mr Secret'}) .unless({path: [ + '/', '/cs3099group-be-4/oauth/token', '/cs3099group-be-4/_supported_protocols_' ] }) diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts index 46945de..60d45c8 100644 --- a/src/db/model/UserGroup.ts +++ b/src/db/model/UserGroup.ts @@ -37,6 +37,9 @@ export default class UserGroup extends Model { @Column public canEditProjects!: boolean; + @Column + public canAccessLogs!: boolean; + @Column public isInternal!: boolean; diff --git a/src/index.ts b/src/index.ts index f172e61..7e21c35 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,18 +52,34 @@ logger.info(`Port ${port} chosen`); isInternal: false, description: 'Systems admin' }); + const logging: UserGroup = new UserGroup({ + name: 'logging', + canAccessLogs: true, + isInternal: false, + description: 'Allows Post to Log' + }); + await logging.save(); await admin.save(); + logger.info('Adding admin user'); const root: User = new User({ username: 'hafeez', - password: 'pass', - userGroups: [admin] + password: 'pass' }); await root.save(); + await root.$set('userGroups', [admin, logging]); + + const user: User | null = await User.findOne({ + include: [{all: true}], + where: { + username: 'hafeez' + } + }); + logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { if (err) { diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 6a08278..3eaafe5 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -239,8 +239,22 @@ describe('routes : protocol', () => { beforeEach(populateDatabase); beforeEach(getToken); + it.only('test log', () => { + return chai.request(app).get(base + '/log') + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + console.log("a") + console.log(err.response.body) + expect(false); + }).then((res: ChaiHttp.Response) => { + console.log("b") + console.log(res.body) + expect(false); + }); + }); + describe('Access all valid routes', () => { - forEach(completeProtocol).it.only( + forEach(completeProtocol).it( '%s %s should be json', (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' diff --git a/test/test-db.ts b/test/test-db.ts index fa62ad7..be5782a 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -55,6 +55,7 @@ export const addUser: (database?: Database, admin?: boolean) => canCreateProjects: true, canDeleteProjects: true, canEditProjects: true, + canAccessLogs: true, isInternal: false }); await priv.save(); -- cgit v1.2.1 From 244fa29c38dcae5732a06cdb39de1a2a00557117 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 13 Apr 2018 16:12:04 +0100 Subject: Fix minor places, and add Postman collection --- src/FileRouter.ts | 194 +++++++++++++++++++++++---------------- src/app.ts | 13 ++- src/logger.ts | 4 +- test/postman.json | 267 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 394 insertions(+), 84 deletions(-) create mode 100644 test/postman.json diff --git a/src/FileRouter.ts b/src/FileRouter.ts index d6d49da..bbcc0f2 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -32,8 +32,10 @@ export type Middleware = * "required": array(string) * }) */ -const getProtocols: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getProtocols: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Fetching supported protocols'); res.locals.data = { supported: [], required: [ @@ -60,8 +62,10 @@ const getProtocols: Middleware = * "value": anything * }) */ -const postLog: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const postLog: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Adding forwarded log'); if (!req.user.hasPrivilege('logging')) { next(new RequestError(401, 'invalid_privilege')); return; @@ -100,8 +104,10 @@ const postLog: Middleware = * "timestamp": string * }) */ -const getLog: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getLog: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Fetching log'); if (!req.user.hasPrivilege('admin')) { next(new RequestError(401, 'invalid_privilege')); } @@ -135,8 +141,10 @@ const getLog: Middleware = * "value": alternative([string, integer, boolean]) * }) */ -const getProperties: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getProperties: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Listing server properties'); res.locals.data = serverConfig; next(); }; @@ -153,8 +161,10 @@ const getProperties: Middleware = * "value": alternative([string, integer, boolean]) * }) */ -const postProperties: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const postProperties: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Editing server properties'); for (const newProp of req.body) { const prop: Property | undefined = serverConfig.find( (p: Property): boolean => p.id === newProp.id @@ -188,8 +198,10 @@ const postProperties: Middleware = * "internal": boolean * }) */ -const getUserPrivileges: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const getUserPrivileges: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + logger.debug('Listing all user privileges'); const usergroups: UserGroup[] = await UserGroup.findAll(); res.locals.data = usergroups.map( (ug: UserGroup) => ug.getPrivilege() @@ -220,6 +232,7 @@ const getUserPrivileges: Middleware = const getUsers: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { + logger.debug('Listing all registered users'); const users: User[] = await User.findAll({ include: [ UserGroup, @@ -240,8 +253,10 @@ const getUsers: Middleware = async( /** * Expose additional configuration options for individual users */ -const getUserProperties: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getUserProperties: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Listing additional properties for a user'); res.locals.data = res.locals.user.properties; next(); }; @@ -266,8 +281,10 @@ const getUserProperties: Middleware = * "private_admin_metadata": metadata * } */ -const getUsername: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getUsername: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug(`Listing user ${res.locals.user}`); if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; @@ -276,8 +293,10 @@ const getUsername: Middleware = next(); }; -const getCurUser: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getCurUser: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Listing current user'); res.locals.data = req.user.fullInfo; next(); }; @@ -300,8 +319,10 @@ const getCurUser: Middleware = * "private_admin_metadata": not_present * } */ -const postCurUser: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const postCurUser: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + logger.debug('Editing current user'); try { await req.user.updateInfo(req.body); await req.user.save(); @@ -328,15 +349,18 @@ const postCurUser: Middleware = * "private_admin_metadata": optional(metadata) * } */ -const postUsername: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const postUsername: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { let user: User | null | undefined = res.locals.user; if (user == null) { + logger.debug('Adding new user'); user = new User({ username: req.params.username, password: req.params.password }); } else { + logger.debug('Editing user'); user.password = req.params.password; } user.metadata = req.body; @@ -354,8 +378,10 @@ const postUsername: Middleware = * "internal": boolean * }) */ -const getProjectRoles: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const getProjectRoles: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + logger.debug('Listing available project roles'); const roles: ContributorGroup[] = await ContributorGroup.findAll(); res.locals.data = roles.filter( (cg: ContributorGroup): boolean => !cg.isInternal @@ -382,8 +408,10 @@ const getProjectRoles: Middleware = * "admin_metadata": optional(metadata) * }) */ -const getProjects: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const getProjects: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + logger.debug('Listing all projects'); const projects: Project[] = await Project.findAll({ include: [ User @@ -412,16 +440,15 @@ const getProjects: Middleware = * "admin_metadata": optional(metadata) * } */ -const getProjectName: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const getProjectName: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + logger.debug('Getting project properties'); const project: Project | null = res.locals.project; if (project == null) { - console.log("was null") return next(new RequestError(404, 'project_not_found')); } else { - console.log(project.contributors); res.locals.data = project.fullInfo; - console.log("wasnt " + res.locals.data) next(); } }; @@ -439,37 +466,39 @@ const getProjectName: Middleware = * "admin_metadata": optional(metadata) * } */ -const postProjectName: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { +const postProjectName: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { let project: Project | null = res.locals.project; let promise: PromiseLike | null = null; if (project == null) { + logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), mimetype: 'inode/directory' }); - console.log(req.params.project_name) promise = file.save(); project = new Project({ name: req.params.project_name, rootFolder: file }); + } else { + logger.debug('Updating project properties'); } project.metadata = req.body; // tslint:disable-next-line:await-promise - console.log("anything prequel") await promise; - console.log("anything") await project.save(); - console.log("anything part 2") next(); }; /** * additional configuration options for individual projects */ -const getProjectProperties: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const getProjectProperties: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Getting project properties'); if (res.locals.project == null) { next(new RequestError(404, 'project_not_found')); } else { @@ -484,6 +513,7 @@ const getProjectProperties: Middleware = const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { + logger.debug(`Getting file in ${req.query.view} view`); const file: File | null = res.locals.file; if (file == null) { return next(new RequestError(404, 'file_not_found')); @@ -508,8 +538,10 @@ const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc */ -const postFilePath: Middleware = - (req: Request, res: Response, next: NextFunction): void => { +const postFilePath: Middleware = ( + req: Request, res: Response, next: NextFunction +): void => { + logger.debug('Receiving file'); if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } @@ -533,6 +565,39 @@ export class FileRouter { this.init(); } + /** + * Take each handler, and attach to one of the Express.Router's + * endpoints. + */ + public init(): void { + this.precondition(); + + // General + this.router.get ('/_supported_protocols_', getProtocols); + this.router.get ('/log', getLog); + this.router.post('/log', postLog); + this.router.get ('/properties', getProperties); + this.router.post('/properties', postProperties); + // Users + this.router.get ('/user_privileges', getUserPrivileges); + this.router.get ('/users', getUsers); + this.router.get ('/users/:username', getUsername); + this.router.post('/users/:username', postUsername); + this.router.get ('/users/:username/properties', getUserProperties); + this.router.get ('/current_user', getCurUser); + this.router.post('/current_user', postCurUser); + // Projects + this.router.get ('/project_roles', getProjectRoles); + this.router.get ('/projects', getProjects); + this.router.get ('/projects/:project_name', getProjectName); + this.router.post('/projects/:project_name', postProjectName); + this.router.get ('/projects/:project_name/properties', getProjectProperties); + // File access + this.router.get ('/projects/:project_name/files/:path', getFilePath); + this.router.post('/projects/:project_name/files/:id', postFilePath); + this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); + } + /** * Introduces variable-preconditioning middleware to the Express app. * @@ -542,6 +607,7 @@ export class FileRouter { * value is set to `null` instead. */ private precondition(): void { + logger.debug('Adding parameter preconditioning to router'); // Fetch a user from their name: this.router.param( 'username', @@ -549,6 +615,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, name: string ): Promise => { + logger.debug(`Searching for user ${name}`); const user: User | null = await User.findOne({ where: { username: name @@ -568,14 +635,14 @@ export class FileRouter { 'project_name', async( req: Request, res: Response, next: NextFunction, - project: string - ): Promise => { + projectName: string + ): Promise => { + logger.debug(`Searching for project ${projectName}`); res.locals.project = await Project.findOne({ where: { - name: project + name: projectName } }); - console.log("## as " + res.locals.project); next(); } ); @@ -587,9 +654,11 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { + logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; if (project == null) { + logger.debug('Project was not found: skipping finding file'); return next(new RequestError(404, 'project_not_found')); } let file: File = project.rootFolder; @@ -637,6 +706,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { + logger.debug(`Searching for file ${fileId}`); const file: File | null = await File.findOne({ where: { uuid: fileId @@ -651,43 +721,9 @@ export class FileRouter { } ); } - - /** - * Take each handler, and attach to one of the Express.Router's - * endpoints. - */ - public init(): void { - this.precondition(); - - // General - this.router.get ('/_supported_protocols_', getProtocols); - this.router.get ('/log', getLog); - this.router.post('/log', postLog); - this.router.get ('/properties', getProperties); - this.router.post('/properties', postProperties); - // Users - this.router.get ('/user_privileges', getUserPrivileges); - this.router.get ('/users', getUsers); - this.router.get ('/users/:username', getUsername); - this.router.post('/users/:username', postUsername); - this.router.get ('/users/:username/properties', getUserProperties); - this.router.get ('/current_user', getCurUser); - this.router.post('/current_user', postCurUser); - // Projects - this.router.get ('/project_roles', getProjectRoles); - this.router.get ('/projects', getProjects); - this.router.get ('/projects/:project_name', getProjectName); - this.router.post('/projects/:project_name', postProjectName); - this.router.get ('/projects/:project_name/properties', getProjectProperties); - // File access - this.router.get ('/projects/:project_name/files/:path', getFilePath); - this.router.post('/projects/:project_name/files/:id', postFilePath); - this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); - } } // Create the FileRouter, and export its configured Express.Router const fileRoutes: FileRouter = new FileRouter(); -fileRoutes.init(); export default fileRoutes.router; diff --git a/src/app.ts b/src/app.ts index d8dfe5d..fd094ef 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,6 +4,7 @@ import * as expressJwt from 'express-jwt'; import * as passport from 'passport'; import { default as authRouter, unauthorisedErr } from './auth'; +import { logger } from './logger'; import { RequestError, errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; @@ -39,11 +40,15 @@ class App { * server. */ public constructor(enableLog: boolean) { + logger.debug('Constructing router'); this.logEnabled = enableLog; this.express = ex(); - this.express.use(( - req: ex.Request, res: ex.Response, next: ex.NextFunction - ): void => { console.log(req.url); next(); }); + this.express.use( + (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { + logger.info(`Connection from ${req.ip} requesting ${req.url}`); + next(); + } + ); this.middleware(); this.mountRoutes(); this.express.use( @@ -57,6 +62,7 @@ class App { data: await res.locals.data }); } + logger.success(`Responded to ${req.ip}`); } ); this.errorware(); @@ -66,6 +72,7 @@ class App { * Configures regular Express middleware. */ private middleware(): void { + logger.debug('Loading basic middleware'); this.express.use(expressJwt({secret: 'Mr Secret'}) .unless({path: [ '/cs3099group-be-4/oauth/token', diff --git a/src/logger.ts b/src/logger.ts index bdcb390..aefb751 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -115,8 +115,8 @@ export let enabled: boolean = true; const consoleTransport: winston.TransportInstance = new winston.transports.Console({ name: 'consoleTransport', - level: 'info', - silent: false, + level: 'verbose', + silent: process.env.NODE_ENV === 'test', handleExceptions: true, humanReadableUncaughtException: true, formatter: ( diff --git a/test/postman.json b/test/postman.json new file mode 100644 index 0000000..164bdc1 --- /dev/null +++ b/test/postman.json @@ -0,0 +1,267 @@ +{ + "info": { + "name": "JH", + "_postman_id": "323a3189-bd95-4f51-b985-d2ca626300ec", + "description": "", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "authorised", + "description": null, + "item": [ + { + "name": "/projects", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "{{host}}/{{endpoint}}/projects", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "projects" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/log", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "{{host}}/{{endpoint}}/log", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "log" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/_supported_protocols", + "request": { + "auth": { + "type": "noauth" + }, + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "{{host}}/{{endpoint}}/_supported_protocols_", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "_supported_protocols_" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/project_roles", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "{{host}}/{{endpoint}}/project_roles", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "project_roles" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/projects/", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{}" + }, + "url": { + "raw": "{{host}}/{{endpoint}}/projects/{{dummy_project}}", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "projects", + "{{dummy_project}}" + ] + }, + "description": "" + }, + "response": [] + } + ] + }, + { + "name": "/oauth/token", + "event": [ + { + "listen": "prerequest", + "script": { + "id": "7cbb2980-4092-4675-af5e-cfcbd1c00b81", + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "7ce27395-de92-457b-97cc-7728824c821d", + "type": "text/javascript", + "exec": [ + "let res = JSON.parse(responseBody);", + "postman.setEnvironmentVariable(\"access_token\", res.access_token);", + "postman.setEnvironmentVariable(\"refresh_token\", res.refresh_token);" + ] + } + } + ], + "request": { + "auth": { + "type": "noauth" + }, + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "grant_type", + "value": "password", + "description": "", + "type": "text" + }, + { + "key": "username", + "value": "{{dummy_admin_username}}", + "description": "", + "type": "text" + }, + { + "key": "password", + "value": "{{dummy_admin_pass}}", + "description": "", + "type": "text" + } + ] + }, + "url": { + "raw": "{{host}}/{{endpoint}}/oauth/token", + "host": [ + "{{host}}" + ], + "path": [ + "{{endpoint}}", + "oauth", + "token" + ] + }, + "description": "wefrwrbjk;" + }, + "response": [] + } + ] +} \ No newline at end of file -- cgit v1.2.1 From f8fa729bb950f1a51eb1cea586483b2132827951 Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 16:25:29 +0100 Subject: fixed privileges in testing database --- test/integration/protocol.routes.test.ts | 14 ---------- test/test-db.ts | 45 ++++++++++++++++++++------------ 2 files changed, 29 insertions(+), 30 deletions(-) diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 906f3bd..ca20da9 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -241,20 +241,6 @@ describe('routes : protocol', () => { beforeEach(populateDatabase); beforeEach(getToken); - it.only('test log', () => { - return chai.request(app).get(base + '/log') - .set('Authorization', `Bearer ${token}`) - .catch((err) => { - console.log("a") - console.log(err.response.body) - expect(false); - }).then((res: ChaiHttp.Response) => { - console.log("b") - console.log(res.body) - expect(false); - }); - }); - describe('Access all valid routes', () => { forEach(completeProtocol).it( '%s %s should be json', diff --git a/test/test-db.ts b/test/test-db.ts index 12fc17c..40ae438 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -56,22 +56,35 @@ export const addUser: (database?: Database, admin?: boolean) => password: 'mock_password', usergroups: [] }; - if (admin) { - const priv: UserGroup = new UserGroup({ - name: 'admin', - canCreateUsers: true, - canDeleteUsers: true, - canEditUsers: true, - canCreateProjects: true, - canDeleteProjects: true, - canEditProjects: true, - canAccessLogs: true, - isInternal: false - }); - await priv.save(); - mockUser.usergroups.push(priv); - } - await new User(mockUser).save(); + + const priv: UserGroup = new UserGroup({ + name: 'admin', + canCreateUsers: true, + canDeleteUsers: true, + canEditUsers: true, + canCreateProjects: true, + canDeleteProjects: true, + canEditProjects: true, + canAccessLogs: true, + isInternal: false + }); + await priv.save(); + mockUser.usergroups.push(priv); + + const logging: UserGroup = new UserGroup({ + name: 'logging', + canAccessLogs: true, + isInternal: false, + description: 'Allows Post to Log' + }); + mockUser.usergroups.push(logging); + + await logging.save(); + + const root: User = await new User(mockUser).save(); + + await root.$set('userGroups', [priv, logging]); + return mockUser; }; -- cgit v1.2.1 From a7567c50bbf01e3a8489d732d2825fa01921f2d3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 16:35:50 +0100 Subject: got it down to 34 errors in the protocol --- src/FileRouter.ts | 1 + test/integration/protocol.routes.test.ts | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index b750094..990110a 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -639,6 +639,7 @@ export class FileRouter { projectName: string ): Promise => { res.locals.project = await Project.findOne({ + include: [{all: true}], where: { name: projectName } diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index ca20da9..2a7cf54 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -170,7 +170,7 @@ describe('routes : protocol', () => { private_user_metadata: types.anything, public_admin_metadata: types.anything, private_admin_metadata: types.anything - }), 401], + }), 200], // TODO types.metadata ['get', '/users/mock_user', { username: types.string, @@ -183,11 +183,11 @@ describe('routes : protocol', () => { private_user_metadata: types.anything, public_admin_metadata: types.anything, private_admin_metadata: types.anything - }, 401], - ['post', '/users/mock_user', null, 401], + }, 200], + ['post', '/users/mock_user', null, 200], ['get', '/users/mock_user/properties', { data: optional(types.anything) - }, 401], + }, 200], ['get', '/current_user', { username: types.string, privileges: array(types.string), -- cgit v1.2.1 From d8688e99fd945122548876466dece0cca8bc315b Mon Sep 17 00:00:00 2001 From: Hafeez Date: Fri, 13 Apr 2018 16:37:01 +0100 Subject: added include --- src/FileRouter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index b750094..990110a 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -639,6 +639,7 @@ export class FileRouter { projectName: string ): Promise => { res.locals.project = await Project.findOne({ + include: [{all: true}], where: { name: projectName } -- cgit v1.2.1 From f2f471e9c081d94622de02a22ca2faeaf8f6647b Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 13 Apr 2018 16:45:31 +0100 Subject: Fix some tests by including users in projects --- src/FileRouter.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index b750094..48ec9c7 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -639,6 +639,9 @@ export class FileRouter { projectName: string ): Promise => { res.locals.project = await Project.findOne({ + include: [ + User + ], where: { name: projectName } -- cgit v1.2.1 From c9a574ec946dc7fda6637db45f3223acd0a08e9f Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 16:45:32 +0100 Subject: fixed user not found --- src/FileRouter.ts | 18 ++++++++++-------- test/integration/protocol.routes.test.ts | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 990110a..e890241 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -257,6 +257,10 @@ const getUserProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Listing additional properties for a user'); + if (res.locals.user == null) { + next(new RequestError(404, 'user_not_found')); + return; + } res.locals.data = res.locals.user.properties; next(); }; @@ -354,16 +358,18 @@ const postUsername: Middleware = async( ): Promise => { let user: User | null | undefined = res.locals.user; if (user == null) { - logger.debug('Adding new user'); + console.log('Adding new user'); user = new User({ username: req.params.username, password: req.params.password }); } else { - logger.debug('Editing user'); + console.log('Editing user'); user.password = req.params.password; } - user.metadata = req.body; + if (req.body) { + user.metadata = req.body; + } next(); }; @@ -622,11 +628,7 @@ export class FileRouter { username: name } }); - if (user == null) { - return next(new RequestError(404, 'user_not_found')); - } else { - res.locals.user = user; - } + res.locals.user = user; next(); } ); diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 2a7cf54..866ac2a 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -184,7 +184,7 @@ describe('routes : protocol', () => { public_admin_metadata: types.anything, private_admin_metadata: types.anything }, 200], - ['post', '/users/mock_user', null, 200], + ['post', '/users/new_user', null, 200], ['get', '/users/mock_user/properties', { data: optional(types.anything) }, 200], -- cgit v1.2.1 From 9367a9510726a3751cb2ea6eee52cec1fb658767 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Fri, 13 Apr 2018 16:46:44 +0100 Subject: changed something --- test/integration/protocol.routes.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 2a7cf54..866ac2a 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -184,7 +184,7 @@ describe('routes : protocol', () => { public_admin_metadata: types.anything, private_admin_metadata: types.anything }, 200], - ['post', '/users/mock_user', null, 200], + ['post', '/users/new_user', null, 200], ['get', '/users/mock_user/properties', { data: optional(types.anything) }, 200], -- cgit v1.2.1 From de1be5ca1789dbd8e8a88ebe042cb767793ef333 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 13 Apr 2018 16:54:22 +0100 Subject: Fix some tests by adding properties in projects --- src/db/model/Project.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index d57eaaa..6cda34e 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -36,6 +36,10 @@ export default class Project extends Model { return this.rootFolderInternal; } + public get properties(): object { + return this; + } + public get metadata(): { public_metadata?: Metadata; private_metadata?: Metadata; -- cgit v1.2.1 From 74b2aeed25fbf4c8bcb4d4ae34044e3d1705db0e Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 16:58:06 +0100 Subject: fixed template matching in test suite --- test/integration/protocol.routes.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 866ac2a..ebe18c2 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -266,14 +266,14 @@ describe('routes : protocol', () => { }); }); forEach(completeProtocol).it( - '%s %s should conform to the general response protocol', + '%s %s should conform to the general response template', (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { - match(responseTemplate, JSON.parse(res.body)).shoul.be.true; + expect(match(responseTemplate)(res.body)).to.be.true; }); }); forEach(completeProtocol).it( @@ -284,7 +284,7 @@ describe('routes : protocol', () => { .get(base + path) .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { - expect(match(temp)(JSON.parse(res.body))).to.be.true; + expect(match(temp)(res.body)).to.be.true; }); } else { return true; -- cgit v1.2.1 From 8555711c7f408e74ea8ad3da1875ddbdef36c509 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Fri, 13 Apr 2018 16:58:50 +0100 Subject: prevent 404 on params --- src/FileRouter.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index e890241..f4d2fdc 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -716,11 +716,8 @@ export class FileRouter { uuid: fileId } }); - if (file == null) { - return next(new RequestError(404, 'file_not_found')); - } else { - res.locals.file = file; - } + + res.locals.file = file; next(); } ); -- cgit v1.2.1 From 9c0ff9a0b7d73e5e2a12c4f87d1aa586c59adec9 Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 21:12:53 +0100 Subject: only 12 failing tests :D --- files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de | 0 package.json | 7 +++--- src/FileRouter.ts | 27 ++++++++++++++++-------- src/matcher/options.ts | 7 +++++- test/integration/protocol.routes.test.ts | 19 ++++++++++++++--- test/test-db.ts | 4 ++-- test/unit/options.unit.test.ts | 10 +++++++++ test/unit/types.unit.test.ts | 1 + yarn.lock | 19 ++++++++++++++++- 9 files changed, 75 insertions(+), 19 deletions(-) create mode 100644 files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de diff --git a/files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de b/files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json index b21bed5..c187871 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "run:postgres": "pg_ctl start", "start": "ts-node src/index.ts", "_lint": "tslint -p './tsconfig.json' -c './tslint.json'", - "lint": "yarn _lint --fix --force './src/**/*.ts'", + "lint": "yarn _lint --fix --force './src/**/*.ts'", "lint:tests": "yarn _lint --fix --force './test/**/*.ts'" }, "repository": { @@ -54,9 +54,9 @@ "@types/passport": "^0.4.2", "@types/passport-local": "^1.0.32", "@types/sequelize": "^4.27.5", + "@types/sharp": "^0.17.6", "@types/sqlite3": "^3.1.1", "@types/supertest": "^2.0.4", - "@types/sharp": "^0.17.6", "@types/uuid": "^3.4.3", "@types/winston": "^2.3.8", "@types/xml-parser": "^1.2.29", @@ -64,6 +64,7 @@ "colors": "^1.1.2", "express": "^4.16.2", "express-jwt": "^5.3.0", + "file-system": "^2.2.2", "jsonwebtoken": "^8.1.1", "mocha-each": "^1.1.0", "morgan": "^1.9.0", @@ -76,9 +77,9 @@ "reflect-metadata": "^0.1.12", "sequelize": "^4.32.7", "sequelize-typescript": "^0.6.2", + "sharp": "^0.20.0", "sqlite3": "^4.0.0", "supertest": "^3.0.0", - "sharp": "^0.20.0", "ts-node": "^3.3.0", "typescript": "^2.7.1", "uuid": "^3.2.1", diff --git a/src/FileRouter.ts b/src/FileRouter.ts index e890241..4ee42dc 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -547,7 +547,7 @@ const getFileId: Middleware = getFile; const postFilePath: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - logger.debug('Receiving file'); + logger.debug('Receiving file to ' + res.locals.parentFolder); if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } @@ -556,7 +556,18 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + /* + console.log("1: " + file.uuid + " -- " + res.locals.project.name) + try { + let x = files.writableStream(file.uuid, res.locals.project.name); + console.log("2") + req.pipe(x); + console.log("3") + } catch (err) { + console.log(err); + } + console.log("4") + */ next(); }; @@ -652,11 +663,12 @@ export class FileRouter { // Fetch a file from its path: this.router.param( - 'file', + 'path', async( req: Request, res: Response, next: NextFunction, filename: string ): Promise => { + console.log("wrong precond") logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; @@ -709,18 +721,15 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - logger.debug(`Searching for file ${fileId}`); + console.log(`Searching for file ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { uuid: fileId } }); - if (file == null) { - return next(new RequestError(404, 'file_not_found')); - } else { - res.locals.file = file; - } + res.locals.file = file; + console.log("precondition: " + file) next(); } ); diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 62e4985..5e7114b 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -18,6 +18,7 @@ const matchNoCurry: if (types.atom(template)) { return template === value; } else if (types.function(template)) { + //console.log("hi there " + value) return template(value); } else if (types.atom(value) || value === undefined) { return false; @@ -82,10 +83,14 @@ export const array = (template: TemplateValue, values?: Value[]) => { if (values === undefined) { return array.bind(null, template); } + //console.trace() + //console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); - return values.every(m); + return values.every((item) => { + return true; + }); }; // tslint:disable-next-line:typedef diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index ebe18c2..7f9f3e7 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -10,6 +10,7 @@ const expect: Chai.ExpectStatic = chai.expect; import { Credentials, Database, addUser, initDB, resetDB, Projec, addProjec, Filee, addFilee } from '../test-db'; import { default as User } from '../../src/db/model/User'; +import * as fs from 'fs'; // Chai-http must be imported this way: // tslint:disable-next-line:no-var-requires no-require-imports @@ -153,7 +154,7 @@ describe('routes : protocol', () => { types.boolean ]) }), 200], - ['post', '/properties', null, 200], + ['post', '/properties?action=update', null, 200], ['get', '/user_privileges', array({ privilege: types.string, description: types.string, @@ -231,7 +232,7 @@ describe('routes : protocol', () => { data: optional(types.anything) }, 200], ['get', '/projects/mocky/files/example/path', null, 200], - ['post', '/projects/mocky/files/mockyfile2', null, 200], + ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200], ['get', '/projects/mocky/files_by_id/file1', null, 200] ]; @@ -257,11 +258,19 @@ describe('routes : protocol', () => { forEach(completeProtocol).it( '%s %s should have a status %4$d', (method: string, path: string, temp: Template, resCode: number) => { - const request: ChaiHttp.Request = method === 'get' + const request: any = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); + /*if (path.includes('/projects/mocky/files/some_file')) { + fs.createReadStream('test/mockUI/ui.html').pipe( + request); + console.log("tasdasdas") + }*/ request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { + if (path.includes('/projects/mocky/files/some_file')) { + console.log("something") + } expect(res).to.have.status(resCode); }); }); @@ -273,6 +282,10 @@ describe('routes : protocol', () => { : chai.request(app).post(base + path); request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { + if(path == '/properties' || path == '/current_user'){ + //console.log(res.body) + //console.log(responseTemplate); + } expect(match(responseTemplate)(res.body)).to.be.true; }); }); diff --git a/test/test-db.ts b/test/test-db.ts index 40ae438..ef980c5 100644 --- a/test/test-db.ts +++ b/test/test-db.ts @@ -112,9 +112,9 @@ export const addFilee: (database: Database, user: Credentials) => path: 'example/path', uuid: 'file1', creator: user, - type: "generic" + type: 'generic' }; await new File(mockFile).save(); return mockFile; -}; \ No newline at end of file +}; diff --git a/test/unit/options.unit.test.ts b/test/unit/options.unit.test.ts index 1925835..29000de 100644 --- a/test/unit/options.unit.test.ts +++ b/test/unit/options.unit.test.ts @@ -159,5 +159,15 @@ describe('Matching:', () => { }; options.match(template, matchee).should.be.false; }); + it('accepts optional matches', () => { + const template = { + a: options.optional(types.array), + b: options.optional(types.anything) + }; + const matchee = { + b: [] + }; + options.match(template)(matchee).should.be.true; + }); }); }); diff --git a/test/unit/types.unit.test.ts b/test/unit/types.unit.test.ts index ad0f99c..f18d5a1 100644 --- a/test/unit/types.unit.test.ts +++ b/test/unit/types.unit.test.ts @@ -30,6 +30,7 @@ describe('Type Checking:', () => { types.anything(1).should.be.true; types.anything('string').should.be.true; types.anything(false).should.be.true; + types.anything([]).should.be.true; }); it('accepts null', () => { types.anything(null).should.be.true; diff --git a/yarn.lock b/yarn.lock index 9d8eb2c..7b18d1c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -824,6 +824,19 @@ eyes@0.1.x: version "0.1.8" resolved "https://registry.yarnpkg.com/eyes/-/eyes-0.1.8.tgz#62cf120234c683785d902348a800ef3e0cc20bc0" +file-match@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/file-match/-/file-match-1.0.2.tgz#c9cad265d2c8adf3a81475b0df475859069faef7" + dependencies: + utils-extend "^1.0.6" + +file-system@^2.2.2: + version "2.2.2" + resolved "https://registry.yarnpkg.com/file-system/-/file-system-2.2.2.tgz#7d65833e3a2347dcd956a813c677153ed3edd987" + dependencies: + file-match "^1.0.1" + utils-extend "^1.0.4" + finalhandler@1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.0.tgz#ce0b6855b45853e791b2fcc680046d88253dd7f5" @@ -2085,7 +2098,7 @@ supports-color@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" -supports-color@^5.2.0: +supports-color@^5.3.0: version "5.3.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.3.0.tgz#5b24ac15db80fa927cf5227a4a33fd3c4c7676c0" dependencies: @@ -2291,6 +2304,10 @@ util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" +utils-extend@^1.0.4, utils-extend@^1.0.6: + version "1.0.8" + resolved "https://registry.yarnpkg.com/utils-extend/-/utils-extend-1.0.8.tgz#ccfd7b64540f8e90ee21eec57769d0651cab8a5f" + utils-merge@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" -- cgit v1.2.1 From 8d355d34cd309122e67f694e22f2023db205794f Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 22:07:19 +0100 Subject: much better --- src/matcher/options.ts | 2 +- test/integration/protocol.routes.test.ts | 38 ++++++++++++++++---------------- test/unit/options.unit.test.ts | 17 ++++++++++++++ 3 files changed, 37 insertions(+), 20 deletions(-) diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 5e7114b..9c78554 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -84,7 +84,7 @@ export const array = (template: TemplateValue, values?: Value[]) => { return array.bind(null, template); } //console.trace() - //console.log(values) + console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 7f9f3e7..ea5dd8e 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -58,8 +58,7 @@ const getToken = async() => { }); }; -import { Template, alternative, array, exact, match, optional - } from '../../src/matcher/options'; +import options, { Template, alternative, array, exact, match, optional } from '../../src/matcher/options'; import { default as types } from '../../src/matcher/types'; // The general response template according to protocol @@ -112,11 +111,11 @@ describe('routes : protocol', () => { // Format: // const completeProtocol: MochaForEachInput[] = [ - ['get', '/_supported_protocols_', exact({ + ['get', '/_supported_protocols_', { supported: array(types.string), required: array(types.string) - }), 200], - ['get', '/log', types.array({ + }, 200], + ['get', '/log', array({ component: types.string, level: alternative([ 'info', @@ -134,7 +133,7 @@ describe('routes : protocol', () => { level: 'info', value: 'sdasdasdasdasdasd' }], 200], - ['get', '/properties', types.array({ + ['get', '/properties', array({ id: types.string, display: optional(match({ category: types.string, @@ -162,8 +161,8 @@ describe('routes : protocol', () => { }), 200], ['get', '/users', array({ username: types.string, - privileges: array(types.string), - projects: array({ + privileges: types.array(types.string), + projects: types.array({ project_name: types.string, access_level: types.string }), @@ -191,8 +190,8 @@ describe('routes : protocol', () => { }, 200], ['get', '/current_user', { username: types.string, - privileges: array(types.string), - projects: array({ + privileges: types.array(types.string), + projects: types.array({ project_name: types.string, access_level: types.string }), @@ -209,7 +208,7 @@ describe('routes : protocol', () => { }), 200], ['get', '/projects', array({ project_name: types.string, - users: array({ + users: types.array({ username: types.string, access_level: types.string }), @@ -228,9 +227,7 @@ describe('routes : protocol', () => { admin_metadata: optional(types.anything) }, 200], ['post', '/projects/mocky', null, 200], - ['get', '/projects/mocky/properties', { - data: optional(types.anything) - }, 200], + ['get', '/projects/mocky/properties', null, 200], ['get', '/projects/mocky/files/example/path', null, 200], ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200], ['get', '/projects/mocky/files_by_id/file1', null, 200] @@ -282,10 +279,7 @@ describe('routes : protocol', () => { : chai.request(app).post(base + path); request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { - if(path == '/properties' || path == '/current_user'){ - //console.log(res.body) - //console.log(responseTemplate); - } + expect(match(responseTemplate)(res.body)).to.be.true; }); }); @@ -297,7 +291,13 @@ describe('routes : protocol', () => { .get(base + path) .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { - expect(match(temp)(res.body)).to.be.true; + if(!match(temp)(res.body.data)){ + console.log("******" + method + " - " + path + "*****8") + console.log(res.body) + console.log(temp); + console.log("*************************************9") + } + expect(match(temp)(res.body.data)).to.be.true; }); } else { return true; diff --git a/test/unit/options.unit.test.ts b/test/unit/options.unit.test.ts index 29000de..a4c879a 100644 --- a/test/unit/options.unit.test.ts +++ b/test/unit/options.unit.test.ts @@ -169,5 +169,22 @@ describe('Matching:', () => { }; options.match(template)(matchee).should.be.true; }); + it('big bad unit test', () => { + const matchee = { status: 'success', + data: [ { privilege: 'admin', description: 'null', internal: false }, + { privilege: 'logging', + description: 'Allows Post to Log', + internal: false } ] }; + const template = { + status: types.string, + data: options.optional(types.anything), + error: options.optional(types.string), + error_description: options.optional(types.string), + user_message: options.optional(types.string), + error_data: options.optional(types.anything) + }; + + options.match(template)(matchee).should.be.true; + }); }); }); -- cgit v1.2.1 From a156860837cb6c044d16802aa5a0cd06ec05648b Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 14 Apr 2018 16:49:47 +0100 Subject: fixed 1 test in auth.routes.test.ts --- test/integration/auth.routes.test.ts | 22 ++++++++-------- test/integration/protocol.routes.test.ts | 44 ++++++++++++++++---------------- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/test/integration/auth.routes.test.ts b/test/integration/auth.routes.test.ts index af3f696..29c0cfc 100644 --- a/test/integration/auth.routes.test.ts +++ b/test/integration/auth.routes.test.ts @@ -65,13 +65,15 @@ const authorisationErr = { error_description: 'user does not have correct authorisation for task' }; +const base: string = '/cs3099group-be-4'; + describe('authentication', () => { before(initDatabase); context('invalid password authentication', () => { before(populateDatabase); it('should reject login to invalid endpoints', () => { return chai.request(app) - .post('/') + .post('/invalid endpoint') .send({ username: mockUser.username, password: mockUser.password, @@ -86,7 +88,7 @@ describe('authentication', () => { }); it('should reject invalid usernames', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: 'invalid', password: mockUser.password, @@ -97,7 +99,7 @@ describe('authentication', () => { }); it('should reject invalid passwords', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: mockUser.username, password: 'asasasas', @@ -108,7 +110,7 @@ describe('authentication', () => { }); it('should reject invalid grant_type', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: mockUser.username, password: mockUser.password, @@ -119,7 +121,7 @@ describe('authentication', () => { }); it('should reject empty usernames', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: '', password: mockUser.password, @@ -130,7 +132,7 @@ describe('authentication', () => { }); it('should reject empty passwords', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: mockUser.username, password: '', @@ -141,7 +143,7 @@ describe('authentication', () => { }); it('should reject empty grant_type', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: mockUser.username, password: mockUser.password, @@ -155,7 +157,7 @@ describe('authentication', () => { before(populateDatabase); it('should accept correct credentials', () => { return chai.request(app) - .post('/cs3099group-be-4/oauth/token') + .post(`${base}/oauth/token`) .send({ username: mockUser.username, password: mockUser.password, @@ -169,7 +171,7 @@ describe('authentication', () => { beforeEach(populateDatabase); beforeEach(getToken); it('should reject invalid tokens', () => { - return chai.request(app).get('/') + return chai.request(app).get(`${base}/users`) .set('Authorization', 'Bearer ' + 'invalid') .then((res) => { expect(res).to.have.status(401); @@ -178,7 +180,7 @@ describe('authentication', () => { }); }); it('should accept valid tokens', () => { - return chai.request(app).get('/') + return chai.request(app).get(`${base}/_supported_protocols_`) .set('Authorization', `Bearer ${token}`) .then((res) => { expect(res).to.have.status(200); diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index ea5dd8e..ad9b892 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -58,7 +58,7 @@ const getToken = async() => { }); }; -import options, { Template, alternative, array, exact, match, optional } from '../../src/matcher/options'; +import options, { Template, alternative, array, exact, match, optional }from '../../src/matcher/options'; import { default as types } from '../../src/matcher/types'; // The general response template according to protocol @@ -82,27 +82,6 @@ const errorResponseTemplate: Template = { type MochaForEachInput = [ string, string, Template, number ]; -describe('routes : errors', () => { - before(initDatabase); - describe('GET invalid routes', () => { - // Should invalid routes also possibly be 401? - it.skip('should have response code 404', () => { - return chai.request(app).get('/invalid/route') - .set('Authorization', `Bearer ${token}`) - .catch((err) => { - expect(err.status).to.equal(404); - }); - }); - it('should conform to the error protocol', () => { - return chai.request(app).get('/invalid/route') - .set('Authorization', `Bearer ${token}`) - .catch((err) => { - expect(match(errorResponseTemplate)(err.response.body)).to.be.true; - }); - }); - }); -}); - describe('routes : protocol', () => { const base: string = '/cs3099group-be-4'; @@ -304,4 +283,25 @@ describe('routes : protocol', () => { } }); }); + + describe('test edge cases', () => { + before(initDatabase); + describe('GET invalid routes', () => { + // Should invalid routes also possibly be 401? + it.skip('should have response code 404', () => { + return chai.request(app).get('/invalid/route') + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + expect(err.status).to.equal(404); + }); + }); + it('should conform to the error protocol', () => { + return chai.request(app).get('/invalid/route') + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; + }); + }); + }); + }); }); -- cgit v1.2.1 From 72704a9fb688acdb57b33846796b13abbeb18a3c Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sat, 14 Apr 2018 18:26:36 +0100 Subject: returns 404 for unused routes only if logged in --- src/app.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app.ts b/src/app.ts index c299cf7..6854c46 100644 --- a/src/app.ts +++ b/src/app.ts @@ -77,7 +77,7 @@ class App { .unless({path: [ '/', '/cs3099group-be-4/oauth/token', - '/cs3099group-be-4/_supported_protocols_' + '/cs3099group-be-4/_supported_protocols_' ] }) ); this.express.use(passport.initialize()); @@ -110,20 +110,20 @@ class App { message: 'Welcome to the CS3099 BE4 server!', important: 'Endpoints start from /cs3099group-be-4/' }); - }); - const errRouter: ex.Router = ex.Router(); - errRouter.get('/*', (req: ex.Request, res: ex.Response): void => { + }); + const errRouter: ex.Router = ex.Router(); + errRouter.get('*', (req: ex.Request, res: ex.Response): void => { res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); - }); + }); this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); this.express.use('/', defRouter); - this.express.use('/XX*', errRouter); + this.express.use('*', errRouter); } /** -- cgit v1.2.1 From 5f687384dfeb807867c5d36bb83f672800599de6 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 14 Apr 2018 18:26:38 +0100 Subject: confirmed matcher doesn't like arrays --- src/matcher/options.ts | 6 +----- test/unit/options.unit.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 9c78554..988d22b 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -83,14 +83,10 @@ export const array = (template: TemplateValue, values?: Value[]) => { if (values === undefined) { return array.bind(null, template); } - //console.trace() - console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); - return values.every((item) => { - return true; - }); + return values.every(m); // }; // tslint:disable-next-line:typedef diff --git a/test/unit/options.unit.test.ts b/test/unit/options.unit.test.ts index a4c879a..4a85c2f 100644 --- a/test/unit/options.unit.test.ts +++ b/test/unit/options.unit.test.ts @@ -170,6 +170,7 @@ describe('Matching:', () => { options.match(template)(matchee).should.be.true; }); it('big bad unit test', () => { + /* tslint:disable:align */ const matchee = { status: 'success', data: [ { privilege: 'admin', description: 'null', internal: false }, { privilege: 'logging', @@ -183,6 +184,36 @@ describe('Matching:', () => { user_message: options.optional(types.string), error_data: options.optional(types.anything) }; + /* tslint:enable:align */ + + options.match(template)(matchee).should.be.true; + }); + it('bigger badder unit test', () => { + /* tslint:disable:align */ + const matchee = [ { project_name: 'mocky', + users: [{ username: 'uname', access_level: 'admin'}], + public_metadata: { creation_date: '2018-04-14T17:13:44.291Z' }, + private_metadata: {}, + admin_metadata: {} } ]; + const template = types.array({ + project_name: types.string, + users: types.array({ + username: types.string, + access_level: types.string + }), + public_metadata: types.anything, + private_metadata: options.optional(types.anything), + admin_metadata: options.optional(types.anything) + }); + /* tslint:enable:align */ + + options.match(template)(matchee).should.be.true; + }); + it('$$ Buy now: unit tests cheap and chearful. only £9.99', () => { + /* tslint:disable:align */ + const matchee: any = [ 'test' ]; + const template = types.array(types.anything); + /* tslint:enable:align */ options.match(template)(matchee).should.be.true; }); -- cgit v1.2.1 From 71a674b70f0003e215f6d9ba5e5b94db36a83b36 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sat, 14 Apr 2018 19:47:18 +0100 Subject: think i fixed something --- src/FileRouter.ts | 2 +- src/app.ts | 23 +++++++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4ee42dc..ff0e65d 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -425,7 +425,7 @@ const getProjects: Middleware = async( }); res.locals.data = projects.map( (p: Project): ProjectFullInfo => p.fullInfo - ); + ); next(); }; diff --git a/src/app.ts b/src/app.ts index 6854c46..1d1c9cb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -111,19 +111,26 @@ class App { important: 'Endpoints start from /cs3099group-be-4/' }); }); - const errRouter: ex.Router = ex.Router(); - errRouter.get('*', (req: ex.Request, res: ex.Response): void => { - res.status(404) + //const errRouter: ex.Router = ex.Router(); + + this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); + this.express.use('/', defRouter); + this.express.use((req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { + console.log(res.locals) + if (Object.keys(res.locals).length === 0) { + console.log(404) + res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); - }); - this.express.use('/cs3099group-be-4', FileRouter); - this.express.use('/cs3099group-be-4', authRouter); - this.express.use('/', defRouter); - this.express.use('*', errRouter); + } + else { + next(); + } + }); } /** -- cgit v1.2.1 From 1e6cb08fcdec54f1263eb1f6fdae6e0f438dfc97 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sun, 15 Apr 2018 17:24:10 +0100 Subject: fixed logging --- src/FileRouter.ts | 34 +++- src/app.ts | 18 +- src/logger.ts | 61 +++--- src/matcher/options.ts | 1 - test/integration/protocol.routes.test.ts | 315 ++++++++++++++++++------------- 5 files changed, 240 insertions(+), 189 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ff0e65d..4e32fb3 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -65,6 +65,7 @@ const getProtocols: Middleware = ( const postLog: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { + res.locals.modified = true; logger.debug('Adding forwarded log'); if (!req.user.hasPrivilege('logging')) { next(new RequestError(401, 'invalid_privilege')); @@ -108,9 +109,15 @@ const getLog: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Fetching log'); + res.locals.modified = true; if (!req.user.hasPrivilege('admin')) { next(new RequestError(401, 'invalid_privilege')); } + /* tslint:disable */ + if(!req.params.level) req.params.level = 'info'; + if(!req.params.before) req.params.before = new Date(); + if(!req.params.after) req.params.after = new Date(0); + /* tslint:enable */ res.locals.data = logger.fetch( req.params.level, { before: new Date(req.params.before), @@ -165,6 +172,7 @@ const postProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Editing server properties'); + res.locals.modified = true; for (const newProp of req.body) { const prop: Property | undefined = serverConfig.find( (p: Property): boolean => p.id === newProp.id @@ -257,6 +265,7 @@ const getUserProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Listing additional properties for a user'); + res.locals.modified = true; if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; @@ -289,6 +298,7 @@ const getUsername: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug(`Listing user ${res.locals.user}`); + res.locals.modified = true; if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; @@ -327,6 +337,7 @@ const postCurUser: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Editing current user'); + res.locals.modified = true; try { await req.user.updateInfo(req.body); await req.user.save(); @@ -357,14 +368,15 @@ const postUsername: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { let user: User | null | undefined = res.locals.user; + res.locals.modified = true; if (user == null) { - console.log('Adding new user'); + logger.debug('Adding new user'); user = new User({ username: req.params.username, password: req.params.password }); } else { - console.log('Editing user'); + logger.debug('Editing user'); user.password = req.params.password; } if (req.body) { @@ -387,6 +399,7 @@ const postUsername: Middleware = async( const getProjectRoles: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { + res.locals.modified = true; logger.debug('Listing available project roles'); const roles: ContributorGroup[] = await ContributorGroup.findAll(); res.locals.data = roles.filter( @@ -418,6 +431,7 @@ const getProjects: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Listing all projects'); + res.locals.modified = true; const projects: Project[] = await Project.findAll({ include: [ User @@ -425,7 +439,7 @@ const getProjects: Middleware = async( }); res.locals.data = projects.map( (p: Project): ProjectFullInfo => p.fullInfo - ); + ); next(); }; @@ -450,6 +464,7 @@ const getProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Getting project properties'); + res.locals.modified = true; const project: Project | null = res.locals.project; if (project == null) { return next(new RequestError(404, 'project_not_found')); @@ -476,6 +491,7 @@ const postProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { let project: Project | null = res.locals.project; + res.locals.modified = true; let promise: PromiseLike | null = null; if (project == null) { logger.debug('Adding new project'); @@ -505,6 +521,7 @@ const getProjectProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Getting project properties'); + res.locals.modified = true; if (res.locals.project == null) { next(new RequestError(404, 'project_not_found')); } else { @@ -520,6 +537,7 @@ const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug(`Getting file in ${req.query.view} view`); + res.locals.modified = true; const file: File | null = res.locals.file; if (file == null) { return next(new RequestError(404, 'file_not_found')); @@ -547,7 +565,8 @@ const getFileId: Middleware = getFile; const postFilePath: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - logger.debug('Receiving file to ' + res.locals.parentFolder); + logger.debug(`Receiving file to ${res.locals.parentFolder}`); + res.locals.modified = true; if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } @@ -611,7 +630,7 @@ export class FileRouter { this.router.get ('/projects/:project_name/properties', getProjectProperties); // File access this.router.get ('/projects/:project_name/files/:path', getFilePath); - this.router.post('/projects/:project_name/files/:id', postFilePath); + this.router.post('/projects/:project_name/files/:path', postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -668,7 +687,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - console.log("wrong precond") + console.log(`parsing path ${filename}`) logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; @@ -721,7 +740,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - console.log(`Searching for file ${fileId}`); + console.log(`parsing id ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { @@ -729,7 +748,6 @@ export class FileRouter { } }); res.locals.file = file; - console.log("precondition: " + file) next(); } ); diff --git a/src/app.ts b/src/app.ts index 1d1c9cb..e9d1d68 100644 --- a/src/app.ts +++ b/src/app.ts @@ -110,26 +110,22 @@ class App { message: 'Welcome to the CS3099 BE4 server!', important: 'Endpoints start from /cs3099group-be-4/' }); - }); - //const errRouter: ex.Router = ex.Router(); - + }); this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); - this.express.use('/', defRouter); - this.express.use((req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { - console.log(res.locals) + this.express.use('/', defRouter); + this.express.use((req: ex.Request, res: ex.Response, + next: ex.NextFunction): void => { if (Object.keys(res.locals).length === 0) { - console.log(404) res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); + } else { + next(); } - else { - next(); - } }); } @@ -149,5 +145,5 @@ export default new App(true).express; */ // tslint:disable-next-line:variable-name export const TestApp: () => ex.Express = (): ex.Express => { - return new App(false).express; + return new App(true).express; }; diff --git a/src/logger.ts b/src/logger.ts index aefb751..9025814 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -4,6 +4,7 @@ import * as colors from 'colors/safe'; import * as winston from 'winston'; import { files } from './files'; +import { QueryOptions } from 'sequelize'; type Colour = (s: string) => string; @@ -252,6 +253,11 @@ const makeLogFunction: (level: LogLevel) => LogFunction = ( }; }; +function forwardLog(level: LogLevel, message: string, meta: LoggingMetadata) + : any { + basicLogger.log(level, message, meta); +} + interface FetchParams { before?: Date; after?: Date; @@ -265,40 +271,27 @@ interface LogItem { timestamp: string; } -const fetchLogs: (level?: LogLevel, params?: FetchParams) => LogItem[] = ( - level?: LogLevel, params: FetchParams = {} -): LogItem[] => { - const matches: (log: any, level?: LogLevel, params?: FetchParams) - => boolean = ( - log: any, minLevel?: LogLevel, fetchParams: FetchParams = {} - ): boolean => { - if (!minLevel) { - // tslint:disable-next-line:no-parameter-reassignment - minLevel = 'info'; - } - const time: Date = new Date(log.timestamp); - if (params.before && params.before < time) { - return false; - } else if (params.after && params.after > time) { - return false; - } else { - return true; - } +/* tslint:disable */ +const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise = (level?: LogLevel, params: FetchParams = {}): Promise => { + const options: winston.QueryOptions = { + from: params.after, + until: params.before, + start: 0, + order: 'desc', + fields: ['user', 'component', 'level', 'message', 'label', 'timestamp'] }; - const out: LogItem[] = []; - basicLogger.stream({ level }).on('log', (log: any): void => { - if (matches(log, level, params)) { - out.push({ - component: log.component, - level: log.level, - value: log.message, - username: log.user, - timestamp: log.timestamp - }); - } + + return new Promise((res, rej): void => { + basicLogger.query(options, function (err, results) { + if (err) { + /* TODO: handle me */ + throw err; + } + res(results.basicFileTransport); + }); }); - return out; }; +/* tslint:enable */ export const logger: { 7: LogFunction; @@ -339,7 +332,7 @@ export const logger: { shutdown: LogFunction; isEnabled: () => boolean; forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void; - fetch: (level: LogLevel, params?: FetchParams) => LogItem[]; + fetch: (level: LogLevel, params?: FetchParams) => Promise; } = { 7: makeLogFunction('7'), debug: makeLogFunction('debug'), @@ -378,8 +371,8 @@ export const logger: { emergency: makeLogFunction('emergency'), shutdown: makeLogFunction('shutdown'), isEnabled: (): boolean => !basicFileTransport.silent, - forward: basicLogger.log, - fetch: fetchLogs + forward: forwardLog, + fetch: fetchLogs2 }; export const logQuery: (query: string, duration: string) => void = ( diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 988d22b..0513eb3 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -18,7 +18,6 @@ const matchNoCurry: if (types.atom(template)) { return template === value; } else if (types.function(template)) { - //console.log("hi there " + value) return template(value); } else if (types.atom(value) || value === undefined) { return false; diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index ad9b892..1e8bf63 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -82,137 +82,138 @@ const errorResponseTemplate: Template = { type MochaForEachInput = [ string, string, Template, number ]; -describe('routes : protocol', () => { - const base: string = '/cs3099group-be-4'; +const base: string = '/cs3099group-be-4'; - /* tslint:disable:align */ +/* tslint:disable:align */ - // Format: - // - const completeProtocol: MochaForEachInput[] = [ - ['get', '/_supported_protocols_', { - supported: array(types.string), - required: array(types.string) - }, 200], - ['get', '/log', array({ - component: types.string, - level: alternative([ - 'info', - 'security', - 'warning', - 'error', - 'critical' - ]), - value: types.anything, - username: types.string, - timestamp: types.string - }), 200], - ['post', '/log', [{ - component: 'tesssst', - level: 'info', - value: 'sdasdasdasdasdasd' - }], 200], - ['get', '/properties', array({ - id: types.string, - display: optional(match({ - category: types.string, - group: types.string, - display_name: types.string, - description: types.string - })), - read_only: types.boolean, - type: alternative([ - 'string', - 'integer', - 'boolean' - ]), - value: alternative([ - types.string, - types.integer, - types.boolean - ]) - }), 200], - ['post', '/properties?action=update', null, 200], - ['get', '/user_privileges', array({ - privilege: types.string, - description: types.string, - internal: types.boolean - }), 200], - ['get', '/users', array({ - username: types.string, - privileges: types.array(types.string), - projects: types.array({ - project_name: types.string, - access_level: types.string - }), - public_user_metadata: types.anything, - private_user_metadata: types.anything, - public_admin_metadata: types.anything, - private_admin_metadata: types.anything - }), 200], - // TODO types.metadata - ['get', '/users/mock_user', { - username: types.string, - privileges: array(types.string), - projects: array({ - project_name: types.string, - access_level: types.string - }), - public_user_metadata: types.anything, - private_user_metadata: types.anything, - public_admin_metadata: types.anything, - private_admin_metadata: types.anything - }, 200], - ['post', '/users/new_user', null, 200], - ['get', '/users/mock_user/properties', { - data: optional(types.anything) - }, 200], - ['get', '/current_user', { - username: types.string, - privileges: types.array(types.string), - projects: types.array({ - project_name: types.string, - access_level: types.string - }), - public_user_metadata: types.anything, - private_user_metadata: types.anything, - public_admin_metadata: types.anything, - private_admin_metadata: types.anything - }, 200], - ['post', '/current_user', null, 200], - ['get', '/project_roles', array({ - role: types.string, - description: types.string, - internal: types.boolean - }), 200], - ['get', '/projects', array({ +// Format: +// +const completeProtocol: MochaForEachInput[] = [ + ['get', '/_supported_protocols_', { + supported: array(types.string), + required: array(types.string) + }, 200], + ['get', '/log', array({ + component: types.string, + level: alternative([ + 'info', + 'security', + 'warning', + 'error', + 'critical' + ]), + value: types.anything, + username: types.string, + timestamp: types.string + }), 200], + ['post', '/log', [{ + component: 'tesssst', + level: 'info', + value: 'sdasdasdasdasdasd' + }], 200], + ['get', '/properties', array({ + id: types.string, + display: optional(match({ + category: types.string, + group: types.string, + display_name: types.string, + description: types.string + })), + read_only: types.boolean, + type: alternative([ + 'string', + 'integer', + 'boolean' + ]), + value: alternative([ + types.string, + types.integer, + types.boolean + ]) + }), 200], + ['post', '/properties?action=update', null, 200], + ['get', '/user_privileges', array({ + privilege: types.string, + description: types.string, + internal: types.boolean + }), 200], + ['get', '/users', array({ + username: types.string, + privileges: types.array(types.string), + projects: types.array({ + project_name: types.string, + access_level: types.string + }), + public_user_metadata: types.anything, + private_user_metadata: types.anything, + public_admin_metadata: types.anything, + private_admin_metadata: types.anything + }), 200], + // TODO types.metadata + ['get', '/users/mock_user', { + username: types.string, + privileges: array(types.string), + projects: array({ project_name: types.string, - users: types.array({ - username: types.string, - access_level: types.string - }), - public_metadata: types.anything, - private_metadata: optional(types.anything), - admin_metadata: optional(types.anything) - }), 200], - ['get', '/projects/mocky', { + access_level: types.string + }), + public_user_metadata: types.anything, + private_user_metadata: types.anything, + public_admin_metadata: types.anything, + private_admin_metadata: types.anything + }, 200], + ['post', '/users/new_user', null, 200], + ['get', '/users/mock_user/properties', { + data: optional(types.anything) + }, 200], + ['get', '/current_user', { + username: types.string, + privileges: types.array(types.string), + projects: types.array({ project_name: types.string, - users: array({ - username: types.string, - access_level: types.string - }), - public_metadata: types.anything, - private_metadata: types.anything, - admin_metadata: optional(types.anything) - }, 200], - ['post', '/projects/mocky', null, 200], - ['get', '/projects/mocky/properties', null, 200], - ['get', '/projects/mocky/files/example/path', null, 200], - ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200], - ['get', '/projects/mocky/files_by_id/file1', null, 200] - ]; + access_level: types.string + }), + public_user_metadata: types.anything, + private_user_metadata: types.anything, + public_admin_metadata: types.anything, + private_admin_metadata: types.anything + }, 200], + ['post', '/current_user', null, 200], + ['get', '/project_roles', array({ + role: types.string, + description: types.string, + internal: types.boolean + }), 200], + ['get', '/projects', array({ + project_name: types.string, + users: types.array({ + username: types.string, + access_level: types.string + }), + public_metadata: types.anything, + private_metadata: optional(types.anything), + admin_metadata: optional(types.anything) + }), 200], + ['get', '/projects/mocky', { + project_name: types.string, + users: array({ + username: types.string, + access_level: types.string + }), + public_metadata: types.anything, + private_metadata: types.anything, + admin_metadata: optional(types.anything) + }, 200], + ['post', '/projects/mocky', null, 200], + ['get', '/projects/mocky/properties', null, 200], + ['get', '/projects/mocky/files/example/path', null, 200], + ['post', '/projects/mocky/files/some_file?action=overwrite', {}, 200], + ['get', '/projects/mocky/files_by_id/file1', null, 200] +]; - /* tslint:enable:align */ +/* tslint:enable:align */ + +describe('routes : protocol', () => { before(initDatabase); beforeEach(populateDatabase); @@ -236,7 +237,7 @@ describe('routes : protocol', () => { (method: string, path: string, temp: Template, resCode: number) => { const request: any = method === 'get' ? chai.request(app).get(base + path) - : chai.request(app).post(base + path); + : chai.request(app).post(base + path).send(temp); /*if (path.includes('/projects/mocky/files/some_file')) { fs.createReadStream('test/mockUI/ui.html').pipe( request); @@ -245,7 +246,7 @@ describe('routes : protocol', () => { request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { if (path.includes('/projects/mocky/files/some_file')) { - console.log("something") + //console.log("something") } expect(res).to.have.status(resCode); }); @@ -255,26 +256,33 @@ describe('routes : protocol', () => { (method: string, path: string, temp: Template, resCode: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) - : chai.request(app).post(base + path); + : chai.request(app).post(base + path).send(temp);; request.set('Authorization', `Bearer ${token}`); return request.then((res: ChaiHttp.Response) => { - + if (!(match(responseTemplate)(res.body))) { + console.log(`${method} ${path} ******************`); + console.log(res.body); + console.log("^^^^^^ received || template vvvvvvvv") + console.log(responseTemplate); + console.log('--------------------------------') + } expect(match(responseTemplate)(res.body)).to.be.true; }); }); forEach(completeProtocol).it( - 'the response for %s %s should conform to its specific response protocol', + '%s %s should conform to its specific response template', (method: string, path: string, temp: Template, resCode: number) => { if (method === 'get' && temp != null) { return chai.request(app) .get(base + path) .set('Authorization', `Bearer ${token}`) .then((res: ChaiHttp.Response) => { - if(!match(temp)(res.body.data)){ - console.log("******" + method + " - " + path + "*****8") - console.log(res.body) + if (!(match(temp)(res.body.data))) { + console.log(`${method} ${path} ******************`); + console.log(res.body.data); + console.log("^^^^^^ received || template vvvvvvvv") console.log(temp); - console.log("*************************************9") + console.log('--------------------------------') } expect(match(temp)(res.body.data)).to.be.true; }); @@ -286,6 +294,9 @@ describe('routes : protocol', () => { describe('test edge cases', () => { before(initDatabase); + beforeEach(populateDatabase); + beforeEach(getToken); + describe('GET invalid routes', () => { // Should invalid routes also possibly be 401? it.skip('should have response code 404', () => { @@ -303,5 +314,39 @@ describe('routes : protocol', () => { }); }); }); + + describe('POST invalid routes', () => { + // Should invalid routes also possibly be 401? + it.skip('should have response code 404', () => { + return chai.request(app).post('/invalid/route') + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + expect(err.status).to.equal(404); + }); + }); + it('should conform to the error protocol', () => { + return chai.request(app).post('/invalid/route') + .set('Authorization', `Bearer ${token}`) + .catch((err) => { + expect(match(errorResponseTemplate)(err.response.body)).to.be.true; + }); + }); + }); +/* + describe('access valid routes with invalid parameters', () => { + forEach(completeProtocol.filter((item, index, arr) => { + return (item[0] == 'post'); + })).it( + '%s %s with null body should throw error', + (method: string, path: string, temp: Template, resCode: number) => { + const request: any = chai.request(app).post(base + path); + request.set('Authorization', `Bearer ${token}`) + .then((res: any) => { + expect(res).to.have.status(400); + }).catch((reason: any) => { + expect(reason.response.body).to.eql("errererere"); + }); + }); + });*/ }); }); -- cgit v1.2.1 From c8998c292d48e833f66cb43ea2c945f1a865a10e Mon Sep 17 00:00:00 2001 From: jw255 Date: Sun, 15 Apr 2018 18:03:01 +0100 Subject: fixed fetching current_user --- src/app.ts | 2 +- src/db/model/User.ts | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/app.ts b/src/app.ts index e9d1d68..4dfeeda 100644 --- a/src/app.ts +++ b/src/app.ts @@ -77,7 +77,7 @@ class App { .unless({path: [ '/', '/cs3099group-be-4/oauth/token', - '/cs3099group-be-4/_supported_protocols_' + '/cs3099group-be-4/_supported_protocols_' ] }) ); this.express.use(passport.initialize()); diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 171e899..3a0ef26 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -126,18 +126,20 @@ export default class User extends Model { } public get fullInfo(): UserFullInfo { + console.log("fullinfo called") // FIXME: Fetch these things if they aren't already present if (this.userGroups === undefined) { - throw new Error('userGroups undefined'); + this.userGroups = []; } else if (this.projects === undefined) { - throw new Error('projects undefined'); + this.projects = []; } + console.log("2") return { username : this.username, - privileges: this.userGroups + privileges: this.userGroups! .filter((ug: UserGroup): boolean => ug.name !== null) .map((ug: UserGroup): string => ug.name as string), - projects : this.projects.map( + projects : this.projects!.map( (p: Project): ProjectInfo => this.getProjectInfo(p) ), // TODO: Check if we have anything to use these for yet? -- cgit v1.2.1 From 848f02bcacc11578314ab2e75ccb5b65dba0a6bc Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sun, 15 Apr 2018 18:22:05 +0100 Subject: started modifying file upload --- src/FileRouter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ff0e65d..0a8d06a 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -556,6 +556,7 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); + console.log(res.locals); /* console.log("1: " + file.uuid + " -- " + res.locals.project.name) try { -- cgit v1.2.1 From acd2cd460ef781ba5ae37d579ac984ca4ee1948c Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sun, 15 Apr 2018 19:44:38 +0100 Subject: file upload works, i thnk --- src/FileRouter.ts | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index d6cea53..9a7dcac 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -575,19 +575,8 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - console.log(res.locals); - /* - console.log("1: " + file.uuid + " -- " + res.locals.project.name) - try { - let x = files.writableStream(file.uuid, res.locals.project.name); - console.log("2") - req.pipe(x); - console.log("3") - } catch (err) { - console.log(err); - } - console.log("4") - */ + //console.log(res.locals); + req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -714,13 +703,14 @@ export class FileRouter { } const parentFolder: File | null = await File.findOne({ include: [ - { model: File, as: 'containedFiles' } + { model: File, as: 'containedFilesInternal'}, ], where: { - parentFolder: file, - name: fileNames[0] + //parentFolder: file, + //name: fileNames[0] } }); + //console.log(parentFolder); if (parentFolder == null) { return next(); } -- cgit v1.2.1 From a41380c2ab3b06dd78f61f723f83b84a386b83a8 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Mon, 16 Apr 2018 16:07:21 +0100 Subject: precondition files works --- src/FileRouter.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 9a7dcac..f941dd6 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -575,7 +575,7 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - //console.log(res.locals); + //console.log(res.locals); req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -701,13 +701,16 @@ export class FileRouter { } fileNames.splice(0, 1); } + if (file == null) { + return next(); + } const parentFolder: File | null = await File.findOne({ include: [ { model: File, as: 'containedFilesInternal'}, ], where: { - //parentFolder: file, - //name: fileNames[0] + parentFolderId: file.id, + name: fileNames[0] } }); //console.log(parentFolder); -- cgit v1.2.1 From d628ed540c883764eff623c7a059bcb588c017bc Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 16:08:08 +0100 Subject: nothing major --- files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 | 11 +++++++++++ files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg | Bin 0 -> 4279 bytes files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 | Bin 0 -> 6785 bytes src/FileRouter.ts | 3 ++- src/db/model/User.ts | 2 -- src/matcher/options.ts | 11 +++++++++++ test/unit/options.unit.test.ts | 6 +++--- 7 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 create mode 100644 files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg create mode 100644 files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 diff --git a/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 b/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 new file mode 100644 index 0000000..b00f005 --- /dev/null +++ b/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 @@ -0,0 +1,11 @@ +------WebKitFormBoundary4I0l9vAyn9AB6jO8 +Content-Disposition: form-data; name="pres"; filename="config" +Content-Type: application/octet-stream + +[core] + repositoryformatversion = 0 + filemode = true + bare = false + logallrefupdates = true + +------WebKitFormBoundary4I0l9vAyn9AB6jO8-- diff --git a/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg b/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg new file mode 100644 index 0000000..dd86d56 Binary files /dev/null and b/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg differ diff --git a/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 b/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 new file mode 100644 index 0000000..d7a00af Binary files /dev/null and b/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 differ diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 9a7dcac..f7a1809 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -689,6 +689,7 @@ export class FileRouter { // TODO Rewrite using sub-queries instead of repeated queries. while (fileNames.length > 2) { const fileOrNull: File | null = await File.findOne({ + include: [{all: true}], where: { name: fileNames[0], parentFolder: file @@ -703,7 +704,7 @@ export class FileRouter { } const parentFolder: File | null = await File.findOne({ include: [ - { model: File, as: 'containedFilesInternal'}, + { model: File, as: 'containedFilesInternal'} ], where: { //parentFolder: file, diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 3a0ef26..73d2356 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -126,14 +126,12 @@ export default class User extends Model { } public get fullInfo(): UserFullInfo { - console.log("fullinfo called") // FIXME: Fetch these things if they aren't already present if (this.userGroups === undefined) { this.userGroups = []; } else if (this.projects === undefined) { this.projects = []; } - console.log("2") return { username : this.username, privileges: this.userGroups! diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 0513eb3..967a6f9 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -15,13 +15,20 @@ export type Value = const matchNoCurry: (template: TemplateValue, value: Value | undefined) => boolean = (template: TemplateValue, value: Value | undefined): boolean => { + console.log("matchNoCurry()") + console.log(template) + console.log(value) if (types.atom(template)) { + console.log("atom") return template === value; } else if (types.function(template)) { + console.log("function") return template(value); } else if (types.atom(value) || value === undefined) { + console.log("atom2") return false; } else if (types.object(template)) { + console.log("object") return Object.keys(template) .every((key: string): boolean => { const v: Value | undefined = value[key]; @@ -34,7 +41,11 @@ const matchNoCurry: // tslint:disable-next-line:typedef export const match = (template: TemplateValue, value?: Value) => { + console.log("match()") + console.log(template) + console.log(value) if (value === undefined) { + console.log("is undefined") return matchNoCurry.bind(null, template); } return matchNoCurry(template, value); diff --git a/test/unit/options.unit.test.ts b/test/unit/options.unit.test.ts index 4a85c2f..fd88ca6 100644 --- a/test/unit/options.unit.test.ts +++ b/test/unit/options.unit.test.ts @@ -209,10 +209,10 @@ describe('Matching:', () => { options.match(template)(matchee).should.be.true; }); - it('$$ Buy now: unit tests cheap and chearful. only £9.99', () => { + it.only('Matching Arrays', () => { /* tslint:disable:align */ - const matchee: any = [ 'test' ]; - const template = types.array(types.anything); + const matchee: any = ['ss']; + const template: any = types.array; /* tslint:enable:align */ options.match(template)(matchee).should.be.true; -- cgit v1.2.1 From 4ec93e886fc10de2c65e9599dbfca2a70db578e3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 19:34:57 +0100 Subject: World War Files, part 1\nRoot folder is automatically created at the start of the server. also project folder should now appear in the filesystem --- .gitignore | 3 + files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 | 11 - files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg | Bin 4279 -> 0 bytes files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 | Bin 6785 -> 0 bytes files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de | 0 src/FileRouter.ts | 20 +- src/db/model/File.ts | 18 ++ src/files.ts | 62 +++--- src/index.ts | 11 + test/JH_environment.json | 52 +++++ test/postman.json.json | 245 +++++++++++++++++++++ 11 files changed, 380 insertions(+), 42 deletions(-) delete mode 100644 files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 delete mode 100644 files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg delete mode 100644 files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 delete mode 100644 files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de create mode 100644 test/JH_environment.json create mode 100644 test/postman.json.json diff --git a/.gitignore b/.gitignore index d5c5f43..1be1136 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ logs/ # Typedoc-generated documentation docs/ + +# project files +files/* diff --git a/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 b/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 deleted file mode 100644 index b00f005..0000000 --- a/files/abc/28b2710e-38bb-4bad-bf40-dde2480e4646 +++ /dev/null @@ -1,11 +0,0 @@ -------WebKitFormBoundary4I0l9vAyn9AB6jO8 -Content-Disposition: form-data; name="pres"; filename="config" -Content-Type: application/octet-stream - -[core] - repositoryformatversion = 0 - filemode = true - bare = false - logallrefupdates = true - -------WebKitFormBoundary4I0l9vAyn9AB6jO8-- diff --git a/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg b/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg deleted file mode 100644 index dd86d56..0000000 Binary files a/files/abc/52f7bb86-f385-4bc1-aea5-38e32363e4df.jpg and /dev/null differ diff --git a/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 b/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 deleted file mode 100644 index d7a00af..0000000 Binary files a/files/abc/d124ef49-e9e3-4794-bf50-76f40797b5d5 and /dev/null differ diff --git a/files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de b/files/mocky/bbb850e4-7c0e-41b9-ae63-a025b81d09de deleted file mode 100644 index e69de29..0000000 diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 70243c3..ca2ed50 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,7 +8,7 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { View, files, views } from './files'; +import { View, files, views, rootPathId, createProjectFolder } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -497,9 +497,12 @@ const postProjectName: Middleware = async( logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory' + mimetype: 'inode/directory', + name: req.params.project_name, + parentFolderId: rootPathId }); promise = file.save(); + createProjectFolder(req.params.project_name); project = new Project({ name: req.params.project_name, rootFolder: file @@ -575,7 +578,6 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - //console.log(res.locals); req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -677,11 +679,12 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - console.log(`parsing path ${filename}`) + filename = filename.replace(/\+/g, "/"); // Replace + with / logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; if (project == null) { + // Project should have been found by previous precondition logger.debug('Project was not found: skipping finding file'); return next(new RequestError(404, 'project_not_found')); } @@ -696,15 +699,21 @@ export class FileRouter { } }); if (fileOrNull == null) { + console.log("fileOrNull was null") return next(); } else { + console.log("^^") + console.log(file) file = fileOrNull; } fileNames.splice(0, 1); } + if (file == null) { + console.log("file was null") return next(); } + console.log(file) const parentFolder: File | null = await File.findOne({ include: [ { model: File, as: 'containedFilesInternal'} @@ -714,7 +723,8 @@ export class FileRouter { name: fileNames[0] } }); - //console.log(parentFolder); + console.log("parent folder: ") + console.log(parentFolder); if (parentFolder == null) { return next(); } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 4026b85..193a785 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -5,6 +5,24 @@ import { default as User } from './User'; import { FileTypeName, mimes } from '../../files'; +/* + * attributes: + * - nameInternal + * - fullPathInternal + * - uuid + * - type + * - size + * - parentFolderId + * - containedFilesInternal + * - creatorName + * - creator + * - rootFolderOf + * - uploadDate + * - modifyDate + * - status + * - metadataInternal +*/ + @Table export default class File extends Model { @AllowNull diff --git a/src/files.ts b/src/files.ts index 8ad7236..42e490a 100644 --- a/src/files.ts +++ b/src/files.ts @@ -6,17 +6,12 @@ import { default as Project } from './db/model/Project'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; - -const path: (filename: string, projectName: string) => string - = (filename: string, projectName: string): string => { +/* tslint:disable */ +const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; }; -const writableStream: ( - filename: string, projectName: string -) => fs.WriteStream = ( - filename: string, projectName: string -): fs.WriteStream => { +const writableStream: (filename: string, projectName: string) => fs.WriteStream = (filename: string, projectName: string): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; @@ -25,29 +20,29 @@ interface RawSize { length: number; } -const readableStream: ( - filename: string, projectName: string, - { offset, length }?: Partial -) => fs.ReadStream = ( - filename: string, projectName: string, - { offset, length }: Partial = - { offset: undefined, length: undefined } -): fs.ReadStream => { +const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream + = (filename: string, projectName: string, { offset, length }: Partial = { offset: undefined, length: undefined }): fs.ReadStream => { const options: object = { - start: offset - ? offset - : 0, - end: offset && length - ? offset + length - : undefined + start: offset? offset: 0, + end: offset && length? offset + length: undefined }; return fs.createReadStream(path(filename, projectName), options); }; +/* +// prj name, file uuid => if exists and return path string/ parent folder +const findParent: (projectName: string, fileUUID: string) => File | null = (projectName: string, fileUUID: string) => { + if(!projectName || !fileUUID){ + return null; + } + function findFile(dir: string, fileList: string[]) : string { + + } -const logPath: -(type: string, projectName?: string) => string = ( - type: string, projectName?: string -): string => { +} +*/ + +const logPath: (type: string, projectName?: string) => string = ( + type: string, projectName?: string): string => { return projectName ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` : `${LOG_BASE_DIRECTORY}/general/${type}`; @@ -198,3 +193,18 @@ class MimeTypeMap extends Map { export const mimes: MimeTypeMap = new MimeTypeMap([ [ 'inode/directory', 'directory' ] ]); + +export const rootPathId: string = '0'; +export const rootPathFile: File | null = null; + +export const createRootFolder: () => void = (): any => { + if (!fs.existsSync(CONTENT_BASE_DIRECTORY)){ + fs.mkdirSync(CONTENT_BASE_DIRECTORY); + } +} + +export const createProjectFolder: (name: string) => void = (projName: string): any => { + if (!fs.existsSync(CONTENT_BASE_DIRECTORY + '/' + projName)){ + fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); + } +} diff --git a/src/index.ts b/src/index.ts index 7e21c35..5960374 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,9 @@ import { default as app } from './app'; logger.info('Importing database ORM'); import { default as seq } from './db/orm'; +import { View, files, views, rootPathId, createRootFolder } from './files'; +import { default as File } from './db/model/File'; import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; @@ -40,6 +42,14 @@ logger.info(`Port ${port} chosen`); process.exit(1); } + logger.info('Setting up directory structure'); + const rootDir: File = new File({ + uuid: rootPathId, + mimetype: 'inode/directory', + name: '/' + }); + await rootDir.save(); + logger.info('Adding admin privileges'); const admin: UserGroup = new UserGroup({ name: 'admin', @@ -70,6 +80,7 @@ logger.info(`Port ${port} chosen`); }); await root.save(); + createRootFolder(); await root.$set('userGroups', [admin, logging]); diff --git a/test/JH_environment.json b/test/JH_environment.json new file mode 100644 index 0000000..bf72d78 --- /dev/null +++ b/test/JH_environment.json @@ -0,0 +1,52 @@ +{ + "id": "ddad923b-9750-c337-ff49-6ee328a72e20", + "name": "JH", + "values": [ + { + "enabled": true, + "key": "host", + "value": "http://localhost:3000", + "type": "text" + }, + { + "enabled": true, + "key": "endpoint", + "value": "cs3099group-be-4", + "type": "text" + }, + { + "enabled": true, + "key": "dummy_admin_username", + "value": "hafeez", + "type": "text" + }, + { + "enabled": true, + "key": "dummy_admin_pass", + "value": "pass", + "type": "text" + }, + { + "enabled": true, + "key": "dummy_project", + "value": "abc", + "type": "text" + }, + { + "enabled": true, + "key": "access_token", + "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvYmplY3QiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwYXNzd29yZEludGVybmFsIjpudWxsLCJjcmVhdGlvbkRhdGUiOiIyMDE4LTA0LTE2VDE2OjExOjU5LjU0M1oiLCJ1cGRhdGVkQXQiOiIyMDE4LTA0LTE2VDE2OjExOjU5LjU0M1oiLCJ1c2VyR3JvdXBzIjpbeyJpZCI6MSwibmFtZSI6ImxvZ2dpbmciLCJjYW5DcmVhdGVVc2VycyI6bnVsbCwiY2FuRGVsZXRlVXNlcnMiOm51bGwsImNhbkVkaXRVc2VycyI6bnVsbCwiY2FuQ3JlYXRlUHJvamVjdHMiOm51bGwsImNhbkRlbGV0ZVByb2plY3RzIjpudWxsLCJjYW5FZGl0UHJvamVjdHMiOm51bGwsImNhbkFjY2Vzc0xvZ3MiOnRydWUsImlzSW50ZXJuYWwiOmZhbHNlLCJkZXNjcmlwdGlvbiI6IkFsbG93cyBQb3N0IHRvIExvZyIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6MX19LHsiaWQiOjIsIm5hbWUiOiJhZG1pbiIsImNhbkNyZWF0ZVVzZXJzIjp0cnVlLCJjYW5EZWxldGVVc2VycyI6dHJ1ZSwiY2FuRWRpdFVzZXJzIjp0cnVlLCJjYW5DcmVhdGVQcm9qZWN0cyI6dHJ1ZSwiY2FuRGVsZXRlUHJvamVjdHMiOnRydWUsImNhbkVkaXRQcm9qZWN0cyI6dHJ1ZSwiY2FuQWNjZXNzTG9ncyI6bnVsbCwiaXNJbnRlcm5hbCI6ZmFsc2UsImRlc2NyaXB0aW9uIjoiU3lzdGVtcyBhZG1pbiIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6Mn19XSwicHJvamVjdHMiOltdfSwiaWF0IjoxNTIzODk1MzgzLCJleHAiOjE1MjM5MTY5ODN9.3kpxdZFReNz24MfK6AN4rc3T1vOaG9AM40RQ4-FL7xI", + "type": "text" + }, + { + "enabled": true, + "key": "refresh_token", + "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvYmplY3QiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwYXNzd29yZEludGVybmFsIjpudWxsLCJjcmVhdGlvbkRhdGUiOiIyMDE4LTA0LTE2VDE2OjExOjU5LjU0M1oiLCJ1cGRhdGVkQXQiOiIyMDE4LTA0LTE2VDE2OjExOjU5LjU0M1oiLCJ1c2VyR3JvdXBzIjpbeyJpZCI6MSwibmFtZSI6ImxvZ2dpbmciLCJjYW5DcmVhdGVVc2VycyI6bnVsbCwiY2FuRGVsZXRlVXNlcnMiOm51bGwsImNhbkVkaXRVc2VycyI6bnVsbCwiY2FuQ3JlYXRlUHJvamVjdHMiOm51bGwsImNhbkRlbGV0ZVByb2plY3RzIjpudWxsLCJjYW5FZGl0UHJvamVjdHMiOm51bGwsImNhbkFjY2Vzc0xvZ3MiOnRydWUsImlzSW50ZXJuYWwiOmZhbHNlLCJkZXNjcmlwdGlvbiI6IkFsbG93cyBQb3N0IHRvIExvZyIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6MX19LHsiaWQiOjIsIm5hbWUiOiJhZG1pbiIsImNhbkNyZWF0ZVVzZXJzIjp0cnVlLCJjYW5EZWxldGVVc2VycyI6dHJ1ZSwiY2FuRWRpdFVzZXJzIjp0cnVlLCJjYW5DcmVhdGVQcm9qZWN0cyI6dHJ1ZSwiY2FuRGVsZXRlUHJvamVjdHMiOnRydWUsImNhbkVkaXRQcm9qZWN0cyI6dHJ1ZSwiY2FuQWNjZXNzTG9ncyI6bnVsbCwiaXNJbnRlcm5hbCI6ZmFsc2UsImRlc2NyaXB0aW9uIjoiU3lzdGVtcyBhZG1pbiIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6Mn19XSwicHJvamVjdHMiOltdfSwiaWF0IjoxNTIzODk1MzgzLCJleHAiOjE1MjM5MTY5ODN9.3kpxdZFReNz24MfK6AN4rc3T1vOaG9AM40RQ4-FL7xI", + "type": "text" + } + ], + "timestamp": 1523895383946, + "_postman_variable_scope": "environment", + "_postman_exported_at": "2018-04-16T16:30:59.939Z", + "_postman_exported_using": "Postman/5.5.2" +} \ No newline at end of file diff --git a/test/postman.json.json b/test/postman.json.json new file mode 100644 index 0000000..14771e0 --- /dev/null +++ b/test/postman.json.json @@ -0,0 +1,245 @@ +{ + "variables": [], + "info": { + "name": "JH", + "_postman_id": "d9fad1ce-92af-fc2c-ff74-074fc681c7ee", + "description": "", + "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json" + }, + "item": [ + { + "name": "authorised", + "description": "", + "item": [ + { + "name": "/projects", + "request": { + "url": "{{host}}/{{endpoint}}/projects", + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "description": "" + }, + "response": [] + }, + { + "name": "/log", + "request": { + "url": "{{host}}/{{endpoint}}/log", + "method": "GET", + "header": [ + { + "key": "", + "value": "", + "disabled": true + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "description": "" + }, + "response": [] + }, + { + "name": "/_supported_protocols", + "request": { + "url": "{{host}}/{{endpoint}}/_supported_protocols_", + "method": "GET", + "header": [ + { + "key": "Authorization", + "value": "Bearer {{access_token}}", + "description": "", + "disabled": true + } + ], + "body": {}, + "description": "" + }, + "response": [] + }, + { + "name": "/project_roles", + "request": { + "url": "{{host}}/{{endpoint}}/project_roles", + "method": "GET", + "header": [ + { + "key": "Authorization", + "value": "Bearer {{access_token}}", + "description": "", + "disabled": true + } + ], + "body": {}, + "description": "" + }, + "response": [] + }, + { + "name": "/projects/", + "request": { + "url": "{{host}}/{{endpoint}}/projects/{{dummy_project}}", + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "description": "" + }, + { + "key": "Authorization", + "value": "Bearer {{access_token}}", + "description": "" + } + ], + "body": { + "mode": "raw", + "raw": "{}" + }, + "description": "" + }, + "response": [] + }, + { + "name": "/projects/abc/files_by_id", + "request": { + "url": "{{host}}/{{endpoint}}/projects/{{dummy_project}}/files_by_id/d124ef49-e9e3-4794-bf50-76f40797b5d5", + "method": "GET", + "header": [ + { + "key": "Authorization", + "value": "Bearer {{access_token}}", + "description": "" + }, + { + "key": "Content-Type", + "value": "image/png", + "description": "", + "disabled": true + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "pres", + "description": "", + "type": "file", + "src": "triangle_down_black.png" + } + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/projects/abc/files", + "request": { + "url": "{{host}}/{{endpoint}}/projects/{{dummy_project}}/files/path/to/image.png", + "method": "POST", + "header": [ + { + "key": "Authorization", + "value": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvYmplY3QiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwYXNzd29yZEludGVybmFsIjpudWxsLCJjcmVhdGlvbkRhdGUiOiIyMDE4LTA0LTE2VDEyOjA1OjUyLjQ2N1oiLCJ1cGRhdGVkQXQiOiIyMDE4LTA0LTE2VDEyOjA1OjUyLjQ2N1oiLCJ1c2VyR3JvdXBzIjpbeyJpZCI6MSwibmFtZSI6ImxvZ2dpbmciLCJjYW5DcmVhdGVVc2VycyI6bnVsbCwiY2FuRGVsZXRlVXNlcnMiOm51bGwsImNhbkVkaXRVc2VycyI6bnVsbCwiY2FuQ3JlYXRlUHJvamVjdHMiOm51bGwsImNhbkRlbGV0ZVByb2plY3RzIjpudWxsLCJjYW5FZGl0UHJvamVjdHMiOm51bGwsImNhbkFjY2Vzc0xvZ3MiOnRydWUsImlzSW50ZXJuYWwiOmZhbHNlLCJkZXNjcmlwdGlvbiI6IkFsbG93cyBQb3N0IHRvIExvZyIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6MX19LHsiaWQiOjIsIm5hbWUiOiJhZG1pbiIsImNhbkNyZWF0ZVVzZXJzIjp0cnVlLCJjYW5EZWxldGVVc2VycyI6dHJ1ZSwiY2FuRWRpdFVzZXJzIjp0cnVlLCJjYW5DcmVhdGVQcm9qZWN0cyI6dHJ1ZSwiY2FuRGVsZXRlUHJvamVjdHMiOnRydWUsImNhbkVkaXRQcm9qZWN0cyI6dHJ1ZSwiY2FuQWNjZXNzTG9ncyI6bnVsbCwiaXNJbnRlcm5hbCI6ZmFsc2UsImRlc2NyaXB0aW9uIjoiU3lzdGVtcyBhZG1pbiIsIlVzZXJIYXNQcml2aWxlZ2UiOnsidXNlcm5hbWUiOiJoYWZlZXoiLCJwcml2aWxlZ2VJZCI6Mn19XSwicHJvamVjdHMiOltdfSwiaWF0IjoxNTIzODgwMzU2LCJleHAiOjE1MjM5MDE5NTZ9.LrRWCzjBQmPtEkthmPJvVdl6XsYqA4Myqw-VFHMbQ8o", + "description": "" + }, + { + "key": "Content-Type", + "value": "image/png", + "description": "" + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "triangle", + "description": "", + "type": "file", + "src": "triangle_down_black.png" + } + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "/", + "request": { + "url": "{{host}}/", + "method": "GET", + "header": [], + "body": {}, + "description": "" + }, + "response": [] + } + ] + }, + { + "name": "/oauth/token", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "let res = JSON.parse(responseBody);", + "postman.setEnvironmentVariable(\"access_token\", res.access_token);", + "postman.setEnvironmentVariable(\"refresh_token\", res.refresh_token);" + ] + } + } + ], + "request": { + "url": "{{host}}/{{endpoint}}/oauth/token", + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "grant_type", + "value": "password", + "description": "", + "type": "text" + }, + { + "key": "username", + "value": "{{dummy_admin_username}}", + "description": "", + "type": "text" + }, + { + "key": "password", + "value": "{{dummy_admin_pass}}", + "description": "", + "type": "text" + } + ] + }, + "description": "wefrwrbjk;" + }, + "response": [] + } + ] +} \ No newline at end of file -- cgit v1.2.1 From c7874c8d2407fc7d046b6ba6856ebfdb46a30f37 Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 20:34:29 +0100 Subject: World War Files - ideas all there, but SQLize part still missing. --- src/FileRouter.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++------ src/files.ts | 7 +++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ca2ed50..df7ca94 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,7 +8,7 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { View, files, views, rootPathId, createProjectFolder } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -565,22 +565,56 @@ const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc */ -const postFilePath: Middleware = ( +/* tslint:disable */ +const postFilePath: Middleware = async( req: Request, res: Response, next: NextFunction -): void => { +): Promise => { logger.debug(`Receiving file to ${res.locals.parentFolder}`); - res.locals.modified = true; + if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } + + // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found + let remainingPath: string = res.locals.path.split(res.locals.deepestFolderName)[1]; + console.log(`remainingPath: ${remainingPath}`) + + while((remainingPath.match(/\//g) || []).length > 1){ + // If there are more subfolders that dont exist, then create them + const subFolder: string = remainingPath.split("/")[1] + logger.debug(`Adding subfolder \'${subFolder}`); + const dir: File = new File({ + uuid: uuid.generate(), + mimetype: 'inode/directory', + name: subFolder, + parentFolderId: res.locals.deepestFolderId + }); + await dir.save(); + + // update parent directory of new directory + addSubFileToFolder(res.locals.deepestFolderId, dir.id); + + // update vars + remainingPath = remainingPath.split(subFolder)[1] + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.id; + console.log(`\tremainingPath: ${remainingPath}`) + console.log(`\tdeepestFolderName: ${res.locals.deepestFolderName}`) + console.log(`\tdeepestFolderId: ${res.locals.deepestFolderId}`) + } + const file: File = new File({ uuid: uuid.generate(), name: res.locals.filename, - parentFolder: res.locals.parentFolder + parentFolder: res.locals.deepestFolderId }); + // update parent directory of new directory + addSubFileToFolder(res.locals.deepestFolderId, file.id); + // pipe the data req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; +/* tslint:enable */ export class FileRouter { public router: Router; @@ -679,8 +713,14 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - filename = filename.replace(/\+/g, "/"); // Replace + with / + // TODO \/ + // We need to find the res.locals.deepestFolderName (and Id) for the currently requested path + + // Replace + with / + filename = filename.replace(/\+/g, '/'); logger.debug(`Searching for file ${filename}`); + res.locals.path = filename; + const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; if (project == null) { diff --git a/src/files.ts b/src/files.ts index 42e490a..6572c53 100644 --- a/src/files.ts +++ b/src/files.ts @@ -208,3 +208,10 @@ export const createProjectFolder: (name: string) => void = (projName: string): a fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); } } + +export const addSubFileToFolder: (parentId: string, subFileId: string) => void = (parentId: string, subFileId: string): any => { + // TODO: + // fetch parent file object from database + // update parent file object + // save +} -- cgit v1.2.1 From 7905240ed1655f9db3f571976034e287d88e1315 Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 10:38:32 +0100 Subject: World War Files - changed precondition + filled addSubFileToFolder() function. Need to test tho --- src/FileRouter.ts | 79 +++++++++++++++++++++++++------------------------------ src/files.ts | 40 +++++++++++++++++----------- 2 files changed, 60 insertions(+), 59 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index df7ca94..4b56b19 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -13,9 +13,6 @@ import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; -// TODO: figure this out -const BASE_FILE_STORAGE: string = 'TODO: figure this out'; - /** * The type of an Express middleware callback. */ @@ -540,7 +537,6 @@ const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug(`Getting file in ${req.query.view} view`); - res.locals.modified = true; const file: File | null = res.locals.file; if (file == null) { return next(new RequestError(404, 'file_not_found')); @@ -566,9 +562,7 @@ const getFileId: Middleware = getFile; * Post a File. / delete / move / etc */ /* tslint:disable */ -const postFilePath: Middleware = async( - req: Request, res: Response, next: NextFunction -): Promise => { +const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { logger.debug(`Receiving file to ${res.locals.parentFolder}`); if (res.locals.file != null) { @@ -579,6 +573,7 @@ const postFilePath: Middleware = async( let remainingPath: string = res.locals.path.split(res.locals.deepestFolderName)[1]; console.log(`remainingPath: ${remainingPath}`) + // Loop the part of the path that doesn't exist yet and create all the folders while((remainingPath.match(/\//g) || []).length > 1){ // If there are more subfolders that dont exist, then create them const subFolder: string = remainingPath.split("/")[1] @@ -610,6 +605,8 @@ const postFilePath: Middleware = async( }); // update parent directory of new directory addSubFileToFolder(res.locals.deepestFolderId, file.id); + + // TODO respond to correct query params (like update metadata, move, etc) // pipe the data req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); @@ -721,59 +718,49 @@ export class FileRouter { logger.debug(`Searching for file ${filename}`); res.locals.path = filename; + // split path into parts const fileNames: string[] = req.params.path.split('/'); + res.locals.filename = fileNames[-1]; const project: Project | null = res.locals.project; if (project == null) { // Project should have been found by previous precondition logger.debug('Project was not found: skipping finding file'); return next(new RequestError(404, 'project_not_found')); } - let file: File = project.rootFolder; - // TODO Rewrite using sub-queries instead of repeated queries. - while (fileNames.length > 2) { + console.debug(fileNames); + + let curDir: File | null = project.rootFolder; + res.locals.deepestFolderId = curDir.id; + res.locals.deepestFolderName = curDir.name; + let i: number = 0; + + // Loop through the path and find the deepest folder that exists. Also find the file if possible. + while (curDir && i < fileNames.length) { const fileOrNull: File | null = await File.findOne({ include: [{all: true}], where: { - name: fileNames[0], - parentFolder: file + name: fileNames[i], + parentFolder: curDir } }); if (fileOrNull == null) { - console.log("fileOrNull was null") + console.log("next subdir not found in DB"); return next(); - } else { - console.log("^^") - console.log(file) - file = fileOrNull; + } + + if(i < fileNames.length-1){ + // Found next subdirectory + console.log(`found subdir ${fileOrNull.name}`); + res.locals.deepestFolderId = fileOrNull.id; + res.locals.deepestFolderName = fileOrNull.name; + }else{ + // Found actual file + console.log(`found file ${fileOrNull.name}`); + res.locals.file = fileOrNull; } - fileNames.splice(0, 1); + curDir = fileOrNull; } - if (file == null) { - console.log("file was null") - return next(); - } - console.log(file) - const parentFolder: File | null = await File.findOne({ - include: [ - { model: File, as: 'containedFilesInternal'} - ], - where: { - parentFolderId: file.id, - name: fileNames[0] - } - }); - console.log("parent folder: ") - console.log(parentFolder); - if (parentFolder == null) { - return next(); - } - res.locals.parentFolder = parentFolder; - const tFile: File | undefined = parentFolder.containedFiles.find( - (f: File): boolean => f.name === fileNames[1] - ); - res.locals.file = tFile; - res.locals.filename = fileNames[1]; next(); } ); @@ -793,6 +780,12 @@ export class FileRouter { } }); res.locals.file = file; + if(file) { + res.locals.filename = file.name; + res.locals.deepestFolderId = file.parentFolderId; + if(file.parentFolder) res.locals.deepestFolderName = file.parentFolder.name; + else console.log("parentfolder not set!") + } next(); } ); diff --git a/src/files.ts b/src/files.ts index 6572c53..a5fd08d 100644 --- a/src/files.ts +++ b/src/files.ts @@ -28,18 +28,6 @@ const readableStream: (filename: string, projectName: string, { offset, length } }; return fs.createReadStream(path(filename, projectName), options); }; -/* -// prj name, file uuid => if exists and return path string/ parent folder -const findParent: (projectName: string, fileUUID: string) => File | null = (projectName: string, fileUUID: string) => { - if(!projectName || !fileUUID){ - return null; - } - function findFile(dir: string, fileList: string[]) : string { - - } - -} -*/ const logPath: (type: string, projectName?: string) => string = ( type: string, projectName?: string): string => { @@ -209,9 +197,29 @@ export const createProjectFolder: (name: string) => void = (projName: string): a } } -export const addSubFileToFolder: (parentId: string, subFileId: string) => void = (parentId: string, subFileId: string): any => { - // TODO: - // fetch parent file object from database - // update parent file object +export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { + // Fetch parent and subFile object from database + const parent: File | null = await File.findOne({ + include: [{all: true}], + where: { + uuid: parentId + } + }); + const file: File | null = await File.findOne({ + include: [{all: true}], + where: { + uuid: subFileId + } + }); + if(!parent || !file){ + return false; + } + // update both objects + parent.containedFiles.push(file); + file.parentFolderId = parent.id; // save + await parent.save(); + await file.save(); + + return true; } -- cgit v1.2.1 From fb54545484732f149223a63d06eff4c7d98b8410 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Tue, 17 Apr 2018 17:39:56 +0100 Subject: Fix tests for matcher, and minor import edits --- src/matcher/index.ts | 1 + test/unit/options.unit.test.ts | 162 ++++++++++++++++++++++------------------- 2 files changed, 88 insertions(+), 75 deletions(-) diff --git a/src/matcher/index.ts b/src/matcher/index.ts index 99cc18c..0806907 100644 --- a/src/matcher/index.ts +++ b/src/matcher/index.ts @@ -10,6 +10,7 @@ export { export { Atom, + isPresent as anything, isNumber as number, isString as string, isBoolean as boolean, diff --git a/test/unit/options.unit.test.ts b/test/unit/options.unit.test.ts index fd88ca6..a442c38 100644 --- a/test/unit/options.unit.test.ts +++ b/test/unit/options.unit.test.ts @@ -10,8 +10,9 @@ import * as chai from 'chai'; chai.should(); -import * as options from '../../src/matcher/options'; -import { default as types } from '../../src/matcher/types'; +import { anything, boolean, not_present, number, string +} from '../../src/matcher'; +import { array, match, optional } from '../../src/matcher/options'; // tslint:disable-next-line:no-require-imports @@ -20,115 +21,115 @@ describe('Matching:', () => { context('for literals', () => { context('accepts matching', () => { it('strings', () => { - options.match('a', 'a').should.be.true; + match('a', 'a').should.be.true; }); it('numbers', () => { - options.match(3, 3).should.be.true; + match(3, 3).should.be.true; }); it('boolean values', () => { - options.match(true, true).should.be.true; + match(true, true).should.be.true; }); it('null to null', () => { - options.match(null, null).should.be.true; + match(null, null).should.be.true; }); }); context('rejects', () => { it('different strings', () => { - options.match('x', 'y').should.be.false; + match('x', 'y').should.be.false; }); it('different numbers', () => { - options.match(20, 42).should.be.false; + match(20, 42).should.be.false; }); it('different boolean values', () => { - options.match(true, false).should.be.false; + match(true, false).should.be.false; }); it('different types', () => { - options.match('55', 55).should.be.false; + match('55', 55).should.be.false; }); it('null matched with non-null values', () => { - options.match(null, false).should.be.false; + match(null, false).should.be.false; }); it('non-null values matched with null', () => { - options.match(0, null).should.be.false; + match(0, null).should.be.false; }); }); }); context('for checker functions', () => { context('accepts', () => { it('values that succeed the checker function', () => { - options.match(types.number, 9).should.be.true; + match(number, 9).should.be.true; }); }); context('rejects', () => { it('values that do not succeed the checker function', () => { - options.match(types.boolean, 'true').should.be.false; + match(boolean, 'true').should.be.false; }); }); }); it('accepts basic things', () => { const template = { - a: types.string + a: string }; const matchee = { a: 'yes' }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('accepts objects with superfluous properties', () => { const template = { - a: types.number + a: number }; const matchee = { a: 40, b: 20 }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('rejects objects missing some properties', () => { const template = { - a: types.boolean, - b: types.number, - c: types.number + a: boolean, + b: number, + c: number }; const matchee = { b: 5 }; - options.match(template, matchee).should.be.false; + match(template, matchee).should.be.false; }); it('accepts objects that omit not_present properties', () => { const template = { - a: types.number, - b: types.not_present, - c: types.not_present + a: number, + b: not_present, + c: not_present }; const matchee = { a: 4 }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('rejects empty objects for non-empty templates', () => { const template = { - a: types.boolean + a: boolean }; const matchee = { }; - options.match(template, matchee).should.be.false; + match(template, matchee).should.be.false; }); it('accepts empty objects for empty templates', () => { const template = { }; const matchee = { }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('accepts nested objects that match', () => { const template = { - a: types.number, + a: number, b: { - ba: types.string, - bb: types.string + ba: string, + bb: string }, - c: types.boolean + c: boolean }; const matchee = { a: 432, @@ -139,7 +140,7 @@ describe('Matching:', () => { c: true, x: false }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('accepts literal matches', () => { const template = { @@ -148,7 +149,7 @@ describe('Matching:', () => { const matchee = { a: 'literal' }; - options.match(template, matchee).should.be.true; + match(template, matchee).should.be.true; }); it('rejects incorrect literal matches', () => { const template = { @@ -157,65 +158,76 @@ describe('Matching:', () => { const matchee = { g: 80 }; - options.match(template, matchee).should.be.false; + match(template, matchee).should.be.false; }); it('accepts optional matches', () => { const template = { - a: options.optional(types.array), - b: options.optional(types.anything) + a: optional(number), + b: optional(anything) }; const matchee = { b: [] }; - options.match(template)(matchee).should.be.true; + match(template)(matchee).should.be.true; }); it('big bad unit test', () => { - /* tslint:disable:align */ - const matchee = { status: 'success', - data: [ { privilege: 'admin', description: 'null', internal: false }, - { privilege: 'logging', - description: 'Allows Post to Log', - internal: false } ] }; + const matchee = { + status: 'success', + data: [ + { + privilege: 'admin', + description: 'null', + internal: false + }, + { + privilege: 'logging', + description: 'Allows Post to Log', + internal: false + } + ] + }; const template = { - status: types.string, - data: options.optional(types.anything), - error: options.optional(types.string), - error_description: options.optional(types.string), - user_message: options.optional(types.string), - error_data: options.optional(types.anything) - }; - /* tslint:enable:align */ + status: string, + data: optional(anything), + error: optional(string), + error_description: optional(string), + user_message: optional(string), + error_data: optional(anything) + }; - options.match(template)(matchee).should.be.true; + match(template)(matchee).should.be.true; }); it('bigger badder unit test', () => { - /* tslint:disable:align */ - const matchee = [ { project_name: 'mocky', - users: [{ username: 'uname', access_level: 'admin'}], - public_metadata: { creation_date: '2018-04-14T17:13:44.291Z' }, + const matchee = [{ + project_name: 'mocky', + users: [{ + username: 'uname', + access_level: 'admin' + }], + public_metadata: { + creation_date: '2018-04-14T17:13:44.291Z' + }, private_metadata: {}, - admin_metadata: {} } ]; - const template = types.array({ - project_name: types.string, - users: types.array({ - username: types.string, - access_level: types.string + admin_metadata: {} + }]; + const template = array({ + project_name: string, + users: array({ + username: string, + access_level: string }), - public_metadata: types.anything, - private_metadata: options.optional(types.anything), - admin_metadata: options.optional(types.anything) + public_metadata: anything, + private_metadata: optional(anything), + admin_metadata: optional(anything) }); - /* tslint:enable:align */ - options.match(template)(matchee).should.be.true; + match(template)(matchee).should.be.true; }); - it.only('Matching Arrays', () => { - /* tslint:disable:align */ - const matchee: any = ['ss']; - const template: any = types.array; - /* tslint:enable:align */ + it('Matching Arrays', () => { + const matchee: string[] = ['ss']; + const template = array(string); - options.match(template)(matchee).should.be.true; + match(template)(matchee).should.be.true; }); }); }); -- cgit v1.2.1 From 8f1837af9400ef0ef5c1cab1e853b46e11b1b76b Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 18:43:06 +0100 Subject: Files - now actually works --- src/FileRouter.ts | 108 ++++++++++++++++++++++++++++++--------------------- src/db/model/File.ts | 14 ++++--- src/files.ts | 7 +++- 3 files changed, 78 insertions(+), 51 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4b56b19..ed6567c 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -495,18 +495,21 @@ const postProjectName: Middleware = async( const file: File = new File({ uuid: uuid.generate(), mimetype: 'inode/directory', - name: req.params.project_name, parentFolderId: rootPathId }); + file.name = ''; // Leave blank as discussed promise = file.save(); createProjectFolder(req.params.project_name); + project = new Project({ name: req.params.project_name, rootFolder: file }); + project.rootFolderId = file.uuid; } else { logger.debug('Updating project properties'); } + project.metadata = req.body; // tslint:disable-next-line:await-promise await promise; @@ -563,48 +566,57 @@ const getFileId: Middleware = getFile; */ /* tslint:disable */ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { - logger.debug(`Receiving file to ${res.locals.parentFolder}`); + logger.debug(`Receiving file ${res.locals.path}`); if (res.locals.file != null) { + // TODO update metadata or append to file next(new RequestError(400, 'file_exists')); } // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found - let remainingPath: string = res.locals.path.split(res.locals.deepestFolderName)[1]; - console.log(`remainingPath: ${remainingPath}`) + let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path + : res.locals.path.split(res.locals.deepestFolderName)[1]; // Loop the part of the path that doesn't exist yet and create all the folders while((remainingPath.match(/\//g) || []).length > 1){ // If there are more subfolders that dont exist, then create them const subFolder: string = remainingPath.split("/")[1] - logger.debug(`Adding subfolder \'${subFolder}`); + logger.debug(`Adding subfolder \'${subFolder}\'`); const dir: File = new File({ uuid: uuid.generate(), mimetype: 'inode/directory', - name: subFolder, - parentFolderId: res.locals.deepestFolderId + nameInternal: subFolder//, + //parentFolderId: res.locals.deepestFolderId }); await dir.save(); // update parent directory of new directory - addSubFileToFolder(res.locals.deepestFolderId, dir.id); - + if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ + logger.debug("adding file to folder failed!") + next(new RequestError(500, 'Adding file to folder failed')) + } // update vars remainingPath = remainingPath.split(subFolder)[1] res.locals.deepestFolderName = subFolder; - res.locals.deepestFolderId = dir.id; - console.log(`\tremainingPath: ${remainingPath}`) - console.log(`\tdeepestFolderName: ${res.locals.deepestFolderName}`) - console.log(`\tdeepestFolderId: ${res.locals.deepestFolderId}`) + res.locals.deepestFolderId = dir.uuid; } + logger.debug(`now adding the actual file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) + const file: File = new File({ uuid: uuid.generate(), - name: res.locals.filename, - parentFolder: res.locals.deepestFolderId + nameInternal: res.locals.filename//, + //parentFolder: res.locals.deepestFolderId }); + file.mimetype = req.headers['content-type']!; + + await file.save(); + // update parent directory of new directory - addSubFileToFolder(res.locals.deepestFolderId, file.id); + if(!await addSubFileToFolder(res.locals.deepestFolderId, file.uuid)){ + logger.debug("adding file to folder failed!") + next(new RequestError(500, 'Adding file to folder failed')) + } // TODO respond to correct query params (like update metadata, move, etc) // pipe the data @@ -710,55 +722,60 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - // TODO \/ - // We need to find the res.locals.deepestFolderName (and Id) for the currently requested path + // Vars we assign here: + // - res.locals.deepestFolderName (...Id): deepest existing folder in path + // - res.locals.path: requested path (using "/") + // - res.locals.filename: requested file name (may be '') + // - res.locals.file: actual file object if it exists + // Vars arleady assigned: + // - res.locals.project: requested project object // Replace + with / - filename = filename.replace(/\+/g, '/'); - logger.debug(`Searching for file ${filename}`); - res.locals.path = filename; - - // split path into parts - const fileNames: string[] = req.params.path.split('/'); - res.locals.filename = fileNames[-1]; + res.locals.path = filename.replace(/\+/g, '/'); + logger.debug(`Searching for path \'${res.locals.path}\'`); + // Split path into parts + const fileNames: string[] = res.locals.path.split('/'); + res.locals.filename = (fileNames.length > 0) ? + fileNames[fileNames.length - 1] : ''; + logger.debug(`Searching for file \'${res.locals.filename}\'`); const project: Project | null = res.locals.project; if (project == null) { // Project should have been found by previous precondition logger.debug('Project was not found: skipping finding file'); return next(new RequestError(404, 'project_not_found')); } - console.debug(fileNames); - let curDir: File | null = project.rootFolder; - res.locals.deepestFolderId = curDir.id; + res.locals.deepestFolderId = curDir.uuid; res.locals.deepestFolderName = curDir.name; let i: number = 0; - - // Loop through the path and find the deepest folder that exists. Also find the file if possible. + // Loop through the path and find the deepest folder that exists. + // Also find the file if possible. while (curDir && i < fileNames.length) { + logger.debug(`Searching for \'${fileNames[i]}\'`); const fileOrNull: File | null = await File.findOne({ include: [{all: true}], where: { - name: fileNames[i], - parentFolder: curDir + nameInternal: fileNames[i], + parentFolderId: curDir.uuid } }); if (fileOrNull == null) { - console.log("next subdir not found in DB"); + logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`); return next(); - } - - if(i < fileNames.length-1){ + } + + if (i < fileNames.length - 1) { // Found next subdirectory - console.log(`found subdir ${fileOrNull.name}`); - res.locals.deepestFolderId = fileOrNull.id; - res.locals.deepestFolderName = fileOrNull.name; - }else{ + logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`); + res.locals.deepestFolderId = fileOrNull.uuid; + res.locals.deepestFolderName = fileOrNull.name; + } else { // Found actual file - console.log(`found file ${fileOrNull.name}`); + logger.debug(`Found file \'${fileOrNull.name}\'`); res.locals.file = fileOrNull; } curDir = fileOrNull; + i++; } next(); @@ -772,7 +789,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - console.log(`parsing id ${fileId}`); + logger.info(`parsing id ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { @@ -783,8 +800,11 @@ export class FileRouter { if(file) { res.locals.filename = file.name; res.locals.deepestFolderId = file.parentFolderId; - if(file.parentFolder) res.locals.deepestFolderName = file.parentFolder.name; - else console.log("parentfolder not set!") + if (file.parentFolder) { + res.locals.deepestFolderName = file.parentFolder.name; + } else { + logger.debug('parentfolder not set!') + } } next(); } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 193a785..8a12431 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -27,7 +27,7 @@ import { FileTypeName, mimes } from '../../files'; export default class File extends Model { @AllowNull @Column - private nameInternal!: string; + public nameInternal!: string; @AllowNull @Column @@ -85,10 +85,14 @@ export default class File extends Model { public set name(name: string) { this.nameInternal = name; - this.fullPathInternal = this.fullPathInternal.substring( - 0, - this.fullPathInternal.lastIndexOf('/') + 1 - ) + this.name; + if (this.fullPathInternal) { + this.fullPathInternal = this.fullPathInternal.substring( + 0, + this.fullPathInternal.lastIndexOf('/') + 1 + ) + this.name; + } else { + this.fullPathInternal = this.name; + } } public get fullPath(): string { diff --git a/src/files.ts b/src/files.ts index a5fd08d..9be0381 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,11 +1,13 @@ import { Request, Response } from 'express'; import * as fs from 'fs'; +import { logger } from './logger'; import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; + /* tslint:disable */ const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; @@ -198,6 +200,7 @@ export const createProjectFolder: (name: string) => void = (projName: string): a } export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { + logger.debug(`adding file ${subFileId}) to directory ${parentId}`) // Fetch parent and subFile object from database const parent: File | null = await File.findOne({ include: [{all: true}], @@ -216,10 +219,10 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis } // update both objects parent.containedFiles.push(file); - file.parentFolderId = parent.id; + file.parentFolderId = parent.uuid; // save - await parent.save(); await file.save(); + await parent.save(); return true; } -- cgit v1.2.1 From 505ae2d6af5ce31360f0f0b018a75cfee59cf3ac Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 22:58:03 +0100 Subject: using multer for files now --- package.json | 46 +++- src/FileRouter.ts | 28 ++- src/files.ts | 20 +- yarn.lock | 673 +++++++++++++++++++----------------------------------- 4 files changed, 315 insertions(+), 452 deletions(-) diff --git a/package.json b/package.json index c187871..f26bbe9 100644 --- a/package.json +++ b/package.json @@ -48,8 +48,10 @@ "@types/colors": "^1.1.3", "@types/express": "^4.0.33", "@types/express-jwt": "^0.0.38", + "@types/fs-extra": "^5.0.2", "@types/jsonwebtoken": "^7.2.5", "@types/morgan": "^1.7.32", + "@types/multer": "^1.3.6", "@types/node": "^6.0.46", "@types/passport": "^0.4.2", "@types/passport-local": "^1.0.32", @@ -65,14 +67,16 @@ "express": "^4.16.2", "express-jwt": "^5.3.0", "file-system": "^2.2.2", + "fs-extra": "^5.0.0", "jsonwebtoken": "^8.1.1", "mocha-each": "^1.1.0", "morgan": "^1.9.0", + "multer": "^1.3.0", "passport": "^0.4.0", "passport-local": "^1.0.0", - "pg": "^7.4.1", - "pg-hstore": "^2.3.2", - "pg-native": "^2.2.0", + "pg": "^7.3.0", + "pg-hstore": "^2.3.1", + "pg-native": "^2.1.9", "pmx": "^1.6.4", "reflect-metadata": "^0.1.12", "sequelize": "^4.32.7", @@ -86,5 +90,41 @@ "winston": "^2.4.0", "xlsx": "^0.11.19", "xml-parser": "^1.2.1" + }, + "resolutions": { + "@types/node": "9.6.5", + "@types/lodash": "4.14.107", + "@types/bluebird": "3.5.20", + "debug": "2.6.9", + "depd": "1.1.2", + "http-errors": "1.6.3", + "iconv-lite": "0.4.19", + "ms": "2.0.0", + "setprototypeof": "1.1.0", + "statuses": "1.5.0", + "mime": "1.4.1", + "async": "1.5.2", + "sprintf-js": "1.1.1", + "pg-types": "1.12.0", + "semver": "4.3.2", + "readable-stream": "1.0.31", + "nan": "2.10.0", + "isarray": "0.0.1", + "string_decoder": "0.10.31", + "glob": "7.1.2", + "minimist": "1.2.0", + "pump": "2.0.1", + "superagent": "3.8.2", + "cookiejar": "2.1.1", + "form-data": "2.3.2", + "chalk": "2.4.0", + "diff": "3.5.0", + "ansi-styles": "3.2.1", + "supports-color": "5.4.0", + "has-flag": "3.0.0", + "source-map": "0.5.7", + "commander": "2.13.0", + "type-detect": "1.0.0", + "wordwrap": "0.0.3" } } diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ed6567c..8dc8468 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -6,13 +6,13 @@ import { UserFullInfo, default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; - import { RequestError } from './errors/errorware'; -import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, moveFile } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; + /** * The type of an Express middleware callback. */ @@ -567,6 +567,8 @@ const getFileId: Middleware = getFile; /* tslint:disable */ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { logger.debug(`Receiving file ${res.locals.path}`); + console.log(req.file); + // req.query.action if (res.locals.file != null) { // TODO update metadata or append to file @@ -605,10 +607,9 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu const file: File = new File({ uuid: uuid.generate(), - nameInternal: res.locals.filename//, - //parentFolder: res.locals.deepestFolderId + nameInternal: res.locals.filename }); - file.mimetype = req.headers['content-type']!; + file.mimetype = req.file.mimetype; await file.save(); @@ -618,9 +619,8 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu next(new RequestError(500, 'Adding file to folder failed')) } - // TODO respond to correct query params (like update metadata, move, etc) - // pipe the data - req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + // Move temp file to proper location + moveFile(req.file.originalname, res.locals.project.name, file.uuid); next(); }; /* tslint:enable */ @@ -665,7 +665,8 @@ export class FileRouter { this.router.get ('/projects/:project_name/properties', getProjectProperties); // File access this.router.get ('/projects/:project_name/files/:path', getFilePath); - this.router.post('/projects/:project_name/files/:path', postFilePath); + this.router.post('/projects/:project_name/files/:path', + upload.single('userfile'), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -730,6 +731,9 @@ export class FileRouter { // Vars arleady assigned: // - res.locals.project: requested project object + //console.log(`req.file.filename: ${req.file}`) + console.log(req.file) + // Replace + with / res.locals.path = filename.replace(/\+/g, '/'); logger.debug(`Searching for path \'${res.locals.path}\'`); @@ -748,7 +752,7 @@ export class FileRouter { res.locals.deepestFolderId = curDir.uuid; res.locals.deepestFolderName = curDir.name; let i: number = 0; - // Loop through the path and find the deepest folder that exists. + // Loop through the path and find the deepest folder that exists. // Also find the file if possible. while (curDir && i < fileNames.length) { logger.debug(`Searching for \'${fileNames[i]}\'`); @@ -797,13 +801,13 @@ export class FileRouter { } }); res.locals.file = file; - if(file) { + if (file) { res.locals.filename = file.name; res.locals.deepestFolderId = file.parentFolderId; if (file.parentFolder) { res.locals.deepestFolderName = file.parentFolder.name; } else { - logger.debug('parentfolder not set!') + logger.debug('parentfolder not set!'); } } next(); diff --git a/src/files.ts b/src/files.ts index 9be0381..b0e63aa 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,6 +1,7 @@ import { Request, Response } from 'express'; -import * as fs from 'fs'; +import * as fs from 'fs-extra'; import { logger } from './logger'; +import * as Multer from 'multer'; import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; @@ -38,6 +39,23 @@ const logPath: (type: string, projectName?: string) => string = ( : `${LOG_BASE_DIRECTORY}/general/${type}`; }; +let storage = Multer.diskStorage({ + destination: function (req, file, cb) { + cb(null, CONTENT_BASE_DIRECTORY) + }, + filename: function (req, file, cb) { + cb(null, `temp-${file.originalname}`) + } +}); + +export const upload: Multer.Instance = Multer({ storage: storage }); + +export const moveFile: (filename: string, projectname: string, fileId: string) => void = + (filename: string, projectname: string, fileId: string): void => { + + fs.moveSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`, `${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); +} + export const files: { path: (f: string, p: string) => string; writableStream: (f: string, p: string) => fs.WriteStream; diff --git a/yarn.lock b/yarn.lock index 7b18d1c..1a2cc9f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,14 +2,10 @@ # yarn lockfile v1 -"@types/bluebird@*": +"@types/bluebird@*", "@types/bluebird@3.5.18", "@types/bluebird@3.5.20": version "3.5.20" resolved "https://registry.yarnpkg.com/@types/bluebird/-/bluebird-3.5.20.tgz#f6363172add6f4eabb8cada53ca9af2781e8d6a1" -"@types/bluebird@3.5.18": - version "3.5.18" - resolved "https://registry.yarnpkg.com/@types/bluebird/-/bluebird-3.5.18.tgz#6a60435d4663e290f3709898a4f75014f279c4d6" - "@types/body-parser@*": version "1.16.8" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.16.8.tgz#687ec34140624a3bec2b1a8ea9268478ae8f3be3" @@ -39,8 +35,10 @@ resolved "https://registry.yarnpkg.com/@types/chai/-/chai-3.5.2.tgz#c11cd2817d3a401b7ba0f5a420f35c56139b1c1e" "@types/colors@^1.1.3": - version "1.1.3" - resolved "https://registry.yarnpkg.com/@types/colors/-/colors-1.1.3.tgz#5413b0a7a1b16dd18be0e3fd57d2feecc81cc776" + version "1.2.1" + resolved "https://registry.yarnpkg.com/@types/colors/-/colors-1.2.1.tgz#57703f1a9f7f5fc40afb81eef13e96acdd1016a6" + dependencies: + colors "*" "@types/continuation-local-storage@*": version "3.2.1" @@ -90,6 +88,12 @@ dependencies: "@types/node" "*" +"@types/fs-extra@^5.0.2": + version "5.0.2" + resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-5.0.2.tgz#235a7e2b56452cc0a6a4809b53e1d1eaffff9c96" + dependencies: + "@types/node" "*" + "@types/geojson@^1.0.0": version "1.0.6" resolved "https://registry.yarnpkg.com/@types/geojson/-/geojson-1.0.6.tgz#3e02972728c69248c2af08d60a48cbb8680fffdf" @@ -111,18 +115,14 @@ resolved "https://registry.yarnpkg.com/@types/highlight.js/-/highlight.js-9.12.2.tgz#6ee7cd395effe5ec80b515d3ff1699068cd0cd1d" "@types/jsonwebtoken@^7.2.5": - version "7.2.5" - resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-7.2.5.tgz#413159d570ec45fc3e7da7ea3f7bca6fb9300e72" + version "7.2.6" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-7.2.6.tgz#8d018c21ca5910b5eb3ebcb385656606a215032f" dependencies: "@types/node" "*" -"@types/lodash@*": - version "4.14.104" - resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.104.tgz#53ee2357fa2e6e68379341d92eb2ecea4b11bb80" - -"@types/lodash@4.14.99": - version "4.14.99" - resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.99.tgz#e6e10c0a4cc16c7409b3181f1e66880d2fb7d4dc" +"@types/lodash@*", "@types/lodash@4.14.107", "@types/lodash@4.14.99": + version "4.14.107" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.107.tgz#b2d2ae3958bfb8ff828495cbe12214af9e4d035e" "@types/marked@0.3.0": version "0.3.0" @@ -142,7 +142,11 @@ dependencies: "@types/mocha" "*" -"@types/mocha@*", "@types/mocha@^2.2.32": +"@types/mocha@*": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-5.0.0.tgz#a3014921991066193f6c8e47290d4d598dfd19e6" + +"@types/mocha@^2.2.32": version "2.2.48" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-2.2.48.tgz#3523b126a0b049482e1c3c11877460f76622ffab" @@ -152,36 +156,38 @@ dependencies: "@types/express" "*" -"@types/node@*": - version "9.4.6" - resolved "https://registry.yarnpkg.com/@types/node/-/node-9.4.6.tgz#d8176d864ee48753d053783e4e463aec86b8d82e" +"@types/multer@^1.3.6": + version "1.3.6" + resolved "https://registry.yarnpkg.com/@types/multer/-/multer-1.3.6.tgz#e00454074bf9fd86d20ea652eba9850eb76604c4" + dependencies: + "@types/express" "*" -"@types/node@6.0.41": - version "6.0.41" - resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.41.tgz#578cf53aaec65887bcaf16792f8722932e8ff8ea" +"@types/node@*", "@types/node@6.0.41", "@types/node@9.6.5": + version "9.6.5" + resolved "https://registry.yarnpkg.com/@types/node/-/node-9.6.5.tgz#ee700810fdf49ac1c399fc5980b7559b3e5a381d" "@types/node@^6.0.46": - version "6.0.101" - resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.101.tgz#0c5911cfb434af4a51c0a499931fe6423207d921" + version "6.0.106" + resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.106.tgz#391bc3598ab5823563f7155847212152893edcd7" "@types/passport-local@^1.0.32": - version "1.0.32" - resolved "https://registry.yarnpkg.com/@types/passport-local/-/passport-local-1.0.32.tgz#0856e3772c46ab8ac89aacf5535fa001a2ce5a13" + version "1.0.33" + resolved "https://registry.yarnpkg.com/@types/passport-local/-/passport-local-1.0.33.tgz#d245b60c5b801cb3aeca1ffab557d5fe1534260d" dependencies: "@types/express" "*" "@types/passport" "*" "@types/passport-strategy" "*" "@types/passport-strategy@*": - version "0.2.32" - resolved "https://registry.yarnpkg.com/@types/passport-strategy/-/passport-strategy-0.2.32.tgz#0c1fb2e3b83621c8faf68c92f37898453ef60f71" + version "0.2.33" + resolved "https://registry.yarnpkg.com/@types/passport-strategy/-/passport-strategy-0.2.33.tgz#a523c6526262f96d9e4063d9285721551d87889b" dependencies: "@types/express" "*" "@types/passport" "*" "@types/passport@*", "@types/passport@^0.4.2": - version "0.4.3" - resolved "https://registry.yarnpkg.com/@types/passport/-/passport-0.4.3.tgz#ca4f9611fb67d0c5d581a9005e9b89a2f5e91a3a" + version "0.4.4" + resolved "https://registry.yarnpkg.com/@types/passport/-/passport-0.4.4.tgz#934acc2b8870fdde1800f48effd92cbf5c2646f5" dependencies: "@types/express" "*" @@ -199,8 +205,8 @@ "@types/validator" "*" "@types/sequelize@^4.27.5": - version "4.27.8" - resolved "https://registry.yarnpkg.com/@types/sequelize/-/sequelize-4.27.8.tgz#432eca1a5acd9ea40a49cc947676fe918aca17ec" + version "4.27.14" + resolved "https://registry.yarnpkg.com/@types/sequelize/-/sequelize-4.27.14.tgz#621dcc33db884e1fca368dc1b9fa7a60b38785d3" dependencies: "@types/bluebird" "*" "@types/continuation-local-storage" "*" @@ -215,8 +221,8 @@ "@types/mime" "*" "@types/sharp@^0.17.6": - version "0.17.6" - resolved "https://registry.yarnpkg.com/@types/sharp/-/sharp-0.17.6.tgz#3138602163b30b4969f75a2755a3f90caaaa9be3" + version "0.17.8" + resolved "https://registry.yarnpkg.com/@types/sharp/-/sharp-0.17.8.tgz#0d02f36030549ccd29f31c1badd06c15a4e998ef" dependencies: "@types/node" "*" @@ -228,14 +234,15 @@ "@types/node" "*" "@types/sqlite3@^3.1.1": - version "3.1.1" - resolved "https://registry.yarnpkg.com/@types/sqlite3/-/sqlite3-3.1.1.tgz#f9b707c574e8d2f73d6c41aaa86e28b6ef85a324" + version "3.1.3" + resolved "https://registry.yarnpkg.com/@types/sqlite3/-/sqlite3-3.1.3.tgz#580d547203b8ad6e11aa6a6769c8ca5d7e197d13" dependencies: + "@types/events" "*" "@types/node" "*" "@types/superagent@*": - version "3.5.7" - resolved "https://registry.yarnpkg.com/@types/superagent/-/superagent-3.5.7.tgz#c170633e7dff01425b4712bb3afac3a12be49b7b" + version "3.5.8" + resolved "https://registry.yarnpkg.com/@types/superagent/-/superagent-3.5.8.tgz#da2b5d6a5bc77b4bf1b6d082ec4c3328ba5c3b9f" dependencies: "@types/node" "*" @@ -256,8 +263,8 @@ resolved "https://registry.yarnpkg.com/@types/validator/-/validator-9.4.0.tgz#a4a80a31d3e4e094806ec446557808423379858d" "@types/winston@^2.3.8": - version "2.3.8" - resolved "https://registry.yarnpkg.com/@types/winston/-/winston-2.3.8.tgz#88964f45ecb5ed1feb4bfb38a24316bee8bf8768" + version "2.3.9" + resolved "https://registry.yarnpkg.com/@types/winston/-/winston-2.3.9.tgz#1ff9f1bb57952fe3d88c1b21c4899ede316a35bc" dependencies: "@types/node" "*" @@ -269,7 +276,7 @@ abbrev@1: version "1.1.1" resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" -accepts@~1.3.4: +accepts@~1.3.5: version "1.3.5" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.5.tgz#eb777df6011723a3b14e8a72c0805c8e86746bd2" dependencies: @@ -291,24 +298,24 @@ align-text@^0.1.1, align-text@^0.1.3: longest "^1.0.1" repeat-string "^1.5.2" -amdefine@>=0.0.4: - version "1.0.1" - resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" - ansi-regex@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - -ansi-styles@^3.2.1: +ansi-styles@3.2.1, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" dependencies: color-convert "^1.9.0" +ap@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/ap/-/ap-0.2.0.tgz#ae0942600b29912f0d2b14ec60c45e8f330b6110" + +append-field@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/append-field/-/append-field-0.1.0.tgz#6ddc58fa083c7bc545d3c5995b2830cc2366d44a" + aproba@^1.0.3: version "1.2.0" resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" @@ -345,14 +352,10 @@ async-listener@^0.6.0: semver "^5.3.0" shimmer "^1.1.0" -async@^1.4.0, async@^1.5.0, async@^1.5.2: +async@1.5.2, async@^1.4.0, async@^1.5.0, async@~1.0.0: version "1.5.2" resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" -async@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/async/-/async-1.0.0.tgz#f8fc04ca3a13784ade9e1641af98578cfbd647a9" - asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" @@ -384,10 +387,11 @@ bindings@1.2.1: resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.2.1.tgz#14ad6113812d2d37d72e67b4cacb4bb726505f11" bl@^1.0.0: - version "1.2.1" - resolved "https://registry.yarnpkg.com/bl/-/bl-1.2.1.tgz#cac328f7bee45730d404b692203fcb590e172d5e" + version "1.2.2" + resolved "https://registry.yarnpkg.com/bl/-/bl-1.2.2.tgz#a160911717103c07410cef63ef51b397c025af9c" dependencies: - readable-stream "^2.0.5" + readable-stream "^2.3.5" + safe-buffer "^5.1.1" bluebird@^3.4.6, bluebird@^3.5.0: version "3.5.1" @@ -423,6 +427,10 @@ buffer-equal-constant-time@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" +buffer-from@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.0.0.tgz#4cb8832d23612589b0406e9e2956c17f06fdf531" + buffer-writer@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-writer/-/buffer-writer-1.0.1.tgz#22a936901e3029afcd7547eb4487ceb697a3bf08" @@ -431,6 +439,13 @@ builtin-modules@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" +busboy@^0.2.11: + version "0.2.14" + resolved "https://registry.yarnpkg.com/busboy/-/busboy-0.2.14.tgz#6c2a622efcf47c57bbbe1e2a9c37ad36c7925453" + dependencies: + dicer "0.2.5" + readable-stream "1.1.x" + bytes@3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048" @@ -447,8 +462,8 @@ center-align@^0.1.1: lazy-cache "^1.0.3" cfb@~1.0.2: - version "1.0.5" - resolved "https://registry.yarnpkg.com/cfb/-/cfb-1.0.5.tgz#5f7cf2fcb385dd41db271cf1f28a83fcd705bf06" + version "1.0.6" + resolved "https://registry.yarnpkg.com/cfb/-/cfb-1.0.6.tgz#d0107fa579a8d79c53a31074a755abcb898017f0" dependencies: commander "^2.14.1" printj "~1.1.2" @@ -471,19 +486,9 @@ chai@^3.5.0: deep-eql "^0.1.3" type-detect "^1.0.0" -chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -chalk@^2.0.0, chalk@^2.3.0: - version "2.3.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.2.tgz#250dc96b07491bfd601e648d66ddf5f60c7a5c65" +chalk@2.4.0, chalk@^1.1.3, chalk@^2.0.0, chalk@^2.3.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.0.tgz#a060a297a6b57e15b61ca63ce84995daa0fe6e52" dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" @@ -543,31 +548,21 @@ color@^3.0.0: color-convert "^1.9.1" color-string "^1.5.2" +colors@*, colors@^1.1.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.2.1.tgz#f4a3d302976aaf042356ba1ade3b1a2c62d9d794" + colors@1.0.x: version "1.0.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" -colors@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" - -combined-stream@1.0.6, combined-stream@^1.0.5: +combined-stream@1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818" dependencies: delayed-stream "~1.0.0" -commander@2.9.0: - version "2.9.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.9.0.tgz#9c99094176e12240cb22d6c5146098400fe0f7d4" - dependencies: - graceful-readlink ">= 1.0.0" - -commander@^2.12.1, commander@^2.14.1, commander@~2.14.1: - version "2.14.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.14.1.tgz#2235123e37af8ca3c65df45b026dbd357b01b9aa" - -commander@~2.13.0: +commander@2.13.0, commander@2.9.0, commander@^2.12.1, commander@^2.14.1, commander@~2.13.0, commander@~2.14.1: version "2.13.0" resolved "https://registry.yarnpkg.com/commander/-/commander-2.13.0.tgz#6964bca67685df7c1f1430c584f07d7597885b9c" @@ -579,6 +574,15 @@ concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" +concat-stream@^1.5.0: + version "1.6.2" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" + dependencies: + buffer-from "^1.0.0" + inherits "^2.0.3" + readable-stream "^2.2.2" + typedarray "^0.0.6" + console-control-strings@^1.0.0, console-control-strings@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" @@ -606,11 +610,7 @@ cookie@0.3.1: version "0.3.1" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb" -cookiejar@2.0.x: - version "2.0.6" - resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.0.6.tgz#0abf356ad00d1c5a219d88d44518046dd026acfe" - -cookiejar@^2.0.6, cookiejar@^2.1.0: +cookiejar@2.0.x, cookiejar@2.1.1, cookiejar@^2.1.0: version "2.1.1" resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.1.tgz#41ad57b1b555951ec171412a81942b1e8200d34a" @@ -629,24 +629,12 @@ cycle@1.0.x: version "1.0.3" resolved "https://registry.yarnpkg.com/cycle/-/cycle-1.0.3.tgz#21e80b2be8580f98b468f379430662b046c34ad2" -debug@2.6.8: - version "2.6.8" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.8.tgz#e731531ca2ede27d188222427da17821d68ff4fc" - dependencies: - ms "2.0.0" - -debug@2.6.9, debug@^2.1.2, debug@^2.2.0, debug@^2.6.3, debug@^2.6.9: +debug@2.6.8, debug@2.6.9, debug@^2.1.2, debug@^2.2.0, debug@^2.6.3, debug@^2.6.9, debug@^3, debug@^3.1.0: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" dependencies: ms "2.0.0" -debug@^3, debug@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" - dependencies: - ms "2.0.0" - decamelize@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" @@ -681,11 +669,7 @@ delegates@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" -depd@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.1.tgz#5783b4e1c459f06fa5ca27f991f3d06e7a310359" - -depd@^1.1.0, depd@~1.1.1: +depd@1.1.2, depd@^1.1.0, depd@~1.1.1, depd@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" @@ -697,11 +681,14 @@ detect-libc@^1.0.2, detect-libc@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" -diff@3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/diff/-/diff-3.2.0.tgz#c9ce393a4b7cbd0b058a725c93df299027868ff9" +dicer@0.2.5: + version "0.2.5" + resolved "https://registry.yarnpkg.com/dicer/-/dicer-0.2.5.tgz#5996c086bb33218c812c090bddc09cd12facb70f" + dependencies: + readable-stream "1.1.x" + streamsearch "0.1.2" -diff@^3.1.0, diff@^3.2.0: +diff@3.2.0, diff@3.5.0, diff@^3.1.0, diff@^3.2.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" @@ -726,7 +713,7 @@ emitter-listener@^1.1.1: dependencies: shimmer "^1.2.0" -encodeurl@~1.0.1: +encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" @@ -744,7 +731,7 @@ escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" -escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: +escape-string-regexp@1.0.5, escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" @@ -769,12 +756,12 @@ expand-template@^1.0.2: resolved "https://registry.yarnpkg.com/expand-template/-/expand-template-1.1.0.tgz#e09efba977bf98f9ee0ed25abd0c692e02aec3fc" express-jwt@^5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/express-jwt/-/express-jwt-5.3.0.tgz#3d90cd65802e6336252f19e6a3df3e149e0c5ea0" + version "5.3.1" + resolved "https://registry.yarnpkg.com/express-jwt/-/express-jwt-5.3.1.tgz#66f05c7dddb5409c037346a98b88965bb10ea4ae" dependencies: async "^1.5.0" express-unless "^0.3.0" - jsonwebtoken "^7.3.0" + jsonwebtoken "^8.1.0" lodash.set "^4.0.0" express-unless@^0.3.0: @@ -782,10 +769,10 @@ express-unless@^0.3.0: resolved "https://registry.yarnpkg.com/express-unless/-/express-unless-0.3.1.tgz#2557c146e75beb903e2d247f9b5ba01452696e20" express@^4.16.2: - version "4.16.2" - resolved "https://registry.yarnpkg.com/express/-/express-4.16.2.tgz#e35c6dfe2d64b7dca0a5cd4f21781be3299e076c" + version "4.16.3" + resolved "https://registry.yarnpkg.com/express/-/express-4.16.3.tgz#6af8a502350db3246ecc4becf6b5a34d22f7ed53" dependencies: - accepts "~1.3.4" + accepts "~1.3.5" array-flatten "1.1.1" body-parser "1.18.2" content-disposition "0.5.2" @@ -793,26 +780,26 @@ express@^4.16.2: cookie "0.3.1" cookie-signature "1.0.6" debug "2.6.9" - depd "~1.1.1" - encodeurl "~1.0.1" + depd "~1.1.2" + encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" - finalhandler "1.1.0" + finalhandler "1.1.1" fresh "0.5.2" merge-descriptors "1.0.1" methods "~1.1.2" on-finished "~2.3.0" parseurl "~1.3.2" path-to-regexp "0.1.7" - proxy-addr "~2.0.2" + proxy-addr "~2.0.3" qs "6.5.1" range-parser "~1.2.0" safe-buffer "5.1.1" - send "0.16.1" - serve-static "1.13.1" + send "0.16.2" + serve-static "1.13.2" setprototypeof "1.1.0" - statuses "~1.3.1" - type-is "~1.6.15" + statuses "~1.4.0" + type-is "~1.6.16" utils-merge "1.0.1" vary "~1.1.2" @@ -837,27 +824,19 @@ file-system@^2.2.2: file-match "^1.0.1" utils-extend "^1.0.4" -finalhandler@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.0.tgz#ce0b6855b45853e791b2fcc680046d88253dd7f5" +finalhandler@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.1.tgz#eebf4ed840079c83f4249038c9d703008301b105" dependencies: debug "2.6.9" - encodeurl "~1.0.1" + encodeurl "~1.0.2" escape-html "~1.0.3" on-finished "~2.3.0" parseurl "~1.3.2" - statuses "~1.3.1" + statuses "~1.4.0" unpipe "~1.0.0" -form-data@1.0.0-rc4: - version "1.0.0-rc4" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-1.0.0-rc4.tgz#05ac6bc22227b43e4461f488161554699d4f8b5e" - dependencies: - async "^1.5.2" - combined-stream "^1.0.5" - mime-types "^2.1.10" - -form-data@^2.3.1: +form-data@2.3.2, form-data@^2.3.1: version "2.3.2" resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099" dependencies: @@ -865,9 +844,9 @@ form-data@^2.3.1: combined-stream "1.0.6" mime-types "^2.1.12" -formidable@^1.0.17, formidable@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/formidable/-/formidable-1.2.0.tgz#ce291bfec67c176e282f891ece2c37de0c83ae84" +formidable@^1.1.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/formidable/-/formidable-1.2.1.tgz#70fb7ca0290ee6ff961090415f4b3df3d2082659" forwarded@~0.1.2: version "0.1.2" @@ -893,7 +872,7 @@ fs-extra@^5.0.0: jsonfile "^4.0.0" universalify "^0.1.0" -fs-minipass@^1.2.3, fs-minipass@^1.2.5: +fs-minipass@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-1.2.5.tgz#06c277218454ec288df77ada54a03b8702aacb9d" dependencies: @@ -924,18 +903,7 @@ github-from-package@0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" -glob@7.1.1: - version "7.1.1" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.2" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@7.1.2, glob@^7.0.0, glob@^7.0.5, glob@^7.1.1: +glob@7.1.1, glob@7.1.2, glob@^7.0.0, glob@^7.0.5, glob@^7.1.1: version "7.1.2" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" dependencies: @@ -950,10 +918,6 @@ graceful-fs@^4.1.2, graceful-fs@^4.1.6: version "4.1.11" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" -"graceful-readlink@>= 1.0.0": - version "1.0.1" - resolved "https://registry.yarnpkg.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz#4cafad76bc62f02fa039b2f94e9a3dd3a391a725" - growl@1.9.2: version "1.9.2" resolved "https://registry.yarnpkg.com/growl/-/growl-1.9.2.tgz#0ea7743715db8d8de2c5ede1775e1b45ac85c02f" @@ -968,17 +932,7 @@ handlebars@^4.0.6: optionalDependencies: uglify-js "^2.6" -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - dependencies: - ansi-regex "^2.0.0" - -has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - -has-flag@^3.0.0: +has-flag@3.0.0, has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" @@ -994,24 +948,20 @@ highlight.js@^9.0.0: version "9.12.0" resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.12.0.tgz#e6d9dbe57cbefe60751f02af336195870c90c01e" -hoek@2.x.x: - version "2.16.3" - resolved "https://registry.yarnpkg.com/hoek/-/hoek-2.16.3.tgz#20bb7403d3cea398e91dc4710a8ff1b8274a25ed" - homedir-polyfill@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.1.tgz#4c2bbc8a758998feebf5ed68580f76d46768b4bc" dependencies: parse-passwd "^1.0.0" -http-errors@1.6.2, http-errors@~1.6.2: - version "1.6.2" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.2.tgz#0a002cc85707192a7e7946ceedc11155f60ec736" +http-errors@1.6.2, http-errors@1.6.3, http-errors@~1.6.2: + version "1.6.3" + resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d" dependencies: - depd "1.1.1" + depd "~1.1.2" inherits "2.0.3" - setprototypeof "1.0.3" - statuses ">= 1.3.1 < 2" + setprototypeof "1.1.0" + statuses ">= 1.4.0 < 2" iconv-lite@0.4.19, iconv-lite@^0.4.4: version "0.4.19" @@ -1034,7 +984,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@2.0.3, inherits@~2.0.1, inherits@~2.0.3: +inherits@2, inherits@2.0.3, inherits@^2.0.3, inherits@~2.0.1: version "2.0.3" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" @@ -1086,27 +1036,10 @@ isarray@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" -isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - -isemail@1.x.x: - version "1.2.0" - resolved "https://registry.yarnpkg.com/isemail/-/isemail-1.2.0.tgz#be03df8cc3e29de4d2c5df6501263f1fa4595e9a" - isstream@0.1.x: version "0.1.2" resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" -joi@^6.10.1: - version "6.10.1" - resolved "https://registry.yarnpkg.com/joi/-/joi-6.10.1.tgz#4d50c318079122000fe5f16af1ff8e1917b77e06" - dependencies: - hoek "2.x.x" - isemail "1.x.x" - moment "2.x.x" - topo "1.x.x" - js-string-escape@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/js-string-escape/-/js-string-escape-1.0.1.tgz#e2625badbc0d67c7533e9edc1068c587ae4137ef" @@ -1136,19 +1069,9 @@ jsonfile@^4.0.0: optionalDependencies: graceful-fs "^4.1.6" -jsonwebtoken@^7.3.0: - version "7.4.3" - resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-7.4.3.tgz#77f5021de058b605a1783fa1283e99812e645638" - dependencies: - joi "^6.10.1" - jws "^3.1.4" - lodash.once "^4.0.0" - ms "^2.0.0" - xtend "^4.0.1" - -jsonwebtoken@^8.1.1: - version "8.2.0" - resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.2.0.tgz#690ec3a9e7e95e2884347ce3e9eb9d389aa598b3" +jsonwebtoken@^8.1.0, jsonwebtoken@^8.1.1: + version "8.2.1" + resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.2.1.tgz#333ee39aa8f238f32fa41693e7a2fb7e42f82b31" dependencies: jws "^3.1.4" lodash.includes "^4.3.0" @@ -1299,8 +1222,8 @@ make-error@^1.1.1: resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.4.tgz#19978ed575f9e9545d2ff8c13e33b5d18a67d535" marked@^0.3.12: - version "0.3.17" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.17.tgz#607f06668b3c6b1246b28f13da76116ac1aa2d2b" + version "0.3.19" + resolved "https://registry.yarnpkg.com/marked/-/marked-0.3.19.tgz#5d47f709c4c9fc3c216b6d46127280f40b39d790" media-typer@0.3.0: version "0.3.0" @@ -1318,42 +1241,30 @@ mime-db@~1.33.0: version "1.33.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db" -mime-types@^2.1.10, mime-types@^2.1.12, mime-types@~2.1.18: +mime-types@^2.1.12, mime-types@~2.1.18: version "2.1.18" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8" dependencies: mime-db "~1.33.0" -mime@1.4.1: +mime@1.4.1, mime@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6" -mime@^1.3.4, mime@^1.4.1: - version "1.6.0" - resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" - mimic-response@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.0.tgz#df3d3652a73fded6b9b0b24146e6fd052353458e" -minimatch@^3.0.0, minimatch@^3.0.2, minimatch@^3.0.4: +minimatch@^3.0.0, minimatch@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" dependencies: brace-expansion "^1.1.7" -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - -minimist@^1.2.0: +minimist@0.0.8, minimist@1.2.0, minimist@^1.2.0, minimist@~0.0.1: version "1.2.0" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" -minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - minipass@^2.2.1, minipass@^2.2.4: version "2.2.4" resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.2.4.tgz#03c824d84551ec38a8d1bb5bc350a5a30a354a40" @@ -1397,14 +1308,14 @@ mocha@^3.1.2: supports-color "3.1.2" moment-timezone@^0.5.14: - version "0.5.14" - resolved "https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.5.14.tgz#4eb38ff9538b80108ba467a458f3ed4268ccfcb1" + version "0.5.15" + resolved "https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.5.15.tgz#0e2acec4a424850b4e0e3e08984532726563ad4c" dependencies: moment ">= 2.9.0" -moment@2.x.x, "moment@>= 2.9.0", moment@^2.20.0: - version "2.21.0" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.21.0.tgz#2a114b51d2a6ec9e6d83cf803f838a878d8a023a" +"moment@>= 2.9.0", moment@^2.20.0: + version "2.22.1" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.22.1.tgz#529a2e9bf973f259c9643d237fda84de3a26e8ad" morgan@^1.9.0: version "1.9.0" @@ -1416,21 +1327,26 @@ morgan@^1.9.0: on-finished "~2.3.0" on-headers "~1.0.1" -ms@2.0.0: +ms@2.0.0, ms@^2.1.1: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" -ms@^2.0.0, ms@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a" - -nan@^2.3.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.8.0.tgz#ed715f3fe9de02b57a5e6252d90a96675e1f085a" +multer@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/multer/-/multer-1.3.0.tgz#092b2670f6846fa4914965efc8cf94c20fec6cd2" + dependencies: + append-field "^0.1.0" + busboy "^0.2.11" + concat-stream "^1.5.0" + mkdirp "^0.5.1" + object-assign "^3.0.0" + on-finished "^2.3.0" + type-is "^1.6.4" + xtend "^4.0.0" -nan@^2.9.2, nan@~2.9.2: - version "2.9.2" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.9.2.tgz#f564d75f5f8f36a6d9456cca7a6c4fe488ab7866" +nan@2.10.0, nan@^2.10.0, nan@^2.3.0, nan@~2.9.2: + version "2.10.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.10.0.tgz#96d0cd610ebd58d4b4de9cc0c6828cda99c7548f" needle@^2.2.0: version "2.2.0" @@ -1451,8 +1367,8 @@ node-abi@^2.2.0: semver "^5.4.1" node-pre-gyp@~0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.9.0.tgz#bdd4c3afac9b1b1ebff0a9ff3362859eb6781bb8" + version "0.9.1" + resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.9.1.tgz#f11c07516dd92f87199dbc7e1838eab7cd56c9e0" dependencies: detect-libc "^1.0.2" mkdirp "^0.5.1" @@ -1500,11 +1416,15 @@ number-is-nan@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" +object-assign@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-3.0.0.tgz#9bedd5ca0897949bca47e7ff408062d549f587f2" + object-assign@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" -on-finished@~2.3.0: +on-finished@^2.3.0, on-finished@~2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947" dependencies: @@ -1591,17 +1511,13 @@ pg-connection-string@0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/pg-connection-string/-/pg-connection-string-0.1.3.tgz#da1847b20940e42ee1492beaf65d49d91b245df7" -pg-hstore@^2.3.2: +pg-hstore@^2.3.1: version "2.3.2" resolved "https://registry.yarnpkg.com/pg-hstore/-/pg-hstore-2.3.2.tgz#f7ef053e7b9b892ae986af2f7cbe86432dfcf24f" dependencies: underscore "^1.7.0" -pg-int8@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/pg-int8/-/pg-int8-1.0.1.tgz#943bd463bf5b71b4170115f80f8efc9a0c0eb78c" - -pg-native@^2.2.0: +pg-native@^2.1.9: version "2.2.0" resolved "https://registry.yarnpkg.com/pg-native/-/pg-native-2.2.0.tgz#bc84756f4ecbf600ff7cb48ea5854141830cf1e4" dependencies: @@ -1613,26 +1529,17 @@ pg-pool@~2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/pg-pool/-/pg-pool-2.0.3.tgz#c022032c8949f312a4f91fb6409ce04076be3257" -pg-types@^1.12.1: - version "1.13.0" - resolved "https://registry.yarnpkg.com/pg-types/-/pg-types-1.13.0.tgz#75f490b8a8abf75f1386ef5ec4455ecf6b345c63" - dependencies: - pg-int8 "1.0.1" - postgres-array "~1.0.0" - postgres-bytea "~1.0.0" - postgres-date "~1.0.0" - postgres-interval "^1.1.0" - -pg-types@~1.12.1: - version "1.12.1" - resolved "https://registry.yarnpkg.com/pg-types/-/pg-types-1.12.1.tgz#d64087e3903b58ffaad279e7595c52208a14c3d2" +pg-types@1.12.0, pg-types@^1.12.1, pg-types@~1.12.1: + version "1.12.0" + resolved "https://registry.yarnpkg.com/pg-types/-/pg-types-1.12.0.tgz#8ad3b7b897e3fd463e62de241ad5fc640b4a66f0" dependencies: + ap "~0.2.0" postgres-array "~1.0.0" postgres-bytea "~1.0.0" postgres-date "~1.0.0" postgres-interval "^1.1.0" -pg@^7.4.1: +pg@^7.3.0: version "7.4.1" resolved "https://registry.yarnpkg.com/pg/-/pg-7.4.1.tgz#f3411c8ddf9f692322fe05e7017a1888e47f78f1" dependencies: @@ -1680,8 +1587,8 @@ postgres-interval@^1.1.0: xtend "^4.0.0" prebuild-install@^2.5.1: - version "2.5.1" - resolved "https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-2.5.1.tgz#0f234140a73760813657c413cdccdda58296b1da" + version "2.5.3" + resolved "https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-2.5.3.tgz#9f65f242782d370296353710e9bc843490c19f69" dependencies: detect-libc "^1.0.3" expand-template "^1.0.2" @@ -1703,36 +1610,25 @@ printj@~1.1.0, printj@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/printj/-/printj-1.1.2.tgz#d90deb2975a8b9f600fb3a1c94e3f4c53c78a222" -process-nextick-args@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" - progress@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.0.tgz#8a1be366bf8fc23db2bd23f10c6fe920b4389d1f" -proxy-addr@~2.0.2: +proxy-addr@~2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.3.tgz#355f262505a621646b3130a728eb647e22055341" dependencies: forwarded "~0.1.2" ipaddr.js "1.6.0" -pump@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/pump/-/pump-1.0.3.tgz#5dfe8311c33bbf6fc18261f9f34702c47c08a954" - dependencies: - end-of-stream "^1.1.0" - once "^1.3.1" - -pump@^2.0.1: +pump@2.0.1, pump@^1.0.0, pump@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz#12399add6e4cf7526d973cbc8b5ce2e2908b3909" dependencies: end-of-stream "^1.1.0" once "^1.3.1" -qs@6.5.1, qs@^6.1.0, qs@^6.2.0, qs@^6.5.1: +qs@6.5.1, qs@^6.2.0, qs@^6.5.1: version "6.5.1" resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" @@ -1749,16 +1645,7 @@ raw-body@2.3.2: iconv-lite "0.4.19" unpipe "1.0.0" -rc@^1.1.6: - version "1.2.5" - resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.5.tgz#275cd687f6e3b36cc756baa26dfee80a790301fd" - dependencies: - deep-extend "~0.4.0" - ini "~1.3.0" - minimist "^1.2.0" - strip-json-comments "~2.0.1" - -rc@^1.1.7: +rc@^1.1.6, rc@^1.1.7: version "1.2.6" resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.6.tgz#eb18989c6d4f4f162c399f79ddd29f3835568092" dependencies: @@ -1767,7 +1654,7 @@ rc@^1.1.7: minimist "^1.2.0" strip-json-comments "~2.0.1" -readable-stream@1.0.31: +readable-stream@1.0.31, readable-stream@1.1.x, readable-stream@^2.0.0, readable-stream@^2.0.5, readable-stream@^2.0.6, readable-stream@^2.2.2, readable-stream@^2.3.5: version "1.0.31" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.31.tgz#8f2502e0bc9e3b0da1b94520aabb4e2603ecafae" dependencies: @@ -1776,18 +1663,6 @@ readable-stream@1.0.31: isarray "0.0.1" string_decoder "~0.10.x" -readable-stream@^2.0.0, readable-stream@^2.0.5, readable-stream@^2.0.6: - version "2.3.5" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.5.tgz#b4f85003a938cbb6ecbce2a124fb1012bd1a838d" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~2.0.0" - safe-buffer "~5.1.1" - string_decoder "~1.0.3" - util-deprecate "~1.0.1" - rechoir@^0.6.2: version "0.6.2" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" @@ -1803,8 +1678,8 @@ repeat-string@^1.5.2: resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" resolve@^1.1.6, resolve@^1.3.2: - version "1.5.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.5.0.tgz#1f09acce796c9a762579f31b2c1cc4c3cddf9f36" + version "1.7.1" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.7.1.tgz#aadd656374fd298aee895bc026b8297418677fd3" dependencies: path-parse "^1.0.5" @@ -1827,7 +1702,7 @@ rimraf@^2.6.1: dependencies: glob "^7.0.5" -safe-buffer@5.1.1, safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: +safe-buffer@5.1.1, safe-buffer@^5.0.1, safe-buffer@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" @@ -1835,22 +1710,18 @@ sax@^1.2.4: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" -semver@4.3.2: +semver@4.3.2, semver@5.*, semver@^5.0.1, semver@^5.3.0, semver@^5.4.1, semver@^5.5.0: version "4.3.2" resolved "https://registry.yarnpkg.com/semver/-/semver-4.3.2.tgz#c7a07158a80bedd052355b770d82d6640f803be7" -semver@5.*, semver@^5.0.1, semver@^5.3.0, semver@^5.4.1, semver@^5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab" - -send@0.16.1: - version "0.16.1" - resolved "https://registry.yarnpkg.com/send/-/send-0.16.1.tgz#a70e1ca21d1382c11d0d9f6231deb281080d7ab3" +send@0.16.2: + version "0.16.2" + resolved "https://registry.yarnpkg.com/send/-/send-0.16.2.tgz#6ecca1e0f8c156d141597559848df64730a6bbc1" dependencies: debug "2.6.9" - depd "~1.1.1" + depd "~1.1.2" destroy "~1.0.4" - encodeurl "~1.0.1" + encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" fresh "0.5.2" @@ -1859,7 +1730,7 @@ send@0.16.1: ms "2.0.0" on-finished "~2.3.0" range-parser "~1.2.0" - statuses "~1.3.1" + statuses "~1.4.0" sequelize-typescript@^0.6.2: version "0.6.3" @@ -1873,8 +1744,8 @@ sequelize-typescript@^0.6.2: glob "7.1.2" sequelize@^4.32.7: - version "4.35.2" - resolved "https://registry.yarnpkg.com/sequelize/-/sequelize-4.35.2.tgz#936db62c0bb63368bdb33ae58e76282aae5ec360" + version "4.37.6" + resolved "https://registry.yarnpkg.com/sequelize/-/sequelize-4.37.6.tgz#f37eec55a285cfdeab27f8a85c5db38034f87126" dependencies: bluebird "^3.5.0" cls-bluebird "^2.1.0" @@ -1894,35 +1765,31 @@ sequelize@^4.32.7: validator "^9.4.1" wkx "^0.4.1" -serve-static@1.13.1: - version "1.13.1" - resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.13.1.tgz#4c57d53404a761d8f2e7c1e8a18a47dbf278a719" +serve-static@1.13.2: + version "1.13.2" + resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.13.2.tgz#095e8472fd5b46237db50ce486a43f4b86c6cec1" dependencies: - encodeurl "~1.0.1" + encodeurl "~1.0.2" escape-html "~1.0.3" parseurl "~1.3.2" - send "0.16.1" + send "0.16.2" set-blocking@~2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" -setprototypeof@1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.0.3.tgz#66567e37043eeb4f04d91bd658c0cbefb55b8e04" - setprototypeof@1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656" sharp@^0.20.0: - version "0.20.0" - resolved "https://registry.yarnpkg.com/sharp/-/sharp-0.20.0.tgz#2ff9f1ae11f068ce7d7591f531cad52c7821d033" + version "0.20.1" + resolved "https://registry.yarnpkg.com/sharp/-/sharp-0.20.1.tgz#13adde896bc9ec0372b0907554e0329f35a7bce6" dependencies: color "^3.0.0" detect-libc "^1.0.3" fs-copy-file-sync "^1.0.1" - nan "^2.9.2" + nan "^2.10.0" npmlog "^4.1.2" prebuild-install "^2.5.1" semver "^5.5.0" @@ -1970,13 +1837,7 @@ source-map-support@^0.4.0: dependencies: source-map "^0.5.6" -source-map@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" - dependencies: - amdefine ">=0.0.4" - -source-map@^0.5.6, source-map@~0.5.1: +source-map@0.5.7, source-map@^0.4.4, source-map@^0.5.6, source-map@~0.5.1: version "0.5.7" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" @@ -1986,14 +1847,10 @@ split@^1.0.0: dependencies: through "2" -sprintf-js@^1.0.3: +sprintf-js@1.1.1, sprintf-js@^1.0.3, sprintf-js@~1.0.2: version "1.1.1" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.1.tgz#36be78320afe5801f6cea3ee78b6e5aab940ea0c" -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - sqlite3@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-4.0.0.tgz#cc0e093ab51873f50d9dfc4126fcbef15d486570" @@ -2011,13 +1868,13 @@ stack-trace@0.0.x: version "0.0.10" resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" -"statuses@>= 1.3.1 < 2": - version "1.4.0" - resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.4.0.tgz#bb73d446da2796106efcc1b601a253d6c46bd087" +statuses@1.5.0, "statuses@>= 1.4.0 < 2", statuses@~1.4.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" -statuses@~1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.3.1.tgz#faf51b9eb74aaef3b3acf4ad5f61abf24cb7b93e" +streamsearch@0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/streamsearch/-/streamsearch-0.1.2.tgz#808b9d0e56fc273d809ba57338e929919a1a9f1a" string-width@^1.0.1, string-width@^1.0.2: version "1.0.2" @@ -2027,16 +1884,10 @@ string-width@^1.0.1, string-width@^1.0.2: is-fullwidth-code-point "^1.0.0" strip-ansi "^3.0.0" -string_decoder@~0.10.x: +string_decoder@0.10.31, string_decoder@~0.10.x: version "0.10.31" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" -string_decoder@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" - dependencies: - safe-buffer "~5.1.0" - strip-ansi@^3.0.0, strip-ansi@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" @@ -2051,22 +1902,7 @@ strip-json-comments@^2.0.0, strip-json-comments@~2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" -superagent@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/superagent/-/superagent-2.3.0.tgz#703529a0714e57e123959ddefbce193b2e50d115" - dependencies: - component-emitter "^1.2.0" - cookiejar "^2.0.6" - debug "^2.2.0" - extend "^3.0.0" - form-data "1.0.0-rc4" - formidable "^1.0.17" - methods "^1.1.1" - mime "^1.3.4" - qs "^6.1.0" - readable-stream "^2.0.5" - -superagent@^3.0.0: +superagent@3.8.2, superagent@^2.0.0, superagent@^3.0.0: version "3.8.2" resolved "https://registry.yarnpkg.com/superagent/-/superagent-3.8.2.tgz#e4a11b9d047f7d3efeb3bbe536d9ec0021d16403" dependencies: @@ -2088,19 +1924,9 @@ supertest@^3.0.0: methods "~1.1.2" superagent "^3.0.0" -supports-color@3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.1.2.tgz#72a262894d9d408b956ca05ff37b2ed8a6e2a2d5" - dependencies: - has-flag "^1.0.0" - -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - -supports-color@^5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.3.0.tgz#5b24ac15db80fa927cf5227a4a33fd3c4c7676c0" +supports-color@3.1.2, supports-color@5.4.0, supports-color@^5.3.0: + version "5.4.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.4.0.tgz#1c6b337402c2137605efe19f10fec390f6faab54" dependencies: has-flag "^3.0.0" @@ -2122,7 +1948,7 @@ tar-stream@^1.1.2: readable-stream "^2.0.0" xtend "^4.0.0" -tar@^4: +tar@^4, tar@^4.4.0: version "4.4.1" resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.1.tgz#b25d5a8470c976fd7a9a8a350f42c59e9fa81749" dependencies: @@ -2134,17 +1960,6 @@ tar@^4: safe-buffer "^5.1.1" yallist "^3.0.2" -tar@^4.4.0: - version "4.4.0" - resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.0.tgz#3aaf8c29b6b800a8215f33efb4df1c95ce2ac2f5" - dependencies: - chownr "^1.0.1" - fs-minipass "^1.2.3" - minipass "^2.2.1" - minizlib "^1.1.0" - mkdirp "^0.5.0" - yallist "^3.0.2" - terraformer-wkt-parser@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/terraformer-wkt-parser/-/terraformer-wkt-parser-1.1.2.tgz#336a0c8fc82094a5aff83288f69aedecd369bf0c" @@ -2161,12 +1976,6 @@ through@2: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" -topo@1.x.x: - version "1.1.0" - resolved "https://registry.yarnpkg.com/topo/-/topo-1.1.0.tgz#e9d751615d1bb87dc865db182fa1ca0a5ef536d5" - dependencies: - hoek "2.x.x" - toposort-class@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toposort-class/-/toposort-class-1.0.1.tgz#7ffd1f78c8be28c3ba45cd4e1a3f5ee193bd9988" @@ -2215,8 +2024,8 @@ tslint@^5.9.1: tsutils "^2.12.1" tsutils@^2.12.1: - version "2.22.2" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.22.2.tgz#0b9f3d87aa3eb95bd32d26ce2b88aa329a657951" + version "2.26.1" + resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.26.1.tgz#9e4a0cb9ff173863f34c22a961969081270d1878" dependencies: tslib "^1.8.1" @@ -2226,21 +2035,21 @@ tunnel-agent@^0.6.0: dependencies: safe-buffer "^5.0.1" -type-detect@0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-0.1.1.tgz#0ba5ec2a885640e470ea4e8505971900dac58822" - -type-detect@^1.0.0: +type-detect@0.1.1, type-detect@1.0.0, type-detect@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-1.0.0.tgz#762217cc06db258ec48908a1298e8b95121e8ea2" -type-is@~1.6.15: +type-is@^1.6.4, type-is@~1.6.15, type-is@~1.6.16: version "1.6.16" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.16.tgz#f89ce341541c672b25ee7ae3c73dee3b2be50194" dependencies: media-typer "0.3.0" mime-types "~2.1.18" +typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + typedoc-default-themes@^0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/typedoc-default-themes/-/typedoc-default-themes-0.5.0.tgz#6dc2433e78ed8bea8e887a3acde2f31785bd6227" @@ -2272,8 +2081,8 @@ typescript@2.7.1: resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.7.1.tgz#bb3682c2c791ac90e7c6210b26478a8da085c359" typescript@^2.7.1: - version "2.7.2" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.7.2.tgz#2d615a1ef4aee4f574425cdff7026edf81919836" + version "2.8.1" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.8.1.tgz#6160e4f8f195d5ba81d4876f9c0cc1fbc0820624" uglify-js@^2.6: version "2.8.29" @@ -2300,10 +2109,6 @@ unpipe@1.0.0, unpipe@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" -util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - utils-extend@^1.0.4, utils-extend@^1.0.6: version "1.0.8" resolved "https://registry.yarnpkg.com/utils-extend/-/utils-extend-1.0.8.tgz#ccfd7b64540f8e90ee21eec57769d0651cab8a5f" @@ -2361,8 +2166,8 @@ window-size@0.1.0: resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" winston@^2.4.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/winston/-/winston-2.4.0.tgz#808050b93d52661ed9fb6c26b3f0c826708b0aee" + version "2.4.1" + resolved "https://registry.yarnpkg.com/winston/-/winston-2.4.1.tgz#a3a9265105564263c6785b4583b8c8aca26fded6" dependencies: async "~1.0.0" colors "1.0.x" @@ -2377,11 +2182,7 @@ wkx@^0.4.1: dependencies: "@types/node" "*" -wordwrap@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" - -wordwrap@~0.0.2: +wordwrap@0.0.2, wordwrap@0.0.3, wordwrap@~0.0.2: version "0.0.3" resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" -- cgit v1.2.1 From f37c8433ea3bca786898c46c03b86557fa0b6bb3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Wed, 18 Apr 2018 16:50:30 +0100 Subject: POST file parameters maybe working --- res/file_upload.ods | Bin 0 -> 14061 bytes src/FileRouter.ts | 177 ++++++++++++++++++++++++++++++++++++++++------------ src/files.ts | 26 +++++++- 3 files changed, 160 insertions(+), 43 deletions(-) create mode 100644 res/file_upload.ods diff --git a/res/file_upload.ods b/res/file_upload.ods new file mode 100644 index 0000000..d20cffe Binary files /dev/null and b/res/file_upload.ods differ diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 8dc8468..3796544 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -7,7 +7,7 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, moveFile } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, deleteFile, truncateFile, saveFile } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -546,7 +546,9 @@ const getFile: Middleware = async( } const project: Project = res.locals.project; const view: View = views[req.query.view || 'meta']; - res.locals.function = view.getResponseFunction(req, res); + // TODO return 400 for unsuported views + // TODO raw view accepts extra query params offset and length + res.locals.function = view.getResponseFunction(req, res); res.locals.data = view.getResponseData(file, project, req.query); next(); }; @@ -561,6 +563,42 @@ const getFilePath: Middleware = getFile; */ const getFileId: Middleware = getFile; +namespace qH { + export const hasAction: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action ? true : false); + } + export const setsMetadata: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'set_metadata' ? true : false); + } + export const mksDir: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'mkdir' ? true : false); + } + export const deletes: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'delete' ? true : false); + } + export const moves: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'move' ? true : false); + } + export const copys: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'copy' ? true : false); + } + export const overwrites: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.overwrite ? req.query.overwrite : false); + } + export const offset: ((req: Request) => number) = (req: Request): number => { + return (req.query.offset ? req.query.offset : 0); + } + export const truncates: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.truncate ? req.query.truncate : false); + } + export const isFinal: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.final ? req.query.final : false); + } + export const nothingSet: ((req: Request) => boolean) = (req: Request): boolean => { + return (!hasAction(req) && !overwrites(req) && !truncates(req) && !isFinal(req)); + } +} + /** * Post a File. / delete / move / etc */ @@ -568,60 +606,119 @@ const getFileId: Middleware = getFile; const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { logger.debug(`Receiving file ${res.locals.path}`); console.log(req.file); - // req.query.action + // req.query.action: set_metadata, mkdir, delete, move, copy + // req.query.overwrite (bool) + // req.query.offset (int) + // req.query.truncate (bool) + // req.query.final (bool) + + // Return 404 when one of these actions is attempted on non-existing file + if (res.locals.file == null && (qH.setsMetadata(req) || qH.deletes(req) || qH.moves(req) || qH.copys(req))){ + logger.debug(`Action \'${req.query.action}\' not valid if file does not exist`); + next(new RequestError(404, 'file_not_found')); + } - if (res.locals.file != null) { - // TODO update metadata or append to file + // Return 400 when one of these actions is attempted on existing file + if (res.locals.file != null && (qH.nothingSet(req) || qH.mksDir(req))) { + logger.debug(`Action \'${req.query.action}\' not valid if file exists`); next(new RequestError(400, 'file_exists')); } - // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found - let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path - : res.locals.path.split(res.locals.deepestFolderName)[1]; - - // Loop the part of the path that doesn't exist yet and create all the folders - while((remainingPath.match(/\//g) || []).length > 1){ - // If there are more subfolders that dont exist, then create them - const subFolder: string = remainingPath.split("/")[1] - logger.debug(`Adding subfolder \'${subFolder}\'`); - const dir: File = new File({ + // Sets final if requested + if (res.locals.file && qH.isFinal(req)) { + res.locals.file.status = 'final'; + } + + // Sets Metadata if requested + if(qH.setsMetadata(req)){ + res.locals.file.metadata = req.body; + await res.locals.file.save(); + next(); + } + + // Deletes File if requested + if(qH.deletes(req)){ + deleteFile(res.locals.file.uuid, res.locals.project.name); + await res.locals.file.delete(); + next(); + } + + // Moves File if requested + if(qH.moves(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Copies File if requested + if(qH.copys(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Overwrite data but not truncate + // eg. OOOONNNNNNOOOO (O = old data, N = new data) + if(qH.overwrites(req) && !qH.truncates(req)){ + // TODO + next(new RequestError(500, 'not_implemented', 'please specify truncate parameter')); + } + + // Create File or Folder if file doesn't exist + if (res.locals.file == null){ + // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found + let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path + : res.locals.path.split(res.locals.deepestFolderName)[1]; + + // Loop the part of the path that doesn't exist yet and create all the folders + while((remainingPath.match(/\//g) || []).length > 1){ + // If there are more subfolders that dont exist, then create them + const subFolder: string = remainingPath.split("/")[1] + logger.debug(`Adding subfolder \'${subFolder}\'`); + const dir: File = new File({ + uuid: uuid.generate(), + mimetype: 'inode/directory', + nameInternal: subFolder + }); + await dir.save(); + + // update parent directory of new directory + if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ + logger.debug("adding file to folder failed!") + next(new RequestError(500, 'Adding file to folder failed')) + } + // update vars + remainingPath = remainingPath.split(subFolder)[1] + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.uuid; + } + + logger.debug(`Writing file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) + res.locals.file = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory', - nameInternal: subFolder//, - //parentFolderId: res.locals.deepestFolderId + nameInternal: res.locals.filename }); - await dir.save(); + res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype; + + await res.locals.file.save(); // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ + if(!await addSubFileToFolder(res.locals.deepestFolderId, res.locals.file.uuid)){ logger.debug("adding file to folder failed!") next(new RequestError(500, 'Adding file to folder failed')) } - // update vars - remainingPath = remainingPath.split(subFolder)[1] - res.locals.deepestFolderName = subFolder; - res.locals.deepestFolderId = dir.uuid; } - logger.debug(`now adding the actual file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) - - const file: File = new File({ - uuid: uuid.generate(), - nameInternal: res.locals.filename - }); - file.mimetype = req.file.mimetype; - - await file.save(); - - // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, file.uuid)){ - logger.debug("adding file to folder failed!") - next(new RequestError(500, 'Adding file to folder failed')) + // Move temp file to proper location (if not directory) + if(!qH.mksDir(req)){ + saveFile(req.file.originalname, res.locals.project.name, res.locals.file.uuid, qH.offset(req)); } - // Move temp file to proper location - moveFile(req.file.originalname, res.locals.project.name, file.uuid); + // Sets final if requested + if (qH.isFinal(req)) { + res.locals.file.status = 'final'; + } + next(); + }; /* tslint:enable */ diff --git a/src/files.ts b/src/files.ts index b0e63aa..92ed165 100644 --- a/src/files.ts +++ b/src/files.ts @@ -50,10 +50,30 @@ let storage = Multer.diskStorage({ export const upload: Multer.Instance = Multer({ storage: storage }); -export const moveFile: (filename: string, projectname: string, fileId: string) => void = - (filename: string, projectname: string, fileId: string): void => { +export const saveFile: (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean) => void = + (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean): void => { + // TODO only overwrite beginning of file and keep rest of data + // ensure file exists + fs.ensureFileSync(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + // truncate to offset + truncateFile(fileId, projectname, offset); + // open streams to append to file + let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + let wStream = fs.createWriteStream(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`, {'flags':'a'}); + rStream.pipe(wStream); +} + +export const deleteFile: (fileId: string, projectName: string) => void = + (fileId: string, projectName: string): void => { - fs.moveSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`, `${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + fs.removeSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); +} + +export const truncateFile: (fileId: string, projectName: string, newLength: number) => void = + (fileId: string, projectName: string, newLength: number): void => { + // get the file descriptor of the file to be truncated + const fd: number = fs.openSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`, 'r+'); + fs.ftruncateSync(fd, newLength); } export const files: { -- cgit v1.2.1 From b9cb14f9368e281ab01d92cc8864cdcb4a0cb386 Mon Sep 17 00:00:00 2001 From: jw255 Date: Thu, 19 Apr 2018 11:08:40 +0100 Subject: minor fixes --- src/FileRouter.ts | 6 +++++- src/files.ts | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 3796544..70d3d51 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -563,6 +563,9 @@ const getFilePath: Middleware = getFile; */ const getFileId: Middleware = getFile; +/** + * Checks the parameters for file posting + */ namespace qH { export const hasAction: ((req: Request) => boolean) = (req: Request): boolean => { return (req.query.action ? true : false); @@ -638,8 +641,9 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu // Deletes File if requested if(qH.deletes(req)){ + logger.info(`File ${res.locals.file.name} will be deleted`) deleteFile(res.locals.file.uuid, res.locals.project.name); - await res.locals.file.delete(); + await res.locals.file.destroy(); next(); } diff --git a/src/files.ts b/src/files.ts index 92ed165..1b8a652 100644 --- a/src/files.ts +++ b/src/files.ts @@ -60,7 +60,11 @@ export const saveFile: (filename: string, projectname: string, fileId: string, o // open streams to append to file let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); let wStream = fs.createWriteStream(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`, {'flags':'a'}); - rStream.pipe(wStream); + rStream.pipe(wStream).on('finish', () => { + fs.removeSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + }).on('error', (err: any) => { + logger.debug(`Error while saving file to proper location: ${err}`); + }); } export const deleteFile: (fileId: string, projectName: string) => void = -- cgit v1.2.1 From 8af06a4e7ea7ebaa29559a345d28791079b77dd3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Thu, 19 Apr 2018 14:21:38 +0100 Subject: no reset --- iris.csv | 151 +++++++++++++++++ report/deliverable-3.zip | Bin 0 -> 6265275 bytes report/deliverable-3/Makefile | 9 ++ report/deliverable-3/appendix/minutes.tex | 68 ++++++++ report/deliverable-3/appendix/scrumboard.tex | 8 + report/deliverable-3/biblio.bib | 189 ++++++++++++++++++++++ report/deliverable-3/graphics/1.png | Bin 0 -> 23078 bytes report/deliverable-3/graphics/2.png | Bin 0 -> 76186 bytes report/deliverable-3/graphics/3.png | Bin 0 -> 37309 bytes report/deliverable-3/graphics/4.png | Bin 0 -> 17337 bytes report/deliverable-3/graphics/5.png | Bin 0 -> 21343 bytes report/deliverable-3/graphics/6.png | Bin 0 -> 28793 bytes report/deliverable-3/graphics/7.png | Bin 0 -> 30848 bytes report/deliverable-3/graphics/burndown.png | Bin 0 -> 21982 bytes report/deliverable-3/graphics/km-dash.png | Bin 0 -> 97345 bytes report/deliverable-3/graphics/scrum.jpg | Bin 0 -> 1829499 bytes report/deliverable-3/graphics/scrum2.jpg | Bin 0 -> 1746169 bytes report/deliverable-3/graphics/scrum3.jpg | Bin 0 -> 1830134 bytes report/deliverable-3/graphics/scrum4.jpg | Bin 0 -> 164302 bytes report/deliverable-3/graphics/scrum5.jpg | Bin 0 -> 152855 bytes report/deliverable-3/graphics/title-logo.png | Bin 0 -> 220102 bytes report/deliverable-3/main.tex | 38 +++++ report/deliverable-3/preamble.tex | 13 ++ report/deliverable-3/texts/aims.tex | 7 + report/deliverable-3/texts/conclusion.tex | 5 + report/deliverable-3/texts/conversion.tex | 135 ++++++++++++++++ report/deliverable-3/texts/logging.tex | 38 +++++ report/deliverable-3/texts/minutes.tex | 72 +++++++++ report/deliverable-3/texts/process-management.tex | 56 +++++++ report/deliverable-3/texts/scrum.tex | 17 ++ report/deliverable-3/texts/testing.tex | 15 ++ report/deliverable-3/texts/typings.tex | 27 ++++ report/deliverable-3/title.tex | 15 ++ src/FileRouter.ts | 5 +- src/files.ts | 2 +- src/index.ts | 25 +-- 36 files changed, 880 insertions(+), 15 deletions(-) create mode 100644 iris.csv create mode 100644 report/deliverable-3.zip create mode 100644 report/deliverable-3/Makefile create mode 100644 report/deliverable-3/appendix/minutes.tex create mode 100644 report/deliverable-3/appendix/scrumboard.tex create mode 100644 report/deliverable-3/biblio.bib create mode 100644 report/deliverable-3/graphics/1.png create mode 100644 report/deliverable-3/graphics/2.png create mode 100644 report/deliverable-3/graphics/3.png create mode 100644 report/deliverable-3/graphics/4.png create mode 100644 report/deliverable-3/graphics/5.png create mode 100644 report/deliverable-3/graphics/6.png create mode 100644 report/deliverable-3/graphics/7.png create mode 100644 report/deliverable-3/graphics/burndown.png create mode 100644 report/deliverable-3/graphics/km-dash.png create mode 100644 report/deliverable-3/graphics/scrum.jpg create mode 100644 report/deliverable-3/graphics/scrum2.jpg create mode 100644 report/deliverable-3/graphics/scrum3.jpg create mode 100644 report/deliverable-3/graphics/scrum4.jpg create mode 100644 report/deliverable-3/graphics/scrum5.jpg create mode 100644 report/deliverable-3/graphics/title-logo.png create mode 100644 report/deliverable-3/main.tex create mode 100644 report/deliverable-3/preamble.tex create mode 100644 report/deliverable-3/texts/aims.tex create mode 100644 report/deliverable-3/texts/conclusion.tex create mode 100644 report/deliverable-3/texts/conversion.tex create mode 100644 report/deliverable-3/texts/logging.tex create mode 100644 report/deliverable-3/texts/minutes.tex create mode 100644 report/deliverable-3/texts/process-management.tex create mode 100644 report/deliverable-3/texts/scrum.tex create mode 100644 report/deliverable-3/texts/testing.tex create mode 100644 report/deliverable-3/texts/typings.tex create mode 100644 report/deliverable-3/title.tex diff --git a/iris.csv b/iris.csv new file mode 100644 index 0000000..6464198 --- /dev/null +++ b/iris.csv @@ -0,0 +1,151 @@ +sepal_length,sepal_width,petal_length,petal_width,species +5.1,3.5,1.4,0.2,setosa +4.9,3,1.4,0.2,setosa +4.7,3.2,1.3,0.2,setosa +4.6,3.1,1.5,0.2,setosa +5,3.6,1.4,0.2,setosa +5.4,3.9,1.7,0.4,setosa +4.6,3.4,1.4,0.3,setosa +5,3.4,1.5,0.2,setosa +4.4,2.9,1.4,0.2,setosa +4.9,3.1,1.5,0.1,setosa +5.4,3.7,1.5,0.2,setosa +4.8,3.4,1.6,0.2,setosa +4.8,3,1.4,0.1,setosa +4.3,3,1.1,0.1,setosa +5.8,4,1.2,0.2,setosa +5.7,4.4,1.5,0.4,setosa +5.4,3.9,1.3,0.4,setosa +5.1,3.5,1.4,0.3,setosa +5.7,3.8,1.7,0.3,setosa +5.1,3.8,1.5,0.3,setosa +5.4,3.4,1.7,0.2,setosa +5.1,3.7,1.5,0.4,setosa +4.6,3.6,1,0.2,setosa +5.1,3.3,1.7,0.5,setosa +4.8,3.4,1.9,0.2,setosa +5,3,1.6,0.2,setosa +5,3.4,1.6,0.4,setosa +5.2,3.5,1.5,0.2,setosa +5.2,3.4,1.4,0.2,setosa +4.7,3.2,1.6,0.2,setosa +4.8,3.1,1.6,0.2,setosa +5.4,3.4,1.5,0.4,setosa +5.2,4.1,1.5,0.1,setosa +5.5,4.2,1.4,0.2,setosa +4.9,3.1,1.5,0.1,setosa +5,3.2,1.2,0.2,setosa +5.5,3.5,1.3,0.2,setosa +4.9,3.1,1.5,0.1,setosa +4.4,3,1.3,0.2,setosa +5.1,3.4,1.5,0.2,setosa +5,3.5,1.3,0.3,setosa +4.5,2.3,1.3,0.3,setosa +4.4,3.2,1.3,0.2,setosa +5,3.5,1.6,0.6,setosa +5.1,3.8,1.9,0.4,setosa +4.8,3,1.4,0.3,setosa +5.1,3.8,1.6,0.2,setosa +4.6,3.2,1.4,0.2,setosa +5.3,3.7,1.5,0.2,setosa +5,3.3,1.4,0.2,setosa +7,3.2,4.7,1.4,versicolor +6.4,3.2,4.5,1.5,versicolor +6.9,3.1,4.9,1.5,versicolor +5.5,2.3,4,1.3,versicolor +6.5,2.8,4.6,1.5,versicolor +5.7,2.8,4.5,1.3,versicolor +6.3,3.3,4.7,1.6,versicolor +4.9,2.4,3.3,1,versicolor +6.6,2.9,4.6,1.3,versicolor +5.2,2.7,3.9,1.4,versicolor +5,2,3.5,1,versicolor +5.9,3,4.2,1.5,versicolor +6,2.2,4,1,versicolor +6.1,2.9,4.7,1.4,versicolor +5.6,2.9,3.6,1.3,versicolor +6.7,3.1,4.4,1.4,versicolor +5.6,3,4.5,1.5,versicolor +5.8,2.7,4.1,1,versicolor +6.2,2.2,4.5,1.5,versicolor +5.6,2.5,3.9,1.1,versicolor +5.9,3.2,4.8,1.8,versicolor +6.1,2.8,4,1.3,versicolor +6.3,2.5,4.9,1.5,versicolor +6.1,2.8,4.7,1.2,versicolor +6.4,2.9,4.3,1.3,versicolor +6.6,3,4.4,1.4,versicolor +6.8,2.8,4.8,1.4,versicolor +6.7,3,5,1.7,versicolor +6,2.9,4.5,1.5,versicolor +5.7,2.6,3.5,1,versicolor +5.5,2.4,3.8,1.1,versicolor +5.5,2.4,3.7,1,versicolor +5.8,2.7,3.9,1.2,versicolor +6,2.7,5.1,1.6,versicolor +5.4,3,4.5,1.5,versicolor +6,3.4,4.5,1.6,versicolor +6.7,3.1,4.7,1.5,versicolor +6.3,2.3,4.4,1.3,versicolor +5.6,3,4.1,1.3,versicolor +5.5,2.5,4,1.3,versicolor +5.5,2.6,4.4,1.2,versicolor +6.1,3,4.6,1.4,versicolor +5.8,2.6,4,1.2,versicolor +5,2.3,3.3,1,versicolor +5.6,2.7,4.2,1.3,versicolor +5.7,3,4.2,1.2,versicolor +5.7,2.9,4.2,1.3,versicolor +6.2,2.9,4.3,1.3,versicolor +5.1,2.5,3,1.1,versicolor +5.7,2.8,4.1,1.3,versicolor +6.3,3.3,6,2.5,virginica +5.8,2.7,5.1,1.9,virginica +7.1,3,5.9,2.1,virginica +6.3,2.9,5.6,1.8,virginica +6.5,3,5.8,2.2,virginica +7.6,3,6.6,2.1,virginica +4.9,2.5,4.5,1.7,virginica +7.3,2.9,6.3,1.8,virginica +6.7,2.5,5.8,1.8,virginica +7.2,3.6,6.1,2.5,virginica +6.5,3.2,5.1,2,virginica +6.4,2.7,5.3,1.9,virginica +6.8,3,5.5,2.1,virginica +5.7,2.5,5,2,virginica +5.8,2.8,5.1,2.4,virginica +6.4,3.2,5.3,2.3,virginica +6.5,3,5.5,1.8,virginica +7.7,3.8,6.7,2.2,virginica +7.7,2.6,6.9,2.3,virginica +6,2.2,5,1.5,virginica +6.9,3.2,5.7,2.3,virginica +5.6,2.8,4.9,2,virginica +7.7,2.8,6.7,2,virginica +6.3,2.7,4.9,1.8,virginica +6.7,3.3,5.7,2.1,virginica +7.2,3.2,6,1.8,virginica +6.2,2.8,4.8,1.8,virginica +6.1,3,4.9,1.8,virginica +6.4,2.8,5.6,2.1,virginica +7.2,3,5.8,1.6,virginica +7.4,2.8,6.1,1.9,virginica +7.9,3.8,6.4,2,virginica +6.4,2.8,5.6,2.2,virginica +6.3,2.8,5.1,1.5,virginica +6.1,2.6,5.6,1.4,virginica +7.7,3,6.1,2.3,virginica +6.3,3.4,5.6,2.4,virginica +6.4,3.1,5.5,1.8,virginica +6,3,4.8,1.8,virginica +6.9,3.1,5.4,2.1,virginica +6.7,3.1,5.6,2.4,virginica +6.9,3.1,5.1,2.3,virginica +5.8,2.7,5.1,1.9,virginica +6.8,3.2,5.9,2.3,virginica +6.7,3.3,5.7,2.5,virginica +6.7,3,5.2,2.3,virginica +6.3,2.5,5,1.9,virginica +6.5,3,5.2,2,virginica +6.2,3.4,5.4,2.3,virginica +5.9,3,5.1,1.8,virginica diff --git a/report/deliverable-3.zip b/report/deliverable-3.zip new file mode 100644 index 0000000..9271bc1 Binary files /dev/null and b/report/deliverable-3.zip differ diff --git a/report/deliverable-3/Makefile b/report/deliverable-3/Makefile new file mode 100644 index 0000000..135009b --- /dev/null +++ b/report/deliverable-3/Makefile @@ -0,0 +1,9 @@ +.PHONY: default clean FORCE + +default : main.pdf + +%.pdf : %.tex FORCE + latexmk -pdf $< + +clean : + latexmk -C diff --git a/report/deliverable-3/appendix/minutes.tex b/report/deliverable-3/appendix/minutes.tex new file mode 100644 index 0000000..44aa702 --- /dev/null +++ b/report/deliverable-3/appendix/minutes.tex @@ -0,0 +1,68 @@ +\section{Meeting Minutes}\label{app:meet} +\begin{lstlisting} + +Group Project Meeting 1 post submission +Date: 12/02/18 +Topics: +Reassigning scrum roles +Creating next set of tasks +Task allocation + +Outcomes: +* Scrum: + * scrum master - Hafeez + * project owner - Calum + +*Tasks: + * Implementing endpoints + * Implementing file conversions + * Improving test coverage + * Writing tests for untested sections + * Connecting all middleware + * Decide on how to deal with errors + * Organising file-system + * Creating a Linter to maintain a consistent file structure + +Group Project Meeting 2 Pre-sprint +Date 19/02/18 +Topics: +Define user stories +Task allocation + +Outcomes: +* Sprint + * 2 Week long sprint + * Mid sprint meeting set for 26/02/18 +* Images + * Dealing with leica and zeiss files +* Testing + * Implementing unit and integration tests +* Logger + * Standard and SQL logger + + +Group Project Meeting 3 mid-Sprint +Date 26/02/18 +Topics: +updating progress + +Outcomes: +* Images + * Continued work on image files + * File extraction and testing + * Stitching +* Logger + * Needed a better one to log problems + +Group Project Meeting 4 post-sprint +Date 05/03/18 +Topics +Final tasks required before deadline + +Outcomes: + * Finishing off of the report + * Finish testing + * Process manager + * Hosting on heroku + +\end{lstlisting} diff --git a/report/deliverable-3/appendix/scrumboard.tex b/report/deliverable-3/appendix/scrumboard.tex new file mode 100644 index 0000000..e868278 --- /dev/null +++ b/report/deliverable-3/appendix/scrumboard.tex @@ -0,0 +1,8 @@ +\section{Scrum Board Images} \label{app:board} + +{ +\centering +\includegraphics[width=\textwidth]{graphics/scrum.jpg} +\includegraphics[width=\textwidth]{graphics/scrum3.jpg} +\includegraphics[width=\textwidth]{graphics/scrum4.jpg} +} diff --git a/report/deliverable-3/biblio.bib b/report/deliverable-3/biblio.bib new file mode 100644 index 0000000..fdfc56b --- /dev/null +++ b/report/deliverable-3/biblio.bib @@ -0,0 +1,189 @@ +@misc {tslint, + howpublished = {https://palantir.github.io/tslint/}, + title = {TSLint}, + publisher = {Palantir Technologies}, + year = {2016}, + note = {Accessed: 2018-03-01} +} + +@misc {protocol, + howpublished = {https://github.com/CS3099JH2017/cs3099jh/tree/master/protocols}, + title = {CS3099JH2017 Protocol}, + publisher = {CS3099 Year Group of 2017/18}, + year = {2018}, + note = {Accessed: 2018-03-02} +} + +@misc {yarn, + howpublished = {https://yarnpkg.com/en/docs}, + title = {Yarn}, + publisher = {Yarn Organization}, + note = {Accessed: 2018-03-02} +} + +@misc {typescript, + howpublished = {https://www.typescriptlang.org/docs/home.html}, + title = {TypeScript}, + publisher = {Microsoft}, + year = {2017}, + note = {Accessed: 2018-03-02} +} + +@misc {sequelize, + howpublished = {http://docs.sequelizejs.com/}, + title = {Sequelize}, + publisher = {Sequelize}, + note = {Accessed: 2018-03-02} +} + +@misc {sequelize-typescript, + howpublished = {https://github.com/RobinBuschmann/sequelize-typescript}, + title = {sequelize-typescript}, + publisher = {Robin Buschmann}, + note = {Accessed: 2018-03-02} +} + +@misc {postgres, + howpublished = {https://www.postgresql.org/docs/}, + title = {PostreSQL}, + publisher = {The PostgreSQL Global Development Group}, + year = {2018}, + note = {Accessed: 2018-03-02} +} + +@misc {mocha, + howpublished = {https://mochajs.org/}, + title = {Mocha}, + publisher = {mochajs}, + note = {Accessed: 2018-03-02} +} + +@misc {mocha-each, + howpublished = {https://github.com/ryym/mocha-each}, + title = {mocha-each}, + publisher = {ryym}, + note = {Accessed: 2018-03-02} +} + +@misc {chai, + howpublished = {http://chaijs.com/api/bdd/}, + title = {Chai Assertion Library}, + publisher = {chaijs}, + note = {Accessed: 2018-03-02} +} + +@misc {chai-http, + howpublished = {http://chaijs.com/plugins/chai-http/}, + title = {Chai HTTP}, + publisher = {chaijs}, + note = {Accessed: 2018-03-02} +} + +@misc {express, + howpublished = {https://expressjs.com/en/4x/api.html}, + title = {Express 4.x}, + publisher = {expressjs}, + year = {2017}, + note = {Accessed: 2018-03-02} +} + +@misc {passport, + howpublished = {http://www.passportjs.org/docs/}, + title = {Passport}, + publisher = {Jared Hanson}, + note = {Accessed: 2018-03-02} +} + +@misc {passport-local, + howpublished = {https://github.com/jaredhanson/passport-local}, + title = {passport-local}, + publisher = {Jared Hanson}, + note = {Accessed: 2018-03-02} +} + +@misc {morgan, + howpublished = {https://github.com/expressjs/morgan}, + title = {morgan}, + publisher = {expressjs}, + note = {Accessed: 2018-03-02} +} + +@misc {typedoc, + howpublished = {http://typedoc.org/guides/usage/}, + title = {TypeDoc}, + publisher = {TypeStrong}, + note = {Accessed: 2018-03-02} +} + +@misc {xlsx, + howpublished = {https://github.com/sheetjs/js-xlsx}, + title = {js-xlsx}, + publisher = {SheetJS}, + note = {Accessed: 2018-03-02} +} + +@misc {docker, + howpublished = {https://hub.docker.com/}, + title = {Docker Hub}, + publisher = {Docker Inc.}, + year = {2016}, + note = {Accessed: 2018-03-02} +} + +@misc {@types, + howpublished = {http://definitelytyped.org/}, + title = {DefinitelyTyped}, + publisher = {DefinitelyTyped}, + year = {2017}, + note = {Accessed: 2018-03-02} +} + +@misc {strongloop, + howpublished = {https://strongloop.com/}, + title = {StrongLoop}, + publisher = {IBM}, + year = {2018}, + note = {Accessed: 2018-03-07} +} + +@misc {pm2, + howpublished = {http://pm2.keymetrics.io/}, + title = {pm2}, + publisher = {KeyMetrics}, + note = {Accessed: 2018-03-07} +} + +@misc {forever, + howpublished = {https://github.com/foreverjs/forever}, + title = {foreverjs}, + publisher = {foreverjs}, + note = {Accessed: 2018-03-07} +} + +@misc {sharp, + howpublished = {https://github.com/lovell/sharp}, + title = {sharp}, + publisher = {Lovell Fuller}, + note = {Accessed: 2018-03-06} +} + +@misc {sharpPerformance, + howpublished = {http://sharp.pixelplumbing.com/en/stable/performance/}, + title = {Sharp Performance}, + publisher = {Lovell Fuller}, + note = {Accessed: 2018-03-06} +} + +@misc {zeissLicence, + howpublished = {https://www.zeiss.com/microscopy/int/products/microscope-software/czi/czi-download.html}, + title = {Apply for Zeiss Licence}, + publisher = {Carl Zeiss Microscopy GmbH}, + note = {Accessed: 2018-03-06} +} + +@misc {openseadragon, + howpublished = {https://openseadragon.github.io/docs/}, + title = {OpenSeadDragon}, + publisher = {openseadragon}, + note = {Accessed: 2019-03-07} +} diff --git a/report/deliverable-3/graphics/1.png b/report/deliverable-3/graphics/1.png new file mode 100644 index 0000000..089b8ef Binary files /dev/null and b/report/deliverable-3/graphics/1.png differ diff --git a/report/deliverable-3/graphics/2.png b/report/deliverable-3/graphics/2.png new file mode 100644 index 0000000..1714110 Binary files /dev/null and b/report/deliverable-3/graphics/2.png differ diff --git a/report/deliverable-3/graphics/3.png b/report/deliverable-3/graphics/3.png new file mode 100644 index 0000000..7eef8dc Binary files /dev/null and b/report/deliverable-3/graphics/3.png differ diff --git a/report/deliverable-3/graphics/4.png b/report/deliverable-3/graphics/4.png new file mode 100644 index 0000000..8379ef7 Binary files /dev/null and b/report/deliverable-3/graphics/4.png differ diff --git a/report/deliverable-3/graphics/5.png b/report/deliverable-3/graphics/5.png new file mode 100644 index 0000000..aeea913 Binary files /dev/null and b/report/deliverable-3/graphics/5.png differ diff --git a/report/deliverable-3/graphics/6.png b/report/deliverable-3/graphics/6.png new file mode 100644 index 0000000..e3fb624 Binary files /dev/null and b/report/deliverable-3/graphics/6.png differ diff --git a/report/deliverable-3/graphics/7.png b/report/deliverable-3/graphics/7.png new file mode 100644 index 0000000..a917d83 Binary files /dev/null and b/report/deliverable-3/graphics/7.png differ diff --git a/report/deliverable-3/graphics/burndown.png b/report/deliverable-3/graphics/burndown.png new file mode 100644 index 0000000..f3ae71d Binary files /dev/null and b/report/deliverable-3/graphics/burndown.png differ diff --git a/report/deliverable-3/graphics/km-dash.png b/report/deliverable-3/graphics/km-dash.png new file mode 100644 index 0000000..840395d Binary files /dev/null and b/report/deliverable-3/graphics/km-dash.png differ diff --git a/report/deliverable-3/graphics/scrum.jpg b/report/deliverable-3/graphics/scrum.jpg new file mode 100644 index 0000000..4b5c911 Binary files /dev/null and b/report/deliverable-3/graphics/scrum.jpg differ diff --git a/report/deliverable-3/graphics/scrum2.jpg b/report/deliverable-3/graphics/scrum2.jpg new file mode 100644 index 0000000..231cf1f Binary files /dev/null and b/report/deliverable-3/graphics/scrum2.jpg differ diff --git a/report/deliverable-3/graphics/scrum3.jpg b/report/deliverable-3/graphics/scrum3.jpg new file mode 100644 index 0000000..012e9b3 Binary files /dev/null and b/report/deliverable-3/graphics/scrum3.jpg differ diff --git a/report/deliverable-3/graphics/scrum4.jpg b/report/deliverable-3/graphics/scrum4.jpg new file mode 100644 index 0000000..ab1f7a5 Binary files /dev/null and b/report/deliverable-3/graphics/scrum4.jpg differ diff --git a/report/deliverable-3/graphics/scrum5.jpg b/report/deliverable-3/graphics/scrum5.jpg new file mode 100644 index 0000000..e79e828 Binary files /dev/null and b/report/deliverable-3/graphics/scrum5.jpg differ diff --git a/report/deliverable-3/graphics/title-logo.png b/report/deliverable-3/graphics/title-logo.png new file mode 100644 index 0000000..8a72423 Binary files /dev/null and b/report/deliverable-3/graphics/title-logo.png differ diff --git a/report/deliverable-3/main.tex b/report/deliverable-3/main.tex new file mode 100644 index 0000000..dce9106 --- /dev/null +++ b/report/deliverable-3/main.tex @@ -0,0 +1,38 @@ +\input{preamble} + +\input{title} + +\begin{document} + + \maketitle + \thispagestyle{empty} + \newpage + \setcounter{page}{1} + + \tableofcontents + \newpage + + \input{texts/aims} + \input{texts/scrum} + \input{texts/conversion} + % \input{texts/protocol} + % \input{texts/auth} + \input{texts/logging} + \input{texts/process-management} + \input{texts/testing} + \input{texts/typings} + \input{texts/conclusion} + + \appendix + \newpage + \input{appendix/scrumboard} + \newpage + \input{appendix/minutes} + + \clearpage + + \nocite{*} + \bibliography{biblio}{} + \bibliographystyle{plain} + +\end{document} diff --git a/report/deliverable-3/preamble.tex b/report/deliverable-3/preamble.tex new file mode 100644 index 0000000..14787a9 --- /dev/null +++ b/report/deliverable-3/preamble.tex @@ -0,0 +1,13 @@ +\documentclass{article} + +\usepackage[margin=1in]{geometry} +\usepackage{a4wide} + +\usepackage{graphicx} +\graphicspath{{./graphics/}} + +\usepackage{float} +\usepackage{listings} +\usepackage{cite} + +\def\file{\texttt} diff --git a/report/deliverable-3/texts/aims.tex b/report/deliverable-3/texts/aims.tex new file mode 100644 index 0000000..e1da3ee --- /dev/null +++ b/report/deliverable-3/texts/aims.tex @@ -0,0 +1,7 @@ +\section{Aims for submission 2} +From our first submission, we now had a working server that allowed a user to access our own mock user interface to log in and access data based on their level of authorisation. Following this we set up a meeting to lay out goals for ourselves that would act as requirements for the second submission. +\begin{description} + \item[Define Specific Protocol] Now that we had a working server, we next wanted to define specific protocol in order to demo our progress using work from another Junior Honours HCI groups. + \item[Manage Filetype Conversions] A main part of this submission was creating a file converter for all the required file types that would be needed. + \item[Testing] As our code was getting more complicated we wanted to make sure that extensive testing was implemented to create a more secure and consistent system. +\end{description} diff --git a/report/deliverable-3/texts/conclusion.tex b/report/deliverable-3/texts/conclusion.tex new file mode 100644 index 0000000..0e40979 --- /dev/null +++ b/report/deliverable-3/texts/conclusion.tex @@ -0,0 +1,5 @@ +\section{Conclusion} +As a group a lot of progress was made for this submission, we were proactive in setting out goals for ourselves and feel we are now well on track to produce an outstanding final hand in. Our continued use of scrum has helped keep workload consistent and effective right through to this submission and we hope to continue in this way. Scrum is essential in our progress as it helps to manage time and organise the team work and so this process will be used for the duration of the project. Having now combined our work with the HCI group we are looking forward to working with teams focused on machine learning to tie together all 3 sections of the application to create the desired system set out by the project owner. + +\subsection{Next Tasks} +Viewing the system as a whole, substantial progress has been made in completing each required task whilst also managing time for each task appropriately. Looking further ahead, our next objectives will surround performance enhancing, further testing and finally completing the integration process with the rest of the system. The process for these will include a large amount of analysis on the working server, which include finding delays between certain requests and responses, measuring time taken for converting files and testing for bugs after integration. Another important aspect is the security of the application, and preventing bugs from leading to exploits which can be used for malicious use. This is particularly important within the medical industry as data confidentiality and integrity are apart of practitioners' policy. One method of testing for this task would be penetration testing, using a suite of tools to attack the application, which would determine any vulnerabilities that exist. \ No newline at end of file diff --git a/report/deliverable-3/texts/conversion.tex b/report/deliverable-3/texts/conversion.tex new file mode 100644 index 0000000..87db332 --- /dev/null +++ b/report/deliverable-3/texts/conversion.tex @@ -0,0 +1,135 @@ +\section{File Conversion} +One of the most key pieces of functionality for the backend groups is the facilitation of the agnosticity of +original file formats to the end user. No matter the original upload format, backend groups should all be +capable of returning files in standard file formats. +These specific ``standards'' were not hard-defined by the specification, however as part of our whole year +protocol, it was decided that \emph{JSON} would be used for file meta-information, as well as the +main structure of all responses from a backend server. \emph{PNG} was decided upon as the standard file format +for all images, since it is very widely supported and has other favourable properties we would like to +take advantage of. + +\subsection{Dealing with Images} +The nature of the file formats that we were expected to abstract over however turned out to be significantly +more challenging than was initially perceived. The file formats of `Leica' and `Zeiss' are widely used in the +medical field (the department we are providing this service for), however almost nowhere else. Upon looking +into this more closely, it was found that the Zeiss file format is very proprietary and licensed. + +This means that in order to even gain access to simply read the documentation you must fill in your details +and make an application for the documentation~\cite{zeissLicence}. Part of the agreement for this documentation is that you are +not allowed to share it with anyone else; you are allowed to write software to \emph{deconstruct} them; you +are strictly \emph{not} allowed to write any software to construct them. + +The documentation gives a description of the various ``segments'' of binary that can appear in the file, and +attempts to assist you in the method to read them. Given the large nature of the file size of a Zeiss, it makes +sense for them to be designed to be `streamable', which they are --- allowing you to read smaller chunks at a +time rather than loading the whole object into memory simultaneously. + +After reading the specification in great detail, it was clear that it was extremely specialised and has +the potential to nest a variety of other file types within itself, as well as have many fields missing +--- as they are optional --- making it quite complex to interpret. In addition to this, the major difficulty +came from the fact that the base file is a proprietary binary file, which also contains things such as 128bit +unsigned integers. This fact, coupled with the substantial file sizes made the choice for languages to deal +with them limited to a systems programming language. Since I had most experience in `C99', then this seemed +the only realistic possibility. + +\subsubsection{Extraction of Zeiss Within `C'} +One major consideration was that --- due to the sheer file size of many of these images --- we would need +to store them on the local \file{/cs/scratch} drive of the lab machines: they are simply too +large to store either on our host servers statically, let alone when working on extracting and expanding the +thousands of smaller files within them. + +With this in mind, and closely comparing the +`C' code against the rough documentation licensed to me, the structures possible within a Zeiss file were +slowly built up. + +Methods were written to print out the contents of various structures as progress was made, in +order to ensure that the offsets for file streaming were continually at the correct locations and the data we +were parsing out of the file was as expected. To this effect, testing of the extraction was run continually +in the standard `C' approach of a couple lines at a time before re-compilation, along with using flags such as +`\verb|--pedantic|' in order to try to catch as many errors as possible. Occasionally \verb|valgrind| was also +run on this extraction code, since significant chunks of memory are allocated and freed during the +extraction process. \verb|valgrind| reports that there are no memory leaks at all --- even +on the larger 12Gb \file{.czi} files. + +\subsubsection{Converting Extracted Files} +Once the files/metadata/attachments had been successfully extracted from the target file, multiple issues were +discovered. +\begin{itemize} + \item The container format for the image segments was in \emph{JPEG-XR}. This is another proprietary + file format, which does not appear to be supported by anything at all, other than Microsoft's own software. + There is also extremely limited library support, especially for non-Windows platforms. + Fortunately, a C++-written \file{.jxr} decoder was found, and could + be compiled on the destination machine. Enough of the executable is able to be compiled before any problems + occur, and this decoder can be copied into the relative path for our own C source. + \item The library for decoding JXR's is only + capable of conversion to \emph{BMP} or \emph{TIFF}, which is not our desired format. Therefore an additional step of + converting the `JXR' to `TIFF', and then to `PNG' using the `imagemagick' command line tools like \verb|convert| + became necessary. + This is an annoying overhead, which is unfortunately unavoidable. + \item By simply extracting every image tile found within the JXR tile, we found that + there were also tiles found at non 1:1 zoom levels, which was wasteful to deal with, since we will be building + a custom image pyramid anyway. This issue was mitigated by adding some logic to only extract the tile to disk if + it was determined to have a 1:1 scaling and thus be on the base layer. + \item In a similar fashion to the previous issue, it also became apparent that there were many tiles in the + base layer which were of non-standard sizes, with some having tiny slivers as they came to edges etc. + The only solution to make these tiles appear on a nice grid of $n^2$ sizes, was to iterate over the fragmented + canvas and stitch together the portions we want. +\end{itemize} + +In order to complete the conversion side of things, it seemed appropriate to move away from C programming, and +even away from the scripts that were being using to control the C, to something like \emph{Python}. +The thought process behind this decision is the fact that Python supports multithreading --- which for something +as parallel as multiple image conversions seemed extremely advantageous. The code to do this section is fairly +small, but absolutely crucial to the overall pipeline of Zeiss format support. + +\subsubsection{Stitching Base Tiles} +Once we finally had all of the base tiles in a 1:1 scale and a format that was easier to deal with, the first task +was to figure out how to build up our own grid across the mismatch of sizes of existing base tiles.\\ +The tile dimensions decided on were 1024:1024. The reason for this, is that it is large enough to contain a +reasonable amount of information, without being so large that our server could provide or clients could load in +a timely manner. + +In order to do this stitching process, a decision was required as to the package to manage the image operations. +After a vast amount of searching and comparisons, the selection was made for \emph{Sharp}~\cite{sharp}. The reason for +this, was that it appeared to be the single library which was capable of all of the different kinds of image +processing jobs we expected to be doing. Another key reason is the fact that it is known in advance that a very +large number of images will need to be processed here, so performance is critical. Sharp appears to perform +very significantly better than its competitors~\cite{sharpPerformance}. Finally, it has typing +support to work with our environment. + +With this set, high level logic was written to check various image bounds for related base tiles to a specific +region request. Regions were then selected out, sorted by x and y offsets, then relevant chunks chopped out of +them and stitched together into a coherent region of our selected size. + +\subsubsection{Building Up Hierarchy of Zoom Levels} +These finalised base layer tiles are written to disk in an output directory and details about their creation +are recorded in a new data structure which will map out the pyramid style hierarchy of the tiles. +A small example of these final titles are shown on the cover page of our Report for interest as they are +legitimate generations in a format we would like. + +Now that the base layer exists, gaining the rest of the tile zoom levels, should be fairly simple --- by moving +up to the next power of two (2048) and collecting 4 images together then scaling this back down to 1024 pixels. +This process can be repeated for each level of zoom we would like to raise to. This will massively speed up +the process of searching through base tiles and stitching many together if we pre-process all of the intermediate +layers. Since most HCI groups are using OpenSeaDragon (which requests things in scales of powers +of two~\cite{openseadragon}), our approach should be a very fast performer with the trade off of larger up-front processing time.\\ +Indexing into this pyramid will be fast with each request too, as they will be separated by `C' value, which is +one of the image's layering options, then by zoom level. + +\subsection{Leica \& Other Formats} +As Zeiss is such a difficult and mammoth file format almost all of my time was spent dealing with purely this, +and it is still not even complete yet. However having looked quickly into Leica, there appears to be +library support, which may make life easier, along with the fact the internal structure appears to be similar to +a BigTiff. More progress on this format will take place for the next deliverable. + +As for other image formats such as JPEG, TIFF etc. These are standard formats and so will be trivial to +convert to our required standard of PNG so is not a significant point of progress currently. + +\subsection{Non image formats (\file{.csv} etc.)} +As for non image formats such as \file{.csv}, it has been decided that the backend should only be responsible of hosting these +files, since there is no way that a backend server could possibly predict what the file should be processed into. +Additionally, there are also many cases where an end-user may wish to deliberately store something in a format +which a backend server checking legitimacy of the file would complain about incorrectly. + +The team hasn't really looked into things such as Excel (\file{.xlsx}) files, however again, pre-emptively looking, there seems to +be fairly wide library support for things like this, so it was not a major concern for this deliverable. diff --git a/report/deliverable-3/texts/logging.tex b/report/deliverable-3/texts/logging.tex new file mode 100644 index 0000000..d0a7255 --- /dev/null +++ b/report/deliverable-3/texts/logging.tex @@ -0,0 +1,38 @@ +\section{Logging} +Server logging has now been formalised: the functionality is imported into +a file and can then be used to log messages at the selection of urgencies +specified in Protocol BE01~\cite{protocol}. + +These outputs have many configuration options, which ideally will be +incorporated into a global configuration handler in future development. + +\subsection{Standard Logging} +By default, the standard logger logs to three places: +\begin{enumerate} + \item Colourised, human-readable messages are printed to the console. + Any error- or critical-level messages are printed through stderr. + \item More verbose JSON editions of messages are written to a basic + logfile. + \item Critical-level messages are additionally written to an extra + logfile. +\end{enumerate} + +\subsection{SQL Query Logging} +A separate logger has been designed for logging the output of +Sequelize~\cite{sequelize}. Since Protocol BE01 does not specify that they +should be retreivable, the output queries can be stored with less associated +metadata. In addition, Sequelize can output the total required time to +process the query, which is stored in the log for future use as profiling +data. + +\subsection{Motivation} +Since basic server functionality has been implemented, the errors produced +will likely be caused by difficult-to-debug problems, such as edge-cases or +data races. With a verbose and thorough logging system, these problems +should be much easier to detect and rectify. + +In addition, Protocol BE01~\cite{protocol} requires of the backend support +for receiving and storing logs from other services. The introduction of a +well-implemented logging system abstracts this from the common use-case of +logging while keeping powerful functionality of forwarding and fetching logs +available for when it is needed. diff --git a/report/deliverable-3/texts/minutes.tex b/report/deliverable-3/texts/minutes.tex new file mode 100644 index 0000000..55aab2a --- /dev/null +++ b/report/deliverable-3/texts/minutes.tex @@ -0,0 +1,72 @@ +\begin{lstlisting} + +Group Project Meeting 1 post submission +Date: 12/02/18 +Topics: +Reassigning scrum roles +Creating next set of tasks +Task allocation + +Outcomes: +* Scrum: + * scrum master - Hafeez + * project owner - Calum + +*Tasks: + * Implementing endpoints + * Implementing file conversions + * Improving test coverage + * Writing tests for untested sections + * Connecting all middleware + * Decide on how to deal with errors + * Organising file-system + * Creating a Linter to maintain a consistent file structure + +Group Project Meeting 2 Pre-sprint +Date 15/02/18 +Topics: +Define user stories +Task allocation + +Outcomes: +* Sprint + * Week long sprint + * Meeting set for 22/02/18 + +Group Project Meeting 3 Post-Sprint +Date 22/02/18 +Topics: +Analysis of work +Next task assignment + +Outcomes: + +Group Project Meeting 4 +Date 24/02/18 +Topics: +Sprint aims +Sprint deadline + +Outcomes: + *Decided to hold a sprint now to leave time + before next submission to finish off all leftover work + +Group Project Meeting 5 +Date 03/03/18 +Topics +Analysis of work todo after sprint +Work needed to complete before deadline + + +Outcomes: + * Finishing off of the report + *Connecting work with another HCI group + *Finish testing + + + + + + + +\end{lstlisting} diff --git a/report/deliverable-3/texts/process-management.tex b/report/deliverable-3/texts/process-management.tex new file mode 100644 index 0000000..d99a73c --- /dev/null +++ b/report/deliverable-3/texts/process-management.tex @@ -0,0 +1,56 @@ +\section{Process Management and Deployment}\label{sec:pm} +In a production environment, many instances of a NodeJS server are run on +one machine; this way NodeJS applications can make use of multiple +processors. For this purpose, research into \emph{process managers} --- +applications used for running and managing production-level systems --- +was carried out. + +\subsection{Process Manager Selection}\label{sec:pms} +A number of process managers were investigated with the hope of +incorporating them into the production +system~\cite{strongloop}\cite{pm2}\cite{forever}. The application pm2 was +chosen, primarily for its highly-configurable \emph{ecosystem}-config files, +and \emph{pmx}\footnote{https://github.com/keymetrics/pmx}, +its profiling extension. + +\subsection{pm2 and KeyMetrics}\label{sec:pm2} + +\begin{figure} + \centering + \includegraphics[width=0.95\linewidth]{km-dash} + \caption{The KeyMetrics dashboard web client in use.}\label{fig:dash} +\end{figure} + +A feature available in \emph{pm2} is the ability to transmit profiling +statistics to a web client, as a dashboard. The dashboard also allows the +user to remotely issue commands to the running instances. Further, +custom profiling information, and custom remote commands, can be created +through the introduction of simple logic into the codebase. + +\subsection{Process Limitations}\label{sec:plim} +Running multiple NodeJS instances can quickly accumulate counts towards a +user process limit: each instance hosts several threads, and each connection +to the PostgreSQL database can pool several threads also, resulting in many +threads per instance. Compounded with the fact that pm2 itself also runs +as a NodeJS instance, this means that a user can reach their process limit +on the host labs very quickly. Using \texttt{nolimit} on process +instantiation is one solution, however this means having to run +\texttt{nolimit} when starting the databse, deamonising the process manager, +starting the server instances, and doing any miscellaneous tasks. This +limitation has stunted hindered attempts to connect to other teams' +products. + +\subsection{Heroku Hosting}\label{sec:her} +In response to the issues addressed in \S\ref{sec:plim}, an attempt to host +an instance of the server on hosting service +\emph{Heroku}\footnote{https://heroku.com/} has been started. This would +alloow the team to interact with other teams, without using a member's +process limit and hindering their productivity. Additionally, it would show +the deployability of the system --- an important factor for a backend +server. + +\subsection{External System Hosting}\label{sec:ext} +Another option is to host instances of the system on devices personally +owned by members of the team. This would give the team absolute control over +configuration of the sytem, and would have the potential to outperform an +instance running on a complementary Heroku service. diff --git a/report/deliverable-3/texts/scrum.tex b/report/deliverable-3/texts/scrum.tex new file mode 100644 index 0000000..ca724c8 --- /dev/null +++ b/report/deliverable-3/texts/scrum.tex @@ -0,0 +1,17 @@ +\section{Continued use of Scrum} +The scrum process was continued as we found this very useful in terms of clearly setting out tasks for each member and managing the progress of the implementation. One of the changes that was made for this sprint was the change in roles between team members. The change in responsibility allows team members to complete new and different jobs. In general the size and the time taken of each individual task was a lot more varied when comparing to the last submission, however, there were certain tasks which were larger in terms of hours put in. These large tasks included creating a logger system and a file converter. +\subsection{Sprints} + +\begin{figure}[h] + \centering + \includegraphics[width=0.6\textwidth]{burndown} + \caption{A Burndown Chart for the past 14 days.}\label{fig:burn} +\end{figure} + +As a team, it was decided that there would only be a single sprint, up until the next point of submission. This was because of the short time period, enough for only a two week sprint. In addition to this, the sprint assessment process was completed more often to ensure that as a team time was managed well and sufficient progress was being made. All the tasks that was set for this sprint were completed within the required time frame. +\subsection{Scrum board} +Again, the scrum board was used to outline and track the completion of each task. The same whiteboard in the John Honey main computer lab was used in order to maintain consistency. This gave a clear visual representation of the objectives. During the sprint, the main jobs required for completion were to further enhance the testing unit to increase its coverage across the implemented systems, implement a simple file converter and introduce a logging system for the server. Much experience was gained from completing previous sprints and so using this experience we were better equipped to handle larger tasks. Examples of the board in use can be found in Appendix \ref{app:board}. + +\subsection{Meetings} +Regular meetings were also held to discuss and evaluate progress. This was crucial in the scrum process and as working in a team to allow a point of communication between each member at the same point in time. An example of a major decision being made during the discussion was the change of language of the file converter implementation. It was decided that the more appropriate language to use would be C as there would more extensive libraries for this particular operation and would also have the advantage of greater efficiency. Multiple meetings were held during the most recent sprint to determine the tasks required for completion, to evaluate whether each task was completed and track progress in between. +The minutes for formal meetings are available in Appendix \ref{app:meet}. diff --git a/report/deliverable-3/texts/testing.tex b/report/deliverable-3/texts/testing.tex new file mode 100644 index 0000000..e3f709b --- /dev/null +++ b/report/deliverable-3/texts/testing.tex @@ -0,0 +1,15 @@ +\section{Testing} +Tests do not currently run on the gitlab server, as the postgres integration with the docker gitlab-ci is still missing. This means any tests run automatically when pushing will fail. \par +When running integration tests locally, please make sure the postgres server is up and running on localhost. +\subsection{Structure} +Testing files were restructured for a more organised and professional approach. All test files end in ``*.\(<\)context\(>\).test.ts'' and were moved to the ``test'' directory. At this moment, ``\(<\)context\(>\)'' includes ``unit'' and ``routes''. Further, they were categorised into \textit{integration} and \textit{unit} tests and moved into corresponding sub-directories. \par +Apart from making test files easier to find, this new structure also allowed us to run specific tests independently to isolate failures and quickly rerun individual tests. For example \texttt{yarn test:routes:auth} runs all authentication tests. +\subsection{Integration Testing} +\texttt{yarn test:routes} +This category of tests targeted the interplay of different server components as it tested server endpoints (routes) rather than internal functions. We aimed to test all routes for responses of success, and various degrees of failure. \par +E.g. \textbf{``auth.routes.test.ts''} tested the authentication middle-ware, checking existing users could log in only with correct usernames, passwords and reauthentication tokens. During our later meetings, we realised that security is a key-component of medical systems, and requires further much more in-depth testing to guarantee safety of patient data. \par +\textbf{``protocol.routes.test.ts''} aims to cover all endpoints specified in the agreed protocol by using the \textit{mocha-each} npm module. This allowed us to write few mocha testing functions iterating over the long list of endpoints, checking HTTP responses to fit the JSON response templates to conform to the protocol. This form of testing is still incomplete. +\subsection{Unit Testing} +\texttt{yarn test:unit} +The main motivation for this category of tests was to find bugs early on without having to run the whole server. This saves time and uncovers new code breaking old functionality. We also found that unit tests improved the design process by forcing implementation of code that is testable. Furthermore, unit tests were often used as a form of documentation, as it aided in understanding how code of other team members worked and could be used. \par +We decided that each team-member was responsible for creating the unit tests for their code. Unfortunately the number and coverage of unit tests is still quite low. This may be the result of prioritising functionality over bug-resilience and test-driven development. diff --git a/report/deliverable-3/texts/typings.tex b/report/deliverable-3/texts/typings.tex new file mode 100644 index 0000000..36297b7 --- /dev/null +++ b/report/deliverable-3/texts/typings.tex @@ -0,0 +1,27 @@ +\section{Type Enforcement} +In order to run JavaScript code as TypeScript code, typings (usually +supplied in a \file{.d.ts}-extended file) are applied at compile-time to +make sense of the original source's variable types. For a couple of +packages that have been used in the submission, these typings are not +available, due to a lack of desirablilty --- the packages in question are +niche and as such see little use. + +\subsection{mocha-each} +One such package is \emph{mocha-each}, a utility package for compacting +Mocha tests for readability and classification~\cite{mocha-each}. Without +typings, this package cannot be used in TypeScript projects. Due to its +single-facet use, however, it was simple to design a custom +\file{.d.ts} file. With small edits to conform to +guidelines~\cite{@types}, typings for +mocha-test were contributed to the DefinitelyTyped types repository\footnote{% +https://github.com/DefinitelyTyped/DefinitelyTyped/% +tree/master/types/mocha-each}. + +\subsection{pmx} +The package pmx (as previously described in \S\ref{sec:pms}) is useful for +profiling. Similarly to mocha-each, however, it does not have supported typing. +Since this package covers a far wider range of functionality, and since said +functionality is very involved with sensitive run-time engine manipulation, +typings were written only for the functions being used by the team, and have +been kept in-house for their incompleteness. The files in question can be found +in \file{src/profiler}. diff --git a/report/deliverable-3/title.tex b/report/deliverable-3/title.tex new file mode 100644 index 0000000..4406ef6 --- /dev/null +++ b/report/deliverable-3/title.tex @@ -0,0 +1,15 @@ +\title{Report \\ Juniour Honours Project \\[0.5ex] Submission 2} +\author{Hafeez Abdul-Rehaman \\[1ex] Johannes Weck \\[1ex] Josh Lee \\[1ex] Calum Duff \\[2ex] Tom Harley} +\date{\today} + +\makeatletter + \def\@maketitle{ + \begin{center} + \includegraphics[width=0.7\linewidth]{title-logo}\\[10ex] + {\huge \bfseries \@title{ }}\\[1ex] + \rule{0.5\textwidth}{.4pt}\\[1ex] + {\LARGE \@author}\\[15ex] + {\large \@date} + \end{center} + } +\makeatother diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 70d3d51..0798ce8 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -548,7 +548,7 @@ const getFile: Middleware = async( const view: View = views[req.query.view || 'meta']; // TODO return 400 for unsuported views // TODO raw view accepts extra query params offset and length - res.locals.function = view.getResponseFunction(req, res); + res.locals.function = view.getResponseFunction(req, res); res.locals.data = view.getResponseData(file, project, req.query); next(); }; @@ -832,9 +832,6 @@ export class FileRouter { // Vars arleady assigned: // - res.locals.project: requested project object - //console.log(`req.file.filename: ${req.file}`) - console.log(req.file) - // Replace + with / res.locals.path = filename.replace(/\+/g, '/'); logger.debug(`Searching for path \'${res.locals.path}\'`); diff --git a/src/files.ts b/src/files.ts index 1b8a652..5b15a10 100644 --- a/src/files.ts +++ b/src/files.ts @@ -169,7 +169,7 @@ export const views: { getResponseData: async( file: File, project: Project, query: Query ): Promise => { - return readableStream(file.name, project.name, query); + return readableStream(file.uuid, project.name, query); }, getResponseFunction: (req: Request, res: Response): Function | null => { return res.send; diff --git a/src/index.ts b/src/index.ts index 5960374..1ce284d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,16 +22,7 @@ const port: number = process.env.PORT : DEFAULT_PORT; logger.info(`Port ${port} chosen`); -// tslint:disable:no-floating-promises -(async(): Promise => { - try { - logger.info('Authenticating with database'); - await seq.authenticate(); - } catch (err) { - logger.error(`Cannot authenticate with database: ${err}`); - process.exit(1); - } - +async function reset(): Promise { try { logger.info('Resetting Database'); await seq.sync({ @@ -91,6 +82,20 @@ logger.info(`Port ${port} chosen`); } }); +} + +// tslint:disable:no-floating-promises +(async(): Promise => { + try { + logger.info('Authenticating with database'); + await seq.authenticate(); + } catch (err) { + logger.error(`Cannot authenticate with database: ${err}`); + process.exit(1); + } + + //await reset(); + logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { if (err) { -- cgit v1.2.1 From 2c7cebcd140cc5413118d8246aa9f51b756c512d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 19 Apr 2018 15:24:55 +0100 Subject: Change minimum recording level for logs --- src/logger.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/logger.ts b/src/logger.ts index 9025814..74ae1f7 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -138,7 +138,7 @@ const consoleTransport: winston.TransportInstance = const basicFileTransport: winston.TransportInstance = new winston.transports.File({ name: 'basicFileTransport', - level: 'info', + level: 'debug', label: 'Basic File Transport', silent: false, colorize: false, @@ -193,7 +193,7 @@ const criticalFileTransport: winston.TransportInstance = const queryFileTransport: winston.TransportInstance = new winston.transports.File({ name: 'queryFileTransport', - level: 'info', + level: 'debug', label: 'Query Logs', silent: false, colorize: false, @@ -271,7 +271,7 @@ interface LogItem { timestamp: string; } -/* tslint:disable */ +/* tslint:disable */ const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise = (level?: LogLevel, params: FetchParams = {}): Promise => { const options: winston.QueryOptions = { from: params.after, -- cgit v1.2.1 From ec1162de99e1744b52fcce0c5341649a7e9a2955 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 19 Apr 2018 16:19:46 +0100 Subject: Add CORS support --- src/app.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index 4dfeeda..09b9e6a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,7 @@ class App { logger.debug('Constructing router'); this.logEnabled = enableLog; this.express = ex(); + this.cors(); this.express.use( (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { logger.info(`Connection from ${req.ip} requesting ${req.url}`); @@ -68,6 +69,22 @@ class App { this.errorware(); } + /** + * Enables Cross-Origin for the server. + */ + public cors(): void { + this.express.use(( + req: ex.Request, res: ex.Response, next: ex.NextFunction + ): void => { + res.header('Access-Control-Allow-Origin', '*'); + res.header( + 'Access-Control-Allow-Headers', + 'Origin, X-Requested-With, Content-Type, Accept' + ); + next(); + }); + } + /** * Configures regular Express middleware. */ @@ -114,8 +131,8 @@ class App { this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); this.express.use('/', defRouter); - this.express.use((req: ex.Request, res: ex.Response, - next: ex.NextFunction): void => { + this.express.use( + (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { if (Object.keys(res.locals).length === 0) { res.status(404) .json({ -- cgit v1.2.1