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 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(-) 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(-) 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(-) 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(-) 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 --- package.json | 4 +++ src/auth.ts | 110 +++++++++++++++++++++++++++++++++++++++++++---------------- 2 files changed, 85 insertions(+), 29 deletions(-) diff --git a/package.json b/package.json index f40379b..6497dba 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,11 @@ "@types/node": "^6.0.46", "body-parser": "^1.18.2", "express": "^4.16.2", + "express-jwt": "^5.3.0", + "jsonwebtoken": "^8.1.1", "morgan": "^1.9.0", + "passport": "^0.4.0", + "passport-local": "^1.0.0", "ts-node": "^3.3.0", "typescript": "^2.7.1" } 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 --- getmepostgres.sh | 59 ++++++++++++++++++++++++++-------------------------- package.json | 1 + runmepostgres.sh | 8 ++++--- src/db/model/User.ts | 17 +++++++++++++++ 4 files changed, 53 insertions(+), 32 deletions(-) create mode 100644 src/db/model/User.ts diff --git a/getmepostgres.sh b/getmepostgres.sh index 50976f8..cb0388a 100755 --- a/getmepostgres.sh +++ b/getmepostgres.sh @@ -1,26 +1,27 @@ #!/bin/bash -echo "> Checking for postgres at ~/pg"; -if [ -d "~/pg" ]; then +PGDIR=${1-"$HOME/pg"} + +echo "> Checking for postgres at $PGDIR"; +if [ -d "$PGDIR" ]; then echo "Postgres Directory exists, nevermind..."; exit 1; fi -echo " "; -echo " "; -echo " "; +echo; +echo; +echo; echo "This installation process takes ~3:50 minutes to complete."; -echo " "; -echo " "; -echo " "; -sleep 3; +echo; +echo; +echo; -echo "> Making postgres directory at ~/pg"; -mkdir ~/pg; +echo "> Making postgres directory at $PGDIR"; +mkdir -p "$PGDIR"; currentDir=$(pwd); -echo "> Chaning dir to ~/pg"; -cd ~/pg; +echo "> Changing dir to $PGDIR"; +cd "$PGDIR"; echo "> Cloning Repo"; git clone https://github.com/postgres/postgres.git; @@ -30,34 +31,34 @@ cd ./postgres; git reset --hard REL_10_1; echo "> Configuring"; -./configure --prefix=$HOME/pg/postgres/ --with-python PYTHON=/usr/bin/python2.7; +./configure --prefix="$PWD" --with-python PYTHON="/usr/bin/python2.7"; echo "> Building Postgres"; -make -j 5; +make; echo "> Installing Postgres"; make install; echo "> Initialise the Database"; -~/pg/postgres/bin/initdb -D ~/pg/postgres/data/; -echo " "; -echo " "; -echo " "; -echo " "; +"$PGDIR/postgres/bin/initdb" -D "$PGDIR/postgres/data/"; +echo; +echo; +echo; +echo; echo "> Starting the postgres server"; -~/pg/postgres/bin/pg_ctl -D ~/pg/postgres/data/ -l POSTGRES_logfile start; +"$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start; echo "> Create the Database"; -~/pg/postgres/bin/createdb be4; +"$PGDIR/postgres/bin/createdb" be4; echo "> Creating Admin user"; -~/pg/postgres/bin/psql -U ${USER} postgres -c "CREATE USER admin WITH PASSWORD 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af';"; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "CREATE USER admin WITH PASSWORD 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af';"; echo "> Granting Admin Permissions"; -~/pg/postgres/bin/psql -U ${USER} postgres -c "ALTER DATABASE be4 OWNER TO admin;"; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "ALTER DATABASE be4 OWNER TO admin;"; -echo " "; -echo " "; -echo " "; -echo " "; -echo " "; +echo; +echo; +echo; +echo; +echo; echo "> Completed the installation of Postgres."; cd $currentDir; diff --git a/package.json b/package.json index 2f9c6fd..6bf1a30 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "@types/express": "^4.0.33", "@types/morgan": "^1.7.32", "@types/node": "^6.0.46", + "@types/sequelize": "^4.27.5", "body-parser": "^1.18.2", "express": "^4.16.2", "morgan": "^1.9.0", diff --git a/runmepostgres.sh b/runmepostgres.sh index 632ea66..b5dd29c 100755 --- a/runmepostgres.sh +++ b/runmepostgres.sh @@ -1,8 +1,10 @@ #!/bin/bash +PGDIR=${1-"$HOME/pg"} + read -p "Press [Enter] key to start Postgres (will already be running if you just got it) use ctl+c to cancel"; echo "> Starting Server"; -~/pg/postgres/bin/pg_ctl -D ~/pg/postgres/data/ -l POSTGRES_logfile start; +"$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start; -#echo "> Conecting as admin user: " + ${USER}; -#~/pg/postgres/bin/psql -U ${USER} postgres; +echo "> Conecting as admin user: " + ${USER}; +~/pg/postgres/bin/psql -U ${USER} postgres; 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 39dedb16ea84c55bce090295138105c2881aaf5c Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 01:20:26 +0000 Subject: fixed runmepostgres.sh to actually use PGDIR --- runmepostgres.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runmepostgres.sh b/runmepostgres.sh index b5dd29c..dfa5764 100755 --- a/runmepostgres.sh +++ b/runmepostgres.sh @@ -7,4 +7,4 @@ echo "> Starting Server"; "$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start; echo "> Conecting as admin user: " + ${USER}; -~/pg/postgres/bin/psql -U ${USER} postgres; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres; -- 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 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 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 --- getmepostgres.sh | 2 +- src/db/orm.ts | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/getmepostgres.sh b/getmepostgres.sh index cb0388a..035b300 100755 --- a/getmepostgres.sh +++ b/getmepostgres.sh @@ -50,7 +50,7 @@ echo "> Starting the postgres server"; echo "> Create the Database"; "$PGDIR/postgres/bin/createdb" be4; echo "> Creating Admin user"; -"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "CREATE USER admin WITH PASSWORD 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af';"; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "CREATE USER admin;"; echo "> Granting Admin Permissions"; "$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "ALTER DATABASE be4 OWNER TO admin;"; 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 dbfb97e718725c4d2e58b20f8de8b7208be025f9 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 17:11:14 +0000 Subject: added log files to .gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 23ace5c..5af7a8f 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ dist/ # Vim swap files *.sw* + +# PostgreSQL log files +*logfile -- 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(-) 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(-) 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. --- package.json | 1 + src/app.ts | 3 +- src/matcher/options.ts | 3 + src/matcher/types.ts | 33 ++++++++++ test/nodeserver.test.ts | 94 +++++++++++++++++++++++++++ test/options.test.ts | 52 +++++++++++++++ test/types.test.ts | 169 ++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 354 insertions(+), 1 deletion(-) create mode 100644 src/matcher/types.ts create mode 100644 test/options.test.ts create mode 100644 test/types.test.ts diff --git a/package.json b/package.json index 6bf1a30..f91eb78 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "@types/sequelize": "^4.27.5", "body-parser": "^1.18.2", "express": "^4.16.2", + "mocha-each": "^1.1.0", "morgan": "^1.9.0", "pg": "^7.4.1", "pg-hstore": "^2.3.2", 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; diff --git a/test/nodeserver.test.ts b/test/nodeserver.test.ts index 83c66e8..5ef6223 100644 --- a/test/nodeserver.test.ts +++ b/test/nodeserver.test.ts @@ -1,12 +1,26 @@ import * as mocha from 'mocha'; import * as chai from 'chai'; import chaiHttp = require('chai-http'); +const forEach = require('mocha-each'); + +import * as options from '../src/matcher/options'; +import { default as types } from '../src/matcher/types'; import app from '../src/app'; +import { type } from 'os'; +app.log_enabled = false; chai.use(chaiHttp); const expect = chai.expect; +const resp_temp = { status: types.string, + data: options.optional(types.anything), + error: options.optional(types.string), + error_description: options.optional(types.string), + user_message: options.optional(types.string), + error_data: options.optional(types.anything) + } + describe('baseRoute', () => { it('should be json', () => { @@ -30,3 +44,83 @@ describe('baseRoute', () => { }); }); + +describe('General protocol', () => { + let complete_protocol = [ + ['get', '/_supported_protocols_', options.exact({supported: types.array(types.string), required: types.array(types.string) }) ], + ['get', '/log' , types.array({ component: types.string, level: options.alternative(["info", "security", "warning", "error", "critical"]), value: types.anything,username: types.string,timestamp: types.string}) ], + ['post','/log' , null ], + ['get' ,'/properties' , types.array({id: types.string, display: options.optional(options.match({category: types.string, group: types.string, display_name: types.string, description: types.string})), read_only: types.boolean,type: options.alternative([types.string, types.integer, types.boolean]),value: options.alternative([types.string, types.integer, types.boolean])}) ], + ['post','/properties' , null ], + ['get' ,'/user_privileges' , types.array({privilege: types.string,description: types.string,internal: types.boolean}) ], + ['get' ,'/users' , types.array({username: types.string,privileges: types.array(types.string),projects: types.array({ project_name: types.string, access_level: types.string}),public_user_metadata: types.anything,private_user_metadata: types.anything,public_admin_metadata: types.anything,private_admin_metadata: types.anything}) ], + // TODO types.metadata + ['get' ,'/users/:username' , {username: types.string,privileges: types.array(types.string),projects: types.array({ project_name: types.string, access_level: types.string}),public_user_metadata: types.anything,private_user_metadata: types.anything,public_admin_metadata: types.anything,private_admin_metadata: types.anything} ], + ['post','/users/:username' , null ], + ['get' ,'/users/:username/properties' , {data: options.optional(types.anything)}], + ['get' ,'/current_user' , {username: types.string,privileges: types.array(types.string),projects: types.array({ project_name: types.string, access_level: types.string}),public_user_metadata: types.anything,private_user_metadata: types.anything,public_admin_metadata: types.anything,private_admin_metadata: types.anything} ], + ['post','/current_user' , null ], + ['get' ,'/project_roles' , types.array({role: types.string,description: types.string,internal: types.boolean})], + ['get' ,'/projects' , types.array({project_name: types.string,users: types.array({ username: types.string, access_level: types.string}),public_metadata: types.anything,private_metadata: options.optional(types.anything),admin_metadata: options.optional(types.anything)}) ], + ['get' ,'/projects/:project_name' , {project_name: types.string,users: types.array({ username: types.string, access_level: types.string}),public_metadata: types.anything,private_metadata: types.anything,admin_metadata: options.optional(types.anything)}], + ['post','/projects/:project_name' , null], + ['get' ,'/projects/:project_name/properties' , {data: options.optional(types.anything)}], + ['get' ,'/projects/:project_name/files/:path' , null], + ['post','/projects/:project_name/files/:id' , null], + ['get' ,'/projects/:project_name/files_by_id/:id' , null] + ]; + + describe('Checking complete Protocol', () => { + forEach(complete_protocol) + .it('%s %s should be json', (method, path, temp) => { + if(method == 'get'){ + return chai.request(app).get(path) + .then(res => { + expect(res.type).to.eql('application/json'); + }); + }else if(method == 'post'){ + return chai.request(app).post(path) + .then(res => { + expect(res.type).to.eql('application/json'); + }); + } + }) + forEach(complete_protocol) + .it('%s %s should have a status 200', (method, path, temp) => { + if(method == 'get'){ + return chai.request(app).get(path) + .then(res => { + expect(res).to.have.status(200); + }); + }else if(method == 'post'){ + return chai.request(app).post(path) + .then(res => { + expect(res).to.have.status(200); + }); + } + }) + forEach(complete_protocol) + .it('%s %s should conform to standard protocol', (method, path, temp) => { + if(method == 'get'){ + return chai.request(app).get(path) + .then(res => { + options.match(resp_temp)(JSON.parse(res.body)).should.be.true; + }); + }else if(method == 'post'){ + return chai.request(app).post(path) + .then(res => { + options.match(resp_temp)(JSON.parse(res.body)).should.be.true; + }); + } + }); + forEach(complete_protocol) + .it('the response for %s %s should comply with its own protocol', (method, path, temp) => { + if(method == 'get' && temp != null){ + return chai.request(app).get(path) + .then(res => { + options.match(temp)(JSON.parse(res.body)).should.be.true; + }); + } + }); + }) +}); diff --git a/test/options.test.ts b/test/options.test.ts new file mode 100644 index 0000000..8622c73 --- /dev/null +++ b/test/options.test.ts @@ -0,0 +1,52 @@ +import * as mocha from 'mocha'; +import chai = require('chai'); +var should = chai.should(); + +import * as options from '../src/matcher/options'; +import { default as types } from '../src/matcher/types'; + +describe('Object Matching:', () => { + describe('Rough Matching', () => { + it('accepts basic things', () => { + let template = { + a: types.string + }; + let matchee = { + a: "yes" + }; + options.rough(template, matchee).should.be.true; + }); + it('accepts objects with superfluous properties', () => { + let template = { + a: types.number + }; + let matchee = { + a: 40, + b: 20 + }; + options.rough(template, matchee).should.be.true; + }); + it('rejects objects missing some properties', () => { + let template = { + a: types.boolean, + b: types.number, + c: types.number + }; + let matchee = { + b: 5 + }; + options.rough(template, matchee).should.be.false; + }); + it('accepts objects that omit not_present properties', () => { + let template = { + a: types.function, + b: types.not_present, + c: types.not_present + }; + let matchee = { + a: new Function() + }; + options.rough(template, matchee).should.be.true; + }); + }); +}); diff --git a/test/types.test.ts b/test/types.test.ts new file mode 100644 index 0000000..6a5d4d0 --- /dev/null +++ b/test/types.test.ts @@ -0,0 +1,169 @@ +import * as mocha from 'mocha'; +import chai = require('chai'); +var should = chai.should(); + +import { default as types } from '../src/matcher/types'; + +describe('Type Checking:', () => { + let x: string; + for (let x of + [ 'object', 'number', 'integer', 'string', 'boolean', 'array' ] + ) { + let name: string = x.charAt(0).toUpperCase() + x.slice(1); + describe(`${name} Checking`, () => { + it('rejects null', () => { + types[x](null).should.be.false; + }); + it('rejects undefined', () => { + types[x](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', () => { + let x: Object = {}; + // 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', () => { + 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', () => { + types.string(new String('String!')).should.be.true; + }); + it('rejects numbers', () => { + types.string(5).should.be.false; + 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; + }); + }); +}); -- cgit v1.2.1 From 42b4435bf61e1cd41abc8a83dfb1a8f960d6fd23 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 8 Feb 2018 18:37:23 +0000 Subject: removed usage of rough in tests --- test/options.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/options.test.ts b/test/options.test.ts index 8622c73..542d38a 100644 --- a/test/options.test.ts +++ b/test/options.test.ts @@ -14,7 +14,7 @@ describe('Object Matching:', () => { let matchee = { a: "yes" }; - options.rough(template, matchee).should.be.true; + options.match(template, matchee).should.be.true; }); it('accepts objects with superfluous properties', () => { let template = { @@ -24,7 +24,7 @@ describe('Object Matching:', () => { a: 40, b: 20 }; - options.rough(template, matchee).should.be.true; + options.match(template, matchee).should.be.true; }); it('rejects objects missing some properties', () => { let template = { @@ -35,7 +35,7 @@ describe('Object Matching:', () => { let matchee = { b: 5 }; - options.rough(template, matchee).should.be.false; + options.match(template, matchee).should.be.false; }); it('accepts objects that omit not_present properties', () => { let template = { @@ -46,7 +46,7 @@ describe('Object Matching:', () => { let matchee = { a: new Function() }; - options.rough(template, matchee).should.be.true; + options.match(template, matchee).should.be.true; }); }); }); -- 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 +- tsconfig.json | 13 +++------ 10 files changed, 204 insertions(+), 51 deletions(-) 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; diff --git a/tsconfig.json b/tsconfig.json index 745ef12..cd3353c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,20 +1,15 @@ { "compilerOptions": { - /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ "target": "es6", - /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "module": "commonjs", - /* Where to output .js files */ - "outDir": "dist" + "outDir": "dist", + "experimentalDecorators": true, + "emitDecoratorMetadata": true }, - /* Where to look for .ts files */ "include": [ "src/**/*.ts" ], - /* Exclude directory */ "exclude": [ "node_modules" - ], - "experimentalDecorators": true, - "emitDecoratorMetadata": true + ] } -- 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(-) 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(-) 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(-) 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(-) 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 8371000fee5286dd4c7aad3a29700660a209e498 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Tue, 20 Feb 2018 16:24:06 +0000 Subject: Add Bluebird promise and dev-dependency support --- tslint.json | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tslint.json b/tslint.json index f86eb35..ba1334e 100644 --- a/tslint.json +++ b/tslint.json @@ -69,7 +69,10 @@ ], "unified-signatures": true, - "await-promise": true, + "await-promise": [ + true, + "Bluebird" + ], "ban-comma-operator": true, "ban": [ false ], "curly": true, @@ -88,9 +91,12 @@ "no-dynamic-delete": true, "no-empty": true, "no-eval": true, - "no-floating-promises": true, + "no-floating-promises": [ + true, + "Bluebird" + ], "no-for-in-array": false, - "no-implicit-dependencies": true, + "no-implicit-dependencies": [ true, "dev" ], "no-inferred-empty-object-type": true, "no-invalid-template-strings": true, "no-invalid-this": true, -- cgit v1.2.1 From d7a8fcfcc1ca2d6f2c1970f86d85ab0d97dc79ee Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Tue, 20 Feb 2018 16:44:29 +0000 Subject: Add Yarn autoclean file --- .yarnclean | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 .yarnclean diff --git a/.yarnclean b/.yarnclean new file mode 100644 index 0000000..b591611 --- /dev/null +++ b/.yarnclean @@ -0,0 +1,45 @@ +# test directories +__tests__ +test +tests +powered-test + +# asset directories +docs +doc +website +images +assets + +# examples +example +examples + +# code coverage directories +coverage +.nyc_output + +# build scripts +Makefile +Gulpfile.js +Gruntfile.js + +# configs +appveyor.yml +circle.yml +codeship-services.yml +codeship-steps.yml +wercker.yml +.tern-project +.gitattributes +.editorconfig +.*ignore +.eslintrc +.jshintrc +.flowconfig +.documentup.json +.yarn-metadata.json +.travis.yml + +# misc +*.md -- 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 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(-) 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