From 5dafe924bbbd5cc09901186ff74e4b68a6dcd52f Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 22 Feb 2018 18:47:08 +0000 Subject: Revert "Revert "Merge branch 'trh/error-middleware' into 'master'"" This reverts commit 3198c6c2474101623e3b95bd038effe210c176a8. --- src/auth.ts | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 src/auth.ts (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..a59e417 --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,136 @@ +import { NextFunction, Request, Response, Router } from 'express'; +import * as expressJwt from 'express-jwt'; +import * as jwt from 'jsonwebtoken'; +import * as passport from 'passport'; +import { Strategy } from 'passport-local'; +import { default as User } from './db/model/User'; + +export class AuthRouter { + public localStrategy: Strategy; + public router: Router; + + public constructor() { + this.localStrategy = Strategy(); + this.router(); + this.init(); + } + + // Used by passport-js to locate a user object from the database by username + public findByUsername(username: string): User { + if (username === user.username) { + return user; + } + return false; + } + + // Find user object from database by user ID + public findUserByID(id): User { + if (id === user.id) { + return user; + } + return false; + } + + // Middleware which generates token and sends it as response + public genToken(req: Request, res: Response) { + const userid = findUserByID(req.body.username); + const token = jwt.sign( + { id: userid }, + 'Mr Secret', + { expiresIn: 21600 } + ); + + res.json({ + token_type: 'bearer', + access_token: token, + refresh_token: token, + expires_in: 21600 + }); + } + + // Checks for errors within request before authentication + public checkErr(req: Request, res: Response, next: NextFunction) { + if (!req.body.grant_type || !req.body.username || !req.body.password) { + res.status(400) + .json({ + error: 'invalid_request', + error_description: 'Missing parameters' + }); + res.end(); + } + + if (req.body.grant_type !== 'refresh_token' + && req.body.grant_type !== 'password') { + res.status(400) + .json({ + error: 'unsupported_grant_type', + error_description: 'invalid grant type' + }); + res.end(); + } + + next(); + } + + // Handle error if user is unauthorised + public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { + if (err.name === 'UnauthorizedError') { + res.status(401).json({ + status: 'error', + error: 'not_authorised', + error_description: + 'user does not have correct authorisation to complete task' + }); + } + next(); + } + + // Configure local strategy to use with passport-js. + private configStrategy() { + passport.use(new localStrategy( (username, password, done) => { + const user = findByUsername(username); + + if (!user || user.password != password) { + return done(null, false); + } + return done(null, user); + })); + } +} +/////////////////////////////////////////////////// + +const app = express(); +const ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes + +app.use(passport.initialize()); +app.use(unauthorisedErr); //currently does not handle userdefined error + +app.post('/login', checkErr, function(req, res, next) { + passport.authenticate('local', { session: false }, function(err, user) { + if (err) { console.log(err); } + + if (!user) { + res.status(400).json({ + error: 'invalid_grant', + error_description: 'Incorrect authentication details' + }); + } + }); + next(); +}, genToken); + +app.get('/logout', function(req, res) { + req.logout(); +}); + +app.get('/test', ensureAuth, function(req, res) { + res.send('you are authenticated!'); +}); + +/* +tasks left: + refreshing tokens + connect to db + revoke tokens/checking validity + logging out +*/ -- cgit v1.2.1 From 0ec3d6b47ecfd62a18af6fc36ede4dcd4ce771cb Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 1 Mar 2018 18:52:35 +0000 Subject: added new request error objects --- src/auth.ts | 73 ++++++++++++++++++++++++------------------------------------- 1 file changed, 29 insertions(+), 44 deletions(-) (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts index a59e417..937f20f 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -8,9 +8,11 @@ import { default as User } from './db/model/User'; export class AuthRouter { public localStrategy: Strategy; public router: Router; + ensureAuth; public constructor() { this.localStrategy = Strategy(); + this.ensureAuth = expressJwt({secret: 'Mr Secret'}); //protects routes this.router(); this.init(); } @@ -48,25 +50,26 @@ export class AuthRouter { }); } + private authenticate(req: Request, res: Response, next: NextFunction) { + passport.authenticate('local', { session: false }, function(err, user) { + if (err) { console.log(err); } + + if (!user) { + next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + } + }); + next(); + } + // Checks for errors within request before authentication public checkErr(req: Request, res: Response, next: NextFunction) { if (!req.body.grant_type || !req.body.username || !req.body.password) { - res.status(400) - .json({ - error: 'invalid_request', - error_description: 'Missing parameters' - }); - res.end(); + next(new RequestError(400, 'invalid_request', 'Missing parameters')); } if (req.body.grant_type !== 'refresh_token' && req.body.grant_type !== 'password') { - res.status(400) - .json({ - error: 'unsupported_grant_type', - error_description: 'invalid grant type' - }); - res.end(); + next(new RequestError(400, 'unsupported_grant_type', 'invalid grant type')); } next(); @@ -75,19 +78,14 @@ export class AuthRouter { // Handle error if user is unauthorised public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { if (err.name === 'UnauthorizedError') { - res.status(401).json({ - status: 'error', - error: 'not_authorised', - error_description: - 'user does not have correct authorisation to complete task' - }); + next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); } next(); } // Configure local strategy to use with passport-js. private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { + passport.use(new localStrategy( (username, password, done) => { const user = findByUsername(username); if (!user || user.password != password) { @@ -96,36 +94,23 @@ export class AuthRouter { return done(null, user); })); } -} -/////////////////////////////////////////////////// -const app = express(); -const ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes + init() { + this.configStrategy(); -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error - -app.post('/login', checkErr, function(req, res, next) { - passport.authenticate('local', { session: false }, function(err, user) { - if (err) { console.log(err); } + this.router.post('/login', this.checkErr, this.authenticate, this.genToken); + this.router.get('/logout', (req, res) => { req.logout(); }); + } +} - if (!user) { - res.status(400).json({ - error: 'invalid_grant', - error_description: 'Incorrect authentication details' - }); - } - }); - next(); -}, genToken); +const authRoutes = new AuthRouter(); +authRoutes.init(); -app.get('/logout', function(req, res) { - req.logout(); -}); +export default authRoutes.router; +/////////////////////////////////////////////////// -app.get('/test', ensureAuth, function(req, res) { - res.send('you are authenticated!'); -}); +app.use(passport.initialize()); +app.use(unauthorisedErr); //currently does not handle userdefined error /* tasks left: -- cgit v1.2.1 From 7a06fd6eac864972a4acc15078627f0ffc20c1f9 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Thu, 1 Mar 2018 19:26:35 +0000 Subject: added middleware to check if admin --- src/auth.ts | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts index 937f20f..3feac5d 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -83,6 +83,14 @@ export class AuthRouter { next(); } + //middleware to check privileges - admin + public isAdmin(req: Request, res: Response, next: NextFunction) { + if (!req.user.admin) { + next(new RequestError(401, 'not_authorised', 'user is not authorised to perform task')); + } + next(); + } + // Configure local strategy to use with passport-js. private configStrategy() { passport.use(new localStrategy( (username, password, done) => { -- cgit v1.2.1 From 84b8b5323654cf43ef549d2151bd3206c666d9d8 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 2 Mar 2018 18:03:31 +0000 Subject: Plug in authentication support - WIP --- src/auth.ts | 100 +++++++++++++++++++++++++++++++----------------------------- 1 file changed, 51 insertions(+), 49 deletions(-) (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts index 3feac5d..d5969c5 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,43 +1,35 @@ +/* tslint:disable:prefer-function-over-method */ + +import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; -import * as expressJwt from 'express-jwt'; import * as jwt from 'jsonwebtoken'; import * as passport from 'passport'; import { Strategy } from 'passport-local'; import { default as User } from './db/model/User'; export class AuthRouter { - public localStrategy: Strategy; public router: Router; - ensureAuth; public constructor() { - this.localStrategy = Strategy(); - this.ensureAuth = expressJwt({secret: 'Mr Secret'}); //protects routes - this.router(); + this.router = Router(); this.init(); } - // Used by passport-js to locate a user object from the database by username - public findByUsername(username: string): User { - if (username === user.username) { - return user; - } - return false; - } + // Middleware which generates token and sends it as response + public async genToken(req: Request, res: Response): Promise { + const user: User | null = await User.findOne({ + where: { + username: req.body.username + } + }); - // Find user object from database by user ID - public findUserByID(id): User { - if (id === user.id) { - return user; + if (user === null) { + // Whoa, what an error! + return; } - return false; - } - // Middleware which generates token and sends it as response - public genToken(req: Request, res: Response) { - const userid = findUserByID(req.body.username); - const token = jwt.sign( - { id: userid }, + const token: string = jwt.sign( + { id: user.username }, 'Mr Secret', { expiresIn: 21600 } ); @@ -50,19 +42,24 @@ export class AuthRouter { }); } - private authenticate(req: Request, res: Response, next: NextFunction) { - passport.authenticate('local', { session: false }, function(err, user) { - if (err) { console.log(err); } - - if (!user) { - next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + private authenticate(req: Request, res: Response, next: NextFunction): void { + passport.authenticate( + 'local', + { session: false }, + (err: Error, user: User) => { + // TODO: Implement + if (err) { throw err; } + + if (!user) { + next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + } } - }); + ); next(); } // Checks for errors within request before authentication - public checkErr(req: Request, res: Response, next: NextFunction) { + public checkErr(req: Request, res: Response, next: NextFunction): void { if (!req.body.grant_type || !req.body.username || !req.body.password) { next(new RequestError(400, 'invalid_request', 'Missing parameters')); } @@ -76,7 +73,7 @@ export class AuthRouter { } // Handle error if user is unauthorised - public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) { + public unauthorisedErr(err: Error, req: Request, res: Response, next: NextFunction): void { if (err.name === 'UnauthorizedError') { next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); } @@ -93,37 +90,42 @@ export class AuthRouter { // Configure local strategy to use with passport-js. private configStrategy() { - passport.use(new localStrategy( (username, password, done) => { - const user = findByUsername(username); - - if (!user || user.password != password) { + // tslint:disable-next-line:typedef + passport.use(new Strategy( async(username, password, done) => { + const user: User | null = await User.findOne({ + where: { + username + } + }); + + if (!user || user.password !== password) { return done(null, false); } return done(null, user); })); } - init() { + public init(): void { this.configStrategy(); this.router.post('/login', this.checkErr, this.authenticate, this.genToken); - this.router.get('/logout', (req, res) => { req.logout(); }); + this.router.get( + '/logout', + (req: Request, res: Response): void => { req.logout(); } + ); } } -const authRoutes = new AuthRouter(); +const authRoutes: AuthRouter = new AuthRouter(); authRoutes.init(); export default authRoutes.router; /////////////////////////////////////////////////// -app.use(passport.initialize()); -app.use(unauthorisedErr); //currently does not handle userdefined error - /* -tasks left: - refreshing tokens - connect to db - revoke tokens/checking validity - logging out -*/ + * tasks left: + * refreshing tokens + * connect to db + * revoke tokens/checking validity + * logging out + */ -- cgit v1.2.1 From 11776b9665c1bc3e49cf602dfa069294a490d5fd Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 3 Mar 2018 14:18:11 +0000 Subject: Fix minor things --- src/auth.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts index d5969c5..b40cddb 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -51,7 +51,9 @@ export class AuthRouter { if (err) { throw err; } if (!user) { - next(new RequestError(400, 'invalid_grant', 'Incorrect authentication details')); + next(new RequestError( + 400, 'invalid_grant', 'Incorrect authentication details' + )); } } ); @@ -73,25 +75,34 @@ export class AuthRouter { } // Handle error if user is unauthorised - public unauthorisedErr(err: Error, req: Request, res: Response, next: NextFunction): void { + public unauthorisedErr( + err: Error, req: Request, res: Response, next: NextFunction + ): void { if (err.name === 'UnauthorizedError') { - next(new RequestError(401, 'not_authorised', 'user does not have correct authorisation to complete task')); + next(new RequestError( + 401, 'not_authorised', + 'user does not have correct authorisation for task' + )); } next(); } - //middleware to check privileges - admin - public isAdmin(req: Request, res: Response, next: NextFunction) { + // Middleware to check privileges - admin + public isAdmin(req: Request, res: Response, next: NextFunction): void { if (!req.user.admin) { - next(new RequestError(401, 'not_authorised', 'user is not authorised to perform task')); + next(new RequestError( + 401, 'not_authorised', + 'user is not authorised to perform task' + )); + return; } next(); } // Configure local strategy to use with passport-js. - private configStrategy() { + private configStrategy(): void { // tslint:disable-next-line:typedef - passport.use(new Strategy( async(username, password, done) => { + passport.use(new Strategy( async(username, password, done) => { const user: User | null = await User.findOne({ where: { username -- cgit v1.2.1 From 652d328dc1d6605687cbd6858a3d27da1c126f7e Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 3 Mar 2018 16:42:16 +0000 Subject: Implement handling of unauthorised requests --- src/auth.ts | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) (limited to 'src/auth.ts') diff --git a/src/auth.ts b/src/auth.ts index b40cddb..083357e 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -7,6 +7,8 @@ import * as passport from 'passport'; import { Strategy } from 'passport-local'; import { default as User } from './db/model/User'; +import { Errorware } from './errors/errorware'; + export class AuthRouter { public router: Router; @@ -74,19 +76,6 @@ export class AuthRouter { next(); } - // Handle error if user is unauthorised - public unauthorisedErr( - err: Error, req: Request, res: Response, next: NextFunction - ): void { - if (err.name === 'UnauthorizedError') { - next(new RequestError( - 401, 'not_authorised', - 'user does not have correct authorisation for task' - )); - } - next(); - } - // Middleware to check privileges - admin public isAdmin(req: Request, res: Response, next: NextFunction): void { if (!req.user.admin) { @@ -127,6 +116,20 @@ export class AuthRouter { } } +// Handle error if user is unauthorised +export const unauthorisedErr: Errorware = + (err: Error, req: Request, res: Response, next: NextFunction): void => { + console.log('fffff'); + if (err.name === 'UnauthorizedError') { + console.log('efewfwf'); + return next(new RequestError( + 401, 'not_authorised', + 'user does not have correct authorisation for task' + )); + } + next(err); +}; + const authRoutes: AuthRouter = new AuthRouter(); authRoutes.init(); -- cgit v1.2.1