From 5dafe924bbbd5cc09901186ff74e4b68a6dcd52f Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 22 Feb 2018 18:47:08 +0000 Subject: Revert "Revert "Merge branch 'trh/error-middleware' into 'master'"" This reverts commit 3198c6c2474101623e3b95bd038effe210c176a8. --- src/FileRouter.ts | 535 +++++++++++++++++++++++---------------- src/app.ts | 14 +- src/auth.ts | 136 ++++++++++ src/db/model/ContributorGroup.ts | 54 ++++ src/db/model/File.ts | 47 ++++ src/db/model/Project.ts | 75 ++++++ src/db/model/User.ts | 78 ++++++ src/db/model/UserGroup.ts | 52 ++++ src/db/model/UserJoinsProject.ts | 27 ++ src/db/orm.ts | 12 + src/errors/errorware.test.ts | 35 +++ src/errors/errorware.ts | 51 ++++ src/index.ts | 49 +++- src/matcher/options.test.ts | 163 ++++++++++++ src/matcher/options.ts | 99 ++++++++ src/matcher/types.test.ts | 178 +++++++++++++ src/matcher/types.ts | 79 ++++++ 17 files changed, 1456 insertions(+), 228 deletions(-) create mode 100644 src/auth.ts create mode 100644 src/db/model/ContributorGroup.ts create mode 100644 src/db/model/File.ts create mode 100644 src/db/model/Project.ts create mode 100644 src/db/model/User.ts create mode 100644 src/db/model/UserGroup.ts create mode 100644 src/db/model/UserJoinsProject.ts create mode 100644 src/db/orm.ts create mode 100644 src/errors/errorware.test.ts create mode 100644 src/errors/errorware.ts create mode 100644 src/matcher/options.test.ts create mode 100644 src/matcher/options.ts create mode 100644 src/matcher/types.test.ts create mode 100644 src/matcher/types.ts (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 8b12d0f..34738bc 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -1,6 +1,15 @@ +import { ContributorGroupFullInfo, default as ContributorGroup + } from './db/model/ContributorGroup'; +import { default as File } from './db/model/File'; +import { ProjectFullInfo, default as Project } from './db/model/Project'; +import { UserFullInfo, default as User } from './db/model/User'; +import { default as UserGroup } from './db/model/UserGroup'; + import { NextFunction, Request, Response, Router } from 'express'; -import { Property, default as serverConfig, - propertyExists } from './serverConfig'; +import { default as serverConfig } from './serverConfig'; + +// TODO: figure this out +const BASE_FILE_STORAGE: string = 'TODO: figure this out'; /** * The type of an Express middleware callback. @@ -8,15 +17,15 @@ import { Property, default as serverConfig, type Middleware = (req: Request, res: Response, next: NextFunction) => void; -/* +/** * Returns the supported Protocols * * The server's unwrapped response MUST match: - - exactly({ - "supported": array(string), - "required": array(string) - }) + * + * exactly({ + * "supported": array(string), + * "required": array(string) + * }) */ const getProtocols: Middleware = (req: Request, res: Response, next: NextFunction): void => { @@ -24,132 +33,137 @@ const getProtocols: Middleware = supported: string[]; required: string[]; } = { - supported: [ - 'BE50' - ], - required: [ - 'BE01' - ] + supported: [], + required: [ + 'BE01' + ] }; res.send(JSON.stringify(returnValue)); }; -/* +/** * Logging Endpoint for all components: * * with a request matching - - array({ - "component": string, - "level": alternative([ - "info", "security", "warning", "error", "critical" - ]), - "value": anything - }) + * + * array({ + * "component": string, + * "level": alternative([ + * "info", + * "security", + * "warning", + * "error", + * "critical" + * ]), + * "value": anything + * }) */ const postLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { res.status(501) - .send({error: 'logging_not_enabled'}); + .send({error : 'logging_not_enabled'}); }; -/* +/** * Clients authorised as a user with the admin privilege can access * * http://backend.endpoint/log?before=&after=&level= * * the server response should match - - array({ - "component": string, - "level": alternative( - ["info", "security", "warning", "error", "critical" - ]), - "value": anything, - "username": string, - "timestamp": string - }) + * + * array({ + * "component": string, + * "level": alternative([ + * "info", + * "security", + * "warning", + * "error", + * "critical" + * ]), + * "value": anything, + * "username": string, + * "timestamp": string + * }) */ const getLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { res.status(501) - .send({error: 'logging_not_enabled'}); + .send({error : 'logging_not_enabled'}); }; -/* +/** * Any authenticated client can access * * http://backend.endpoint/properties * * the server SHOULD respond with a list of properties, * with the unwrapped response matching - - array({ - "id": string, - "display": optional({ - "category": string, - "group": string, - "display_name": string, - "description": string - }), - "read_only": boolean, - "type": alternative(["string", "integer", "boolean"]), - "value": alternative([string, integer, boolean]) - }) + * + * array({ + * "id": string, + * "display": optional({ + * "category": string, + * "group": string, + * "display_name": string, + * "description": string + * }), + * "read_only": boolean, + * "type": alternative(["string", "integer", "boolean"]), + * "value": alternative([string, integer, boolean]) + * }) */ const getProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.send(serverConfig); + res.status(200) + .send(serverConfig); }; -/* +/** * To update properties the client POSTs to * * http://backend.endpoint/properties?action=update * * with body - - array({ - "id": string, - "value": alternative([string, integer, boolean]) - }) + * + * array({ + * "id": string, + * "value": alternative([string, integer, boolean]) + * }) */ const postProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { let success: boolean = true; // For each property to update - let prop: Property; - for (prop of req.body) { + for (const prop of req.body) { - // Check that the property has an ID and a value + // 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' - }); + error: 'invalid_request', + error_description: 'A supplied property is missing an id or value' + }); success = false; break; } // Find out if the property exists in the config and if so, at which index - const index: number = propertyExists(prop.id); + 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 + /* 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 - }); + error: 'invalid_property', + error_data: prop.id, + error_description: description + }); success = false; break; } @@ -165,222 +179,262 @@ const postProperties: Middleware = } }; -/* +/** * Listing available privileges * * And the server's response, unwrapped, must match - - array({ - "privilege": string, - "description": string, - "internal": boolean - }) + * + * array({ + * "privilege": string, + * "description": string, + * "internal": boolean + * }) */ const getUserPriveleges: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise => { + const usergroups: UserGroup[] = await UserGroup.findAll(); + res.json(usergroups.map( + (ug: UserGroup) => ug.getPrivelege() + )); }; -/* +/** * Listing users * * If the client is authorised as a user with the admin privilege * the server MUST respond with a list of users, * with the unwrapped response matching - - array({ - "username": string, - "privileges": array(string), - "projects": array({ - "project_name": string, - "access_level": string - }), - "public_user_metadata": metadata, - "private_user_metadata": metadata, - "public_admin_metadata": metadata, - "private_admin_metadata": metadata - }) + * + * array({ + * "username": string, + * "privileges": array(string), + * "projects": array({ + * "project_name": string, + * "access_level": string + * }), + * "public_user_metadata": metadata, + * "private_user_metadata": metadata, + * "public_admin_metadata": metadata, + * "private_admin_metadata": metadata + * }) */ const getUsers: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); - + async(req: Request, res: Response, next: NextFunction): Promise => { + const users: User[] = await User.findAll({ + include: [ + UserGroup, + Project + ] + }); + res.json(users.map( + (u: User) => u.getUserFullInfo() + )); }; -/* - * expose additional configuration options for individual users - * - * +/** + * Expose additional configuration options for individual users */ const getUserProperties: Middleware = - (req: Request, res: Response, next: NextFunction): void => { + (req: Request, res: Response, next: NextFunction, user?: string): void => { res.status(500) - .send(); + .send({ + error: 'unsupported', + error_description: + 'Users on this server dont have additional configuration options.' + }); }; -/* +const userInfoFromName: (name: string) => Promise = + async(name: string): Promise => { + 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(); + } +}; + +/** * Listing a particular User * * If the client is authorised as a user with the admin privilege - * the server MUST respond with details of the particular user - * if they exist (unwrapped response): - - { - "username": string, - "privileges": array(string), - "projects": array({ - "project_name": string, - "access_level": string - }), - "public_user_metadata": metadata, - "private_user_metadata": metadata, - "public_admin_metadata": metadata, - "private_admin_metadata": metadata - } + * the server MUST respond with details of the particular user if they exist + * (unwrapped response): + * + * { + * "username": string, + * "privileges": array(string), + * "projects": array({ + * "project_name": string, + * "access_level": string + * }), + * "public_user_metadata": metadata, + * "private_user_metadata": metadata, + * "public_admin_metadata": metadata, + * "private_admin_metadata": metadata + * } */ -const getUsername: - (req: Request, res: Response, next: NextFunction, user?: string) => void = - (req: Request, res: Response, next: NextFunction, user?: string): void => { - res.status(500) - .send(); +const getUsername: Middleware = + async(req: Request, res: Response, next: NextFunction): Promise => { + const info: UserFullInfo = await userInfoFromName(req.params.username); + res.json(info); }; const getCurUser: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); - const curUser: string = ''; - getUsername(req, res, next, curUser); + res.json({ + todo: 'need to findo out where authenticated user info goes' + }); }; -/* +/** * Updating the current user * * http://backend.endpoint/current_user?action=update * * with body matching - - { - "password": optional({ - "old": string, - "new": string - }), - "public_user_metadata": optional(metadata), - "private_user_metadata": optional(metadata), - "public_admin_metadata": not_present, - "private_admin_metadata": not_present - } -*/ + * + * { + * "password": optional({ + * "old": string, + * "new": string + * }), + * "public_user_metadata": optional(metadata), + * "private_user_metadata": optional(metadata), + * "public_admin_metadata": not_present, + * "private_admin_metadata": not_present + * } + */ const postCurUser: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + res.json({todo: 'need to implement meeeee'}); }; -/* +/** * Creating a User/updating a user * * http://backend.endpoint/users/?action=create * * with body matching - - { - "privileges": array(string), - "password": string, - "public_user_metadata": optional(metadata), - "private_user_metadata": optional(metadata), - "public_admin_metadata": optional(metadata), - "private_admin_metadata": optional(metadata) - } + * + * { + * "privileges": array(string), + * "password": string, + * "public_user_metadata": optional(metadata), + * "private_user_metadata": optional(metadata), + * "public_admin_metadata": optional(metadata), + * "private_admin_metadata": optional(metadata) + * } */ const postUsername: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + res.json({todo: 'need to implement meeeee'}); }; -/* +/** * Listing available Roles * * The servers response, unwrapped, must match - - array({ - "role": string, - "description": string, - "internal": boolean - }) + * + * array({ + * "role": string, + * "description": string, + * "internal": boolean + * }) */ const getProjectRoles: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise => { + const roles: ContributorGroup[] = await ContributorGroup.findAll(); + res.json(roles.map( + (cg: ContributorGroup) => cg.getContributorGroupFullInfo() + )); }; -/* +/** * Listing Projects * * The server MUST respond with a list of projects, * with the unwrapped response matching - - array({ - "project_name": string, - "users": array({ - "username": string, - "access_level": string - }), - "public_metadata": metadata, - "private_metadata": optional(metadata), - "admin_metadata": optional(metadata) - }) + * + * array({ + * "project_name": string, + * "users": array({ + * "username": string, + * "access_level": string + * }), + * "public_metadata": metadata, + * "private_metadata": optional(metadata), + * "admin_metadata": optional(metadata) + * }) */ const getProjects: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise => { + const projects: Project[] = await Project.findAll({ + include: [ + User + ] + }); + res.json(projects.map( + (p: Project) => p.getProjectFullInfo() + )); }; -/* +/** * Listing a specific Project * * The server MUST respond with details of the particular project * if it exists (unwrapped response): - - { - "project_name": string, - "users": array({ - "username": string, - "access_level": string - }), - "public_metadata": metadata, - "private_metadata": metadata, - "admin_metadata": optional(metadata) - } + * + * { + * "project_name": string, + * "users": array({ + * "username": string, + * "access_level": string + * }), + * "public_metadata": metadata, + * "private_metadata": metadata, + * "admin_metadata": optional(metadata) + * } */ const getProjectName: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise => { + const project: Project | null = await Project.findOne({ + where: { + name: req.params.project_name + } + }); + if (project === null) { + throw new Error(`Project ${req.params.project_name} does not exist`); + } else { + res.json(project); + } }; -/* +/** * Creating a Project / updating a project / deleting / Project grants * * http://backend.endpoint/projects/?action=create * * with body matching - - { - "public_metadata": optional(metadata), - "private_metadata": optional(metadata), - "admin_metadata": optional(metadata) - } + * + * { + * "public_metadata": optional(metadata), + * "private_metadata": optional(metadata), + * "admin_metadata": optional(metadata) + * } */ const postProjectName: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + res.json({todo: 'need to implement meeeee'}); }; /* @@ -389,34 +443,78 @@ const postProjectName: Middleware = const getProjectProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { res.status(500) - .send(); + .send({ + error: 'unsupported', + error_description: + 'Projects on this server dont have additional configuration options.' + }); +}; + +const getChildFile: (names: string[], parentUuid: string) => Promise = + async(names: string[], parentUuid: string): Promise => { + // 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`); + } else { + if (names.length === 1) { + return child; + } else { + names.splice(0, 1); + return getChildFile(names, child.uuid); + } + } }; /** * GET a File. */ const getFilePath: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise => { + 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}` + ); + } }; /** * GET a File. */ const getFileId: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + (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}` + ); }; /** * Post a File. / delete / move / etc */ const postFilePath: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + (req: Request, res: Response, next: NextFunction): void => { + res.json({todo: 'need to implement meeeee'}); }; export class FileRouter { @@ -466,4 +564,5 @@ export class FileRouter { const fileRoutes: FileRouter = new FileRouter(); fileRoutes.init(); -export default fileRoutes.router; +const ex: Router = fileRoutes.router; +export default ex; diff --git a/src/app.ts b/src/app.ts index c81be8a..a843179 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,20 +1,26 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; -import FileRouter from './FileRouter'; import * as logger from 'morgan'; +import { errorHandler } from './errors/errorware'; +import FileRouter from './FileRouter'; + class App { public express: ex.Express; + public logEnabled: boolean = true; public constructor() { this.express = ex(); this.middleware(); this.mountRoutes(); + this.errorware(); } // Configure Express middleware. private middleware(): void { - this.express.use(logger('combined')); + if (this.logEnabled) { + this.express.use(logger('combined')); + } this.express.use(bodyParser.json()); this.express.use(bodyParser.urlencoded({ extended: false })); } @@ -31,6 +37,10 @@ class App { this.express.use('/', defRouter); this.express.use('/cs3099group-be-4', FileRouter); } + + private errorware(): void { + this.express.use(errorHandler); + } } export default new App().express; diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..a59e417 --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,136 @@ +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'; + +export class AuthRouter { + public localStrategy: Strategy; + public router: Router; + + public constructor() { + this.localStrategy = Strategy(); + this.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; + } + + // Find user object from database by user ID + public findUserByID(id): User { + if (id === user.id) { + return user; + } + 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 }, + 'Mr Secret', + { expiresIn: 21600 } + ); + + res.json({ + token_type: 'bearer', + access_token: token, + refresh_token: token, + expires_in: 21600 + }); + } + + // Checks for errors within request before authentication + public checkErr(req: Request, res: Response, next: NextFunction) { + if (!req.body.grant_type || !req.body.username || !req.body.password) { + res.status(400) + .json({ + error: 'invalid_request', + error_description: 'Missing parameters' + }); + res.end(); + } + + 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(); + } + + // 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' + }); + } + next(); + } + + // Configure local strategy to use with passport-js. + private configStrategy() { + passport.use(new localStrategy( (username, password, done) => { + const user = findByUsername(username); + + 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 + +app.post('/login', checkErr, function(req, res, next) { + passport.authenticate('local', { session: false }, function(err, user) { + if (err) { console.log(err); } + + if (!user) { + res.status(400).json({ + error: 'invalid_grant', + error_description: 'Incorrect authentication details' + }); + } + }); + next(); +}, genToken); + +app.get('/logout', function(req, res) { + req.logout(); +}); + +app.get('/test', ensureAuth, function(req, res) { + res.send('you are authenticated!'); +}); + +/* +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 new file mode 100644 index 0000000..6bbcf4a --- /dev/null +++ b/src/db/model/ContributorGroup.ts @@ -0,0 +1,54 @@ +import { AllowNull, Column, DataType, HasMany, Model, Table + } from 'sequelize-typescript'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class ContributorGroup extends Model { + @AllowNull + @Column(DataType.TEXT) + public name: string | null = null; + + /* "Error: Foreign key for "ContributorGroup" + * is missing on "UserJoinsProject"." */ + @HasMany(() => UserJoinsProject, 'contributorGroupId') + public uses: UserJoinsProject[] = []; + + @Column + public canCreateFiles: boolean = false; + + @Column + public canDeleteFiles: boolean = false; + + @Column + public canViewFiles: boolean = false; + + @Column + public canAddUsers: boolean = false; + + @Column + public canRemoveUsers: boolean = false; + + @Column + public canEditUserPermissions: boolean = false; + + @AllowNull + @Column(DataType.TEXT) + public description: string | null = null; + + @Column + public isInternal: boolean = true; + + public getContributorGroupFullInfo(): ContributorGroupFullInfo { + return { + role: `${this.name}`, + description: `${this.description}`, + internal: this.isInternal + }; + } +} + +export interface ContributorGroupFullInfo { + role: string; + description: string; + internal: boolean; +} diff --git a/src/db/model/File.ts b/src/db/model/File.ts new file mode 100644 index 0000000..225512d --- /dev/null +++ b/src/db/model/File.ts @@ -0,0 +1,47 @@ +import { default as Project } from './Project'; +import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany, + HasOne, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; +import { default as User } from './User'; + +@Table +export default class File extends Model { + @Column + public name: string = ''; + + @PrimaryKey + @Column + public uuid: string = ''; + + @Column + public mimetype: string = ''; + + @ForeignKey(() => File) + @AllowNull + @Column(DataType.TEXT) + public parentFolderId: string | null = null; + + @BelongsTo(() => File) + public parentFolder: File = new File(); + + @HasMany(() => File) + public containedFiles: File[] = []; + + @ForeignKey(() => User) + @AllowNull + @Column(DataType.TEXT) + public creatorName: string | null = null; + + @BelongsTo(() => User) + public creator: User = new User(); + + @HasOne(() => Project) + public rootFolderOf: Project = new Project(); + + @CreatedAt + @Column + public uploadDate: Date = new Date(); + + @UpdatedAt + @Column + public modifyDate: Date = new Date(); +} diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts new file mode 100644 index 0000000..2c26a04 --- /dev/null +++ b/src/db/model/Project.ts @@ -0,0 +1,75 @@ +import { default as ContributorGroup } from './ContributorGroup'; +import { default as File } from './File'; +import { BelongsTo, BelongsToMany, Column, CreatedAt, ForeignKey, + Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class Project extends Model { + + @PrimaryKey + @Column + public name: string = ''; + + @BelongsToMany(() => User, () => UserJoinsProject) + public contributors: User[] = []; + + @ForeignKey(() => File) + @Column + public rootFolderId: string = ''; + + @BelongsTo(() => File) + public rootFolder: File = new File(); + + @CreatedAt + @Column + public creationDate: Date = new Date(); + + @UpdatedAt + @Column + public lastActivity: Date = new Date(); + + public getAccessLevel(user: User): ContributorGroup { + throw new Error(`unimplemented, ${this}`); + } + + public getUserInfo(user: User): UserInfo { + return { + username: user.username, + access_level: this.getAccessLevel(user) + .toString() + }; + } + + public getProjectFullInfo(): ProjectFullInfo { + return { + project_name: this.name, + users: this.contributors + .map( + (u: User) => this.getUserInfo(u) + ), + public_metadata: { + creation_date: this.creationDate + }, + // TODO: Check if we have anything to use these for yet? + private_metadata: {}, + admin_metadata: {} + }; + } +} + +interface Metadata {} + +interface UserInfo { + username: string; + access_level: string; +} + +export interface ProjectFullInfo { + project_name: string; + users: UserInfo[]; + public_metadata: Metadata; + private_metadata?: Metadata; + admin_metadata?: Metadata; +} diff --git a/src/db/model/User.ts b/src/db/model/User.ts new file mode 100644 index 0000000..5a9af07 --- /dev/null +++ b/src/db/model/User.ts @@ -0,0 +1,78 @@ +import { default as File } from './File'; +import { default as Project } from './Project'; +import { BelongsTo, BelongsToMany, Column, CreatedAt, ForeignKey, HasMany, + Model, PrimaryKey, Table } from 'sequelize-typescript'; +import { default as UserGroup } from './UserGroup'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class User extends Model { + @PrimaryKey + @Column + public username: string = ''; + + @Column + public password: string = ''; + + @ForeignKey(() => UserGroup) + @Column + public userGroupId: number = 0; + + @BelongsTo(() => UserGroup) + public userGroup: UserGroup = new UserGroup(); + + @BelongsToMany(() => Project, () => UserJoinsProject) + public projects: Project[] = []; + + @HasMany(() => File) + public createdFiles: File[] = []; + + @CreatedAt + @Column + public creationDate: Date = new Date(); + + // TODO implement + public getAccessLevel(project: Project): string { + throw new Error(`unimplemented, ${this}`); + } + + public getProjectInfo(project: Project): ProjectInfo { + return { + project_name: project.name, + access_level: this.getAccessLevel(project) + }; + } + + public getUserFullInfo(): UserFullInfo { + return { + username : this.username, + privileges: [`${this.userGroup.name}`], + projects : this.projects.map( + (p: Project) => this.getProjectInfo(p) + ), + // TODO: Check if we have anything to use these for yet? + public_user_metadata: {}, + private_user_metadata: {}, + public_admin_metadata: {}, + private_admin_metadata: {} + }; + } +} + +// TODO MAKE PRETTY below +interface Metadata {} + +interface ProjectInfo { + project_name: string; + access_level: string; +} + +export interface UserFullInfo { + username: string; + privileges: string[]; + projects: ProjectInfo[]; + public_user_metadata: Metadata; + private_user_metadata: Metadata; + public_admin_metadata: Metadata; + private_admin_metadata: Metadata; +} diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts new file mode 100644 index 0000000..865fbbc --- /dev/null +++ b/src/db/model/UserGroup.ts @@ -0,0 +1,52 @@ +import { AllowNull, Column, DataType, HasMany, Model, Table + } from 'sequelize-typescript'; +import { default as User } from './User'; + +interface UserPrivilege { + privilege: string; + description: string; + internal: boolean; +} + +@Table +export default class UserGroup extends Model { + @AllowNull + @Column(DataType.TEXT) + public name: string | null = null; + + @HasMany(() => User) + public users: User[] = []; + + @Column + public canCreateUsers: boolean = false; + + @Column + public canDeleteUsers: boolean = false; + + @Column + public canEditUsers: boolean = false; + + @Column + public canCreateProjects: boolean = false; + + @Column + public canDeleteProjects: boolean = false; + + @Column + public canEditProjects: boolean = false; + + @Column + public isInternal: boolean = true; + + @AllowNull + @Column(DataType.TEXT) + public description: string | null = null; + + public getPrivelege(): UserPrivilege { + return { + privilege : `${this.name}`, + description : `${this.description}`, + internal : this.isInternal + }; + } +} diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts new file mode 100644 index 0000000..36a1591 --- /dev/null +++ b/src/db/model/UserJoinsProject.ts @@ -0,0 +1,27 @@ +import { default as Project } from './Project'; +import { BelongsTo, Column, CreatedAt, ForeignKey, Model, Table + } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as ContributorGroup } from './UserGroup'; + +@Table +export default class UserJoinsProject extends Model { + @ForeignKey(() => User) + @Column + public username: string = ''; + + @ForeignKey(() => Project) + @Column + public projectName: string = ''; + + @CreatedAt + @Column + public joinDate: Date = new Date(); + + @ForeignKey(() => ContributorGroup) + @Column + public contributorGroupId: number = 0; + + @BelongsTo(() => ContributorGroup) + public contributorGroup: ContributorGroup = new ContributorGroup(); +} diff --git a/src/db/orm.ts b/src/db/orm.ts new file mode 100644 index 0000000..01d8037 --- /dev/null +++ b/src/db/orm.ts @@ -0,0 +1,12 @@ +import { Sequelize } from 'sequelize-typescript'; + +const seq: Sequelize = new Sequelize({ + database: 'be4', + dialect: 'postgres', + username: 'admin', + password: '', + operatorsAliases: false, + modelPaths: [`${__dirname}/model`] +}); + +export default seq; diff --git a/src/errors/errorware.test.ts b/src/errors/errorware.test.ts new file mode 100644 index 0000000..eb85cc6 --- /dev/null +++ b/src/errors/errorware.test.ts @@ -0,0 +1,35 @@ +/* tslint:disable:no-unused-expression */ +// Disabled to allow chai-style assertions. + +import * as chai from 'chai'; +chai.should(); + +import { ErrorResponseBlock, RequestError } from './errorware'; + +describe('RequestError', () => { + describe('constructor', () => { + it('constructs simple errors', () => { + const err: RequestError = new RequestError( + 404, 'user_not_found' + ); + err.code.should.equal(404); + err.name.should.equal('user_not_found'); + }); + it('constructs with sensible defaults', () => { + const err: RequestError = new RequestError(); + err.code.should.not.be.undefined; + err.name.should.not.be.undefined; + }); + }); + describe('response generation', () => { + it('generates responses', () => { + const err: RequestError = new RequestError( + 500, 'internal_server_error' + ); + const response: ErrorResponseBlock = + err.responseBlock(); + response.status.should.equal('error'); + response.error.should.equal('internal_server_error'); + }); + }); +}); diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts new file mode 100644 index 0000000..8b7e015 --- /dev/null +++ b/src/errors/errorware.ts @@ -0,0 +1,51 @@ +import { NextFunction, Request, Response } from 'express'; + +export interface ErrorResponseBlock { + status: string; + error: string; + error_description?: string; + user_message?: string; + // tslint:disable-next-line:no-any + error_data?: any; +} + +export class RequestError extends Error { + public code: number; + public userMessage?: string; + // tslint:disable-next-line:no-any + public errorData?: any; + + public constructor( + errCode: number = 500, + errName: string = 'internal_server_error', + errDescription?: string, + errUserMessage?: string, + // tslint:disable-next-line:no-any + errData?: any + ) { + super(errDescription); + this.code = errCode; + this.name = errName; + this.userMessage = errUserMessage; + this.errorData = errData; + } + + public responseBlock(): ErrorResponseBlock { + return { + status: 'error', + error: this.name, + error_description: this.message, + user_message: this.userMessage, + error_data: this.errorData + }; + } +} + +type Errorware = + (err: RequestError, 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()); +}; diff --git a/src/index.ts b/src/index.ts index 54ff848..06989ef 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,12 @@ /* tslint:disable:no-console * This only goes here until we have a logging system */ -import app from './app'; +console.log('begin import'); +import { default as app } from './app'; +import { default as seq } from './db/orm'; +console.log('end import'); -console.log('Welcome to the CS3099 Server thingy!'); +import { default as UserGroup } from './db/model/UserGroup'; const DEFAULT_PORT: number = 3000; @@ -12,10 +15,40 @@ const port: number = process.env.PORT ? process.env.PORT : DEFAULT_PORT; -app.listen(port, (err: Error): void => { - if (err) { - return console.log(err); - } +// tslint:disable:no-floating-promises +(async(): Promise => { + console.log('Booting PSQL database'); - return console.log(`server is listening on port ${port}`); -}); + await seq.authenticate(); + + console.log('Resetting Database'); + + await seq.sync({ + force: true + }); + + const admin: UserGroup = new UserGroup({ + name: 'admin', + canCreateUsers: true, + canDeleteUsers: true, + canEditUsers: true, + canCreateProjects: true, + canDeleteProjects: true, + canEditProjects: true, + isInternal: false, + description: 'Systems admin' + }); + + // tslint:disable:no-floating-promises + admin.save(); + + console.log('Booting ExpressJS server'); + + app.listen(port, (err: Error) => { + if (err) { + return console.log(err); + } else { + return console.log(`server is listening on port ${port}`); + } + }); +})(); diff --git a/src/matcher/options.test.ts b/src/matcher/options.test.ts new file mode 100644 index 0000000..ff5763e --- /dev/null +++ b/src/matcher/options.test.ts @@ -0,0 +1,163 @@ +/* tslint:disable:typedef */ +// Disabled to allow quick template creation. + +/* tslint:disable:newline-per-chained-call */ +// Disabled to allow Chai- and Mocha-style test formatting. + +/* tslint:disable:no-unused-expression */ +// Disabled to allow `...to.be.true`. + +import * as chai from 'chai'; +chai.should(); + +import * as options from './options'; +import { default as types } from './types'; + +// tslint:disable-next-line:no-require-imports + +describe('Matching:', () => { + describe('Rough Matching', () => { + context('for literals', () => { + context('accepts matching', () => { + it('strings', () => { + options.match('a', 'a').should.be.true; + }); + it('numbers', () => { + options.match(3, 3).should.be.true; + }); + it('boolean values', () => { + options.match(true, true).should.be.true; + }); + it('null to null', () => { + options.match(null, null).should.be.true; + }); + }); + context('rejects', () => { + it('different strings', () => { + options.match('x', 'y').should.be.false; + }); + it('different numbers', () => { + options.match(20, 42).should.be.false; + }); + it('different boolean values', () => { + options.match(true, false).should.be.false; + }); + it('different types', () => { + options.match('55', 55).should.be.false; + }); + it('null matched with non-null values', () => { + options.match(null, false).should.be.false; + }); + it('non-null values matched with null', () => { + options.match(0, null).should.be.false; + }); + }); + }); + context('for checker functions', () => { + context('accepts', () => { + it('values that succeed the checker function', () => { + options.match(types.number, 9).should.be.true; + }); + }); + context('rejects', () => { + it('values that do not succeed the checker function', () => { + options.match(types.boolean, 'true').should.be.false; + }); + }); + }); + it('accepts basic things', () => { + const template = { + a: types.string + }; + const matchee = { + a: 'yes' + }; + options.match(template, matchee).should.be.true; + }); + it('accepts objects with superfluous properties', () => { + const template = { + a: types.number + }; + const matchee = { + a: 40, + b: 20 + }; + options.match(template, matchee).should.be.true; + }); + it('rejects objects missing some properties', () => { + const template = { + a: types.boolean, + b: types.number, + c: types.number + }; + const matchee = { + b: 5 + }; + options.match(template, matchee).should.be.false; + }); + it('accepts objects that omit not_present properties', () => { + const template = { + a: types.number, + b: types.not_present, + c: types.not_present + }; + const matchee = { + a: 4 + }; + options.match(template, matchee).should.be.true; + }); + it('rejects empty objects for non-empty templates', () => { + const template = { + a: types.boolean + }; + const matchee = { + }; + options.match(template, matchee).should.be.false; + }); + it('accepts empty objects for empty templates', () => { + const template = { + }; + const matchee = { + }; + options.match(template, matchee).should.be.true; + }); + it('accepts nested objects that match', () => { + const template = { + a: types.number, + b: { + ba: types.string, + bb: types.string + }, + c: types.boolean + }; + const matchee = { + a: 432, + b: { + ba: 'baracus', + bb: 'ATEAM' + }, + c: true, + x: false + }; + options.match(template, matchee).should.be.true; + }); + it('accepts literal matches', () => { + const template = { + a: 'literal' + }; + const matchee = { + a: 'literal' + }; + options.match(template, matchee).should.be.true; + }); + it('rejects incorrect literal matches', () => { + const template = { + g: 99 + }; + const matchee = { + g: 80 + }; + options.match(template, matchee).should.be.false; + }); + }); +}); diff --git a/src/matcher/options.ts b/src/matcher/options.ts new file mode 100644 index 0000000..62e4985 --- /dev/null +++ b/src/matcher/options.ts @@ -0,0 +1,99 @@ +import { Atom, default as types } from './types'; + +type Checker = ((value: Value | undefined) => boolean); + +export type TemplateValue = + Atom | Template | Checker; + +export interface Template { + [key: string]: TemplateValue | undefined; +} + +export type Value = + { [key: string]: Value | undefined } | Atom; + +const matchNoCurry: + (template: TemplateValue, value: Value | undefined) => boolean = + (template: TemplateValue, value: Value | undefined): boolean => { + if (types.atom(template)) { + return template === value; + } else if (types.function(template)) { + return template(value); + } else if (types.atom(value) || value === undefined) { + return false; + } else if (types.object(template)) { + return Object.keys(template) + .every((key: string): boolean => { + const v: Value | undefined = value[key]; + return matchNoCurry(template[key] as TemplateValue, v); + }); + } else { + throw new Error(`Unknown template value: ${template}`); + } +}; + +// tslint:disable-next-line:typedef +export const match = (template: TemplateValue, value?: Value) => { + if (value === undefined) { + return matchNoCurry.bind(null, template); + } + return matchNoCurry(template, value); +}; + +// tslint:disable-next-line:typedef +export const exact = (template: Template, value?: Value) => { + if (value === undefined) { + return exact.bind(null, template); + } + if (!match(template, value)) { + return false; + } + if (!types.atom(value)) { + const k1: string[] = Object.keys(template); + const k2: string[] = Object.keys(value); + return k2.every((x: string) => k1.indexOf(x) < 0); + } else { + return true; + } +}; + +// tslint:disable-next-line:typedef +export const optional = (template: TemplateValue, value?: Value) => { + if (value === undefined) { + return optional.bind(null, template); + } + return types.undefined(value) || match(template, value); +}; + +// tslint:disable-next-line:typedef +export const alternative = (templates: TemplateValue[], value?: Value) => { + if (value === undefined) { + return alternative.bind(null, templates); + } + if (templates.length === 0) { + return false; + } else { + return templates.some((t: TemplateValue): boolean => match(t, value)); + } +}; + +// tslint:disable-next-line:typedef +export const array = (template: TemplateValue, values?: Value[]) => { + if (values === undefined) { + return array.bind(null, template); + } + const m: Checker = types.function(template) + ? template + : match.bind(null, template); + return values.every(m); +}; + +// tslint:disable-next-line:typedef +const options = { + match, + exact, + optional, + alternative, + array +}; +export default options; diff --git a/src/matcher/types.test.ts b/src/matcher/types.test.ts new file mode 100644 index 0000000..398064c --- /dev/null +++ b/src/matcher/types.test.ts @@ -0,0 +1,178 @@ +/* tslint:disable:no-unused-expression */ +// Disabled to allow `...to.be.true`. + +import * as chai from 'chai'; +chai.should(); + +import { default as types } from './types'; + +describe('Type Checking:', () => { + for (const x of [ + { name: 'Object', func: types.object }, + { name: 'Number', func: types.number }, + { name: 'Integer', func: types.integer }, + { name: 'String', func: types.string }, + { name: 'Boolean', func: types.boolean }, + { name: 'Array', func: types.array } + ]) { + describe(`${x.name} Checking`, () => { + it('rejects null', () => { + x.func(null).should.be.false; + }); + it('rejects undefined', () => { + x.func(undefined).should.be.false; + }); + }); + } + + describe('Presence Checking', () => { + it('accepts non-undefined values', () => { + types.anything(1).should.be.true; + types.anything('string').should.be.true; + types.anything(false).should.be.true; + }); + it('accepts null', () => { + types.anything(null).should.be.true; + }); + it('rejects undefined', () => { + types.anything(undefined).should.be.false; + }); + it('rejects objects without the named property', () => { + const x: { [key: string]: number } = {}; + /* There's no way to pick a key that definitely won't be + /* on the object */ + types.anything(x["hopefully this isn't a property"]) + .should.be.false; + }); + }); + + describe('Absence Checking', () => { + it('accepts undefined', () => { + types.not_present(undefined).should.be.true; + }); + }); + + describe('Number Checking', () => { + it('accepts positive integers', () => { + types.number(4).should.be.true; + }); + it('accepts negative integers', () => { + types.number(-10).should.be.true; + }); + it('accepts floats', () => { + types.number(3.14).should.be.true; + }); + it('accepts zero', () => { + types.number(0).should.be.true; + }); + it('accepts boxed numbers', () => { + // tslint:disable-next-line:no-construct + types.number(new Number(20)).should.be.true; + }); + it('rejects strings', () => { + types.number('haha').should.be.false; + }); + it('rejects objects', () => { + types.number(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.number([1, 2, 3]).should.be.false; + }); + it('rejects things that look like numbers', () => { + types.number('1234').should.be.false; + types.number('-3.14').should.be.false; + }); + it('accepts NaN', () => { + types.number(NaN).should.be.true; + }); + it('accepts Infinity', () => { + types.number(Infinity).should.be.true; + }); + }); + + describe('Integer Checking', () => { + it('rejects non-integer numbers', () => { + types.integer(3.14).should.be.false; + }); + it('rejects NaN', () => { + types.integer(NaN).should.be.false; + }); + it('rejects Infinity', () => { + types.integer(Infinity).should.be.false; + }); + }); + + describe('String Checking', () => { + it('accepts basic primitive strings', () => { + types.string('string!').should.be.true; + }); + it('accepts strings of numbers', () => { + types.string('1234').should.be.true; + }); + it('accepts the empty string', () => { + types.string('').should.be.true; + }); + it('accepts non-primitive string objects', () => { + // tslint:disable-next-line:no-construct + types.string(new String('String!')).should.be.true; + }); + it('rejects numbers', () => { + types.string(5).should.be.false; + // tslint:disable-next-line:no-construct + types.string(new Number(28)).should.be.false; + }); + it('rejects objects', () => { + types.string(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.string(['ah', 'ha']).should.be.false; + }); + }); + + describe('Boolean Checking', () => { + it('accepts true and false', () => { + types.boolean(true).should.be.true; + types.boolean(false).should.be.true; + }); + it('rejects numbers', () => { + types.boolean(2).should.be.false; + }); + it('rejects strings', () => { + types.boolean('not boolean').should.be.false; + }); + it('rejects strings of boolean values', () => { + types.boolean('true').should.be.false; + }); + it('rejects objects', () => { + types.boolean(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.boolean([true, true, false]).should.be.false; + }); + it('rejects falsy values', () => { + types.boolean(0).should.be.false; + }); + }); + + describe('Array Checking', () => { + it('accepts arrays', () => { + types.array([1, 'two', false]).should.be.true; + }); + it('accepts empty arrays', () => { + types.array([]).should.be.true; + types.array(new Array()).should.be.true; + }); + it('rejects strings', () => { + types.array('not an array').should.be.false; + }); + it('rejects strings that look like arrays', () => { + types.array('[1, 2, false]').should.be.false; + }); + it('rejects numbers', () => { + types.array(8).should.be.false; + }); + it('rejects objects', () => { + types.array(new Object()).should.be.false; + }); + }); +}); diff --git a/src/matcher/types.ts b/src/matcher/types.ts new file mode 100644 index 0000000..aad1e9f --- /dev/null +++ b/src/matcher/types.ts @@ -0,0 +1,79 @@ +/* tslint:disable:no-any */ + +type Checker = (v: any) => v is T; + +export type Atom = Number | String | Boolean | null; + +const typeCheckerGenerator: (test: T) => Checker = + (test: T): Checker => { + const f: Checker = (value: any): value is T => + value != null && value.constructor === test.constructor; + return f; +}; + +export const isObject: Checker = + typeCheckerGenerator({}); + +export const isNumber: Checker = + typeCheckerGenerator(0); + +export const isString: Checker = + typeCheckerGenerator(''); + +export const isBoolean: Checker = + typeCheckerGenerator(true); + +export const isArray: Checker = + typeCheckerGenerator([]); + +export const isFunction: Checker = + typeCheckerGenerator(new Function()); + +export const isNull: Checker = + (v: any): v is null => v === null; + +export const isUndefined: Checker = + (v: any): v is undefined => v === undefined; + +export const isPresent: (v: any) => boolean = + (v: any): boolean => !isUndefined(v); + +export const isInteger: Checker = + (v: any): v is Number => isNumber(v) && Number.isInteger(v as number); + +export const isAtom: Checker = + (v: any): v is Atom => + isNull(v) || isNumber(v) || isString(v) || isBoolean(v); + +const types: { + object: Checker; + number: Checker; + string: Checker; + boolean: Checker; + array: Checker; + function: Checker; + integer: Checker; + null: Checker; + present: (v: any) => boolean; + is_present: (v: any) => boolean; + not_present: Checker; + undefined: Checker; + anything: (v: any) => boolean; + atom: Checker; +} = { + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + array: isArray, + function: isFunction, + integer: isInteger, + null: isNull, + present: isPresent, + is_present: isPresent, + not_present: isUndefined, + undefined: isUndefined, + anything: isPresent, + atom: isAtom +}; +export default types; -- cgit v1.2.1 From 0ec3d6b47ecfd62a18af6fc36ede4dcd4ce771cb Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 1 Mar 2018 18:52:35 +0000 Subject: added new request error objects --- src/auth.ts | 73 ++++++++++++++++++++++++------------------------------------- 1 file changed, 29 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts index a59e417..937f20f 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -8,9 +8,11 @@ import { default as User } from './db/model/User'; export class AuthRouter { public localStrategy: Strategy; public router: Router; + ensureAuth; public constructor() { this.localStrategy = Strategy(); + this.ensureAuth = expressJwt({secret: 'Mr Secret'}); //protects routes this.router(); this.init(); } @@ -48,25 +50,26 @@ export class AuthRouter { }); } + private authenticate(req: Request, res: Response, next: NextFunction) { + passport.authenticate('local', { session: false }, function(err, user) { + if (err) { console.log(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) { 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(); @@ -75,19 +78,14 @@ export class AuthRouter { // 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' - }); + next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); } next(); } // Configure local strategy to use with passport-js. private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { + passport.use(new localStrategy( (username, password, done) => { const user = findByUsername(username); if (!user || user.password != password) { @@ -96,36 +94,23 @@ export class AuthRouter { return done(null, user); })); } -} -/////////////////////////////////////////////////// -const app = express(); -const ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes + init() { + this.configStrategy(); -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error - -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, res) => { req.logout(); }); + } +} - if (!user) { - res.status(400).json({ - error: 'invalid_grant', - error_description: 'Incorrect authentication details' - }); - } - }); - next(); -}, genToken); +const authRoutes = new AuthRouter(); +authRoutes.init(); -app.get('/logout', function(req, res) { - req.logout(); -}); +export default authRoutes.router; +/////////////////////////////////////////////////// -app.get('/test', ensureAuth, function(req, res) { - res.send('you are authenticated!'); -}); +app.use(passport.initialize()); +app.use(unauthorisedErr); //currently does not handle userdefined error /* tasks left: -- cgit v1.2.1 From 7a06fd6eac864972a4acc15078627f0ffc20c1f9 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 1 Mar 2018 19:26:35 +0000 Subject: added middleware to check if admin --- src/auth.ts | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts index 937f20f..3feac5d 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -83,6 +83,14 @@ export class AuthRouter { next(); } + //middleware to check privileges - admin + public isAdmin(req: Request, res: Response, next: NextFunction) { + if (!req.user.admin) { + next(new RequestError(401, 'not_authorised', 'user is not authorised to perform task')); + } + next(); + } + // Configure local strategy to use with passport-js. private configStrategy() { passport.use(new localStrategy( (username, password, done) => { -- cgit v1.2.1 From 8bd1d19dbd899047bc8503dbe682358ddfc564cc Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 1 Mar 2018 19:48:47 +0000 Subject: Implement GET and POST request handlers --- src/FileRouter.ts | 341 ++++++++++++++++++++------------------- src/app.ts | 122 +++++++++++++- src/db/model/ContributorGroup.ts | 22 +-- src/db/model/File.ts | 34 ++-- src/db/model/Project.ts | 77 ++++++++- src/db/model/User.ts | 155 +++++++++++++++--- src/db/model/UserGroup.ts | 30 ++-- src/db/model/UserHasPrivilege.ts | 14 ++ src/db/model/UserJoinsProject.ts | 10 +- src/files.ts | 22 +++ src/logger.ts | 26 +++ src/serverConfig.ts | 156 +++++++++--------- src/uuid.ts | 7 + 13 files changed, 701 insertions(+), 315 deletions(-) create mode 100644 src/db/model/UserHasPrivilege.ts create mode 100644 src/files.ts create mode 100644 src/logger.ts create mode 100644 src/uuid.ts (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 34738bc..98fd5c4 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -6,7 +6,12 @@ import { UserFullInfo, default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; -import { default as serverConfig } from './serverConfig'; + +import { RequestError } from './errors/errorware'; +import { files } from './files'; +import { logger } from './logger'; +import { Property, default as serverConfig } from './serverConfig'; +import { uuid } from './uuid'; // TODO: figure this out const BASE_FILE_STORAGE: string = 'TODO: figure this out'; @@ -29,16 +34,13 @@ type Middleware = */ const getProtocols: Middleware = (req: Request, res: Response, next: NextFunction): void => { - const returnValue: { - supported: string[]; - required: string[]; - } = { - supported: [], - required: [ - 'BE01' - ] + res.locals.data = { + supported: [], + required: [ + 'BE01' + ] }; - res.send(JSON.stringify(returnValue)); + next(); }; /** @@ -60,8 +62,21 @@ const getProtocols: Middleware = */ const postLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(501) - .send({error : 'logging_not_enabled'}); + if (!req.user.hasPrivilege('logging')) { + next(new RequestError(400, 'invalid_privilege')); + return; + } else if (!logger.isEnabled()) { + next(new RequestError(501, 'logging_not_enabled')); + return; + } + for (const item of req.body) { + logger.log(item.level, item.value, { + component: item.component, + user: req.user.username, + external: true + }); + } + next(); }; /** @@ -87,8 +102,16 @@ const postLog: Middleware = */ const getLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(501) - .send({error : 'logging_not_enabled'}); + if (!req.user.hasPrivilege('admin')) { + next(new RequestError(400, 'invalid_privilege')); + } + res.locals.data = logger.fetch( + req.params.level, { + before: new Date(req.params.before), + after: new Date(req.params.after) + } + ); + next(); }; /** @@ -114,8 +137,8 @@ const getLog: Middleware = */ const getProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(200) - .send(serverConfig); + res.locals.data = serverConfig; + next(); }; /** @@ -132,51 +155,26 @@ const getProperties: Middleware = */ const postProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - let success: boolean = true; - - // For each property to update - for (const prop of req.body) { - - // Check that the property has and id and a value - if (!prop.hasOwnProperty('id') || !prop.hasOwnProperty('value')) { - res.status(400) - .send({ - error: 'invalid_request', - error_description: 'A supplied property is missing an id or value' - }); - success = false; - break; + for (const newProp of req.body) { + const prop: Property | undefined = serverConfig.find( + (p: Property): boolean => p.id === newProp.id + ); + if (prop === undefined) { + next(new RequestError(400, 'invalid_property', undefined, newProp.id)); + return; + } else if (prop.readOnly) { + next(new RequestError(400, 'invalid_property', undefined, newProp.id)); + return; } - - // Find out if the property exists in the config and if so, at which index - const index: number = serverConfig.indexOf(prop.id); - - // Check some of the properties values to ensure that it can be updated - if (index === -1 || serverConfig[index].readOnly) { - /* TODO Implement an or, using Tom's type checker - * to ensure the value is "valid" based on the type of the property */ - const description: string = index === -1 - ? 'Property not found' - : 'Property is Read_Only'; - res.status(400) - .send({ - error: 'invalid_property', - error_data: prop.id, - error_description: description - }); - success = false; - break; + try { + prop.value = newProp.value; + } catch (err) { + // FIXME: Assuming it's a value-type error, but it might not be! + next(new RequestError(400, 'invalid_property_value', undefined, newProp.id)); + return; } - - // Make the update to the property - serverConfig[index].value = prop.value; - } - - // Tell the client that everything was okay; - if (success) { - res.status(200) - .send(); } + next(); }; /** @@ -190,12 +188,13 @@ const postProperties: Middleware = * "internal": boolean * }) */ -const getUserPriveleges: Middleware = +const getUserPrivileges: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { 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( - (u: User) => u.getUserFullInfo() - )); + res.locals.data = users.map( + (u: User) => { + const info: UserFullInfo = u.fullInfo; + if (!req.user.hasPrivilege('admin')) { + info.private_user_metadata = undefined; + info.private_admin_metadata = undefined; + } + return info; + } + ); + next(); }; /** * Expose additional configuration options for individual users */ const getUserProperties: Middleware = - (req: Request, res: Response, next: NextFunction, user?: string): void => { - res.status(500) - .send({ - error: 'unsupported', - error_description: - 'Users on this server dont have additional configuration options.' - }); -}; - -const userInfoFromName: (name: string) => Promise = - async(name: string): Promise => { - 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 = * } */ const getUsername: Middleware = - async(req: Request, res: Response, next: NextFunction): Promise => { - 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 => { + 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 => { + 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 => { const roles: ContributorGroup[] = await ContributorGroup.findAll(); - res.json(roles.map( - (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( - (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 => { - 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 => { + let project: Project | null = res.locals.project; + let promise: PromiseLike | 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 = - async(names: string[], parentUuid: string): Promise => { - // 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 = */ const getFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { - const project: Project | null = await Project.findOne({ - where: { - name: req.params.project_name - } - }); - - if (project === null) { - throw new Error( - `Project of name ${req.params.project_name} does not exist` - ); - } else { - const file: File = await getChildFile( - req.params.project_name, project.rootFolderId - ); - - res.sendFile( - `${BASE_FILE_STORAGE}/${req.params.project_name}/${file.uuid}` - ); + const file: File | null = res.locals.file; + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; } + res.locals.function = res.sendFile; + res.locals.data = + `${BASE_FILE_STORAGE}/${res.locals.project.name}/${file.uuid}`; + next(); }; /** @@ -503,10 +493,14 @@ const getFilePath: Middleware = */ const getFileId: Middleware = (req: Request, res: Response, next: NextFunction): void => { - // TODO: implement correctness of project folder checking. - res.sendFile( - `${BASE_FILE_STORAGE}/${req.params.project_name}/${req.params.id}` - ); + const file: File | null = res.locals.file; + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; + } + res.locals.function = res.sendFile; + res.locals.data = files.path(req.params.id, res.locals.project.name); + next(); }; /** @@ -514,7 +508,16 @@ const getFileId: Middleware = */ const postFilePath: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.json({todo: 'need to implement meeeee'}); + if (res.locals.file != null) { + next(new RequestError(400, 'file_exists')); + } + const file: File = new File({ + uuid: uuid.generate(), + name: res.locals.filename, + parentFolder: res.locals.parentFolder + }); + req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + next(); }; export class FileRouter { @@ -524,8 +527,8 @@ export class FileRouter { * Initialize the FileRouter */ public constructor() { - this.router = Router(); - this.init(); + this.router = Router(); + this.init(); } /** @@ -540,7 +543,7 @@ export class FileRouter { this.router.get ('/properties', getProperties); this.router.post('/properties', postProperties); // Users - this.router.get ('/user_privileges', getUserPriveleges); + this.router.get ('/user_privileges', getUserPrivileges); this.router.get ('/users', getUsers); this.router.get ('/users/:username', getUsername); this.router.post('/users/:username', postUsername); diff --git a/src/app.ts b/src/app.ts index a843179..86b0c1c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -2,15 +2,20 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; import * as logger from 'morgan'; -import { errorHandler } from './errors/errorware'; +import { RequestError, errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; +import { default as File } from './db/model/File'; +import { default as Project } from './db/model/Project'; +import { default as User } from './db/model/User'; + class App { public express: ex.Express; public logEnabled: boolean = true; public constructor() { this.express = ex(); + this.precondition(); this.middleware(); this.mountRoutes(); this.errorware(); @@ -41,6 +46,121 @@ class App { private errorware(): void { this.express.use(errorHandler); } + + private precondition(): void { + // Fetch a user from their name: + this.express.param( + 'username', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + name: string + ): Promise => { + 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 => { + res.locals.project = await Project.findOne({ + where: { + name: project + } + }); + next(); + } + ); + + // Fetch a file from its path: + this.express.param( + 'file', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + filename: string + ): Promise => { + const fileNames: string[] = req.params.path.split('/'); + const project: Project | null = res.locals.project; + if (project === null) { + 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 => { + const file: File | null = await File.findOne({ + where: { + uuid: fileId + } + }); + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; + } else { + res.locals.file = file; + } + next(); + } + ); + } } export default new App().express; diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index 6bbcf4a..d3a5867 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -6,39 +6,39 @@ import { default as UserJoinsProject } from './UserJoinsProject'; export default class ContributorGroup extends Model { @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 { + @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 { - @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 { }; } - public getProjectFullInfo(): ProjectFullInfo { + public get fullInfo(): ProjectFullInfo { + if (this.contributors === undefined) { + throw new Error('contributors undefined'); + } return { project_name: this.name, users: this.contributors diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 5a9af07..0c9d521 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -1,41 +1,124 @@ import { default as File } from './File'; import { default as Project } from './Project'; -import { BelongsTo, BelongsToMany, Column, CreatedAt, ForeignKey, HasMany, +import { BelongsToMany, Column, CreatedAt, HasMany, Model, PrimaryKey, Table } from 'sequelize-typescript'; import { default as UserGroup } from './UserGroup'; +import { default as UserHasPrivilege } from './UserHasPrivilege'; import { default as UserJoinsProject } from './UserJoinsProject'; @Table export default class User extends Model { @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 { }; } - 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( - (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 { private_admin_metadata: {} }; } + + public updateInfo(newInfo: { + password?: { old: string; new: string }; + public_user_metadata?: Metadata; + private_user_metadata?: Metadata; + }): void { + if (newInfo.password !== undefined) { + if (this.authenticate(newInfo.password.old)) { + this.password = newInfo.password.new; + } + } + } + + public authenticate(password: string): boolean { + // TODO use salting (and maybe even constant-time comparison?) + return password === this.password; + } + + public get password(): string { + return this.passwordInternal; + } + + public set password(newPassword: string) { + // TODO use salting + this.password = newPassword; + } } // TODO MAKE PRETTY below @@ -72,7 +189,9 @@ export interface UserFullInfo { privileges: string[]; projects: ProjectInfo[]; public_user_metadata: Metadata; - private_user_metadata: Metadata; + private_user_metadata?: Metadata; public_admin_metadata: Metadata; - private_admin_metadata: Metadata; + private_admin_metadata?: Metadata; } + +export interface UserProperty {} diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts index 865fbbc..7d42425 100644 --- a/src/db/model/UserGroup.ts +++ b/src/db/model/UserGroup.ts @@ -1,6 +1,7 @@ -import { AllowNull, Column, DataType, HasMany, Model, Table - } from 'sequelize-typescript'; +import { AllowNull, BelongsToMany, Column, DataType, Model, Table, + Unique } from 'sequelize-typescript'; import { default as User } from './User'; +import { default as UserHasPrivilege } from './UserHasPrivilege'; interface UserPrivilege { privilege: string; @@ -11,38 +12,39 @@ interface UserPrivilege { @Table export default class UserGroup extends Model { @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 { + @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 { @ForeignKey(() => User) @Column - public username: string = ''; + public username!: string; @ForeignKey(() => Project) @Column - public projectName: string = ''; + public projectName!: string; @CreatedAt @Column - public joinDate: Date = new Date(); + public joinDate!: Date; @ForeignKey(() => ContributorGroup) @Column - public contributorGroupId: number = 0; + public contributorGroupId!: number; @BelongsTo(() => ContributorGroup) - public contributorGroup: ContributorGroup = new ContributorGroup(); + public contributorGroup?: ContributorGroup; } diff --git a/src/files.ts b/src/files.ts new file mode 100644 index 0000000..daab817 --- /dev/null +++ b/src/files.ts @@ -0,0 +1,22 @@ +import * as fs from 'fs'; + +const CONTENT_BASE_DIRECTORY: string = './files'; + +const path: (filename: string, projectName: string) => string + = (filename: string, projectName: string): string => { + return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; +}; + +const writableStream: + (filename: string, projectName: string) => fs.WriteStream = + (filename: string, projectName: string): fs.WriteStream => { + return fs.createWriteStream(path(filename, projectName)); +}; + +export const files: { + path: (f: string, p: string) => string; + writableStream: (f: string, p: string) => fs.WriteStream; +} = { + path, + writableStream +}; diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..70c6455 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,26 @@ +/* tslint:disable:no-any */ + +interface Metadata { + [key: string]: any; +} + +export const logger: { + log: ( + level: string, + value: any, + meta: Metadata + ) => void; + fetch: ( + level: string, + meta: Metadata + ) => any[]; + isEnabled: () => boolean; +} = { + log: (level: string, value: any, meta: Metadata): void => { + return; + }, + fetch: (level: string, meta: Metadata): any[] => { + return []; + }, + isEnabled: (): boolean => false +}; diff --git a/src/serverConfig.ts b/src/serverConfig.ts index ea7b195..136995a 100644 --- a/src/serverConfig.ts +++ b/src/serverConfig.ts @@ -1,64 +1,54 @@ +import { default as types } from './matcher/types'; + +type Value = string | number | boolean; +type ValueString = 'string' | 'number' | 'integer' | 'boolean'; + const serverConfig: Property[] = []; /** * A way to display user-configurable properties. */ -class PropertyDisplay { +interface PropertyDisplay { /** * The category the property belongs to. */ - public category: string; + category: string; /** * The group the property belongs to. */ - public group: string; + group: string; /** * The name for the property to display to a user. */ - public displayName: string; + displayName: string; /** * The description of the property. */ - public description: string; - - /** - * Constructs a [[PropertyDisplay]] using its properties. - * - * @param cat The property's category. - * @param grp The property's group. - * @param dn The property's displayable name. - * @param desc A description of the property. - */ - public constructor(cat: string, grp: string, dn: string, desc: string) { - this.category = cat; - this.group = grp; - this.displayName = dn; - this.description = desc; - } + description: string; } /** * A server property that infuences the running of the server. * Loaded from configs at launch, and possibly editable during run-time. */ -export interface Property { +export class Property { /** * The property's unique ID. */ - id: string; + public id: string; /** * How to display the property to the user. */ - display?: PropertyDisplay; + public display?: PropertyDisplay; /** * Is the property read-only, or can it be edited at run-time? */ - readOnly: boolean; + public readOnly: boolean; /** * The variable type of the property. @@ -66,71 +56,81 @@ export interface Property { * These strings represent Javascript types directly, * except `"integer"`, which is a `number` in logic. */ - type: 'string' | 'number' | 'integer' | 'boolean'; + public type: ValueString; /** * The value of the property. */ - value: string | number | boolean; + private valueInternal!: Value; + + public constructor( + id: string, + type: ValueString, + value: Value, + readOnly: boolean = true, + display?: PropertyDisplay + ) { + this.id = id; + this.display = display; + this.readOnly = readOnly; + this.type = type; + this.valueInternal = value; + } + + public get value(): Value { + return this.valueInternal; + } + + public set value(value: Value) { + if (!this.readOnly) { + throw new Error('this property is read-only'); + } else if (!types[this.type](value)) { + throw new Error(`value ${value} is not of type ${this.type}`); + } + this.valueInternal = value; + } } // Logging -let propertyDisplay: PropertyDisplay = new PropertyDisplay( - 'Logging', - 'BE4', - 'Is logging enabled?', - 'This property defines if logging is currently enabled on this backend server.' -); - -serverConfig.push({ - id: 'Server_Log', - display: propertyDisplay, - readOnly: false, - type: 'boolean', - value: false -}); +let propertyDisplay: PropertyDisplay = { + category: 'logging', + group: 'BE4', + displayName: 'Is logging enabled?', + description: + 'This property defines if logging is enabled on this backend server.' +}; + +serverConfig.push(new Property( + 'Server_Log', + 'boolean', + false, + false, + propertyDisplay +)); // Caching Settings (global) -serverConfig.push({ - id: 'Global_Cache_Limit', - readOnly: true, - type: 'integer', - value: 1 -}); +serverConfig.push(new Property( + 'Global_Cache_Limit', + 'integer', + 1, + true +)); // Caching Settings (project level) -propertyDisplay = new PropertyDisplay( - 'Caching', - 'BE4', - 'Caching Type', - 'This property defines the current caching style for this project.' -); - -serverConfig.push({ - id: 'project_example', - display: propertyDisplay, - readOnly: false, - type: 'integer', - value: 1 -}); - -/** - * Checks if a property exists in the server's property list. - * - * @param propKey The property unique ID to search for. - * @returns The index of the property in the server's property list, - * or `-1` if the property is not present. - */ -export const propertyExists: (propKey: string) => number = - (propKey: string): number => { - let found: number = -1; - for (const prop in serverConfig) { - if (serverConfig[prop].id === propKey) { - found = parseInt(prop, 10); - break; - } - } - return found; +propertyDisplay = { + category: 'Caching', + group: 'BE4', + displayName: 'Caching Type', + description: + 'This property defines the current caching style for this project.' }; +serverConfig.push(new Property( + 'project_example', + 'integer', + 1, + false, + propertyDisplay +)); + export default serverConfig; diff --git a/src/uuid.ts b/src/uuid.ts new file mode 100644 index 0000000..983a92d --- /dev/null +++ b/src/uuid.ts @@ -0,0 +1,7 @@ +import { v4 } from 'uuid'; + +export const uuid: { + generate: () => string; +} = { + generate: v4 +}; -- cgit v1.2.1 From 10e00fba97f0227a7e3d61d2725326d4a5d37bfa Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 1 Mar 2018 22:06:42 +0000 Subject: Add miniature response-wrapper middleware --- src/app.ts | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index 86b0c1c..28b97a7 100644 --- a/src/app.ts +++ b/src/app.ts @@ -18,6 +18,15 @@ class App { this.precondition(); this.middleware(); this.mountRoutes(); + this.express.use( + async(req: ex.Request, res: ex.Response, next: ex.NextFunction): + Promise => { + res.json({ + status: 'success', + data: await res.locals.data + }); + } + ); this.errorware(); } -- cgit v1.2.1 From 84b8b5323654cf43ef549d2151bd3206c666d9d8 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 2 Mar 2018 18:03:31 +0000 Subject: Plug in authentication support - WIP --- src/FileRouter.ts | 2 +- src/app.ts | 8 ++++ src/auth.ts | 100 ++++++++++++++++++++++++------------------------ src/db/model/User.ts | 6 +-- src/errors/errorware.ts | 13 +++++-- src/index.ts | 14 ++++++- 6 files changed, 84 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 34738bc..7bc9187 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -534,7 +534,7 @@ 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); diff --git a/src/app.ts b/src/app.ts index a843179..c6527c8 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,6 +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 } from './auth'; import { errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; @@ -18,6 +22,8 @@ class App { // 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')); } @@ -36,9 +42,11 @@ class App { }); this.express.use('/', defRouter); this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); } private errorware(): void { + //this.express.use(authRouter.unauthorisedErr); this.express.use(errorHandler); } } diff --git a/src/auth.ts b/src/auth.ts index 3feac5d..d5969c5 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,43 +1,35 @@ +/* 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'; export class AuthRouter { - public localStrategy: Strategy; public router: Router; - ensureAuth; public constructor() { - this.localStrategy = Strategy(); - this.ensureAuth = expressJwt({secret: 'Mr Secret'}); //protects routes - 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 { + 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 } ); @@ -50,19 +42,24 @@ export class AuthRouter { }); } - private authenticate(req: Request, res: Response, next: NextFunction) { - passport.authenticate('local', { session: false }, function(err, user) { - if (err) { console.log(err); } - - if (!user) { - next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + 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) { next(new RequestError(400, 'invalid_request', 'Missing parameters')); } @@ -76,7 +73,7 @@ export class AuthRouter { } // Handle error if user is unauthorised - public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { + public unauthorisedErr(err: Error, req: Request, res: Response, next: NextFunction): void { if (err.name === 'UnauthorizedError') { next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); } @@ -93,37 +90,42 @@ export class AuthRouter { // Configure local strategy to use with passport-js. private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { - const user = findByUsername(username); - - if (!user || user.password != password) { + // 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) { return done(null, false); } return done(null, user); })); } - init() { + public init(): void { this.configStrategy(); this.router.post('/login', this.checkErr, this.authenticate, this.genToken); - this.router.get('/logout', (req, res) => { req.logout(); }); + this.router.get( + '/logout', + (req: Request, res: Response): void => { req.logout(); } + ); } } -const authRoutes = new AuthRouter(); +const authRoutes: AuthRouter = new AuthRouter(); authRoutes.init(); export default authRoutes.router; /////////////////////////////////////////////////// -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error - /* -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/User.ts b/src/db/model/User.ts index 5a9af07..9b3190c 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -9,14 +9,14 @@ import { default as UserJoinsProject } from './UserJoinsProject'; export default class User extends Model { @PrimaryKey @Column - public username: string = ''; + public username!: string; @Column - public password: string = ''; + public password!: string; @ForeignKey(() => UserGroup) @Column - public userGroupId: number = 0; + public userGroupId!: number; @BelongsTo(() => UserGroup) public userGroup: UserGroup = new UserGroup(); diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts index 8b7e015..45a76b3 100644 --- a/src/errors/errorware.ts +++ b/src/errors/errorware.ts @@ -42,10 +42,15 @@ export class RequestError extends Error { } type Errorware = - (err: RequestError, req: Request, res: Response, next: NextFunction) => void; + (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 => { + if ((err as RequestError).responseBlock) { + const rerr: RequestError = err as RequestError; + res.status(rerr.code) + .json(rerr.responseBlock()); + } else { + res.send(err); + } }; 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'); -- cgit v1.2.1 From 11776b9665c1bc3e49cf602dfa069294a490d5fd Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 3 Mar 2018 14:18:11 +0000 Subject: Fix minor things --- src/FileRouter.ts | 7 +++---- src/app.ts | 11 ++++++++--- src/auth.ts | 27 +++++++++++++++++++-------- src/db/model/User.ts | 15 ++------------- 4 files changed, 32 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 1c62621..8d13401 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -229,8 +229,8 @@ const getUsers: Middleware = (u: User) => { const info: UserFullInfo = u.fullInfo; if (!req.user.hasPrivilege('admin')) { - info.private_user_metadata = undefined; - info.private_admin_metadata = undefined; + delete info.private_user_metadata; + delete info.private_admin_metadata; } return info; } @@ -567,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; diff --git a/src/app.ts b/src/app.ts index 83082a9..7776c02 100644 --- a/src/app.ts +++ b/src/app.ts @@ -36,7 +36,12 @@ class App { // 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(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')); @@ -51,7 +56,7 @@ 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); @@ -60,7 +65,7 @@ class App { } private errorware(): void { - //this.express.use(authRouter.unauthorisedErr); + // TODO: this.express.use(authRouter.unauthorisedErr); this.express.use(errorHandler); } diff --git a/src/auth.ts b/src/auth.ts index d5969c5..b40cddb 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -51,7 +51,9 @@ export class AuthRouter { if (err) { throw err; } if (!user) { - next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + next(new RequestError( + 400, 'invalid_grant', 'Incorrect authentication details' + )); } } ); @@ -73,25 +75,34 @@ export class AuthRouter { } // Handle error if user is unauthorised - public unauthorisedErr(err: Error, req: Request, res: Response, next: NextFunction): void { + public unauthorisedErr( + err: Error, req: Request, res: Response, next: NextFunction + ): void { if (err.name === 'UnauthorizedError') { - next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); + next(new RequestError( + 401, 'not_authorised', + 'user does not have correct authorisation for task' + )); } next(); } - //middleware to check privileges - admin - public isAdmin(req: Request, res: Response, next: NextFunction) { + // 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')); + 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() { + private configStrategy(): void { // tslint:disable-next-line:typedef - passport.use(new Strategy( async(username, password, done) => { + passport.use(new Strategy( async(username, password, done) => { const user: User | null = await User.findOne({ where: { username diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 19a93f0..d290fd9 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -13,21 +13,10 @@ export default class User extends Model { public username!: string; @Column -<<<<<<< HEAD - public password!: string; - - @ForeignKey(() => UserGroup) - @Column - public userGroupId!: number; - - @BelongsTo(() => UserGroup) - public userGroup: UserGroup = new UserGroup(); -======= private readonly passwordInternal!: string; @BelongsToMany(() => UserGroup, () => UserHasPrivilege) public userGroups?: UserGroup[]; ->>>>>>> trh/gets @BelongsToMany(() => Project, () => UserJoinsProject) public projects?: Project[]; @@ -200,9 +189,9 @@ export interface UserFullInfo { privileges: string[]; projects: ProjectInfo[]; public_user_metadata: Metadata; - private_user_metadata?: Metadata; + private_user_metadata: Metadata; public_admin_metadata: Metadata; - private_admin_metadata?: Metadata; + private_admin_metadata: Metadata; } export interface UserProperty {} -- cgit v1.2.1 From 652d328dc1d6605687cbd6858a3d27da1c126f7e Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 3 Mar 2018 16:42:16 +0000 Subject: Implement handling of unauthorised requests --- src/app.ts | 4 ++-- src/auth.ts | 29 ++++++++++++++++------------- src/errors/errorware.ts | 24 ++++++++++++++++-------- 3 files changed, 34 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index 7776c02..4e35063 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,7 +4,7 @@ import * as expressJwt from 'express-jwt'; import * as logger from 'morgan'; import * as passport from 'passport'; -import { default as authRouter } from './auth'; +import { unauthorisedErr, default as authRouter } from './auth'; import { RequestError, errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; @@ -65,7 +65,7 @@ class App { } private errorware(): void { - // TODO: this.express.use(authRouter.unauthorisedErr); + this.express.use(unauthorisedErr); this.express.use(errorHandler); } diff --git a/src/auth.ts b/src/auth.ts index b40cddb..083357e 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -7,6 +7,8 @@ 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 router: Router; @@ -74,19 +76,6 @@ export class AuthRouter { next(); } - // Handle error if user is unauthorised - public unauthorisedErr( - err: Error, req: Request, res: Response, next: NextFunction - ): void { - if (err.name === 'UnauthorizedError') { - next(new RequestError( - 401, 'not_authorised', - 'user does not have correct authorisation for task' - )); - } - next(); - } - // Middleware to check privileges - admin public isAdmin(req: Request, res: Response, next: NextFunction): void { if (!req.user.admin) { @@ -127,6 +116,20 @@ export class AuthRouter { } } +// 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); +}; + const authRoutes: AuthRouter = new AuthRouter(); authRoutes.init(); diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts index 45a76b3..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,16 +48,17 @@ export class RequestError extends Error { } } -type Errorware = +export type Errorware = (err: Error, req: Request, res: Response, next: NextFunction) => void; export const errorHandler: Errorware = (err: Error, req: Request, res: Response, next: NextFunction): void => { - if ((err as RequestError).responseBlock) { - const rerr: RequestError = err as RequestError; - res.status(rerr.code) - .json(rerr.responseBlock()); - } else { - res.send(err); - } + console.log(err); + if (RequestError.is(err)) { + console.log('fewkuihfklsfv'); + res.status(err.code) + .json(err.responseBlock()); + } else { + res.send(err); + } }; -- cgit v1.2.1