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 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 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