diff options
| author | cjd24 | 2018-03-04 18:15:30 +0000 |
|---|---|---|
| committer | cjd24 | 2018-03-04 18:15:30 +0000 |
| commit | 955da66072042089cf457ab6406bfd7c97c4286f (patch) | |
| tree | 379e4c4ea0bc008b3004b87b75bba8fc0348b18d /src | |
| parent | Playing around trying to get a list of base tiles we may be interested in for... (diff) | |
| parent | Implement handling of unauthorised requests (diff) | |
| download | medicine-955da66072042089cf457ab6406bfd7c97c4286f.tar.gz medicine-955da66072042089cf457ab6406bfd7c97c4286f.zip | |
Merge branch ‘trh/payload-checker’ into cjd24/conversion
Diffstat (limited to 'src')
| -rw-r--r-- | src/FileRouter.ts | 346 | ||||
| -rw-r--r-- | src/app.ts | 146 | ||||
| -rw-r--r-- | src/auth.ts | 167 | ||||
| -rw-r--r-- | src/db/model/ContributorGroup.ts | 22 | ||||
| -rw-r--r-- | src/db/model/File.ts | 34 | ||||
| -rw-r--r-- | src/db/model/Project.ts | 77 | ||||
| -rw-r--r-- | src/db/model/User.ts | 151 | ||||
| -rw-r--r-- | src/db/model/UserGroup.ts | 30 | ||||
| -rw-r--r-- | src/db/model/UserHasPrivilege.ts | 14 | ||||
| -rw-r--r-- | src/db/model/UserJoinsProject.ts | 10 | ||||
| -rw-r--r-- | src/errors/errorware.ts | 23 | ||||
| -rw-r--r-- | src/files.ts | 22 | ||||
| -rw-r--r-- | src/index.ts | 14 | ||||
| -rw-r--r-- | src/logger.ts | 26 | ||||
| -rw-r--r-- | src/serverConfig.ts | 156 | ||||
| -rw-r--r-- | src/uuid.ts | 7 |
16 files changed, 842 insertions, 403 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 34738bc..8d13401 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')) { + delete info.private_user_metadata; + delete info.private_admin_metadata; + } + 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(); } /** @@ -534,13 +537,13 @@ export class FileRouter { */ public init(): void { // General - this.router.get ('/_supported_protocols_', getProtocols); + this.router.get ('/_supported_protocols_', getProtocols); this.router.get ('/log', getLog); this.router.post('/log', postLog); this.router.get ('/properties', getProperties); this.router.post('/properties', postProperties); // Users - this.router.get ('/user_privileges', getUserPriveleges); + this.router.get ('/user_privileges', getUserPrivileges); this.router.get ('/users', getUsers); this.router.get ('/users/:username', getUsername); this.router.post('/users/:username', postUsername); @@ -564,5 +567,4 @@ export class FileRouter { const fileRoutes: FileRouter = new FileRouter(); fileRoutes.init(); -const ex: Router = fileRoutes.router; -export default ex; +export default fileRoutes.router; @@ -1,23 +1,48 @@ 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 { errorHandler } from './errors/errorware'; +import { unauthorisedErr, default as authRouter } from './auth'; + +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.express.use( + async(req: ex.Request, res: ex.Response, next: ex.NextFunction): + Promise<void> => { + res.json({ + status: 'success', + data: await res.locals.data + }); + } + ); this.errorware(); } // Configure Express middleware. private middleware(): void { + this.express.use(expressJwt({secret: 'Mr Secret'}) + .unless({path: [ + '/cs3099group-be-4/login', + '/cs3099group-be-4/_supported_protocols_' + ] }) + ); + this.express.use(passport.initialize()); if (this.logEnabled) { this.express.use(logger('combined')); } @@ -31,16 +56,133 @@ class App { defRouter.get('/', (req: ex.Request, res: ex.Response): void => { res.json({ message: 'Welcome to the CS3099 BE4 server!', - important : 'Endpoints start from /cs3099group-be-4/' + important: 'Endpoints start from /cs3099group-be-4/' }); }); this.express.use('/', defRouter); this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); } private errorware(): void { + this.express.use(unauthorisedErr); 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/auth.ts b/src/auth.ts index a59e417..083357e 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,41 +1,37 @@ +/* tslint:disable:prefer-function-over-method */ + +import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; -import * as expressJwt from 'express-jwt'; import * as jwt from 'jsonwebtoken'; import * as passport from 'passport'; import { Strategy } from 'passport-local'; import { default as User } from './db/model/User'; +import { Errorware } from './errors/errorware'; + export class AuthRouter { - public localStrategy: Strategy; public router: Router; public constructor() { - this.localStrategy = Strategy(); - this.router(); + this.router = Router(); this.init(); } - // Used by passport-js to locate a user object from the database by username - public findByUsername(username: string): User { - if (username === user.username) { - return user; - } - return false; - } + // Middleware which generates token and sends it as response + public async genToken(req: Request, res: Response): Promise<void> { + const user: User | null = await User.findOne({ + where: { + username: req.body.username + } + }); - // Find user object from database by user ID - public findUserByID(id): User { - if (id === user.id) { - return user; + if (user === null) { + // Whoa, what an error! + return; } - return false; - } - // Middleware which generates token and sends it as response - public genToken(req: Request, res: Response) { - const userid = findUserByID(req.body.username); - const token = jwt.sign( - { id: userid }, + const token: string = jwt.sign( + { id: user.username }, 'Mr Secret', { expiresIn: 21600 } ); @@ -48,89 +44,102 @@ export class AuthRouter { }); } + private authenticate(req: Request, res: Response, next: NextFunction): void { + passport.authenticate( + 'local', + { session: false }, + (err: Error, user: User) => { + // TODO: Implement + if (err) { throw err; } + + if (!user) { + next(new RequestError( + 400, 'invalid_grant', 'Incorrect authentication details' + )); + } + } + ); + next(); + } + // Checks for errors within request before authentication - public checkErr(req: Request, res: Response, next: NextFunction) { + public checkErr(req: Request, res: Response, next: NextFunction): void { if (!req.body.grant_type || !req.body.username || !req.body.password) { - res.status(400) - .json({ - error: 'invalid_request', - error_description: 'Missing parameters' - }); - res.end(); + next(new RequestError(400, 'invalid_request', 'Missing parameters')); } if (req.body.grant_type !== 'refresh_token' && req.body.grant_type !== 'password') { - res.status(400) - .json({ - error: 'unsupported_grant_type', - error_description: 'invalid grant type' - }); - res.end(); + next(new RequestError(400, 'unsupported_grant_type', 'invalid grant type')); } next(); } - // Handle error if user is unauthorised - public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { - if (err.name === 'UnauthorizedError') { - res.status(401).json({ - status: 'error', - error: 'not_authorised', - error_description: - 'user does not have correct authorisation to complete task' - }); + // Middleware to check privileges - admin + public isAdmin(req: Request, res: Response, next: NextFunction): void { + if (!req.user.admin) { + next(new RequestError( + 401, 'not_authorised', + 'user is not authorised to perform task' + )); + return; } next(); } // Configure local strategy to use with passport-js. - private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { - const user = findByUsername(username); + private configStrategy(): void { + // tslint:disable-next-line:typedef + passport.use(new Strategy( async(username, password, done) => { + const user: User | null = await User.findOne({ + where: { + username + } + }); - if (!user || user.password != password) { + if (!user || user.password !== password) { return done(null, false); } return done(null, user); })); } -} -/////////////////////////////////////////////////// - -const app = express(); -const ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error + public init(): void { + this.configStrategy(); -app.post('/login', checkErr, function(req, res, next) { - passport.authenticate('local', { session: false }, function(err, user) { - if (err) { console.log(err); } + this.router.post('/login', this.checkErr, this.authenticate, this.genToken); + this.router.get( + '/logout', + (req: Request, res: Response): void => { req.logout(); } + ); + } +} - if (!user) { - res.status(400).json({ - error: 'invalid_grant', - error_description: 'Incorrect authentication details' - }); - } - }); - next(); -}, genToken); +// Handle error if user is unauthorised +export const unauthorisedErr: Errorware = + (err: Error, req: Request, res: Response, next: NextFunction): void => { + console.log('fffff'); + if (err.name === 'UnauthorizedError') { + console.log('efewfwf'); + return next(new RequestError( + 401, 'not_authorised', + 'user does not have correct authorisation for task' + )); + } + next(err); +}; -app.get('/logout', function(req, res) { - req.logout(); -}); +const authRoutes: AuthRouter = new AuthRouter(); +authRoutes.init(); -app.get('/test', ensureAuth, function(req, res) { - res.send('you are authenticated!'); -}); +export default authRoutes.router; +/////////////////////////////////////////////////// /* -tasks left: - refreshing tokens - connect to db - revoke tokens/checking validity - logging out -*/ + * tasks left: + * refreshing tokens + * connect to db + * revoke tokens/checking validity + * logging out + */ 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..d290fd9 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 @@ -76,3 +193,5 @@ export interface UserFullInfo { public_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/errors/errorware.ts b/src/errors/errorware.ts index 8b7e015..e2355de 100644 --- a/src/errors/errorware.ts +++ b/src/errors/errorware.ts @@ -10,6 +10,13 @@ export interface ErrorResponseBlock { } export class RequestError extends Error { + public static is(test: Object): test is RequestError { + const err: RequestError = test as RequestError; + return err.code !== undefined + && err.name !== undefined + && err.responseBlock !== undefined; + } + public code: number; public userMessage?: string; // tslint:disable-next-line:no-any @@ -41,11 +48,17 @@ export class RequestError extends Error { } } -type Errorware = - (err: RequestError, req: Request, res: Response, next: NextFunction) => void; +export type Errorware = + (err: Error, req: Request, res: Response, next: NextFunction) => void; export const errorHandler: Errorware = - (err: RequestError, req: Request, res: Response, next: NextFunction): void => { - res.status(err.code) - .json(err.responseBlock()); + (err: Error, req: Request, res: Response, next: NextFunction): void => { + console.log(err); + if (RequestError.is(err)) { + console.log('fewkuihfklsfv'); + res.status(err.code) + .json(err.responseBlock()); + } else { + res.send(err); + } }; 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/index.ts b/src/index.ts index 06989ef..c6adf32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ import { default as app } from './app'; import { default as seq } from './db/orm'; console.log('end import'); +import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; const DEFAULT_PORT: number = 3000; @@ -39,8 +40,17 @@ const port: number = process.env.PORT description: 'Systems admin' }); - // tslint:disable:no-floating-promises - admin.save(); + await admin.save(); + + console.log(admin.id); + + const root: User = new User({ + username: 'hafeez', + password: 'pass', + userGroup: admin + }); + + root.save(); console.log('Booting ExpressJS server'); 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 +}; |
