From cf8d0097d83d77e9a59d46d5969c83d6d03cfbe6 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Wed, 7 Feb 2018 00:04:43 +0000 Subject: started creating authentication middleware --- src/auth.ts | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 src/auth.ts (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..c587fcf --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,92 @@ +import * as passport from 'passport'; +import * as passportLocal from 'passport-local'; +import * as jwt from 'jsonwebtoken'; + +const LocalStrategy = passportLocal.Strategy; + +//Used by passport-js to locate a user object from the database by username +function findByUsername(username) { + +} + +//Find user obejct from database by user ID +function findUserByID(id) { + +} + +//middleware which generates token and sends it as response +function genToken(req, res) { + var userid = findUserByID(req.username); + + var token = jwt.sign({ + id: userid + }, 'Mr Secret', { + expiresIn: 21600 + }); + + res.json({ + "token_type": "bearer", + "access_token": token, + "refresh_token": token, + "expires_in": 21600 + }); +} + +function checkErr(req, res, next) { + if (!req.grant_type || !req.username || !req.password) { + res.status(400).json({ + "error": "invalid_request", + "error_description": "Missing parameters" + }); + res.end(); + } + + if (req.grant_type != "refresh_token" || req.grant_type != "password") { + res.status(400).json({ + "error": "unsupported_grant_type", + "error_description": "invalid grant type" + }); + res.end(); + } + + next(); +} + + + +//Configure local strategy to use with passport-js. +passport.use(new LocalStrategy({ + function(username, password, done) { + var user = findByUsername(username); + + if (!user || user.password != password) { + return done(null, false); + } + return done(null, user); + } +})); + +passport.serializeUser(function(user, done) { + done(null, user.id); +}); + +passport.deserializeUser(function(id, done) { + var user = findUserByID(id); + done(null, user); +}); + + +/////////////////////////////////////////////////// +app.use(passport.initialize()); +app.use(passport.session()); + +app.post('/login', checkErr, passport.authenticate('local', function(err, user) { + if (!user) { + res.status(400).json({ + "error": "invalid_grant", + "error_description": "Incorrect authentication details" + }); + } +}), genToken); + +app.get('/logout', ) \ No newline at end of file -- cgit v1.2.1 From c86122ea21e69d63a67a45b8eb91450df3d0ccf2 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Wed, 7 Feb 2018 00:10:05 +0000 Subject: added ensureAuth method --- src/auth.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts index c587fcf..fb37787 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -52,6 +52,11 @@ function checkErr(req, res, next) { next(); } +//Checks if user is still authenticated otherwise redirects +function ensureAuthenticated(req, res, next) { + if (req.isAuthenticated()) { return next(); } + res.redirect('/login'); +} //Configure local strategy to use with passport-js. @@ -89,4 +94,6 @@ app.post('/login', checkErr, passport.authenticate('local', function(err, user) } }), genToken); -app.get('/logout', ) \ No newline at end of file +app.get('/logout', function(req, res) { + req.logout(); +}); \ No newline at end of file -- cgit v1.2.1 From 79b80371d94e258c2cc1eeee41625ccc212369f6 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 7 Feb 2018 12:22:49 +0000 Subject: removed types from options.ts to remove ts-node ambiguity --- src/matcher/options.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 1ffa24e..b356c7b 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -1,9 +1,6 @@ import { default as types } from './types'; -type matchType - = (boolean | ((T) => boolean)); - -export function match(template: Object, value?: Object): matchType { +export function match(template: Object, value?: Object) { if (value === undefined) { return match.bind(null, template); } @@ -16,7 +13,7 @@ export function match(template: Object, value?: Object): matchType { return true; } -export function exact(template: Object, value?: Object): matchType { +export function exact(template: Object, value?: Object) { if (value === undefined) { return exact.bind(null, template); } @@ -28,7 +25,7 @@ export function exact(template: Object, value?: Object): matchType { && k2.every((x) => k1.indexOf(x) < 0); } -export function optional(template: Function, value?: any): matchType { +export function optional(template: Function, value?: any) { if (value === undefined) { return optional.bind(null, template); } @@ -37,7 +34,7 @@ export function optional(template: Function, value?: any): matchType { || template(value); } -export function alternative(templates: any[], value?: any): matchType { +export function alternative(templates: any[], value?: any) { if (value === undefined) { return alternative.bind(null, templates); } @@ -58,8 +55,7 @@ export function alternative(templates: any[], value?: any): matchType { } } -export function array(template: Object, values?: Array): -matchType> { +export function array(template: Object, values?: Array) { if (values === undefined) { return array.bind(null, template); } -- cgit v1.2.1 From f60e3d9858f6037db3b27d5574ac95310127d302 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 7 Feb 2018 12:48:48 +0000 Subject: matching now supports nested functions --- src/matcher/options.test.ts | 20 ++++++++++++++++++++ src/matcher/options.ts | 8 +++++++- 2 files changed, 27 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/matcher/options.test.ts b/src/matcher/options.test.ts index f3d498c..058ef9e 100644 --- a/src/matcher/options.test.ts +++ b/src/matcher/options.test.ts @@ -63,5 +63,25 @@ describe('Object Matching:', () => { }; options.match(template, matchee).should.be.true; }); + it('accepts nested objects that match', () => { + let template = { + a: types.number, + b: { + ba: types.string, + bb: types.function + }, + c: types.boolean + }; + let matchee = { + a: 432, + b: { + ba: "barracus", + bb: new Function(), + }, + c: true, + x: false + }; + options.match(template, matchee).should.be.true; + }); }); }); diff --git a/src/matcher/options.ts b/src/matcher/options.ts index b356c7b..e93c2fd 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -6,7 +6,13 @@ export function match(template: Object, value?: Object) { } for (let k of Object.keys(template)) { - if (!template[k](value[k])) { + let f; + if (types.object(template[k])) { + f = match(template[k]); + } else { + f = template[k]; + } + if (!f(value[k])) { return false; } } -- cgit v1.2.1 From 5e482ce4408f2e1926d1e9af3270a52ffcc83df6 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 7 Feb 2018 14:18:55 +0000 Subject: added literal matching --- src/matcher/options.test.ts | 20 +++++++++++++++++++- src/matcher/options.ts | 5 ++++- 2 files changed, 23 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/matcher/options.test.ts b/src/matcher/options.test.ts index 058ef9e..39c4b3e 100644 --- a/src/matcher/options.test.ts +++ b/src/matcher/options.test.ts @@ -75,7 +75,7 @@ describe('Object Matching:', () => { let matchee = { a: 432, b: { - ba: "barracus", + ba: "baracus", bb: new Function(), }, c: true, @@ -83,5 +83,23 @@ describe('Object Matching:', () => { }; options.match(template, matchee).should.be.true; }); + it('accepts literal matches', () => { + let template = { + a: "literal" + }; + let matchee = { + a: "literal" + }; + options.match(template, matchee).should.be.true; + }); + it('rejects incorrect literal matches', () => { + let template = { + g: 99 + }; + let matchee = { + g: 80 + }; + options.match(template, matchee).should.be.false; + }); }); }); diff --git a/src/matcher/options.ts b/src/matcher/options.ts index e93c2fd..2e65105 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -9,9 +9,12 @@ export function match(template: Object, value?: Object) { let f; if (types.object(template[k])) { f = match(template[k]); - } else { + } else if (types.function(template[k])) { f = template[k]; + } else { + f = (v) => v === template[k]; } + if (!f(value[k])) { return false; } -- cgit v1.2.1 From 90e0994e28a7d4af7eb098bc026ae6778b1406ae Mon Sep 17 00:00:00 2001 From: Hafeez Date: Wed, 7 Feb 2018 16:46:13 +0000 Subject: added route protection and tested with simple dummy server --- src/auth.ts | 110 ++++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 81 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts index fb37787..cb89b26 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -2,21 +2,38 @@ import * as passport from 'passport'; import * as passportLocal from 'passport-local'; import * as jwt from 'jsonwebtoken'; +import * as express from 'express'; +import * as bodyParser from 'body-parser'; +import * as expressJwt from 'express-jwt'; + const LocalStrategy = passportLocal.Strategy; +//user object for basic testing +var user = { + "id": 23, + "username": "har4", + "password": "secret" +} + //Used by passport-js to locate a user object from the database by username function findByUsername(username) { - + if (username == user.username) { + return user; + } + return false; } //Find user obejct from database by user ID function findUserByID(id) { - + if (id == user.id) { + return user; + } + return false; } //middleware which generates token and sends it as response -function genToken(req, res) { - var userid = findUserByID(req.username); +function genToken(req, res) { + var userid = findUserByID(req.body.username); var token = jwt.sign({ id: userid @@ -32,16 +49,17 @@ function genToken(req, res) { }); } -function checkErr(req, res, next) { - if (!req.grant_type || !req.username || !req.password) { +//checks for errors within request before authentication +function checkErr(req, res, next) { + if (!req.body.grant_type || !req.body.username || !req.body.password) { res.status(400).json({ "error": "invalid_request", "error_description": "Missing parameters" - }); - res.end(); + }); + res.end(); } - if (req.grant_type != "refresh_token" || req.grant_type != "password") { + 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" @@ -52,15 +70,22 @@ function checkErr(req, res, next) { next(); } -//Checks if user is still authenticated otherwise redirects -function ensureAuthenticated(req, res, next) { - if (req.isAuthenticated()) { return next(); } - res.redirect('/login'); +//handle error if user is unauthorised +function unauthorisedErr(err, req, res, next) { + console.log(err); + 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. -passport.use(new LocalStrategy({ +passport.use(new LocalStrategy( function(username, password, done) { var user = findByUsername(username); @@ -68,10 +93,12 @@ passport.use(new LocalStrategy({ return done(null, false); } return done(null, user); - } -})); + }) +); + -passport.serializeUser(function(user, done) { +//both methods below needed for persistant sessions +/*passport.serializeUser(function(user, done) { done(null, user.id); }); @@ -79,21 +106,46 @@ passport.deserializeUser(function(id, done) { var user = findUserByID(id); done(null, user); }); - +*/ /////////////////////////////////////////////////// -app.use(passport.initialize()); -app.use(passport.session()); -app.post('/login', checkErr, passport.authenticate('local', function(err, user) { - if (!user) { - res.status(400).json({ - "error": "invalid_grant", - "error_description": "Incorrect authentication details" - }); - } -}), genToken); +var app = express(); +var ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes +app.use(bodyParser.json()); + +app.use(passport.initialize()); +//app.use(passport.session()); +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(); -}); \ No newline at end of file +}); + +app.get('/test', ensureAuth, function(req, res) { + res.send("you are authenticated!"); +}); + +app.listen(3000); + +/* +tasks left: + refreshing tokens + connect to db + revoke tokens/checking validity + logging out +*/ -- cgit v1.2.1 From 1bd45e04ea49d198a85a78eeac7ab6ce67db1ccf Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 7 Feb 2018 18:08:13 +0000 Subject: started working on ORM for DB --- src/db/model/User.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/db/model/User.ts (limited to 'src') diff --git a/src/db/model/User.ts b/src/db/model/User.ts new file mode 100644 index 0000000..8a3fc1d --- /dev/null +++ b/src/db/model/User.ts @@ -0,0 +1,17 @@ +import { + Table, + Column +} from 'sequelize-typescript'; + +@Table +class User extends Model { + @Column + @PrimaryKey + username: string; + + @Column + password: string; + + @CreatedAt + creationDate: Date; +} -- cgit v1.2.1 From 50712e8c6cedaa9900897acc187a1237c76f5887 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 01:21:10 +0000 Subject: further work on ORM model --- src/db/model/File.ts | 32 ++++++++++++++++++++++++++++++++ src/db/model/Project.ts | 20 ++++++++++++++++++++ src/db/model/User.ts | 18 +++++++++++++----- src/db/model/UserJoinsProject.ts | 20 ++++++++++++++++++++ 4 files changed, 85 insertions(+), 5 deletions(-) create mode 100644 src/db/model/File.ts create mode 100644 src/db/model/Project.ts create mode 100644 src/db/model/UserJoinsProject.ts (limited to 'src') diff --git a/src/db/model/File.ts b/src/db/model/File.ts new file mode 100644 index 0000000..b88fef4 --- /dev/null +++ b/src/db/model/File.ts @@ -0,0 +1,32 @@ +import * from 'sequelize-typescript'; + +@Table +export default class File extends Model { + @Column + @Unique + @NotNull + name: string; + + @Column + @PrimaryKey + uuid: string; + + @Column + mimetype: string; + + @Column + @ForeignKey(() => File) + parentFolderId: string; + + @BelongsTo(() => File) + parentFolder: File; + + @HasMany(() => File) + containedFiles: File[]; + + @CreatedAt + uploadDate: Date; + + @UpdatedAt + modifyDate: Date; +} diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts new file mode 100644 index 0000000..1c91efd --- /dev/null +++ b/src/db/model/Project.ts @@ -0,0 +1,20 @@ +import * from 'sequelize-typescript'; + +@Table +export default class Project extends Model { + @Column + @PrimaryKey + name: string; + + @Column + @BelongsToMany(() => User, () => UserJoinsProject) + contributors: User[]; + + @Column + @CreatedAt + creationDate: Date; + + @Column + @UpdatedAt + lastActivity: Date; +} diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 8a3fc1d..1988034 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -1,17 +1,25 @@ -import { - Table, - Column -} from 'sequelize-typescript'; +import * from 'sequelize-typescript'; @Table -class User extends Model { +export default class User extends Model { @Column @PrimaryKey username: string; @Column + @NotNull password: string; + @Column + @ForeignKey(() => UserGroup) + userGroupId: number; + + @BelongsTo(() => UserGroup) + userGroup: UserGroup; + + @BelongsToMany(() => Project, () => UserJoinsProject) + projects: Project[]; + @CreatedAt creationDate: Date; } diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts new file mode 100644 index 0000000..ffc173a --- /dev/null +++ b/src/db/model/UserJoinsProject.ts @@ -0,0 +1,20 @@ +import * from 'sequelize-typescript'; + +@Table +export default class UserJoinsProject extends Model { + @Column + @ForeignKey(() => User) + username: string; + + @Column + @ForeignKey(() => Project) + projectName: string; + + @Column + @CreatedAt + joinDate: Date; + + @Column + @ForeignKey(() => UserGroup) + userGroupId: number; +} -- cgit v1.2.1 From 3335f23194b90bffd534699b852322f5259ae693 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 15:02:10 +0000 Subject: should be almost functional now --- src/db/model/ContributorGroup.ts | 34 ++++++++++++++++++++++++++++++++++ src/db/model/File.ts | 12 ++++++++++++ src/db/model/Project.ts | 10 ++++++++++ src/db/model/User.ts | 7 +++++++ src/db/model/UserGroup.ts | 34 ++++++++++++++++++++++++++++++++++ src/db/model/UserJoinsProject.ts | 5 ++++- src/db/orm.ts | 14 ++++++++++++++ 7 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 src/db/model/ContributorGroup.ts create mode 100644 src/db/model/UserGroup.ts create mode 100644 src/db/orm.ts (limited to 'src') diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts new file mode 100644 index 0000000..8e90a1e --- /dev/null +++ b/src/db/model/ContributorGroup.ts @@ -0,0 +1,34 @@ +import * from 'sequelize-typescript'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +export default class ContributorGroup extends Model { + @Column + name: string; + + @HasMany(() => UserJoinsProject) + uses: UserJoinsProject[]; + + @Column + @NotNull + canCreateFiles: boolean; + + @Column + @NotNull + canDeleteFiles: boolean; + + @Column + @NotNull + canViewFiles: boolean; + + @Column + @NotNull + canAddUsers: boolean; + + @Column + @NotNull + canRemoveUsers: boolean; + + @Column + @NotNull + canEditUserPermissions: boolean; +} diff --git a/src/db/model/File.ts b/src/db/model/File.ts index b88fef4..cc5e784 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -1,4 +1,6 @@ import * from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as Project } from './Project'; @Table export default class File extends Model { @@ -24,6 +26,16 @@ export default class File extends Model { @HasMany(() => File) containedFiles: File[]; + @Column + @ForeignKey(() => User) + creatorName: string; + + @BelongsTo(() => User) + creator: User; + + @BelongsTo(() => Project) + rootFolderOf: Project; + @CreatedAt uploadDate: Date; diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index 1c91efd..b1b2397 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -1,4 +1,7 @@ import * from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as UserJoinsProject } from './UserJoinsProject'; +import { default as File } from './File'; @Table export default class Project extends Model { @@ -10,6 +13,13 @@ export default class Project extends Model { @BelongsToMany(() => User, () => UserJoinsProject) contributors: User[]; + @Column + @ForeignKey(() => File) + rootFolderId: string; + + @BelongsTo(() => File) + rootFolder: File; + @Column @CreatedAt creationDate: Date; diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 1988034..f3ec962 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -1,4 +1,8 @@ import * from 'sequelize-typescript'; +import { default as UserGroup } from './UserGroup'; +import { default as Project } from './Project'; +import { default as UserJoinsProject } './UserJoinsProject'; +import { default as File } './File'; @Table export default class User extends Model { @@ -20,6 +24,9 @@ export default class User extends Model { @BelongsToMany(() => Project, () => UserJoinsProject) projects: Project[]; + @HasMany(() => File) + createdFiles: File[]; + @CreatedAt creationDate: Date; } diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts new file mode 100644 index 0000000..5c8cf10 --- /dev/null +++ b/src/db/model/UserGroup.ts @@ -0,0 +1,34 @@ +import * from 'sequelize-typescript'; +import { default as User } from './User'; + +export default class UserGroup extends Model { + @Column + name: string; + + @HasMany(() => User) + users: User[]; + + @Column + @NotNull + canCreateUsers: boolean; + + @Column + @NotNull + canDeleteUsers: boolean; + + @Column + @NotNull + canEditUsers: boolean; + + @Column + @NotNull + canCreateProjects: boolean; + + @Column + @NotNull + canDeleteProjects: boolean; + + @Column + @NotNull + canEditProjects: boolean; +} diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts index ffc173a..e929926 100644 --- a/src/db/model/UserJoinsProject.ts +++ b/src/db/model/UserJoinsProject.ts @@ -1,4 +1,7 @@ import * from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as Project } from './Project'; +import { default as ContributorGroup } from './UserGroup'; @Table export default class UserJoinsProject extends Model { @@ -15,6 +18,6 @@ export default class UserJoinsProject extends Model { joinDate: Date; @Column - @ForeignKey(() => UserGroup) + @ForeignKey(() => ContributorGroup) userGroupId: number; } diff --git a/src/db/orm.ts b/src/db/orm.ts new file mode 100644 index 0000000..300c90f --- /dev/null +++ b/src/db/orm.ts @@ -0,0 +1,14 @@ +import { Sequelize } from 'sequelize-typescript'; + +const seq = new Sequelize({ + database: 'be4', + dialect: 'postgres', + username: 'admin', + password: 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af', + storage: ':memory:', + operatorsAliases: false, + modelPaths: [__dirname + 'model'] +}); + +seq.authenticate() + .then(() => console.log('Logged in!')); -- cgit v1.2.1 From 2163349b8e5c5a5eca21c5865563552365e42209 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 17:07:31 +0000 Subject: removed postgres password --- src/db/orm.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/db/orm.ts b/src/db/orm.ts index 300c90f..7bfa5b4 100644 --- a/src/db/orm.ts +++ b/src/db/orm.ts @@ -4,8 +4,7 @@ const seq = new Sequelize({ database: 'be4', dialect: 'postgres', username: 'admin', - password: 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af', - storage: ':memory:', + password: '', operatorsAliases: false, modelPaths: [__dirname + 'model'] }); -- cgit v1.2.1 From d4e2bb0ab011b3e69c4e3eaecaae0ad378f0183d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 17:12:32 +0000 Subject: models should now do basic functioning --- src/db/model/ContributorGroup.ts | 7 +------ src/db/model/File.ts | 6 +++++- src/db/model/Project.ts | 1 - src/db/model/User.ts | 1 - src/db/model/UserGroup.ts | 6 ------ 5 files changed, 6 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index 8e90a1e..c2ff2b6 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -3,32 +3,27 @@ import { default as UserJoinsProject } from './UserJoinsProject'; export default class ContributorGroup extends Model { @Column + @AllowNull name: string; @HasMany(() => UserJoinsProject) uses: UserJoinsProject[]; @Column - @NotNull canCreateFiles: boolean; @Column - @NotNull canDeleteFiles: boolean; @Column - @NotNull canViewFiles: boolean; @Column - @NotNull canAddUsers: boolean; @Column - @NotNull canRemoveUsers: boolean; @Column - @NotNull canEditUserPermissions: boolean; } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index cc5e784..bb5759d 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -6,7 +6,6 @@ import { default as Project } from './Project'; export default class File extends Model { @Column @Unique - @NotNull name: string; @Column @@ -18,9 +17,11 @@ export default class File extends Model { @Column @ForeignKey(() => File) + @AllowNull parentFolderId: string; @BelongsTo(() => File) + @AllowNull parentFolder: File; @HasMany(() => File) @@ -28,6 +29,7 @@ export default class File extends Model { @Column @ForeignKey(() => User) + @AllowNull creatorName: string; @BelongsTo(() => User) @@ -36,9 +38,11 @@ export default class File extends Model { @BelongsTo(() => Project) rootFolderOf: Project; + @Column @CreatedAt uploadDate: Date; + @Column @UpdatedAt modifyDate: Date; } diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index b1b2397..2648409 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -9,7 +9,6 @@ export default class Project extends Model { @PrimaryKey name: string; - @Column @BelongsToMany(() => User, () => UserJoinsProject) contributors: User[]; diff --git a/src/db/model/User.ts b/src/db/model/User.ts index f3ec962..8b0a72c 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -11,7 +11,6 @@ export default class User extends Model { username: string; @Column - @NotNull password: string; @Column diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts index 5c8cf10..89f234d 100644 --- a/src/db/model/UserGroup.ts +++ b/src/db/model/UserGroup.ts @@ -9,26 +9,20 @@ export default class UserGroup extends Model { users: User[]; @Column - @NotNull canCreateUsers: boolean; @Column - @NotNull canDeleteUsers: boolean; @Column - @NotNull canEditUsers: boolean; @Column - @NotNull canCreateProjects: boolean; @Column - @NotNull canDeleteProjects: boolean; @Column - @NotNull canEditProjects: boolean; } -- cgit v1.2.1 From 2c520720c4292d0db159be2655742cd0f82e0880 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 17:13:34 +0000 Subject: configured server to use pg server on lab machines --- src/db/orm.ts | 3 +-- src/index.ts | 30 ++++++++++++++++++++---------- 2 files changed, 21 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/db/orm.ts b/src/db/orm.ts index 7bfa5b4..78d5832 100644 --- a/src/db/orm.ts +++ b/src/db/orm.ts @@ -9,5 +9,4 @@ const seq = new Sequelize({ modelPaths: [__dirname + 'model'] }); -seq.authenticate() - .then(() => console.log('Logged in!')); +export default seq; diff --git a/src/index.ts b/src/index.ts index 69150e2..a8756ad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,14 +1,24 @@ -console.log('Welcome to the CS3099 Server thingy!'); - -import app from './app' +import { default as seq } from './db/orm'; +import { default as app } from './app'; // use default port 3000 or port supplied by OS -const port = process.env.PORT || 3000 +const port: number = process.env.PORT || 3000; + +(async () => { + console.log('Booting PSQL database'); + + await seq.authenticate(); + await seq.sync({ + force: true + }); -app.listen(port, (err) => { - if (err) { - return console.log(err) - } + console.log('Booting ExpressJS server'); - return console.log(`server is listening on port ${port}`) -}) \ No newline at end of file + app.listen(port, (err) => { + if (err) { + return console.log(err); + } else { + return console.log(`server is listening on port ${port}`); + } + }); +})(); -- cgit v1.2.1 From 05f1604a853bb3e2a066ceab1305abbc11d1d99d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 18:33:40 +0000 Subject: Revert "Revert "Merge branch 'testing'"" This reverts commit 0a9ebb01c27ed0a648922d243e877194977ce4d1. --- src/app.ts | 3 ++- src/matcher/options.ts | 3 +++ src/matcher/types.ts | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/matcher/types.ts (limited to 'src') diff --git a/src/app.ts b/src/app.ts index 83bf2b0..f2fbe0c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -6,6 +6,7 @@ import FileRouter from './FileRouter'; class App { public express + public log_enabled : boolean; constructor () { this.express = express() @@ -15,7 +16,7 @@ class App { // Configure Express middleware. private middleware(): void { - this.express.use(logger('combined')); + if(this.log_enabled) this.express.use(logger('combined')); this.express.use(bodyParser.json()); this.express.use(bodyParser.urlencoded({ extended: false })); } diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 2e65105..7412675 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -1,5 +1,8 @@ import { default as types } from './types'; +type matchType + = (boolean | ((T) => boolean)); + export function match(template: Object, value?: Object) { if (value === undefined) { return match.bind(null, template); diff --git a/src/matcher/types.ts b/src/matcher/types.ts new file mode 100644 index 0000000..70b2d47 --- /dev/null +++ b/src/matcher/types.ts @@ -0,0 +1,33 @@ +function typeCheckerGenerator(test: T): (v: any) => v is T { + let f = (value): value is T => + value != null && value.constructor === test.constructor; + return f; +} + +let isObject = typeCheckerGenerator({}); +let isNumber = typeCheckerGenerator(0); +let isString = typeCheckerGenerator(""); +let isBoolean = typeCheckerGenerator(true); +let isArray = typeCheckerGenerator>([]); +let isFunction = typeCheckerGenerator(new Function()); +let isNull = (v) => v === null; +let isUndefined = (v) => v === undefined; +let isPresent = (v) => !isUndefined(v); +let isInteger = (value: any) => isNumber(value) + && Number.isInteger(value as number); + +let types = { + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + array: isArray, + function: isFunction, + integer: isInteger, + null: isNull, + not_present: isUndefined, + undefined: isUndefined, + anything: isPresent +}; + +export default types; -- cgit v1.2.1 From c1666f2879537d85a79170f35f927565bc49da71 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 8 Feb 2018 22:33:06 +0000 Subject: Edited some Model stuff, and filled in more stubs to use ORM models --- src/FileRouter.ts | 58 ++++++++++++++++++++++++++++++++-------- src/db/initPostgresDB.ts | 1 + src/db/model/ContributorGroup.ts | 8 +++--- src/db/model/File.ts | 24 ++++++++++------- src/db/model/Project.ts | 53 ++++++++++++++++++++++++++++++++---- src/db/model/User.ts | 58 ++++++++++++++++++++++++++++++++++++---- src/db/model/UserGroup.ts | 23 +++++++++++++++- src/db/model/UserJoinsProject.ts | 15 ++++++----- src/db/orm.ts | 2 +- 9 files changed, 200 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 19a9126..34347a8 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -1,4 +1,8 @@ import {Router, Request, Response, NextFunction} from 'express'; +import {default as UserGroup} from './db/model/UserGroup'; +import {default as User} from './db/model/User'; +import Project from './db/model/Project'; + var serverConfig = require('./serverConfig'); const Files = null;//require('../data'); @@ -145,7 +149,12 @@ export class FileRouter { }) */ public getUserPriveleges(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + UserGroup.findAll() + .then((permissions) => { + res.json(permissions.map( + (p: UserGroup) => p.getPrivelege() + )); + }); } /* @@ -168,8 +177,12 @@ export class FileRouter { }) */ public getUsers(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); - + User.findAll() + .then((user) => { + res.json(user.map( + (u: User) => u.getUserFullInfo() + )); + }); } /* @@ -178,7 +191,17 @@ export class FileRouter { * */ public getUserProperties(req: Request, res: Response, next: NextFunction, user?: String){ - res.status(500).send(); + res.status(500).send({error: "unsupported", error_description: "Users on this server dont have additional configuration options."}); + } + + private async userInfoFromName(name: string) { + let user: User = await User.findOne({ + where: { + username: name + } + }); + + return user.getUserFullInfo(); } /* @@ -200,13 +223,15 @@ export class FileRouter { } */ public getUsername(req: Request, res: Response, next: NextFunction, user?: String){ - res.status(500).send(); + this.userInfoFromName(req.params.username) + .then((info) => res.json(info)); } public getCurUser(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); - let curUser : String = ""; - this.getUsername(req, res, next, curUser); + // TODO need to findo out where authenticated user info goes + // this.userInfoFromName(req.params.username) + // .then((info) => res.json(info)); + res.json({todo: "need to findo out where authenticated user info goes"}); } /* @@ -284,7 +309,12 @@ export class FileRouter { }) */ public getProjects(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + Project.findAll() + .then((project) => { + res.json(project.map( + (p: Project) => p.getProjectFullInfo() + )); + }); } /* @@ -304,7 +334,12 @@ export class FileRouter { } */ public getProjectName(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + Project.findOne({ + where: { + name: req.params.project_name + } + }).then((project: Project) => res.json(project)); + } /* @@ -400,4 +435,5 @@ export class FileRouter { const fileRoutes = new FileRouter(); fileRoutes.init(); -export default fileRoutes.router; +var ex: Router = fileRoutes.router; +export default ex; diff --git a/src/db/initPostgresDB.ts b/src/db/initPostgresDB.ts index 307d9b6..1bb1d77 100644 --- a/src/db/initPostgresDB.ts +++ b/src/db/initPostgresDB.ts @@ -3,6 +3,7 @@ const Op = Sequelize.Op; const gres = new Sequelize('postgres://admin:eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af@localhost:5432/be4', {operatorsAliases : false}); + gres .authenticate() .then(() => { diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index c2ff2b6..a2808a0 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -1,12 +1,14 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, AllowNull, HasMany} from 'sequelize-typescript'; import { default as UserJoinsProject } from './UserJoinsProject'; +@Table export default class ContributorGroup extends Model { - @Column @AllowNull + @Column name: string; - @HasMany(() => UserJoinsProject) + // "Error: Foreign key for "ContributorGroup" is missing on "UserJoinsProject"." + // @HasMany(() => UserJoinsProject) uses: UserJoinsProject[]; @Column diff --git a/src/db/model/File.ts b/src/db/model/File.ts index bb5759d..b8cf784 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -1,48 +1,52 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, Unique, PrimaryKey, ForeignKey, AllowNull, + HasMany, BelongsTo, CreatedAt, UpdatedAt} from 'sequelize-typescript'; import { default as User } from './User'; import { default as Project } from './Project'; @Table export default class File extends Model { @Column - @Unique name: string; - @Column @PrimaryKey + @Column uuid: string; @Column mimetype: string; - @Column @ForeignKey(() => File) @AllowNull + @Column parentFolderId: string; @BelongsTo(() => File) - @AllowNull parentFolder: File; @HasMany(() => File) containedFiles: File[]; - @Column @ForeignKey(() => User) @AllowNull + @Column creatorName: string; @BelongsTo(() => User) creator: User; - @BelongsTo(() => Project) - rootFolderOf: Project; + // @ForeignKey(() => Project) + // @AllowNull + // @Column + // rootFolderOfProjectId: string; + // + // @BelongsTo(() => Project) + // rootFolderOf: Project; - @Column @CreatedAt + @Column uploadDate: Date; - @Column @UpdatedAt + @Column modifyDate: Date; } diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index 2648409..7128296 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -1,29 +1,72 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, PrimaryKey, BelongsToMany, + ForeignKey, BelongsTo, CreatedAt, UpdatedAt} from 'sequelize-typescript'; import { default as User } from './User'; import { default as UserJoinsProject } from './UserJoinsProject'; import { default as File } from './File'; @Table export default class Project extends Model { - @Column + @PrimaryKey + @Column name: string; @BelongsToMany(() => User, () => UserJoinsProject) contributors: User[]; - @Column @ForeignKey(() => File) + @Column rootFolderId: string; @BelongsTo(() => File) rootFolder: File; - @Column @CreatedAt + @Column creationDate: Date; - @Column @UpdatedAt + @Column lastActivity: Date; + + getAccessLevel(arg0: any): any { + return "unimplemented, Will be db query on UserJoinsProject table"; + } + + getUserInfo(user: User): UserInfo { + return { + username: user.username, + access_level: this.getAccessLevel(user) + } + } + + 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: {} + }; + } } + +type metadata = {}; + +type UserInfo = { + username: string, + access_level: string +}; + +type 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 index 8b0a72c..1f7f146 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -1,20 +1,22 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, PrimaryKey, ForeignKey, BelongsTo, + BelongsToMany, HasMany, CreatedAt} from 'sequelize-typescript'; import { default as UserGroup } from './UserGroup'; import { default as Project } from './Project'; -import { default as UserJoinsProject } './UserJoinsProject'; -import { default as File } './File'; +import { default as UserJoinsProject } from './UserJoinsProject'; +import { default as File } from './File'; + @Table export default class User extends Model { - @Column @PrimaryKey + @Column username: string; @Column password: string; - @Column @ForeignKey(() => UserGroup) + @Column userGroupId: number; @BelongsTo(() => UserGroup) @@ -27,5 +29,51 @@ export default class User extends Model { createdFiles: File[]; @CreatedAt + @Column creationDate: Date; + + //TODO implement + getAccessLevel(project: Project): string { + return "null"; + } + + getProjectInfo(project: Project): ProjectInfo { + return { + project_name: project.name, + access_level: this.getAccessLevel(project) + }; + } + + 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 +type metadata = {}; + +type ProjectInfo = { + project_name: string, + access_level: string +}; + +type 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 index 89f234d..35eb33d 100644 --- a/src/db/model/UserGroup.ts +++ b/src/db/model/UserGroup.ts @@ -1,6 +1,13 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, HasMany} from 'sequelize-typescript'; import { default as User } from './User'; +type UserPrivilege = { + privilege: string, + description: string, + internal: boolean +} + +@Table export default class UserGroup extends Model { @Column name: string; @@ -25,4 +32,18 @@ export default class UserGroup extends Model { @Column canEditProjects: boolean; + + @Column + isInternal: boolean + + @Column + description: string; + + 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 index e929926..230e1dd 100644 --- a/src/db/model/UserJoinsProject.ts +++ b/src/db/model/UserJoinsProject.ts @@ -1,23 +1,26 @@ -import * from 'sequelize-typescript'; +import {Table, Model, Column, ForeignKey, CreatedAt, BelongsTo} from 'sequelize-typescript'; import { default as User } from './User'; import { default as Project } from './Project'; import { default as ContributorGroup } from './UserGroup'; @Table export default class UserJoinsProject extends Model { - @Column @ForeignKey(() => User) + @Column username: string; - @Column @ForeignKey(() => Project) + @Column projectName: string; - @Column @CreatedAt + @Column joinDate: Date; - @Column @ForeignKey(() => ContributorGroup) - userGroupId: number; + @Column + contributorGroupId: number; + + @BelongsTo(() => ContributorGroup) + contributorGroup: ContributorGroup; } diff --git a/src/db/orm.ts b/src/db/orm.ts index 78d5832..02ae74b 100644 --- a/src/db/orm.ts +++ b/src/db/orm.ts @@ -6,7 +6,7 @@ const seq = new Sequelize({ username: 'admin', password: '', operatorsAliases: false, - modelPaths: [__dirname + 'model'] + modelPaths: [__dirname + '/model'] }); export default seq; -- cgit v1.2.1 From 0da1e36bbe9bb359134ec11074be64f627ca3e07 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 8 Feb 2018 23:10:27 +0000 Subject: begun improving code structure for modularisation --- src/auth.ts | 165 +++++++++++++++++++++++++++--------------------------------- 1 file changed, 74 insertions(+), 91 deletions(-) (limited to 'src') diff --git a/src/auth.ts b/src/auth.ts index cb89b26..3e2dafe 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,121 +1,105 @@ import * as passport from 'passport'; import * as passportLocal from 'passport-local'; import * as jwt from 'jsonwebtoken'; - -import * as express from 'express'; -import * as bodyParser from 'body-parser'; +import {Router, Request, Response, NextFunction} from 'express'; import * as expressJwt from 'express-jwt'; -const LocalStrategy = passportLocal.Strategy; - -//user object for basic testing -var user = { - "id": 23, - "username": "har4", - "password": "secret" -} +export class AuthRouter { + LocalStrategy: any + router: Router -//Used by passport-js to locate a user object from the database by username -function findByUsername(username) { - if (username == user.username) { - return user; + constructor() { + this.LocalStrategy = passportLocal.Strategy(); + this.router(); + this.init(); } - return false; -} -//Find user obejct from database by user ID -function findUserByID(id) { - if (id == user.id) { - return user; + //Used by passport-js to locate a user object from the database by username + public findByUsername(username) { + if (username == user.username) { + return user; + } + return false; } - return false; -} - -//middleware which generates token and sends it as response -function genToken(req, res) { - var userid = findUserByID(req.body.username); - - var 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 -function checkErr(req, res, next) { - if (!req.body.grant_type || !req.body.username || !req.body.password) { - res.status(400).json({ - "error": "invalid_request", - "error_description": "Missing parameters" - }); - res.end(); + //Find user obejct from database by user ID + public findUserByID(id) { + if (id == user.id) { + return user; + } + return false; } - 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" + //middleware which generates token and sends it as response + public genToken(req: Request, res: Response) { + var userid = findUserByID(req.body.username); + + var token = jwt.sign({ + id: userid + }, 'Mr Secret', { + expiresIn: 21600 }); - res.end(); - } - - next(); -} -//handle error if user is unauthorised -function unauthorisedErr(err, req, res, next) { - console.log(err); - if (err.name === 'UnauthorizedError') { - res.status(401).json({ - "status": "error", - "error": "not_authorised", - "error_description": "user does not have correct authorisation to complete task" - }); + res.json({ + "token_type": "bearer", + "access_token": token, + "refresh_token": token, + "expires_in": 21600 + }); } - next(); -} - -//Configure local strategy to use with passport-js. -passport.use(new LocalStrategy( - function(username, password, done) { - var user = findByUsername(username); + //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 (!user || user.password != password) { - return done(null, false); + 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(); } - return done(null, user); - }) -); + next(); + } -//both methods below needed for persistant sessions -/*passport.serializeUser(function(user, done) { - done(null, user.id); -}); + //handle error if user is unauthorised + public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { + console.log(err); + 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(); + } -passport.deserializeUser(function(id, done) { - var user = findUserByID(id); - done(null, user); -}); -*/ + //Configure local strategy to use with passport-js. + private configStrategy() { + passport.use(new LocalStrategy( (username, password, done) => { + var user = findByUsername(username); + if (!user || user.password != password) { + return done(null, false); + } + return done(null, user); + })); + } +} /////////////////////////////////////////////////// var app = express(); var ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes -app.use(bodyParser.json()); app.use(passport.initialize()); -//app.use(passport.session()); app.use(unauthorisedErr); //currently does not handle userdefined error app.post('/login', checkErr, function(req, res, next) { @@ -140,7 +124,6 @@ app.get('/test', ensureAuth, function(req, res) { res.send("you are authenticated!"); }); -app.listen(3000); /* tasks left: -- cgit v1.2.1 From 9c4004778fee393ad2288bda7f51bceea937d4d3 Mon Sep 17 00:00:00 2001 From: cjd24 Date: Thu, 8 Feb 2018 23:28:31 +0000 Subject: Finiisshed? up nearly all of the stubs for get requests - Waiting to fix the db problem to implement others --- src/FileRouter.ts | 82 +++++++++++++++++++++++++++++----------- src/db/model/ContributorGroup.ts | 20 ++++++++++ 2 files changed, 80 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 34347a8..151cdf6 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -1,11 +1,13 @@ import {Router, Request, Response, NextFunction} from 'express'; import {default as UserGroup} from './db/model/UserGroup'; import {default as User} from './db/model/User'; +import { default as File } from './db/model/File'; import Project from './db/model/Project'; +import ContributorGroup from './db/model/ContributorGroup'; var serverConfig = require('./serverConfig'); const Files = null;//require('../data'); - +const BASE_FILE_STORAGE: string = __dirname + '/storage'; export class FileRouter { router: Router @@ -253,8 +255,7 @@ export class FileRouter { } */ public postCurUser(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); - + res.json({todo: "need to implement meeeee"}); } /* @@ -274,7 +275,7 @@ export class FileRouter { } */ public postUsername(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + res.json({todo: "need to implement meeeee"}); } /* @@ -289,7 +290,12 @@ export class FileRouter { }) */ public getProjectRoles(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + ContributorGroup.findAll() + .then((cgs: ContributorGroup[]) => { + res.json(cgs.map( + (cg: ContributorGroup) => cg.getGroupFullInfo() + )); + }); } /* @@ -310,8 +316,8 @@ export class FileRouter { */ public getProjects(req: Request, res: Response, next: NextFunction){ Project.findAll() - .then((project) => { - res.json(project.map( + .then((projects) => { + res.json(projects.map( (p: Project) => p.getProjectFullInfo() )); }); @@ -356,45 +362,77 @@ export class FileRouter { } */ public postProjectName(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + res.json({todo: "need to implement meeeee"}); } /* * additional configuration options for individual projects */ public getProjectProperties(req: Request, res: Response, next: NextFunction){ - res.status(500).send(); + res.status(500).send({error: "unsupported", error_description: "Projects on this server dont have additional configuration options."}); + } + + private async getChildFile(names: string[], parentUuid: string): Promise { + //TODO: Check that this works lol :3 + let child: File = await File.findOne({ + where: { + parentFolderId: parentUuid, + name: names[0] + } + }); + if (names.length === 1) { + return child; + } else { + names.splice(0, 1); + return await this.getChildFile(names, child.uuid); + } } /** * GET a File. */ - public getFile_path(req: Request, res: Response, next: NextFunction) { - res.status(500).send(); - // let fileID = req.params.file; - // - // res.send("File"); + public async getFile_path(req: Request, res: Response, next: NextFunction) { + req.params.project_name + req.params.path + + let project: Project = await Project.findOne({ + where: { + name: req.params.project_name + } + }); + + let file: File = await this.getChildFile( + req.params.project_name, project.rootFolderId); + + res.sendFile(`${BASE_FILE_STORAGE}/${req.params.project_name}/${file.uuid}`); } /** * GET a File. */ public getFile_id(req: Request, res: Response, next: NextFunction) { - res.status(500).send(); - // let fileID = req.params.file; - // - // res.send("File"); + + //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 */ public postFile_path(req: Request, res: Response, next: NextFunction) { - // let fileID = req.params.file; - // - // res.send("File"); - res.status(500).send(); + res.json({todo: "need to implement meeeee"}); } diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index a2808a0..8ecb648 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -28,4 +28,24 @@ export default class ContributorGroup extends Model { @Column canEditUserPermissions: boolean; + + @Column + description: string; + + @Column + isInternal: boolean; + + getGroupFullInfo(): GroupFullInfo { + return { + role: this.name, + description: this.description, + internal: this.isInternal + }; + } } + +type GroupFullInfo = { + role: string, + description: string, + internal: boolean +}; -- cgit v1.2.1 From 7913e19e2f83296dc96a67e6437f6006b1d894ac Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 9 Feb 2018 05:59:48 +0000 Subject: various work I forgot to commit --- src/FileRouter.ts | 30 ++++++++++++++++++++++-------- src/db/model/ContributorGroup.ts | 2 +- src/db/model/File.ts | 13 ++++--------- src/db/model/User.ts | 3 ++- src/index.ts | 25 +++++++++++++++++++++++++ src/matcher/options.ts | 9 +++++++++ src/matcher/types.ts | 25 ++++++++++++------------- 7 files changed, 75 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 151cdf6..bffc454 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -31,9 +31,12 @@ export class FileRouter { }) */ public getProtocols(req: Request, res: Response, next: NextFunction){ - var returnValue = {}; - returnValue['supported'] = ["BE50"]; - returnValue['required'] = "BE01"; + var returnValue = { + supported: [], + required: [ + "BE01" + ] + }; res.send(JSON.stringify(returnValue)); } @@ -179,8 +182,12 @@ export class FileRouter { }) */ public getUsers(req: Request, res: Response, next: NextFunction){ - User.findAll() - .then((user) => { + User.findAll({ + include: [ + UserGroup, + Project + ] + }).then((user) => { res.json(user.map( (u: User) => u.getUserFullInfo() )); @@ -200,7 +207,11 @@ export class FileRouter { let user: User = await User.findOne({ where: { username: name - } + }, + include: [ + UserGroup, + Project + ] }); return user.getUserFullInfo(); @@ -315,8 +326,11 @@ export class FileRouter { }) */ public getProjects(req: Request, res: Response, next: NextFunction){ - Project.findAll() - .then((projects) => { + Project.findAll({ + include: [ + User + ] + ).then((projects) => { res.json(projects.map( (p: Project) => p.getProjectFullInfo() )); diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts index 8ecb648..0fe859d 100644 --- a/src/db/model/ContributorGroup.ts +++ b/src/db/model/ContributorGroup.ts @@ -8,7 +8,7 @@ export default class ContributorGroup extends Model { name: string; // "Error: Foreign key for "ContributorGroup" is missing on "UserJoinsProject"." - // @HasMany(() => UserJoinsProject) + @HasMany(() => UserJoinsProject, 'contributorGroupId') uses: UserJoinsProject[]; @Column diff --git a/src/db/model/File.ts b/src/db/model/File.ts index b8cf784..09323e2 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -1,5 +1,5 @@ import {Table, Model, Column, Unique, PrimaryKey, ForeignKey, AllowNull, - HasMany, BelongsTo, CreatedAt, UpdatedAt} from 'sequelize-typescript'; + HasMany, BelongsTo, CreatedAt, UpdatedAt, HasOne} from 'sequelize-typescript'; import { default as User } from './User'; import { default as Project } from './Project'; @@ -33,14 +33,9 @@ export default class File extends Model { @BelongsTo(() => User) creator: User; - - // @ForeignKey(() => Project) - // @AllowNull - // @Column - // rootFolderOfProjectId: string; - // - // @BelongsTo(() => Project) - // rootFolderOf: Project; + + @HasOne(() => Project) + rootFolderOf: Project; @CreatedAt @Column diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 1f7f146..c677fcd 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -45,9 +45,10 @@ export default class User extends Model { } getUserFullInfo() : UserFullInfo { + console.log(this); return { username : this.username, - privileges : [this.userGroup.name], + privileges: [this.userGroup.name], projects : this.projects.map( (p: Project) => this.getProjectInfo(p) ), diff --git a/src/index.ts b/src/index.ts index a8756ad..5e8a9d0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,9 @@ import { default as seq } from './db/orm'; import { default as app } from './app'; +import { default as User } from './db/model/UserGroup'; +import { default as UserGroup } from './db/model/UserGroup'; + // use default port 3000 or port supplied by OS const port: number = process.env.PORT || 3000; @@ -8,10 +11,32 @@ const port: number = process.env.PORT || 3000; console.log('Booting PSQL database'); await seq.authenticate(); + + console.log('Resetting Database'); + await seq.sync({ force: true }); + let admin: UserGroup = new UserGroup({ + name: 'admin', + canCreateUsers: true, + canDeleteUsers: true, + canEditUsers: true, + canCreateProjects: true, + canDeleteProjects: true, + canEditProjects: true, + isInternal: false, + description: 'Systems admin' + }); + admin.save(); + + // let user: User = new User({ + // username: 'Tom', + // password: 'woa' + // }); + // user.save(); + console.log('Booting ExpressJS server'); app.listen(port, (err) => { diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 7412675..c1d1aeb 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -75,3 +75,12 @@ export function array(template: Object, values?: Array) { let m = match(template) as ((Object) => boolean); return values.every(m); } + +const options = { + match = match, + exact = exact, + optional = optional, + alternative = alternative, + array = array +}; +export default options; diff --git a/src/matcher/types.ts b/src/matcher/types.ts index 70b2d47..3870df4 100644 --- a/src/matcher/types.ts +++ b/src/matcher/types.ts @@ -4,19 +4,19 @@ function typeCheckerGenerator(test: T): (v: any) => v is T { return f; } -let isObject = typeCheckerGenerator({}); -let isNumber = typeCheckerGenerator(0); -let isString = typeCheckerGenerator(""); -let isBoolean = typeCheckerGenerator(true); -let isArray = typeCheckerGenerator>([]); -let isFunction = typeCheckerGenerator(new Function()); -let isNull = (v) => v === null; -let isUndefined = (v) => v === undefined; -let isPresent = (v) => !isUndefined(v); -let isInteger = (value: any) => isNumber(value) - && Number.isInteger(value as number); +export const isObject = typeCheckerGenerator({}); +export const isNumber = typeCheckerGenerator(0); +export const isString = typeCheckerGenerator(""); +export const isBoolean = typeCheckerGenerator(true); +export const isArray = typeCheckerGenerator>([]); +export const isFunction = typeCheckerGenerator(new Function()); +export const isNull = (v) => v === null; +export const isUndefined = (v) => v === undefined; +export const isPresent = (v) => !isUndefined(v); +export const isInteger = (value: any) => isNumber(value) + && Number.isInteger(value as number); -let types = { +const types = { object: isObject, number: isNumber, string: isString, @@ -29,5 +29,4 @@ let types = { undefined: isUndefined, anything: isPresent }; - export default types; -- cgit v1.2.1 From 3b4320c569dbf962af8a35ca0f16519a1de128db Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 9 Feb 2018 16:17:35 +0000 Subject: minor fixes --- src/FileRouter.ts | 2 +- src/matcher/options.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index bffc454..423c1a7 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -330,7 +330,7 @@ export class FileRouter { include: [ User ] - ).then((projects) => { + }).then((projects) => { res.json(projects.map( (p: Project) => p.getProjectFullInfo() )); diff --git a/src/matcher/options.ts b/src/matcher/options.ts index c1d1aeb..9b07163 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -77,10 +77,10 @@ export function array(template: Object, values?: Array) { } const options = { - match = match, - exact = exact, - optional = optional, - alternative = alternative, - array = array + match : match, + exact : exact, + optional : optional, + alternative : alternative, + array : array }; export default options; -- cgit v1.2.1 From 9858d16011dd91add5b7c2bf637c433ed6b74f0f Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 22 Feb 2018 16:57:42 +0000 Subject: Add error-handling middleware with basic tests --- src/errors/errorware.test.ts | 35 ++++++++++++++++++++++++++++++ src/errors/errorware.ts | 51 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/errors/errorware.test.ts create mode 100644 src/errors/errorware.ts (limited to 'src') 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()); +}; -- cgit v1.2.1 From 9686185e7ea2e54a541d1df597883ea9d7f0c338 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 22 Feb 2018 17:15:24 +0000 Subject: Include error-handling in middleware stack --- src/app.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index 4f0e0d7..a843179 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,8 +1,10 @@ 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; @@ -11,6 +13,7 @@ class App { this.express = ex(); this.middleware(); this.mountRoutes(); + this.errorware(); } // Configure Express middleware. @@ -34,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; -- cgit v1.2.1