aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorcjd242018-04-19 20:48:19 +0100
committercjd242018-04-19 20:48:19 +0100
commit92e23d37f843e49eda01a4d0ea7ed8005efffdb2 (patch)
tree7c08678dfce9bf82eaa4f71f5e23182f8515d386 /src
parentAdded a write of the base teir JSON object, made the images actually write to... (diff)
parentMerge branch 'trh/gets' into cjd24/conversion (diff)
downloadmedicine-92e23d37f843e49eda01a4d0ea7ed8005efffdb2.tar.gz
medicine-92e23d37f843e49eda01a4d0ea7ed8005efffdb2.zip

Merge branch ‘cjd24/conversion’ of https://gitlab.cs.st-andrews.ac.uk/cs3099group-be-4/project-code into cjd24/conversion

Diffstat (limited to 'src')
-rw-r--r--src/FileRouter.ts493
-rw-r--r--src/app.ts184
-rw-r--r--src/auth.ts7
-rw-r--r--src/db/model/File.ts76
-rw-r--r--src/db/model/Project.ts4
-rw-r--r--src/db/model/User.ts8
-rw-r--r--src/db/model/UserGroup.ts3
-rw-r--r--src/files.ts256
-rw-r--r--src/index.ts56
-rw-r--r--src/logger.ts231
-rw-r--r--src/matcher/index.ts1
-rw-r--r--src/matcher/options.ts13
12 files changed, 1049 insertions, 283 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 4d6eb16..53fc537 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -6,15 +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 { RequestError } from './errors/errorware';
-import { files } 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';
-// TODO: figure this out
-const BASE_FILE_STORAGE: string = 'TODO: figure this out';
/**
* The type of an Express middleware callback.
@@ -32,8 +29,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,10 +59,13 @@ 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 => {
+ res.locals.modified = true;
+ logger.debug('Adding forwarded log');
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'));
@@ -100,11 +102,19 @@ 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');
+ res.locals.modified = true;
if (!req.user.hasPrivilege('admin')) {
- next(new RequestError(400, 'invalid_privilege'));
+ 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),
@@ -135,8 +145,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 +165,11 @@ 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');
+ res.locals.modified = true;
for (const newProp of req.body) {
const prop: Property | undefined = serverConfig.find(
(p: Property): boolean => p.id === newProp.id
@@ -188,8 +203,10 @@ const postProperties: Middleware =
* "internal": boolean
* })
*/
-const getUserPrivileges: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const getUserPrivileges: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ logger.debug('Listing all user privileges');
const usergroups: UserGroup[] = await UserGroup.findAll();
res.locals.data = usergroups.map(
(ug: UserGroup) => ug.getPrivilege()
@@ -220,6 +237,7 @@ const getUserPrivileges: Middleware =
const getUsers: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
+ logger.debug('Listing all registered users');
const users: User[] = await User.findAll({
include: [
UserGroup,
@@ -240,8 +258,15 @@ 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.modified = true;
+ if (res.locals.user == null) {
+ next(new RequestError(404, 'user_not_found'));
+ return;
+ }
res.locals.data = res.locals.user.properties;
next();
};
@@ -266,9 +291,12 @@ const getUserProperties: Middleware =
* "private_admin_metadata": metadata
* }
*/
-const getUsername: Middleware =
- (req: Request, res: Response, next: NextFunction): void => {
- if (res.locals.user === null) {
+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;
}
@@ -276,8 +304,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 +330,11 @@ const getCurUser: Middleware =
* "private_admin_metadata": not_present
* }
*/
-const postCurUser: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const postCurUser: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ logger.debug('Editing current user');
+ res.locals.modified = true;
try {
await req.user.updateInfo(req.body);
await req.user.save();
@@ -328,18 +361,24 @@ const postCurUser: Middleware =
* "private_admin_metadata": optional(metadata)
* }
*/
-const postUsername: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const postUsername: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): 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;
}
- user.metadata = req.body;
+ if (req.body) {
+ user.metadata = req.body;
+ }
next();
};
@@ -354,8 +393,11 @@ const postUsername: Middleware =
* "internal": boolean
* })
*/
-const getProjectRoles: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const getProjectRoles: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ res.locals.modified = true;
+ logger.debug('Listing available project roles');
const roles: ContributorGroup[] = await ContributorGroup.findAll();
res.locals.data = roles.filter(
(cg: ContributorGroup): boolean => !cg.isInternal
@@ -382,8 +424,11 @@ const getProjectRoles: Middleware =
* "admin_metadata": optional(metadata)
* })
*/
-const getProjects: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const getProjects: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ logger.debug('Listing all projects');
+ res.locals.modified = true;
const projects: Project[] = await Project.findAll({
include: [
User
@@ -412,8 +457,11 @@ const getProjects: Middleware =
* "admin_metadata": optional(metadata)
* }
*/
-const getProjectName: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const getProjectName: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ 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'));
@@ -436,20 +484,32 @@ const getProjectName: Middleware =
* "admin_metadata": optional(metadata)
* }
*/
-const postProjectName: Middleware =
- async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+const postProjectName: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
let project: Project | null = res.locals.project;
+ res.locals.modified = true;
let promise: PromiseLike<File> | null = null;
if (project == null) {
+ logger.debug('Adding new project');
const file: File = new File({
- mimetype: 'inode/directory'
+ uuid: uuid.generate(),
+ mimetype: 'inode/directory',
+ 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;
@@ -460,8 +520,11 @@ const postProjectName: Middleware =
/**
* 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');
+ res.locals.modified = true;
if (res.locals.project == null) {
next(new RequestError(404, 'project_not_found'));
} else {
@@ -473,53 +536,195 @@ const getProjectProperties: Middleware =
/**
* GET a File.
*/
-const getFilePath: Middleware = async(
+const getFile: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
+ logger.debug(`Getting file in ${req.query.view} view`);
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'];
+ // 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();
};
/**
* 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;
+const getFilePath: Middleware = getFile;
+
+/**
+ * GET a File.
+ */
+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);
}
- res.locals.function = res.sendFile;
- res.locals.data = files.path(req.params.id, res.locals.project.name);
- next();
-};
+ 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
*/
-const postFilePath: Middleware =
- (req: Request, res: Response, next: NextFunction): void => {
- if (res.locals.file != null) {
+/* tslint:disable */
+const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => {
+ logger.debug(`Receiving file ${res.locals.path}`);
+ console.log(req.file);
+ // 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'));
+ }
+
+ // 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'));
}
- 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));
+
+ // 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)){
+ logger.info(`File ${res.locals.file.name} will be deleted`)
+ deleteFile(res.locals.file.uuid, res.locals.project.name);
+ await res.locals.file.destroy();
+ 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(),
+ nameInternal: res.locals.filename
+ });
+ 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, res.locals.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));
+ }
+
+ // Sets final if requested
+ if (qH.isFinal(req)) {
+ res.locals.file.status = 'final';
+ }
+
next();
+
};
+/* tslint:enable */
export class FileRouter {
public router: Router;
@@ -537,6 +742,8 @@ export class FileRouter {
* endpoints.
*/
public init(): void {
+ this.precondition();
+
// General
this.router.get ('/_supported_protocols_', getProtocols);
this.router.get ('/log', getLog);
@@ -559,13 +766,161 @@ 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',
+ upload.single('userfile'), postFilePath);
this.router.get ('/projects/:project_name/files_by_id/:id', getFileId);
}
+
+ /**
+ * 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 {
+ logger.debug('Adding parameter preconditioning to router');
+ // Fetch a user from their name:
+ this.router.param(
+ 'username',
+ async(
+ req: Request, res: Response, next: NextFunction,
+ name: string
+ ): Promise<void> => {
+ logger.debug(`Searching for user ${name}`);
+ const user: User | null = await User.findOne({
+ include: [{all: true}],
+ 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,
+ projectName: string
+ ): Promise<void> => {
+ res.locals.project = await Project.findOne({
+ include: [
+ User
+ ],
+ where: {
+ name: projectName
+ }
+ });
+ next();
+ }
+ );
+
+ // Fetch a file from its path:
+ this.router.param(
+ 'path',
+ async(
+ req: Request, res: Response, next: NextFunction,
+ filename: string
+ ): Promise<void> => {
+ // 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 /
+ 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'));
+ }
+ let curDir: File | null = project.rootFolder;
+ 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.
+ while (curDir && i < fileNames.length) {
+ logger.debug(`Searching for \'${fileNames[i]}\'`);
+ const fileOrNull: File | null = await File.findOne({
+ include: [{all: true}],
+ where: {
+ nameInternal: fileNames[i],
+ parentFolderId: curDir.uuid
+ }
+ });
+ if (fileOrNull == null) {
+ logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`);
+ return next();
+ }
+
+ if (i < fileNames.length - 1) {
+ // Found next subdirectory
+ logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`);
+ res.locals.deepestFolderId = fileOrNull.uuid;
+ res.locals.deepestFolderName = fileOrNull.name;
+ } else {
+ // Found actual file
+ logger.debug(`Found file \'${fileOrNull.name}\'`);
+ res.locals.file = fileOrNull;
+ }
+ curDir = fileOrNull;
+ i++;
+ }
+
+ next();
+ }
+ );
+
+ // Fetch a file from its UUID:
+ this.router.param(
+ 'id',
+ async(
+ req: Request, res: Response, next: NextFunction,
+ fileId: string
+ ): Promise<void> => {
+ logger.info(`parsing id ${fileId}`);
+ const file: File | null = await File.findOne({
+ include: [{all: true}],
+ where: {
+ uuid: fileId
+ }
+ });
+ 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 {
+ logger.debug('parentfolder not set!');
+ }
+ }
+ next();
+ }
+ );
+ }
}
// 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 c627027..09b9e6a 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -1,10 +1,10 @@
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';
+import { logger } from './logger';
import { RequestError, errorHandler } from './errors/errorware';
import FileRouter from './FileRouter';
@@ -24,7 +24,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;
@@ -40,29 +40,59 @@ class App {
* server.
*/
public constructor(enableLog: boolean) {
+ logger.debug('Constructing router');
this.logEnabled = enableLog;
this.express = ex();
- this.precondition();
+ this.cors();
+ 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(
async(req: ex.Request, res: ex.Response, next: ex.NextFunction):
Promise<void> => {
- 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
+ });
+ }
+ logger.success(`Responded to ${req.ip}`);
}
);
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.
*/
private middleware(): void {
+ logger.debug('Loading basic middleware');
this.express.use(expressJwt({secret: 'Mr Secret'})
.unless({path: [
+ '/',
'/cs3099group-be-4/oauth/token',
'/cs3099group-be-4/_supported_protocols_'
] })
@@ -83,9 +113,6 @@ class App {
}
next();
});
- if (this.logEnabled) {
- this.express.use(logger('combined'));
- }
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: false }));
}
@@ -101,17 +128,22 @@ class App {
important: 'Endpoints start from /cs3099group-be-4/'
});
});
- defRouter.get('/*', (req: ex.Request, res: ex.Response): void => {
- res.status(404)
+ 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 => {
+ if (Object.keys(res.locals).length === 0) {
+ res.status(404)
.json({
status: 'error',
error : 'invalid_route',
error_description: 'Endpoints start from /cs3099group-be-4/'
});
+ } else {
+ next();
+ }
});
- this.express.use('/cs3099group-be-4', FileRouter);
- this.express.use('/cs3099group-be-4', authRouter);
- this.express.use('/', defRouter);
}
/**
@@ -121,126 +153,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<void> => {
- 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<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) {
- 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<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(true).express;
@@ -250,5 +162,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/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) {
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 33043f0..8a12431 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -3,18 +3,45 @@ 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';
+
+/*
+ * attributes:
+ * - nameInternal
+ * - fullPathInternal
+ * - uuid
+ * - type
+ * - size
+ * - parentFolderId
+ * - containedFilesInternal
+ * - creatorName
+ * - creator
+ * - rootFolderOf
+ * - uploadDate
+ * - modifyDate
+ * - status
+ * - metadataInternal
+*/
+
@Table
export default class File extends Model<File> {
@AllowNull
@Column
- public name!: string;
+ public 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 +73,39 @@ export default class File extends Model<File> {
@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;
+ if (this.fullPathInternal) {
+ this.fullPathInternal = this.fullPathInternal.substring(
+ 0,
+ this.fullPathInternal.lastIndexOf('/') + 1
+ ) + this.name;
+ } else {
+ this.fullPathInternal = 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 +116,16 @@ export default class File extends Model<File> {
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/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<Project> {
return this.rootFolderInternal;
}
+ public get properties(): object {
+ return this;
+ }
+
public get metadata(): {
public_metadata?: Metadata;
private_metadata?: Metadata;
diff --git a/src/db/model/User.ts b/src/db/model/User.ts
index 171e899..73d2356 100644
--- a/src/db/model/User.ts
+++ b/src/db/model/User.ts
@@ -128,16 +128,16 @@ export default class User extends Model<User> {
public get fullInfo(): UserFullInfo {
// 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 = [];
}
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?
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
@@ -38,6 +38,9 @@ export default class UserGroup extends Model<UserGroup> {
public canEditProjects!: boolean;
@Column
+ public canAccessLogs!: boolean;
+
+ @Column
public isInternal!: boolean;
@AllowNull
diff --git a/src/files.ts b/src/files.ts
index 644d24e..5b15a10 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -1,28 +1,85 @@
-import * as fs from 'fs';
+import { Request, Response } from 'express';
+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';
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));
};
-const logPath:
-(type: string, projectName?: string) => string = (
- type: string, projectName?: string
-): string => {
+interface RawSize {
+ offset: number;
+ length: number;
+}
+
+const readableStream: (filename: string, projectName: string, { offset, length }?: Partial<RawSize>) => fs.ReadStream
+ = (filename: string, projectName: string, { offset, length }: Partial<RawSize> = { 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): string => {
return projectName
? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}`
: `${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 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).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 =
+ (fileId: string, projectName: string): void => {
+
+ 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: {
path: (f: string, p: string) => string;
writableStream: (f: string, p: string) => fs.WriteStream;
@@ -32,3 +89,182 @@ export const files: {
writableStream,
logPath
};
+
+export type ViewName = 'raw' | 'meta';
+
+interface Query extends Partial<RawSize> {
+ children?: boolean;
+}
+
+export interface View {
+ getContents: (file: File) => object;
+ getResponseData: (file: File, project: Project, query: Query) =>
+ Promise<object>;
+ 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<MetaResponseData> = async(
+ file: File, project: Project, query: Query
+): Promise<MetaResponseData> => {
+ 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<object> => {
+ return readableStream(file.uuid, 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<string, string> {
+ 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' ]
+]);
+
+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);
+ }
+}
+
+export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise<boolean> = async(parentId: string, subFileId: string): Promise<boolean> => {
+ 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}],
+ 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.uuid;
+ // save
+ await file.save();
+ await parent.save();
+
+ return true;
+}
diff --git a/src/index.ts b/src/index.ts
index f172e61..1ce284d 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';
@@ -20,16 +22,7 @@ const port: number = process.env.PORT
: DEFAULT_PORT;
logger.info(`Port ${port} chosen`);
-// tslint:disable:no-floating-promises
-(async(): Promise<void> => {
- 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<void> {
try {
logger.info('Resetting Database');
await seq.sync({
@@ -40,6 +33,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',
@@ -52,17 +53,48 @@ 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();
+ createRootFolder();
+
+ await root.$set('userGroups', [admin, logging]);
+
+ const user: User | null = await User.findOne({
+ include: [{all: true}],
+ where: {
+ username: 'hafeez'
+ }
+ });
+
+}
+
+// tslint:disable:no-floating-promises
+(async(): Promise<void> => {
+ 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) => {
diff --git a/src/logger.ts b/src/logger.ts
index bbb0a73..74ae1f7 100644
--- a/src/logger.ts
+++ b/src/logger.ts
@@ -4,27 +4,107 @@ import * as colors from 'colors/safe';
import * as winston from 'winston';
import { files } from './files';
+import { QueryOptions } from 'sequelize';
-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;
@@ -36,8 +116,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: (
@@ -58,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,
@@ -113,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,
@@ -173,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;
@@ -186,54 +271,108 @@ 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 => {
- 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<LogItem[]> = (level?: LogLevel, params: FetchParams = {}): Promise<LogItem[]> => {
+ 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.meta.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;
+ 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[];
+ fetch: (level: LogLevel, params?: FetchParams) => Promise<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
+ forward: forwardLog,
+ fetch: fetchLogs2
};
export const logQuery: (query: string, duration: string) => void = (
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/src/matcher/options.ts b/src/matcher/options.ts
index 62e4985..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);
@@ -85,7 +96,7 @@ export const array = (template: TemplateValue, values?: Value[]) => {
const m: Checker = types.function(template)
? template
: match.bind(null, template);
- return values.every(m);
+ return values.every(m); //
};
// tslint:disable-next-line:typedef