aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Harley2018-03-01 19:48:47 +0000
committerTom Harley2018-03-01 19:48:47 +0000
commit8bd1d19dbd899047bc8503dbe682358ddfc564cc (patch)
treeda016b8bb301a3f74123aceeee1d1a3427301fd6
parentRevert "Revert "Merge branch 'trh/error-middleware' into 'master'"" (diff)
downloadmedicine-8bd1d19dbd899047bc8503dbe682358ddfc564cc.tar.gz
medicine-8bd1d19dbd899047bc8503dbe682358ddfc564cc.zip

Implement GET and POST request handlers

-rw-r--r--package.json2
-rw-r--r--src/FileRouter.ts341
-rw-r--r--src/app.ts122
-rw-r--r--src/db/model/ContributorGroup.ts22
-rw-r--r--src/db/model/File.ts34
-rw-r--r--src/db/model/Project.ts77
-rw-r--r--src/db/model/User.ts155
-rw-r--r--src/db/model/UserGroup.ts30
-rw-r--r--src/db/model/UserHasPrivilege.ts14
-rw-r--r--src/db/model/UserJoinsProject.ts10
-rw-r--r--src/files.ts22
-rw-r--r--src/logger.ts26
-rw-r--r--src/serverConfig.ts156
-rw-r--r--src/uuid.ts7
-rw-r--r--yarn.lock6
15 files changed, 709 insertions, 315 deletions
diff --git a/package.json b/package.json
index 559efc7..8359cf3 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,7 @@
"@types/passport": "^0.4.2",
"@types/passport-local": "^1.0.32",
"@types/sequelize": "^4.27.5",
+ "@types/uuid": "^3.4.3",
"body-parser": "^1.18.2",
"express": "^4.16.2",
"express-jwt": "^5.3.0",
@@ -60,6 +61,7 @@
"sequelize-typescript": "^0.6.2",
"ts-node": "^3.3.0",
"typescript": "^2.7.1",
+ "uuid": "^3.2.1",
"xlsx": "^0.11.19"
}
}
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 34738bc..98fd5c4 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -6,7 +6,12 @@ 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 { default as serverConfig } from './serverConfig';
+
+import { RequestError } from './errors/errorware';
+import { files } from './files';
+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';
@@ -29,16 +34,13 @@ type Middleware =
*/
const getProtocols: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- const returnValue: {
- supported: string[];
- required: string[];
- } = {
- supported: [],
- required: [
- 'BE01'
- ]
+ res.locals.data = {
+ supported: [],
+ required: [
+ 'BE01'
+ ]
};
- res.send(JSON.stringify(returnValue));
+ next();
};
/**
@@ -60,8 +62,21 @@ const getProtocols: Middleware =
*/
const postLog: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.status(501)
- .send({error : 'logging_not_enabled'});
+ if (!req.user.hasPrivilege('logging')) {
+ next(new RequestError(400, 'invalid_privilege'));
+ return;
+ } else if (!logger.isEnabled()) {
+ next(new RequestError(501, 'logging_not_enabled'));
+ return;
+ }
+ for (const item of req.body) {
+ logger.log(item.level, item.value, {
+ component: item.component,
+ user: req.user.username,
+ external: true
+ });
+ }
+ next();
};
/**
@@ -87,8 +102,16 @@ const postLog: Middleware =
*/
const getLog: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.status(501)
- .send({error : 'logging_not_enabled'});
+ if (!req.user.hasPrivilege('admin')) {
+ next(new RequestError(400, 'invalid_privilege'));
+ }
+ res.locals.data = logger.fetch(
+ req.params.level, {
+ before: new Date(req.params.before),
+ after: new Date(req.params.after)
+ }
+ );
+ next();
};
/**
@@ -114,8 +137,8 @@ const getLog: Middleware =
*/
const getProperties: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.status(200)
- .send(serverConfig);
+ res.locals.data = serverConfig;
+ next();
};
/**
@@ -132,51 +155,26 @@ const getProperties: Middleware =
*/
const postProperties: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- let success: boolean = true;
-
- // For each property to update
- for (const prop of req.body) {
-
- // Check that the property has and id and a value
- if (!prop.hasOwnProperty('id') || !prop.hasOwnProperty('value')) {
- res.status(400)
- .send({
- error: 'invalid_request',
- error_description: 'A supplied property is missing an id or value'
- });
- success = false;
- break;
+ for (const newProp of req.body) {
+ const prop: Property | undefined = serverConfig.find(
+ (p: Property): boolean => p.id === newProp.id
+ );
+ if (prop === undefined) {
+ next(new RequestError(400, 'invalid_property', undefined, newProp.id));
+ return;
+ } else if (prop.readOnly) {
+ next(new RequestError(400, 'invalid_property', undefined, newProp.id));
+ return;
}
-
- // Find out if the property exists in the config and if so, at which index
- const index: number = serverConfig.indexOf(prop.id);
-
- // Check some of the properties values to ensure that it can be updated
- if (index === -1 || serverConfig[index].readOnly) {
- /* TODO Implement an or, using Tom's type checker
- * to ensure the value is "valid" based on the type of the property */
- const description: string = index === -1
- ? 'Property not found'
- : 'Property is Read_Only';
- res.status(400)
- .send({
- error: 'invalid_property',
- error_data: prop.id,
- error_description: description
- });
- success = false;
- break;
+ try {
+ prop.value = newProp.value;
+ } catch (err) {
+ // FIXME: Assuming it's a value-type error, but it might not be!
+ next(new RequestError(400, 'invalid_property_value', undefined, newProp.id));
+ return;
}
-
- // Make the update to the property
- serverConfig[index].value = prop.value;
- }
-
- // Tell the client that everything was okay;
- if (success) {
- res.status(200)
- .send();
}
+ next();
};
/**
@@ -190,12 +188,13 @@ const postProperties: Middleware =
* "internal": boolean
* })
*/
-const getUserPriveleges: Middleware =
+const getUserPrivileges: Middleware =
async(req: Request, res: Response, next: NextFunction): Promise<void> => {
const usergroups: UserGroup[] = await UserGroup.findAll();
- res.json(usergroups.map(
- (ug: UserGroup) => ug.getPrivelege()
- ));
+ res.locals.data = usergroups.map(
+ (ug: UserGroup) => ug.getPrivilege()
+ );
+ next();
};
/**
@@ -226,41 +225,26 @@ const getUsers: Middleware =
Project
]
});
- res.json(users.map<UserFullInfo>(
- (u: User) => u.getUserFullInfo()
- ));
+ res.locals.data = users.map<UserFullInfo>(
+ (u: User) => {
+ const info: UserFullInfo = u.fullInfo;
+ if (!req.user.hasPrivilege('admin')) {
+ info.private_user_metadata = undefined;
+ info.private_admin_metadata = undefined;
+ }
+ return info;
+ }
+ );
+ next();
};
/**
* Expose additional configuration options for individual users
*/
const getUserProperties: Middleware =
- (req: Request, res: Response, next: NextFunction, user?: string): void => {
- res.status(500)
- .send({
- error: 'unsupported',
- error_description:
- 'Users on this server dont have additional configuration options.'
- });
-};
-
-const userInfoFromName: (name: string) => Promise<UserFullInfo> =
- async(name: string): Promise<UserFullInfo> => {
- const user: User | null = await User.findOne({
- where: {
- username: name
- },
- include: [
- UserGroup,
- Project
- ]
- });
-
- if (user === null) {
- throw new Error(`No user of name ${name} in database.`);
- } else {
- return user.getUserFullInfo();
- }
+ (req: Request, res: Response, next: NextFunction): void => {
+ res.locals.data = res.locals.user.properties;
+ next();
};
/**
@@ -284,16 +268,19 @@ const userInfoFromName: (name: string) => Promise<UserFullInfo> =
* }
*/
const getUsername: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
- const info: UserFullInfo = await userInfoFromName(req.params.username);
- res.json(info);
+ (req: Request, res: Response, next: NextFunction): void => {
+ if (res.locals.user === null) {
+ next(new RequestError(404, 'user_not_found'));
+ return;
+ }
+ res.locals.data = res.locals.user.fullInfo;
+ next();
};
const getCurUser: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.json({
- todo: 'need to findo out where authenticated user info goes'
- });
+ res.locals.data = req.user.fullInfo;
+ next();
};
/**
@@ -315,8 +302,15 @@ const getCurUser: Middleware =
* }
*/
const postCurUser: Middleware =
- (req: Request, res: Response, next: NextFunction): void => {
- res.json({todo: 'need to implement meeeee'});
+ async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+ try {
+ await req.user.updateInfo(req.body);
+ await req.user.save();
+ } catch (err) {
+ next(err);
+ return;
+ }
+ next();
};
/**
@@ -336,8 +330,18 @@ const postCurUser: Middleware =
* }
*/
const postUsername: Middleware =
- (req: Request, res: Response, next: NextFunction): void => {
- res.json({todo: 'need to implement meeeee'});
+ async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+ let user: User | null | undefined = res.locals.user;
+ if (user == null) {
+ user = new User({
+ username: req.params.username,
+ password: req.params.password
+ });
+ } else {
+ user.password = req.params.password;
+ }
+ user.metadata = req.body;
+ next();
};
/**
@@ -354,9 +358,12 @@ const postUsername: Middleware =
const getProjectRoles: Middleware =
async(req: Request, res: Response, next: NextFunction): Promise<void> => {
const roles: ContributorGroup[] = await ContributorGroup.findAll();
- res.json(roles.map<ContributorGroupFullInfo>(
- (cg: ContributorGroup) => cg.getContributorGroupFullInfo()
- ));
+ res.locals.data = roles.filter(
+ (cg: ContributorGroup): boolean => !cg.isInternal
+ ).map(
+ (cg: ContributorGroup): ContributorGroupFullInfo => cg.fullInfo
+ );
+ next();
};
/**
@@ -383,9 +390,10 @@ const getProjects: Middleware =
User
]
});
- res.json(projects.map<ProjectFullInfo>(
- (p: Project) => p.getProjectFullInfo()
- ));
+ res.locals.data = projects.map(
+ (p: Project): ProjectFullInfo => p.fullInfo
+ );
+ next();
};
/**
@@ -407,15 +415,12 @@ const getProjects: Middleware =
*/
const getProjectName: Middleware =
async(req: Request, res: Response, next: NextFunction): Promise<void> => {
- const project: Project | null = await Project.findOne({
- where: {
- name: req.params.project_name
- }
- });
+ const project: Project | null = res.locals.project;
if (project === null) {
- throw new Error(`Project ${req.params.project_name} does not exist`);
+ next(new RequestError(404, 'project_not_found'));
} else {
- res.json(project);
+ res.locals.data = project.fullInfo;
+ next();
}
};
@@ -433,42 +438,37 @@ const getProjectName: Middleware =
* }
*/
const postProjectName: Middleware =
- (req: Request, res: Response, next: NextFunction): void => {
- res.json({todo: 'need to implement meeeee'});
+ async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+ let project: Project | null = res.locals.project;
+ let promise: PromiseLike<File> | null = null;
+ if (project === null) {
+ const file: File = new File({
+ mimetype: 'inode/directory'
+ });
+ promise = file.save();
+ project = new Project({
+ uuid: uuid.generate(),
+ name: req.params.project_name,
+ rootFolder: file
+ });
+ }
+ project.metadata = req.body;
+ // tslint:disable-next-line:await-promise
+ await promise;
+ await project.save();
+ next();
};
-/*
+/**
* additional configuration options for individual projects
*/
const getProjectProperties: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.status(500)
- .send({
- error: 'unsupported',
- error_description:
- 'Projects on this server dont have additional configuration options.'
- });
-};
-
-const getChildFile: (names: string[], parentUuid: string) => Promise<File> =
- async(names: string[], parentUuid: string): Promise<File> => {
- // TODO: Check that this works lol :3
- const child: File | null = await File.findOne({
- where: {
- parentFolderId: parentUuid,
- name: names[0]
- }
- });
-
- if (child === null) {
- throw new Error(`File of name ${names[0]} does not exist`);
+ if (res.locals.project == null) {
+ next(new RequestError(404, 'project_not_found'));
} else {
- if (names.length === 1) {
- return child;
- } else {
- names.splice(0, 1);
- return getChildFile(names, child.uuid);
- }
+ res.locals.data = res.locals.project.properties;
+ next();
}
};
@@ -477,25 +477,15 @@ const getChildFile: (names: string[], parentUuid: string) => Promise<File> =
*/
const getFilePath: Middleware =
async(req: Request, res: Response, next: NextFunction): Promise<void> => {
- const project: Project | null = await Project.findOne({
- where: {
- name: req.params.project_name
- }
- });
-
- if (project === null) {
- throw new Error(
- `Project of name ${req.params.project_name} does not exist`
- );
- } else {
- const file: File = await getChildFile(
- req.params.project_name, project.rootFolderId
- );
-
- res.sendFile(
- `${BASE_FILE_STORAGE}/${req.params.project_name}/${file.uuid}`
- );
+ 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 =
+ `${BASE_FILE_STORAGE}/${res.locals.project.name}/${file.uuid}`;
+ next();
};
/**
@@ -503,10 +493,14 @@ const getFilePath: Middleware =
*/
const getFileId: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- // TODO: implement correctness of project folder checking.
- res.sendFile(
- `${BASE_FILE_STORAGE}/${req.params.project_name}/${req.params.id}`
- );
+ 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();
};
/**
@@ -514,7 +508,16 @@ const getFileId: Middleware =
*/
const postFilePath: Middleware =
(req: Request, res: Response, next: NextFunction): void => {
- res.json({todo: 'need to implement meeeee'});
+ if (res.locals.file != null) {
+ next(new RequestError(400, 'file_exists'));
+ }
+ const file: File = new File({
+ uuid: uuid.generate(),
+ name: res.locals.filename,
+ parentFolder: res.locals.parentFolder
+ });
+ req.pipe(files.writableStream(file.uuid, res.locals.project.name));
+ next();
};
export class FileRouter {
@@ -524,8 +527,8 @@ export class FileRouter {
* Initialize the FileRouter
*/
public constructor() {
- this.router = Router();
- this.init();
+ this.router = Router();
+ this.init();
}
/**
@@ -540,7 +543,7 @@ export class FileRouter {
this.router.get ('/properties', getProperties);
this.router.post('/properties', postProperties);
// Users
- this.router.get ('/user_privileges', getUserPriveleges);
+ this.router.get ('/user_privileges', getUserPrivileges);
this.router.get ('/users', getUsers);
this.router.get ('/users/:username', getUsername);
this.router.post('/users/:username', postUsername);
diff --git a/src/app.ts b/src/app.ts
index a843179..86b0c1c 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -2,15 +2,20 @@ import * as bodyParser from 'body-parser';
import * as ex from 'express';
import * as logger from 'morgan';
-import { errorHandler } from './errors/errorware';
+import { RequestError, errorHandler } from './errors/errorware';
import FileRouter from './FileRouter';
+import { default as File } from './db/model/File';
+import { default as Project } from './db/model/Project';
+import { default as User } from './db/model/User';
+
class App {
public express: ex.Express;
public logEnabled: boolean = true;
public constructor() {
this.express = ex();
+ this.precondition();
this.middleware();
this.mountRoutes();
this.errorware();
@@ -41,6 +46,121 @@ class App {
private errorware(): void {
this.express.use(errorHandler);
}
+
+ 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<void> => {
+ const user: User | null = await User.findOne({
+ where: {
+ username: name
+ }
+ });
+ if (user === null) {
+ next(new RequestError(404, 'user_not_found'));
+ return;
+ } 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<void> => {
+ 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<void> => {
+ 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;
+ }
+ 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) {
+ next();
+ return;
+ } 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) {
+ next();
+ return;
+ }
+ 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<void> => {
+ const file: File | null = await File.findOne({
+ where: {
+ uuid: fileId
+ }
+ });
+ if (file === null) {
+ next(new RequestError(404, 'file_not_found'));
+ return;
+ } else {
+ res.locals.file = file;
+ }
+ next();
+ }
+ );
+ }
}
export default new App().express;
diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts
index 6bbcf4a..d3a5867 100644
--- a/src/db/model/ContributorGroup.ts
+++ b/src/db/model/ContributorGroup.ts
@@ -6,39 +6,39 @@ import { default as UserJoinsProject } from './UserJoinsProject';
export default class ContributorGroup extends Model<ContributorGroup> {
@AllowNull
@Column(DataType.TEXT)
- public name: string | null = null;
+ public name!: string | null;
/* "Error: Foreign key for "ContributorGroup"
* is missing on "UserJoinsProject"." */
@HasMany(() => UserJoinsProject, 'contributorGroupId')
- public uses: UserJoinsProject[] = [];
+ public uses?: UserJoinsProject[];
@Column
- public canCreateFiles: boolean = false;
+ public canCreateFiles!: boolean;
@Column
- public canDeleteFiles: boolean = false;
+ public canDeleteFiles!: boolean;
@Column
- public canViewFiles: boolean = false;
+ public canViewFiles!: boolean;
@Column
- public canAddUsers: boolean = false;
+ public canAddUsers!: boolean;
@Column
- public canRemoveUsers: boolean = false;
+ public canRemoveUsers!: boolean;
@Column
- public canEditUserPermissions: boolean = false;
+ public canEditUserPermissions!: boolean;
@AllowNull
@Column(DataType.TEXT)
- public description: string | null = null;
+ public description!: string | null;
@Column
- public isInternal: boolean = true;
+ public isInternal!: boolean;
- public getContributorGroupFullInfo(): ContributorGroupFullInfo {
+ public get fullInfo(): ContributorGroupFullInfo {
return {
role: `${this.name}`,
description: `${this.description}`,
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 225512d..50c8e74 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -5,43 +5,55 @@ import { default as User } from './User';
@Table
export default class File extends Model<File> {
+ @AllowNull
@Column
- public name: string = '';
+ public name!: string;
@PrimaryKey
@Column
- public uuid: string = '';
+ public uuid!: string;
@Column
- public mimetype: string = '';
+ public mimetype!: string;
@ForeignKey(() => File)
@AllowNull
@Column(DataType.TEXT)
- public parentFolderId: string | null = null;
+ public parentFolderId!: string | null;
@BelongsTo(() => File)
- public parentFolder: File = new File();
+ public parentFolder?: File;
@HasMany(() => File)
- public containedFiles: File[] = [];
+ public containedFilesInternal?: File[];
@ForeignKey(() => User)
@AllowNull
@Column(DataType.TEXT)
- public creatorName: string | null = null;
+ public creatorName!: string | null;
@BelongsTo(() => User)
- public creator: User = new User();
+ public creator?: User;
@HasOne(() => Project)
- public rootFolderOf: Project = new Project();
+ public rootFolderOf?: Project;
@CreatedAt
@Column
- public uploadDate: Date = new Date();
+ public uploadDate!: Date;
@UpdatedAt
@Column
- public modifyDate: Date = new Date();
+ public modifyDate!: Date;
+
+ public get containedFiles(): File[] {
+ if (this.containedFilesInternal === undefined) {
+ throw new Error('containedFiles is undefined');
+ }
+ return this.containedFilesInternal;
+ }
+
+ public set containedFiles(files: File[]) {
+ this.containedFilesInternal = files;
+ }
}
diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts
index 2c26a04..388c5e5 100644
--- a/src/db/model/Project.ts
+++ b/src/db/model/Project.ts
@@ -7,28 +7,86 @@ import { default as UserJoinsProject } from './UserJoinsProject';
@Table
export default class Project extends Model<Project> {
-
@PrimaryKey
@Column
- public name: string = '';
+ public name!: string;
@BelongsToMany(() => User, () => UserJoinsProject)
- public contributors: User[] = [];
+ public contributors?: User[];
@ForeignKey(() => File)
@Column
- public rootFolderId: string = '';
+ public rootFolderId!: string;
@BelongsTo(() => File)
- public rootFolder: File = new File();
+ private readonly rootFolderInternal?: File;
@CreatedAt
@Column
- public creationDate: Date = new Date();
+ public creationDate!: Date;
@UpdatedAt
@Column
- public lastActivity: Date = new Date();
+ public lastActivity!: Date;
+
+ public get rootFolder(): File {
+ if (this.rootFolderInternal === undefined) {
+ throw new Error('rootFolderInternal is undefined');
+ }
+ return this.rootFolderInternal;
+ }
+
+ public get metadata(): {
+ public_metadata?: Metadata;
+ private_metadata?: Metadata;
+ admin_metadata?: Metadata;
+ } {
+ return {
+ public_metadata: this.publicMetadata,
+ private_metadata: this.privateMetadata,
+ admin_metadata: this.adminMetadata
+ };
+ }
+
+ public set metadata(newMetadata: {
+ public_metadata?: Metadata;
+ private_metadata?: Metadata;
+ admin_metadata?: Metadata;
+ }) {
+ if (newMetadata.public_metadata) {
+ this.publicMetadata = newMetadata.public_metadata;
+ }
+ if (newMetadata.private_metadata) {
+ this.privateMetadata = newMetadata.private_metadata;
+ }
+ if (newMetadata.admin_metadata) {
+ this.adminMetadata = newMetadata.admin_metadata;
+ }
+ }
+
+ public get publicMetadata(): Metadata {
+ return {};
+ }
+
+ public set publicMetadata(newMetadata: Metadata) {
+ return;
+ }
+
+ public get privateMetadata(): Metadata {
+ return {};
+ }
+
+ public set privateMetadata(newMetadata: Metadata) {
+ return;
+ }
+
+ public get adminMetadata(): Metadata {
+ return {};
+ }
+
+ public set adminMetadata(newMetadata: Metadata) {
+ return;
+ }
public getAccessLevel(user: User): ContributorGroup {
throw new Error(`unimplemented, ${this}`);
@@ -42,7 +100,10 @@ export default class Project extends Model<Project> {
};
}
- public getProjectFullInfo(): ProjectFullInfo {
+ public get fullInfo(): ProjectFullInfo {
+ if (this.contributors === undefined) {
+ throw new Error('contributors undefined');
+ }
return {
project_name: this.name,
users: this.contributors
diff --git a/src/db/model/User.ts b/src/db/model/User.ts
index 5a9af07..0c9d521 100644
--- a/src/db/model/User.ts
+++ b/src/db/model/User.ts
@@ -1,41 +1,124 @@
import { default as File } from './File';
import { default as Project } from './Project';
-import { BelongsTo, BelongsToMany, Column, CreatedAt, ForeignKey, HasMany,
+import { BelongsToMany, Column, CreatedAt, HasMany,
Model, PrimaryKey, Table } from 'sequelize-typescript';
import { default as UserGroup } from './UserGroup';
+import { default as UserHasPrivilege } from './UserHasPrivilege';
import { default as UserJoinsProject } from './UserJoinsProject';
@Table
export default class User extends Model<User> {
@PrimaryKey
@Column
- public username: string = '';
+ public username!: string;
@Column
- public password: string = '';
+ private readonly passwordInternal!: string;
- @ForeignKey(() => UserGroup)
- @Column
- public userGroupId: number = 0;
-
- @BelongsTo(() => UserGroup)
- public userGroup: UserGroup = new UserGroup();
+ @BelongsToMany(() => UserGroup, () => UserHasPrivilege)
+ public userGroups?: UserGroup[];
@BelongsToMany(() => Project, () => UserJoinsProject)
- public projects: Project[] = [];
+ public projects?: Project[];
@HasMany(() => File)
- public createdFiles: File[] = [];
+ public createdFiles?: File[];
@CreatedAt
@Column
- public creationDate: Date = new Date();
+ public creationDate!: Date;
+
+ // TODO: Implement
+ public get properties(): UserProperty[] {
+ return [];
+ }
+
+ // TODO: Implement
+ public set properties(newProps: UserProperty[]) {
+ return;
+ }
+
+ public get metadata(): {
+ public_user_metadata?: Metadata;
+ private_user_metadata?: Metadata;
+ public_admin_metadata?: Metadata;
+ private_admin_metadata?: Metadata;
+ } {
+ return {
+ public_user_metadata: this.publicUserMetadata,
+ private_user_metadata: this.privateUserMetadata,
+ public_admin_metadata: this.publicAdminMetadata,
+ private_admin_metadata: this.privateAdminMetadata
+ };
+ }
+
+ public set metadata(newMetadata: {
+ public_user_metadata?: Metadata;
+ private_user_metadata?: Metadata;
+ public_admin_metadata?: Metadata;
+ private_admin_metadata?: Metadata;
+ }) {
+ if (newMetadata.public_user_metadata) {
+ this.publicUserMetadata = newMetadata.public_user_metadata;
+ }
+ if (newMetadata.private_user_metadata) {
+ this.privateUserMetadata = newMetadata.private_user_metadata;
+ }
+ if (newMetadata.public_admin_metadata) {
+ this.publicAdminMetadata = newMetadata.public_admin_metadata;
+ }
+ if (newMetadata.private_admin_metadata) {
+ this.privateAdminMetadata = newMetadata.private_admin_metadata;
+ }
+ }
+
+ public get publicUserMetadata(): Metadata {
+ return {};
+ }
+
+ public set publicUserMetadata(newMetadata: Metadata) {
+ return;
+ }
+
+ public get privateUserMetadata(): Metadata {
+ return {};
+ }
+
+ public set privateUserMetadata(newMetadata: Metadata) {
+ return;
+ }
+
+ public get publicAdminMetadata(): Metadata {
+ return {};
+ }
+
+ public set publicAdminMetadata(newMetadata: Metadata) {
+ return;
+ }
+
+ public get privateAdminMetadata(): Metadata {
+ return {};
+ }
+
+ public set privateAdminMetadata(newMetadata: Metadata) {
+ return;
+ }
// TODO implement
public getAccessLevel(project: Project): string {
throw new Error(`unimplemented, ${this}`);
}
+ public hasPrivilege(privilege: string): boolean {
+ // FIXME: Fetch these things if they aren't already present
+ if (this.userGroups === undefined) {
+ throw new Error('usergroups undefined');
+ }
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.name === privilege
+ );
+ }
+
public getProjectInfo(project: Project): ProjectInfo {
return {
project_name: project.name,
@@ -43,12 +126,20 @@ export default class User extends Model<User> {
};
}
- public getUserFullInfo(): UserFullInfo {
+ public get fullInfo(): UserFullInfo {
+ // FIXME: Fetch these things if they aren't already present
+ if (this.userGroups === undefined) {
+ throw new Error('userGroups undefined');
+ } else if (this.projects === undefined) {
+ throw new Error('projects undefined');
+ }
return {
username : this.username,
- privileges: [`${this.userGroup.name}`],
- projects : this.projects.map<ProjectInfo>(
- (p: Project) => this.getProjectInfo(p)
+ 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)
),
// TODO: Check if we have anything to use these for yet?
public_user_metadata: {},
@@ -57,6 +148,32 @@ export default class User extends Model<User> {
private_admin_metadata: {}
};
}
+
+ public updateInfo(newInfo: {
+ password?: { old: string; new: string };
+ public_user_metadata?: Metadata;
+ private_user_metadata?: Metadata;
+ }): void {
+ if (newInfo.password !== undefined) {
+ if (this.authenticate(newInfo.password.old)) {
+ this.password = newInfo.password.new;
+ }
+ }
+ }
+
+ public authenticate(password: string): boolean {
+ // TODO use salting (and maybe even constant-time comparison?)
+ return password === this.password;
+ }
+
+ public get password(): string {
+ return this.passwordInternal;
+ }
+
+ public set password(newPassword: string) {
+ // TODO use salting
+ this.password = newPassword;
+ }
}
// TODO MAKE PRETTY below
@@ -72,7 +189,9 @@ export interface UserFullInfo {
privileges: string[];
projects: ProjectInfo[];
public_user_metadata: Metadata;
- private_user_metadata: Metadata;
+ private_user_metadata?: Metadata;
public_admin_metadata: Metadata;
- private_admin_metadata: Metadata;
+ private_admin_metadata?: Metadata;
}
+
+export interface UserProperty {}
diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts
index 865fbbc..7d42425 100644
--- a/src/db/model/UserGroup.ts
+++ b/src/db/model/UserGroup.ts
@@ -1,6 +1,7 @@
-import { AllowNull, Column, DataType, HasMany, Model, Table
- } from 'sequelize-typescript';
+import { AllowNull, BelongsToMany, Column, DataType, Model, Table,
+ Unique } from 'sequelize-typescript';
import { default as User } from './User';
+import { default as UserHasPrivilege } from './UserHasPrivilege';
interface UserPrivilege {
privilege: string;
@@ -11,38 +12,39 @@ interface UserPrivilege {
@Table
export default class UserGroup extends Model<UserGroup> {
@AllowNull
+ @Unique
@Column(DataType.TEXT)
- public name: string | null = null;
+ public name!: string | null;
- @HasMany(() => User)
- public users: User[] = [];
+ @BelongsToMany(() => User, () => UserHasPrivilege)
+ public users?: User[];
@Column
- public canCreateUsers: boolean = false;
+ public canCreateUsers!: boolean;
@Column
- public canDeleteUsers: boolean = false;
+ public canDeleteUsers!: boolean;
@Column
- public canEditUsers: boolean = false;
+ public canEditUsers!: boolean;
@Column
- public canCreateProjects: boolean = false;
+ public canCreateProjects!: boolean;
@Column
- public canDeleteProjects: boolean = false;
+ public canDeleteProjects!: boolean;
@Column
- public canEditProjects: boolean = false;
+ public canEditProjects!: boolean;
@Column
- public isInternal: boolean = true;
+ public isInternal!: boolean;
@AllowNull
@Column(DataType.TEXT)
- public description: string | null = null;
+ public description!: string | null;
- public getPrivelege(): UserPrivilege {
+ public getPrivilege(): UserPrivilege {
return {
privilege : `${this.name}`,
description : `${this.description}`,
diff --git a/src/db/model/UserHasPrivilege.ts b/src/db/model/UserHasPrivilege.ts
new file mode 100644
index 0000000..17105c0
--- /dev/null
+++ b/src/db/model/UserHasPrivilege.ts
@@ -0,0 +1,14 @@
+import { Column, ForeignKey, Model, Table } from 'sequelize-typescript';
+import { default as User } from './User';
+import { default as Privilege } from './UserGroup';
+
+@Table
+export default class UserHasPrivilege extends Model<UserHasPrivilege> {
+ @ForeignKey(() => User)
+ @Column
+ public username!: string;
+
+ @ForeignKey(() => Privilege)
+ @Column
+ public privilegeId!: number;
+}
diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts
index 36a1591..2bf7ea0 100644
--- a/src/db/model/UserJoinsProject.ts
+++ b/src/db/model/UserJoinsProject.ts
@@ -8,20 +8,20 @@ import { default as ContributorGroup } from './UserGroup';
export default class UserJoinsProject extends Model<UserJoinsProject> {
@ForeignKey(() => User)
@Column
- public username: string = '';
+ public username!: string;
@ForeignKey(() => Project)
@Column
- public projectName: string = '';
+ public projectName!: string;
@CreatedAt
@Column
- public joinDate: Date = new Date();
+ public joinDate!: Date;
@ForeignKey(() => ContributorGroup)
@Column
- public contributorGroupId: number = 0;
+ public contributorGroupId!: number;
@BelongsTo(() => ContributorGroup)
- public contributorGroup: ContributorGroup = new ContributorGroup();
+ public contributorGroup?: ContributorGroup;
}
diff --git a/src/files.ts b/src/files.ts
new file mode 100644
index 0000000..daab817
--- /dev/null
+++ b/src/files.ts
@@ -0,0 +1,22 @@
+import * as fs from 'fs';
+
+const CONTENT_BASE_DIRECTORY: string = './files';
+
+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 => {
+ return fs.createWriteStream(path(filename, projectName));
+};
+
+export const files: {
+ path: (f: string, p: string) => string;
+ writableStream: (f: string, p: string) => fs.WriteStream;
+} = {
+ path,
+ writableStream
+};
diff --git a/src/logger.ts b/src/logger.ts
new file mode 100644
index 0000000..70c6455
--- /dev/null
+++ b/src/logger.ts
@@ -0,0 +1,26 @@
+/* tslint:disable:no-any */
+
+interface Metadata {
+ [key: string]: any;
+}
+
+export const logger: {
+ log: (
+ level: string,
+ value: any,
+ meta: Metadata
+ ) => void;
+ fetch: (
+ level: string,
+ meta: Metadata
+ ) => any[];
+ isEnabled: () => boolean;
+} = {
+ log: (level: string, value: any, meta: Metadata): void => {
+ return;
+ },
+ fetch: (level: string, meta: Metadata): any[] => {
+ return [];
+ },
+ isEnabled: (): boolean => false
+};
diff --git a/src/serverConfig.ts b/src/serverConfig.ts
index ea7b195..136995a 100644
--- a/src/serverConfig.ts
+++ b/src/serverConfig.ts
@@ -1,64 +1,54 @@
+import { default as types } from './matcher/types';
+
+type Value = string | number | boolean;
+type ValueString = 'string' | 'number' | 'integer' | 'boolean';
+
const serverConfig: Property[] = [];
/**
* A way to display user-configurable properties.
*/
-class PropertyDisplay {
+interface PropertyDisplay {
/**
* The category the property belongs to.
*/
- public category: string;
+ category: string;
/**
* The group the property belongs to.
*/
- public group: string;
+ group: string;
/**
* The name for the property to display to a user.
*/
- public displayName: string;
+ displayName: string;
/**
* The description of the property.
*/
- public description: string;
-
- /**
- * Constructs a [[PropertyDisplay]] using its properties.
- *
- * @param cat The property's category.
- * @param grp The property's group.
- * @param dn The property's displayable name.
- * @param desc A description of the property.
- */
- public constructor(cat: string, grp: string, dn: string, desc: string) {
- this.category = cat;
- this.group = grp;
- this.displayName = dn;
- this.description = desc;
- }
+ description: string;
}
/**
* A server property that infuences the running of the server.
* Loaded from configs at launch, and possibly editable during run-time.
*/
-export interface Property {
+export class Property {
/**
* The property's unique ID.
*/
- id: string;
+ public id: string;
/**
* How to display the property to the user.
*/
- display?: PropertyDisplay;
+ public display?: PropertyDisplay;
/**
* Is the property read-only, or can it be edited at run-time?
*/
- readOnly: boolean;
+ public readOnly: boolean;
/**
* The variable type of the property.
@@ -66,71 +56,81 @@ export interface Property {
* These strings represent Javascript types directly,
* except `"integer"`, which is a `number` in logic.
*/
- type: 'string' | 'number' | 'integer' | 'boolean';
+ public type: ValueString;
/**
* The value of the property.
*/
- value: string | number | boolean;
+ private valueInternal!: Value;
+
+ public constructor(
+ id: string,
+ type: ValueString,
+ value: Value,
+ readOnly: boolean = true,
+ display?: PropertyDisplay
+ ) {
+ this.id = id;
+ this.display = display;
+ this.readOnly = readOnly;
+ this.type = type;
+ this.valueInternal = value;
+ }
+
+ public get value(): Value {
+ return this.valueInternal;
+ }
+
+ public set value(value: Value) {
+ 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}`);
+ }
+ this.valueInternal = value;
+ }
}
// Logging
-let propertyDisplay: PropertyDisplay = new PropertyDisplay(
- 'Logging',
- 'BE4',
- 'Is logging enabled?',
- 'This property defines if logging is currently enabled on this backend server.'
-);
-
-serverConfig.push({
- id: 'Server_Log',
- display: propertyDisplay,
- readOnly: false,
- type: 'boolean',
- value: false
-});
+let propertyDisplay: PropertyDisplay = {
+ category: 'logging',
+ group: 'BE4',
+ displayName: 'Is logging enabled?',
+ description:
+ 'This property defines if logging is enabled on this backend server.'
+};
+
+serverConfig.push(new Property(
+ 'Server_Log',
+ 'boolean',
+ false,
+ false,
+ propertyDisplay
+));
// Caching Settings (global)
-serverConfig.push({
- id: 'Global_Cache_Limit',
- readOnly: true,
- type: 'integer',
- value: 1
-});
+serverConfig.push(new Property(
+ 'Global_Cache_Limit',
+ 'integer',
+ 1,
+ true
+));
// Caching Settings (project level)
-propertyDisplay = new PropertyDisplay(
- 'Caching',
- 'BE4',
- 'Caching Type',
- 'This property defines the current caching style for this project.'
-);
-
-serverConfig.push({
- id: 'project_example',
- display: propertyDisplay,
- readOnly: false,
- type: 'integer',
- value: 1
-});
-
-/**
- * Checks if a property exists in the server's property list.
- *
- * @param propKey The property unique ID to search for.
- * @returns The index of the property in the server's property list,
- * or `-1` if the property is not present.
- */
-export const propertyExists: (propKey: string) => number =
- (propKey: string): number => {
- let found: number = -1;
- for (const prop in serverConfig) {
- if (serverConfig[prop].id === propKey) {
- found = parseInt(prop, 10);
- break;
- }
- }
- return found;
+propertyDisplay = {
+ category: 'Caching',
+ group: 'BE4',
+ displayName: 'Caching Type',
+ description:
+ 'This property defines the current caching style for this project.'
};
+serverConfig.push(new Property(
+ 'project_example',
+ 'integer',
+ 1,
+ false,
+ propertyDisplay
+));
+
export default serverConfig;
diff --git a/src/uuid.ts b/src/uuid.ts
new file mode 100644
index 0000000..983a92d
--- /dev/null
+++ b/src/uuid.ts
@@ -0,0 +1,7 @@
+import { v4 } from 'uuid';
+
+export const uuid: {
+ generate: () => string;
+} = {
+ generate: v4
+};
diff --git a/yarn.lock b/yarn.lock
index bcd1c9e..bc305ec 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -217,6 +217,12 @@
"@types/glob" "*"
"@types/node" "*"
+"@types/uuid@^3.4.3":
+ version "3.4.3"
+ resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.3.tgz#121ace265f5569ce40f4f6d0ff78a338c732a754"
+ dependencies:
+ "@types/node" "*"
+
"@types/validator@*":
version "6.3.0"
resolved "https://registry.yarnpkg.com/@types/validator/-/validator-6.3.0.tgz#d7454bd67c6a933a9dbe939ae16edbf0f6894e70"