diff options
| author | Tom Harley | 2018-03-02 18:03:31 +0000 |
|---|---|---|
| committer | Tom Harley | 2018-03-02 18:03:31 +0000 |
| commit | 84b8b5323654cf43ef549d2151bd3206c666d9d8 (patch) | |
| tree | 1ddcff5f713d7cca2c14f94ee97808cc7f4a354b | |
| parent | added middleware to check if admin (diff) | |
| download | medicine-84b8b5323654cf43ef549d2151bd3206c666d9d8.tar.gz medicine-84b8b5323654cf43ef549d2151bd3206c666d9d8.zip | |
Plug in authentication support - WIP
| -rw-r--r-- | src/FileRouter.ts | 2 | ||||
| -rw-r--r-- | src/app.ts | 8 | ||||
| -rw-r--r-- | src/auth.ts | 100 | ||||
| -rw-r--r-- | src/db/model/User.ts | 6 | ||||
| -rw-r--r-- | src/errors/errorware.ts | 13 | ||||
| -rw-r--r-- | src/index.ts | 14 |
6 files changed, 84 insertions, 59 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 34738bc..7bc9187 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -534,7 +534,7 @@ export class FileRouter { */ public init(): void { // General - this.router.get ('/_supported_protocols_', getProtocols); + this.router.get ('/_supported_protocols_', getProtocols); this.router.get ('/log', getLog); this.router.post('/log', postLog); this.router.get ('/properties', getProperties); @@ -1,6 +1,10 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; +import * as expressJwt from 'express-jwt'; import * as logger from 'morgan'; +import * as passport from 'passport'; + +import { default as authRouter } from './auth'; import { errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; @@ -18,6 +22,8 @@ class App { // Configure Express middleware. private middleware(): void { + this.express.use(expressJwt({secret: 'Mr Secret'}).unless({path: ['/cs3099group-be-4/login', '/cs3099group-be-4/_supported_protocols_'] })); + this.express.use(passport.initialize()); if (this.logEnabled) { this.express.use(logger('combined')); } @@ -36,9 +42,11 @@ class App { }); this.express.use('/', defRouter); this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); } private errorware(): void { + //this.express.use(authRouter.unauthorisedErr); this.express.use(errorHandler); } } diff --git a/src/auth.ts b/src/auth.ts index 3feac5d..d5969c5 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,43 +1,35 @@ +/* tslint:disable:prefer-function-over-method */ + +import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; -import * as expressJwt from 'express-jwt'; import * as jwt from 'jsonwebtoken'; import * as passport from 'passport'; import { Strategy } from 'passport-local'; import { default as User } from './db/model/User'; export class AuthRouter { - public localStrategy: Strategy; public router: Router; - ensureAuth; public constructor() { - this.localStrategy = Strategy(); - this.ensureAuth = expressJwt({secret: 'Mr Secret'}); //protects routes - this.router(); + this.router = Router(); this.init(); } - // Used by passport-js to locate a user object from the database by username - public findByUsername(username: string): User { - if (username === user.username) { - return user; - } - return false; - } + // Middleware which generates token and sends it as response + public async genToken(req: Request, res: Response): Promise<void> { + const user: User | null = await User.findOne({ + where: { + username: req.body.username + } + }); - // Find user object from database by user ID - public findUserByID(id): User { - if (id === user.id) { - return user; + if (user === null) { + // Whoa, what an error! + return; } - return false; - } - // Middleware which generates token and sends it as response - public genToken(req: Request, res: Response) { - const userid = findUserByID(req.body.username); - const token = jwt.sign( - { id: userid }, + const token: string = jwt.sign( + { id: user.username }, 'Mr Secret', { expiresIn: 21600 } ); @@ -50,19 +42,24 @@ export class AuthRouter { }); } - private authenticate(req: Request, res: Response, next: NextFunction) { - passport.authenticate('local', { session: false }, function(err, user) { - if (err) { console.log(err); } - - if (!user) { - next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + private authenticate(req: Request, res: Response, next: NextFunction): void { + passport.authenticate( + 'local', + { session: false }, + (err: Error, user: User) => { + // TODO: Implement + if (err) { throw err; } + + if (!user) { + next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + } } - }); + ); next(); } // Checks for errors within request before authentication - public checkErr(req: Request, res: Response, next: NextFunction) { + public checkErr(req: Request, res: Response, next: NextFunction): void { if (!req.body.grant_type || !req.body.username || !req.body.password) { next(new RequestError(400, 'invalid_request', 'Missing parameters')); } @@ -76,7 +73,7 @@ export class AuthRouter { } // Handle error if user is unauthorised - public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { + public unauthorisedErr(err: Error, req: Request, res: Response, next: NextFunction): void { if (err.name === 'UnauthorizedError') { next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); } @@ -93,37 +90,42 @@ export class AuthRouter { // Configure local strategy to use with passport-js. private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { - const user = findByUsername(username); - - if (!user || user.password != password) { + // tslint:disable-next-line:typedef + passport.use(new Strategy( async(username, password, done) => { + const user: User | null = await User.findOne({ + where: { + username + } + }); + + if (!user || user.password !== password) { return done(null, false); } return done(null, user); })); } - init() { + public init(): void { this.configStrategy(); this.router.post('/login', this.checkErr, this.authenticate, this.genToken); - this.router.get('/logout', (req, res) => { req.logout(); }); + this.router.get( + '/logout', + (req: Request, res: Response): void => { req.logout(); } + ); } } -const authRoutes = new AuthRouter(); +const authRoutes: AuthRouter = new AuthRouter(); authRoutes.init(); export default authRoutes.router; /////////////////////////////////////////////////// -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error - /* -tasks left: - refreshing tokens - connect to db - revoke tokens/checking validity - logging out -*/ + * tasks left: + * refreshing tokens + * connect to db + * revoke tokens/checking validity + * logging out + */ diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 5a9af07..9b3190c 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -9,14 +9,14 @@ import { default as UserJoinsProject } from './UserJoinsProject'; export default class User extends Model<User> { @PrimaryKey @Column - public username: string = ''; + public username!: string; @Column - public password: string = ''; + public password!: string; @ForeignKey(() => UserGroup) @Column - public userGroupId: number = 0; + public userGroupId!: number; @BelongsTo(() => UserGroup) public userGroup: UserGroup = new UserGroup(); diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts index 8b7e015..45a76b3 100644 --- a/src/errors/errorware.ts +++ b/src/errors/errorware.ts @@ -42,10 +42,15 @@ export class RequestError extends Error { } type Errorware = - (err: RequestError, req: Request, res: Response, next: NextFunction) => void; + (err: Error, req: Request, res: Response, next: NextFunction) => void; export const errorHandler: Errorware = - (err: RequestError, req: Request, res: Response, next: NextFunction): void => { - res.status(err.code) - .json(err.responseBlock()); + (err: Error, req: Request, res: Response, next: NextFunction): void => { + if ((err as RequestError).responseBlock) { + const rerr: RequestError = err as RequestError; + res.status(rerr.code) + .json(rerr.responseBlock()); + } else { + res.send(err); + } }; diff --git a/src/index.ts b/src/index.ts index 06989ef..c6adf32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ import { default as app } from './app'; import { default as seq } from './db/orm'; console.log('end import'); +import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; const DEFAULT_PORT: number = 3000; @@ -39,8 +40,17 @@ const port: number = process.env.PORT description: 'Systems admin' }); - // tslint:disable:no-floating-promises - admin.save(); + await admin.save(); + + console.log(admin.id); + + const root: User = new User({ + username: 'hafeez', + password: 'pass', + userGroup: admin + }); + + root.save(); console.log('Booting ExpressJS server'); |
