diff options
| author | Tom Harley | 2018-04-22 22:30:54 +0100 |
|---|---|---|
| committer | Tom Harley | 2018-04-22 22:31:23 +0100 |
| commit | 1b2fe66acf4041728dcb772ee9638b6b79f34d1a (patch) | |
| tree | ecb03f6551e35336f5a654f3b3257435cbadfb6d | |
| parent | Edit file uploads to use raw data instead of forms (diff) | |
| parent | fixxed tests (diff) | |
| download | medicine-1b2fe66acf4041728dcb772ee9638b6b79f34d1a.tar.gz medicine-1b2fe66acf4041728dcb772ee9638b6b79f34d1a.zip | |
Merge branch ‘trh/gets’ of gitlab.cs.st-andrews.ac.uk:cs3099group-be-4/project-code into trh/gets
| -rw-r--r-- | Report/.DS_Store | bin | 0 -> 6148 bytes | |||
| -rw-r--r-- | package.json | 2 | ||||
| -rw-r--r-- | report/deliverable-3/main.bbl | 134 | ||||
| -rw-r--r-- | report/deliverable-3/main.blg | 73 | ||||
| -rw-r--r-- | res/.DS_Store | bin | 0 -> 6148 bytes | |||
| -rw-r--r-- | src/.DS_Store | bin | 0 -> 8196 bytes | |||
| -rw-r--r-- | src/FileRouter.ts | 213 | ||||
| -rwxr-xr-x | src/conversion/czi/JxrDecApp | bin | 0 -> 296464 bytes | |||
| -rw-r--r-- | src/db/.DS_Store | bin | 0 -> 6148 bytes | |||
| -rw-r--r-- | src/db/model/ContributorGroup.ts | 13 | ||||
| -rw-r--r-- | src/db/model/Project.ts | 88 | ||||
| -rw-r--r-- | src/db/model/User.ts | 73 | ||||
| -rw-r--r-- | src/db/model/UserJoinsProject.ts | 10 | ||||
| -rw-r--r-- | src/files.ts | 8 | ||||
| -rw-r--r-- | src/index.ts | 76 | ||||
| -rw-r--r-- | src/mimetype.ts | 27 | ||||
| -rw-r--r-- | src/serverConfig.ts | 2 | ||||
| -rw-r--r-- | test/.DS_Store | bin | 0 -> 6148 bytes | |||
| -rw-r--r-- | test/integration/protocol.routes.test.ts | 21 | ||||
| -rw-r--r-- | test/unit/Tissue Slides.00030.v13.csv | 3 |
20 files changed, 636 insertions, 107 deletions
diff --git a/Report/.DS_Store b/Report/.DS_Store Binary files differnew file mode 100644 index 0000000..f384dd0 --- /dev/null +++ b/Report/.DS_Store diff --git a/package.json b/package.json index 7abf238..991305d 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "_lint": "tslint -p './tsconfig.json' -c './tslint.json'", "lint": "yarn _lint --fix --force './src/**/*.ts'", "lint:tests": "yarn _lint --fix --force './test/**/*.ts'", - "serve": "pm2 start ecosystem.config.js", + "serve": "pm2 restart ecosystem.config.js", "console": "pm2 monit" }, "repository": { diff --git a/report/deliverable-3/main.bbl b/report/deliverable-3/main.bbl new file mode 100644 index 0000000..5ffb189 --- /dev/null +++ b/report/deliverable-3/main.bbl @@ -0,0 +1,134 @@ +\begin{thebibliography}{10} + +\bibitem{zeissLicence} +Apply for zeiss licence. +\newblock + https://www.zeiss.com/microscopy/int/products/microscope-software/czi/czi-download.html. +\newblock Accessed: 2018-03-06. + +\bibitem{chai} +Chai assertion library. +\newblock http://chaijs.com/api/bdd/. +\newblock Accessed: 2018-03-02. + +\bibitem{chai-http} +Chai http. +\newblock http://chaijs.com/plugins/chai-http/. +\newblock Accessed: 2018-03-02. + +\bibitem{forever} +foreverjs. +\newblock https://github.com/foreverjs/forever. +\newblock Accessed: 2018-03-07. + +\bibitem{xlsx} +js-xlsx. +\newblock https://github.com/sheetjs/js-xlsx. +\newblock Accessed: 2018-03-02. + +\bibitem{mocha} +Mocha. +\newblock https://mochajs.org/. +\newblock Accessed: 2018-03-02. + +\bibitem{mocha-each} +mocha-each. +\newblock https://github.com/ryym/mocha-each. +\newblock Accessed: 2018-03-02. + +\bibitem{morgan} +morgan. +\newblock https://github.com/expressjs/morgan. +\newblock Accessed: 2018-03-02. + +\bibitem{openseadragon} +Openseaddragon. +\newblock https://openseadragon.github.io/docs/. +\newblock Accessed: 2019-03-07. + +\bibitem{passport} +Passport. +\newblock http://www.passportjs.org/docs/. +\newblock Accessed: 2018-03-02. + +\bibitem{passport-local} +passport-local. +\newblock https://github.com/jaredhanson/passport-local. +\newblock Accessed: 2018-03-02. + +\bibitem{pm2} +pm2. +\newblock http://pm2.keymetrics.io/. +\newblock Accessed: 2018-03-07. + +\bibitem{sequelize} +Sequelize. +\newblock http://docs.sequelizejs.com/. +\newblock Accessed: 2018-03-02. + +\bibitem{sequelize-typescript} +sequelize-typescript. +\newblock https://github.com/RobinBuschmann/sequelize-typescript. +\newblock Accessed: 2018-03-02. + +\bibitem{sharp} +sharp. +\newblock https://github.com/lovell/sharp. +\newblock Accessed: 2018-03-06. + +\bibitem{sharpPerformance} +Sharp performance. +\newblock http://sharp.pixelplumbing.com/en/stable/performance/. +\newblock Accessed: 2018-03-06. + +\bibitem{typedoc} +Typedoc. +\newblock http://typedoc.org/guides/usage/. +\newblock Accessed: 2018-03-02. + +\bibitem{yarn} +Yarn. +\newblock https://yarnpkg.com/en/docs. +\newblock Accessed: 2018-03-02. + +\bibitem{docker} +Docker hub. +\newblock https://hub.docker.com/, 2016. +\newblock Accessed: 2018-03-02. + +\bibitem{tslint} +Tslint. +\newblock https://palantir.github.io/tslint/, 2016. +\newblock Accessed: 2018-03-01. + +\bibitem{@types} +Definitelytyped. +\newblock http://definitelytyped.org/, 2017. +\newblock Accessed: 2018-03-02. + +\bibitem{express} +Express 4.x. +\newblock https://expressjs.com/en/4x/api.html, 2017. +\newblock Accessed: 2018-03-02. + +\bibitem{typescript} +Typescript. +\newblock https://www.typescriptlang.org/docs/home.html, 2017. +\newblock Accessed: 2018-03-02. + +\bibitem{protocol} +Cs3099jh2017 protocol. +\newblock https://github.com/CS3099JH2017/cs3099jh/tree/master/protocols, 2018. +\newblock Accessed: 2018-03-02. + +\bibitem{postgres} +Postresql. +\newblock https://www.postgresql.org/docs/, 2018. +\newblock Accessed: 2018-03-02. + +\bibitem{strongloop} +Strongloop. +\newblock https://strongloop.com/, 2018. +\newblock Accessed: 2018-03-07. + +\end{thebibliography} diff --git a/report/deliverable-3/main.blg b/report/deliverable-3/main.blg new file mode 100644 index 0000000..dcb4ea0 --- /dev/null +++ b/report/deliverable-3/main.blg @@ -0,0 +1,73 @@ +This is BibTeX, Version 0.99d (TeX Live 2016) +Capacity: max_strings=35307, hash_size=35307, hash_prime=30011 +The top-level auxiliary file: main.aux +The style file: plain.bst +Database file #1: biblio.bib +Warning--to sort, need author or key in zeissLicence +Warning--to sort, need author or key in sharp +Warning--to sort, need author or key in sharpPerformance +Warning--to sort, need author or key in openseadragon +Warning--to sort, need author or key in protocol +Warning--to sort, need author or key in sequelize +Warning--to sort, need author or key in strongloop +Warning--to sort, need author or key in pm2 +Warning--to sort, need author or key in forever +Warning--to sort, need author or key in mocha-each +Warning--to sort, need author or key in @types +Warning--to sort, need author or key in tslint +Warning--to sort, need author or key in yarn +Warning--to sort, need author or key in typescript +Warning--to sort, need author or key in sequelize-typescript +Warning--to sort, need author or key in postgres +Warning--to sort, need author or key in mocha +Warning--to sort, need author or key in chai +Warning--to sort, need author or key in chai-http +Warning--to sort, need author or key in express +Warning--to sort, need author or key in passport +Warning--to sort, need author or key in passport-local +Warning--to sort, need author or key in morgan +Warning--to sort, need author or key in typedoc +Warning--to sort, need author or key in xlsx +Warning--to sort, need author or key in docker +You've used 26 entries, + 2118 wiz_defined-function locations, + 597 strings with 5770 characters, +and the built_in function-call counts, 4422 in all, are: += -- 450 +> -- 26 +< -- 0 ++ -- 26 +- -- 0 +* -- 140 +:= -- 513 +add.period$ -- 78 +call.type$ -- 26 +change.case$ -- 78 +chr.to.int$ -- 0 +cite$ -- 52 +duplicate$ -- 182 +empty$ -- 599 +format.name$ -- 0 +if$ -- 1101 +int.to.chr$ -- 0 +int.to.str$ -- 26 +missing$ -- 0 +newline$ -- 133 +num.names$ -- 0 +pop$ -- 244 +preamble$ -- 1 +purify$ -- 52 +quote$ -- 0 +skip$ -- 137 +stack$ -- 0 +substring$ -- 130 +swap$ -- 26 +text.length$ -- 0 +text.prefix$ -- 0 +top$ -- 0 +type$ -- 104 +warning$ -- 26 +while$ -- 0 +width$ -- 28 +write$ -- 244 +(There were 26 warnings) diff --git a/res/.DS_Store b/res/.DS_Store Binary files differnew file mode 100644 index 0000000..8c8bb1a --- /dev/null +++ b/res/.DS_Store diff --git a/src/.DS_Store b/src/.DS_Store Binary files differnew file mode 100644 index 0000000..2d5870d --- /dev/null +++ b/src/.DS_Store diff --git a/src/FileRouter.ts b/src/FileRouter.ts index dd5e74b..8896e47 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -5,17 +5,20 @@ import { ProjectFullInfo, default as Project } from './db/model/Project'; import { UserFullInfo, default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; +import * as bodyParser from 'body-parser'; import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; import { View, addSubFileToFolder, copyFile, createProjectFolder, deleteFile, - rootPathId, saveFile, views } from './files'; + saveFile, views } from './files'; +import { appendFileSync } from 'fs'; import { logger } from './logger'; import { mimetype } from './mimetype'; +import { Contains } from 'sequelize-typescript'; import { Property, default as serverConfig } from './serverConfig'; +import UserHasPrivilege from './db/model/UserHasPrivilege'; +import UserJoinsProject from './db/model/UserJoinsProject'; import { uuid } from './uuid'; -import * as bodyParser from 'body-parser'; - /** * The type of an Express middleware callback. */ @@ -248,14 +251,14 @@ const getUsers: Middleware = async( Project ] }); - res.locals.data = users.map((u: User): UserFullInfo => { - const info: UserFullInfo = u.fullInfo; - if (!req.user.hasPrivilege('admin')) { - delete info.private_user_metadata; - delete info.private_admin_metadata; - } + res.locals.data = Promise.all(users.map((u: User): Promise<UserFullInfo> => { + const info: Promise<UserFullInfo> = u.getFullInfo(); return info; - }); + })); + if (!req.user.hasPrivilege('admin')) { + delete res.locals.data.private_user_metadata; + delete res.locals.data.private_admin_metadata; + } next(); }; @@ -295,24 +298,24 @@ const getUserProperties: Middleware = ( * "private_admin_metadata": metadata * } */ -const getUsername: Middleware = ( +const getUsername: Middleware = async( req: Request, res: Response, next: NextFunction -): void => { +): Promise<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; } - res.locals.data = res.locals.user.fullInfo; + res.locals.data = await res.locals.user.getFullInfo(); next(); }; -const getCurUser: Middleware = ( +const getCurUser: Middleware = async( req: Request, res: Response, next: NextFunction -): void => { +): Promise<void> => { logger.debug('Listing current user'); - res.locals.data = req.user.fullInfo; + res.locals.data = await req.user.getFullInfo(); next(); }; @@ -370,19 +373,65 @@ const postUsername: Middleware = async( ): Promise<void> => { let user: User | null | undefined = res.locals.user; res.locals.modified = true; - 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; + + if( req.query.action === 'update'){ + if (user!= null){ + logger.debug('Editing user'); + + if(req.body.password != null){ + user.password = req.body.password; + } + if (req.body) { + user.metadata = req.body; + } + await user.save(); + if(req.body.privileges != null){ + const priv: UserGroup[] | null = await UserGroup.findAll({ + include: [{all: true}], + where: { + name: req.body.privileges + } + }) + await user.$set('userGroups', priv); + } + } + else{ + next(new RequestError(404, 'user_not_found')); + return; + } } - if (req.body) { - user.metadata = req.body; + else if( req.query.action === 'delete'){ + logger.debug('Deleting a user'); + if (user!= null){ + await user.destroy(); + } + else{ + next(new RequestError(404, 'user_not_found')); + return; + } } + else{ + if (user == null) { + logger.debug('Adding new user'); + const priv: UserGroup[] | null = await UserGroup.findAll({ + include: [{all: true}], + where: { + name: req.body.privileges + } + }) + user = new User({ + username: req.params.username, + password: req.params.password, + }); + await user.save(); + await user.$set('userGroups', priv); + } + else{ + next(new RequestError(400, 'user_already_exists')); + return; + } + } + await user.save(); next(); }; @@ -438,9 +487,9 @@ const getProjects: Middleware = async( User ] }); - res.locals.data = projects.map( - (p: Project): ProjectFullInfo => p.fullInfo - ); + res.locals.data = Promise.all(projects.map( + (p: Project): Promise<ProjectFullInfo> => p.getFullInfo() + )); next(); }; @@ -470,7 +519,7 @@ const getProjectName: Middleware = async( if (project == null) { return next(new RequestError(404, 'project_not_found')); } else { - res.locals.data = project.fullInfo; + res.locals.data = await project.getFullInfo(); next(); } }; @@ -494,38 +543,81 @@ const postProjectName: Middleware = async( let project: Project | null = res.locals.project; res.locals.modified = true; let promise: PromiseLike<File> | null = null; - if (project == null) { - if (req.query.action !== 'create') { - return next(new RequestError(404, 'project-not-found')); - } - logger.debug('Adding new project'); - const file: File = new File({ - uuid: uuid.generate(), - type: 'directory', - status: 'ready', - 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; + if (req.query.action === 'update') { + logger.debug('Adding new project'); + if (project != null) { + project.metadata = req.body; + await project.save(); + } else { + next(new RequestError(400, 'project_not_found')); + } + } else if (req.query.action === 'delete') { + if (project != null) { + project.destroy(); + } else { + next(new RequestError(400, 'project_not_found')); + } + } else if (req.query.action === 'update_grant') { + if (project == null) { + next(new RequestError(400, 'project_not_found')); + } else { + const ujp: UserJoinsProject | null = await UserJoinsProject.findOne({ + include: [{all: true}], + where: { + username: req.body.username, + projectName: project.name + } + }); + if (ujp != null) { + await ujp.destroy(); + } + if (req.body.access_level !== 'none') { + try { + let ujp: UserJoinsProject = new UserJoinsProject({ + username: req.body.username, + projectName: project.name, + contributorGroupName: req.body.access_level + }); + await ujp.save(); + } catch (err) { + next(new RequestError(400, 'invalid_access_level')); + } + } + } } else { - if (req.query.action === 'create') { - return next(new RequestError(400, 'project_already_exists')); + if (project == null) { + logger.debug('Adding new project'); + const file: File = new File({ + uuid: uuid.generate(), + }); + file.mimetype = 'inode/directory'; + file.name = ''; + promise = file.save(); + project = new Project({ + name: req.params.project_name, + rootFolderId: file.uuid + }); + + createProjectFolder(req.params.project_name); + + project.metadata = req.body; + // tslint:disable-next-line:await-promise + await promise; + await project.save() + const contribute: UserJoinsProject = new UserJoinsProject({ + username: req.user.username, + projectName: req.params.project_name, + contributorGroupName: 'projectOwner' + + }) + contribute.save() + } else { + next(new RequestError(400, 'project_already_exists')); } - logger.debug('Updating project properties'); } - project.metadata = req.body; - // tslint:disable-next-line:await-promise - await promise; - await project.save(); - next(); + next() }; /** @@ -588,6 +680,9 @@ const getFileFromPath: (req: Request, res: Response) => Promise<void> = async( throw new RequestError(404, 'project_not_found'); } let curDir: File | null = project.rootFolder; + if (!curDir) { + throw new Error(`Project ${project.name} has been left with no root folder`); + } res.locals.deepestFolderId = curDir.uuid; res.locals.deepestFolderName = curDir.name; if (fileNames.length === 0) { @@ -953,7 +1048,7 @@ export class FileRouter { } }); if (user == null) { - return next(new RequestError(404, 'user_not_found')); + //return next(new RequestError(404, 'user_not_found')); } else { res.locals.user = user; } diff --git a/src/conversion/czi/JxrDecApp b/src/conversion/czi/JxrDecApp Binary files differnew file mode 100755 index 0000000..bc35f65 --- /dev/null +++ b/src/conversion/czi/JxrDecApp diff --git a/src/db/.DS_Store b/src/db/.DS_Store Binary files differnew file mode 100644 index 0000000..6a62f95 --- /dev/null +++ b/src/db/.DS_Store diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index d3a5867..da7243d 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -1,12 +1,16 @@ -import { AllowNull, Column, DataType, HasMany, Model, Table +import { AllowNull, Column, DataType, HasMany, Model, PrimaryKey, Table } from 'sequelize-typescript'; import { default as UserJoinsProject } from './UserJoinsProject'; @Table export default class ContributorGroup extends Model<ContributorGroup> { - @AllowNull + @PrimaryKey @Column(DataType.TEXT) - public name!: string | null; + public name!: string; + + // @PrimaryKey + // @Column + // public username!: string; /* "Error: Foreign key for "ContributorGroup" * is missing on "UserJoinsProject"." */ @@ -31,6 +35,9 @@ export default class ContributorGroup extends Model<ContributorGroup> { @Column public canEditUserPermissions!: boolean; + @Column + public canDeleteProject!: boolean; + @AllowNull @Column(DataType.TEXT) public description!: string | null; diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index 6cda34e..7b30d56 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -1,5 +1,6 @@ import { default as ContributorGroup } from './ContributorGroup'; import { default as File } from './File'; +import { NotVoid } from 'lodash'; import { BelongsTo, BelongsToMany, Column, CreatedAt, DataType, ForeignKey, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; import { default as User } from './User'; @@ -92,30 +93,99 @@ export default class Project extends Model<Project> { return; } - public getAccessLevel(user: User): ContributorGroup { - throw new Error(`unimplemented, ${this}`); + public async hasAccessLevel(user: User, accessLevel: string): Promise<boolean> { + const ujps: UserJoinsProject[] | null = await UserJoinsProject.findAll({ + include: [ ContributorGroup], + where: { + username: user.username, + projectName: this.name + } + }); + if (ujps != null) { + const adders: ContributorGroup[] = await ujps.map((ujp: UserJoinsProject): ContributorGroup => { + if (ujp.contributorGroup != null) { + return ujp.contributorGroup; + } else { + throw new Error('Missing contributor group'); + } + }); + if (adders.some((cg: ContributorGroup): boolean => cg.name == accessLevel)) { + return true; + } + + switch (accessLevel) { + case 'canCreateFiles': + return adders.some( + (cg: ContributorGroup): boolean => cg.canCreateFiles + ); + case 'canDeleteFiles': + return adders.some( + (cg: ContributorGroup): boolean => cg.canDeleteFiles + ); + case 'canViewFiles': + return adders.some( + (cg: ContributorGroup): boolean => cg.canViewFiles + ); + case 'canAddUsers': + return adders.some( + (cg: ContributorGroup): boolean => cg.canAddUsers + ); + case 'canRemoveUsers': + return adders.some( + (cg: ContributorGroup): boolean => cg.canRemoveUsers + ); + case 'canEditUserPermissions': + return adders.some( + (cg: ContributorGroup): boolean => cg.canEditUserPermissions + ); + case 'canDeleteProject': + return adders.some( + (cg: ContributorGroup): boolean => cg.canDeleteProject + ); + default: + throw new Error('invalid access role'); + } + } else { + return(false); + } + } + + public async getAccessLevel(user: User): Promise<String[]> { + const ujps: UserJoinsProject[] | null = await UserJoinsProject.findAll({ + include: [ ContributorGroup], + where: { + username: user.username, + projectName: this.name + } + }); + const listContributors: String[] = await ujps.map((ujp: UserJoinsProject): String => { + if (ujp.contributorGroup != undefined) { + return ujp.contributorGroupName; + } else { + throw new Error('Invalid access'); + } + }); + return listContributors; } - public getUserInfo(user: User): UserInfo { + public async getUserInfo(user: User): Promise<UserInfo> { return { username: user.username, - access_level: this.getAccessLevel(user) - .toString() + access_level: (await this.getAccessLevel(user)).join() }; } - public get fullInfo(): ProjectFullInfo { + public async getFullInfo(): Promise<ProjectFullInfo> { if (this.contributors === undefined) { throw new Error('contributors undefined'); } return { project_name: this.name, - users: this.contributors - .map((u: User): UserInfo => this.getUserInfo(u)), + users: await Promise.all(this.contributors + .map( (u: User): Promise<UserInfo> => this.getUserInfo(u))), public_metadata: { creation_date: this.creationDate }, - // TODO: Check if we have anything to use these for yet? private_metadata: {}, admin_metadata: {} }; diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 76e055d..3c0abe2 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -1,3 +1,4 @@ +import { RequestError } from '../../errors/errorware'; import { default as File } from './File'; import { default as Project } from './Project'; import { BelongsToMany, Column, CreatedAt, DataType, HasMany, @@ -6,6 +7,9 @@ import { default as UserGroup } from './UserGroup'; import { default as UserHasPrivilege } from './UserHasPrivilege'; import { default as UserJoinsProject } from './UserJoinsProject'; +import ContributorGroup from './ContributorGroup'; +import { truncateFile } from '../../files'; + @Table export default class User extends Model<User> { @PrimaryKey @@ -13,7 +17,7 @@ export default class User extends Model<User> { public username!: string; @Column - private readonly passwordInternal!: string; + private passwordInternal!: string; @BelongsToMany(() => UserGroup, () => UserHasPrivilege) public userGroups?: UserGroup[]; @@ -104,28 +108,59 @@ export default class User extends Model<User> { return; } - // TODO implement - public getAccessLevel(project: Project): string { - throw new Error(`unimplemented, ${this}`); - } - public hasPrivilege(privilege: string): boolean { if (this.userGroups === undefined) { throw new Error('usergroups undefined'); } - return this.userGroups.some( - (ug: UserGroup): boolean => ug.name === privilege - ); + if (this.userGroups.some((ug: UserGroup): boolean => ug.name == privilege)) { + return true; + } + switch (privilege) { + case 'canCreateUsers': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canCreateUsers + ); + case 'canDeleteUsers': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canDeleteUsers + ); + case 'canEditUsers': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canEditUsers + ); + case 'canCreateProjects': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canCreateProjects + ); + case 'canDeleteProjects': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canDeleteProjects + ); + case 'canEditProjects': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canEditProjects + ); + case 'canAccessLogs': + return this.userGroups.some( + (ug: UserGroup): boolean => ug.canAccessLogs + ); + default: + throw new Error('privilege undefined'); + } + } + + public async getAccessLevel(project: Project): Promise<string> { + return (await project.getAccessLevel(this)).join(); } - public getProjectInfo(project: Project): ProjectInfo { + public async getProjectInfo(project: Project): Promise<ProjectInfo> { return { project_name: project.name, - access_level: this.getAccessLevel(project) + access_level: await this.getAccessLevel(project) }; } - public get fullInfo(): UserFullInfo { + public async getFullInfo(): Promise<UserFullInfo> { // FIXME: Fetch these things if they aren't already present if (this.userGroups === undefined) { this.userGroups = []; @@ -137,8 +172,8 @@ export default class User extends Model<User> { privileges: this.userGroups .filter((ug: UserGroup): boolean => ug.name !== null) .map((ug: UserGroup): string => ug.name as string), - projects : this.projects!.map( - (p: Project): ProjectInfo => this.getProjectInfo(p) + projects : await Promise.all( this.projects!.map( + (p: Project): Promise<ProjectInfo> => this.getProjectInfo(p)) ), // TODO: Check if we have anything to use these for yet? public_user_metadata: {}, @@ -154,15 +189,17 @@ export default class User extends Model<User> { private_user_metadata?: Metadata; }): void { if (newInfo.password !== undefined) { - if (this.authenticate(newInfo.password.old)) { - this.password = newInfo.password.new; + if (!this.authenticate(newInfo.password.old)) { + this.passwordInternal = newInfo.password.new; + } else { + throw new RequestError(400, 'invalid_password'); } } } public authenticate(password: string): boolean { // TODO use salting (and maybe even constant-time comparison?) - return password === this.password; + return password === this.passwordInternal; } public get password(): string { @@ -171,7 +208,7 @@ export default class User extends Model<User> { public set password(newPassword: string) { // TODO use salting - this.password = newPassword; + this.passwordInternal = newPassword; } } diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts index 0948517..c2aa33a 100644 --- a/src/db/model/UserJoinsProject.ts +++ b/src/db/model/UserJoinsProject.ts @@ -1,8 +1,8 @@ +import { default as ContributorGroup } from './ContributorGroup'; import { default as Project } from './Project'; import { BelongsTo, Column, CreatedAt, DataType, ForeignKey, Model, Table } from 'sequelize-typescript'; import { default as User } from './User'; -import { default as ContributorGroup } from './UserGroup'; @Table export default class UserJoinsProject extends Model<UserJoinsProject> { @@ -14,14 +14,14 @@ export default class UserJoinsProject extends Model<UserJoinsProject> { @Column public projectName!: string; + @ForeignKey(() => ContributorGroup) + @Column + public contributorGroupName!: string; + @CreatedAt @Column(DataType.DATE) public joinDate!: Date; - @ForeignKey(() => ContributorGroup) - @Column - public contributorGroupId!: number; - @BelongsTo(() => ContributorGroup) public contributorGroup?: ContributorGroup; } diff --git a/src/files.ts b/src/files.ts index b5495d8..a0bed00 100644 --- a/src/files.ts +++ b/src/files.ts @@ -349,16 +349,20 @@ export const rootPathFile: File | null = null; export const createRootFolder: () => Promise<void> = async( ): Promise<void> => { - if (!(await fs.access(CONTENT_BASE_DIRECTORY))) { + try { await fs.mkdir(CONTENT_BASE_DIRECTORY); + } catch (e) { + logger.warn(`error when creating base folder: ${e}`); } }; export const createProjectFolder: (name: string) => Promise<void> = async( projName: string ): Promise<void> => { - if (!(await fs.access(CONTENT_BASE_DIRECTORY + '/' + projName))) { + try { await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName); + } catch (e) { + logger.warn(`error when creating folder for project ${projName}: ${e}`); } }; diff --git a/src/index.ts b/src/index.ts index d5708d7..ffb6f68 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,10 @@ - +import * as fs from 'fs-extra'; import { logger } from './logger'; logger.info('Starting up server'); +logger.info('Creating necessary directories'); +fs.ensureDirSync('logs/general'); +fs.ensureDirSync('files'); logger.info('Importing server logic'); import { default as app } from './app'; @@ -10,6 +13,7 @@ logger.info('Importing database ORM'); import { createRootFolder, rootPathId } from './files'; import { default as seq } from './db/orm'; +import { default as ContributorGroup } from './db/model/ContributorGroup'; import { default as File } from './db/model/File'; import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; @@ -60,8 +64,77 @@ async function reset(): Promise<void> { description: 'Allows Post to Log' }); + const userManagement: UserGroup = new UserGroup({ + name: 'userManagement', + canCreateUsers: true, + canDeleteUsers: true, + canEditUsers: true, + isInternal: false, + description: 'Allows management of other users' + }); + + const projectAdmin: UserGroup = new UserGroup({ + name: 'projectAdmin', + canDeleteProjects: true, + canEditProjects: true, + isInternal: false, + description: 'Admin privileges on other projects ' + }); + + const standardUser: UserGroup = new UserGroup({ + name: 'standardUser', + canCreateProjects: true, + isInternal: true, + description: 'Allows creation of new projects' + }); + await logging.save(); await admin.save(); + await userManagement.save(); + await projectAdmin.save(); + await standardUser.save(); + + const projectOwner: ContributorGroup = new ContributorGroup({ + name: 'projectOwner', + canCreateFiles: true, + canAddUsers: true, + canRemoveUsers: true, + canDeleteFiles: true, + canDeleteProject: true, + canEditUserPermissions: true, + canViewFiles: true, + isInternal: false, + description: 'Project Admin' + }); + + const standardProjectUser: ContributorGroup = new ContributorGroup({ + name: 'standardProjectUser', + canCreateFiles: true, + canViewFiles: true, + isInternal: false, + description: 'Allows working on a project' + }); + + const readOnlyProjectUser: ContributorGroup = new ContributorGroup({ + name: 'readOnlyProjectUser', + canViewFiles: true, + isInternal: false, + description: 'Allows viewing of files in a project ' + }); + + const projectUserManagement: ContributorGroup = new ContributorGroup({ + name: 'projectUserManagement', + canAddUsers: true, + canEditUserPermissions: true, + canRemoveUsers: true, + isInternal: false, + description: 'Allows managament of users in a Project' + }); + + await projectOwner.save(); + await standardProjectUser.save(); + await readOnlyProjectUser.save(); + await projectUserManagement.save(); logger.info('Adding admin user'); const root: User = new User({ @@ -95,6 +168,7 @@ async function reset(): Promise<void> { // /await reset(); + logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { if (err) { diff --git a/src/mimetype.ts b/src/mimetype.ts new file mode 100644 index 0000000..dc06d54 --- /dev/null +++ b/src/mimetype.ts @@ -0,0 +1,27 @@ +import * as fromData from 'file-type'; +import { lookup as fromName } from 'mime-types'; + +const DEFAULT_MIMETYPE: string = 'application/octet-stream'; + +export const mimetype: ( + contentType?: string, data?: Buffer, name?: string +) => string = ( + contentType?: string, data?: Buffer, name?: string +): string => { + if (contentType && contentType !== DEFAULT_MIMETYPE) { + return contentType; + } + if (data) { + const fType: fromData.FileTypeResult = fromData(data); + if (fType) { + return fType.mime; + } + } + if (name) { + const mType: string | false = fromName(name); + if (mType) { + return mType; + } + } + return DEFAULT_MIMETYPE; +}; diff --git a/src/serverConfig.ts b/src/serverConfig.ts index 136995a..5d2575a 100644 --- a/src/serverConfig.ts +++ b/src/serverConfig.ts @@ -82,7 +82,7 @@ export class Property { } public set value(value: Value) { - if (!this.readOnly) { + if (this.readOnly) { throw new Error('this property is read-only'); } else if (!types[this.type](value)) { throw new Error(`value ${value} is not of type ${this.type}`); diff --git a/test/.DS_Store b/test/.DS_Store Binary files differnew file mode 100644 index 0000000..eef9cc0 --- /dev/null +++ b/test/.DS_Store diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index a371fd5..d60f844 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -103,7 +103,8 @@ const completeProtocol: MochaForEachInput[] = [ 'warning', 'error', 'critical', - 'success' + 'success', + 'failure' ]), message: types.anything, label: optional(types.string), @@ -135,7 +136,7 @@ const completeProtocol: MochaForEachInput[] = [ ]) }), 200], ['post', '/properties?action=update', - [{id: 'new_prop', value: 'some_value'}], 200], + [{id: 'project_example', value: 2}], 200], ['get', '/user_privileges', array({ privilege: types.string, description: types.string, @@ -166,7 +167,8 @@ const completeProtocol: MochaForEachInput[] = [ public_admin_metadata: types.anything, private_admin_metadata: types.anything }, 200], - ['post', '/users/new_user', null, 200], + ['post', '/users/new_user?action=create', + {password: 'secret', privileges: []}, 200], ['get', '/users/mock_user/properties', { data: optional(types.anything) }, 200], @@ -182,7 +184,10 @@ const completeProtocol: MochaForEachInput[] = [ public_admin_metadata: types.anything, private_admin_metadata: types.anything }, 200], - ['post', '/current_user', null, 200], + ['post', '/current_user?action=update', {password: { + old: 'pass', + new: 'newpass' + }}, 200], ['get', '/project_roles', array({ role: types.string, description: types.string, @@ -208,11 +213,11 @@ const completeProtocol: MochaForEachInput[] = [ private_metadata: types.anything, admin_metadata: optional(types.anything) }, 200], - ['post', '/projects/mocky', null, 200], + ['post', '/projects/mocky2', {}, 200], ['get', '/projects/mocky/properties', null, 200], - ['post', '/projects/mocky/files/folder+some_file?action=overwrite', {}, 200], - ['get', '/projects/mocky/files/folder+some_file', null, 200], - ['get', '/projects/mocky/files_by_id/file1', null, 200] + ['post', '/projects/mocky/files/foler/file?action=overwrite', {}, 200], + ['get', '/projects/mocky/files/foler/file', null, 200] + //['get', '/projects/mocky/files_by_id/file1', null, 200] ]; /* tslint:enable:align */ diff --git a/test/unit/Tissue Slides.00030.v13.csv b/test/unit/Tissue Slides.00030.v13.csv new file mode 100644 index 0000000..32a365f --- /dev/null +++ b/test/unit/Tissue Slides.00030.v13.csv @@ -0,0 +1,3 @@ +inner_x;inner_y;level_name;class_name;Mean CK;Mean D240;Mean DAPI;Standard deviation CK;Standard deviation D240;Standard deviation DAPI;Ratio CK;Ratio D240;Ratio DAPI;Area (µm²);Border length (Pxl);Length (µm);Length/Thickness;Length/Width;Number of pixels;Perimeter;Rel. Border to Image Border;Thickness (Pxl);Vessel Wall thickness (µm);Volume (Pxl);Width (µm);Asymmetry;Border index;Circularity;Compactness;Density;Elliptic Fit;Ellipticity;Roundness;Shape index
+278;1644;TissueLevel (ROI and bud map);Markers 1 and 2;111.91269841;49.00952381;43.888888889;46.453427751;53.507779331;27.926326608;0.54641907759;0.23929133309;0.21428958932;139.167;158;16.324198007;undefined;1.1350017263;630;0;0;undefined;0;630;14.382531435;0.22056688527;1.5490196078;2.5842367704;1.6870615231;2.0749555783;0.66031746032;0.3083863821;0.91206852044;1.573717669
+314;1630;TissueLevel (ROI and bud map);vessel border to bud invasion;8.1280438312;65.000202922;28.99411526;10.822207323;66.30369822;25.807309309;0.079591224399;0.63649333643;0.28391543917;1088.5952;608;54.52;undefined;1.5064935065;4928;0;0;undefined;0;4928;36.19;0.41167215052;2.0965517241;1.786429407;1.8125;2.1469508548;0.60470779221;0.26168440136;1.0913355585;2.1652509527
\ No newline at end of file |
