From 5e058deb90b008215e8dd62e38858f90dd882853 Mon Sep 17 00:00:00 2001 From: cratepull Date: Mon, 25 Jul 2016 18:17:29 -0500 Subject: [PATCH] Update moment, mongoose libs, simplify methods, enhance error handling --- app.js | 17 ++++++----------- controllers/auth.js | 12 +++++++----- lib/jwtauth.js | 16 +++++++++------- models/user.js | 3 +-- package.json | 11 ++++++----- seed.js | 8 +++++--- 6 files changed, 34 insertions(+), 33 deletions(-) diff --git a/app.js b/app.js index adc6e11..4a77e2c 100644 --- a/app.js +++ b/app.js @@ -4,6 +4,7 @@ var express = require('express') var colors = require('colors') var mongoose = require('mongoose'); +var bodyParser = require('body-parser'); var url = require('url') var jwt = require('jwt-simple'); @@ -22,6 +23,7 @@ var jwtauth = require('./lib/jwtauth') */ mongoose.connect('mongodb://localhost/jwttest'); + /** * Create the express app * NOTE: purposely not using var so that app is accesible in modules. @@ -33,16 +35,9 @@ app = express() */ app.set('jwtTokenSecret', 'secret-value') -/** - * A simple middleware to restrict access to authenticated users. - */ -var requireAuth = function(req, res, next) { - if (!req.user) { - res.end('Not authorized', 401) - } else { - next() - } -} +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); + /** * Load up the controllers @@ -60,6 +55,6 @@ var server = app.listen(3000, function() { /** * An example protected route. */ -app.get('/secret', express.bodyParser(), jwtauth, requireAuth, function(req, res){ +app.get('/secret', jwtauth, function(req, res){ res.send('Hello ' + req.user.username) }) diff --git a/controllers/auth.js b/controllers/auth.js index 167c9c6..d309aed 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -5,15 +5,17 @@ var moment = require('moment') module.exports.set = function(app) { - app.get('/token', express.bodyParser(), function(req, res){ + app.get('/token', function(req, res){ // express.bodyParser() is now deprecated if (req.headers.username && req.headers.password) { - + // Fetch the appropriate user, if they exist UserModel.findOne({ username: req.headers.username }, function(err, user) { - if (err) { + + if (err || user === null) { // user cannot be found; may wish to log that fact here. For simplicity, just return a 401 res.send('Authentication error', 401) + return } user.comparePassword(req.headers.password, function(err, isMatch) { @@ -24,7 +26,7 @@ module.exports.set = function(app) { if (isMatch) { // Great, user has successfully authenticated, so we can generate and send them a token. - var expires = moment().add('days', 7).valueOf() + var expires = moment().add(7, "days").valueOf() // format ("days", 7) is deprecaded. var token = jwt.encode( { iss: user.id, @@ -34,7 +36,7 @@ module.exports.set = function(app) { ); res.json({ token : token, - expires : expires, + expires : moment(expires).format("DD MMM YYYY hh:mm a"), // Enhace the response user : user.toJSON() }); } else { diff --git a/lib/jwtauth.js b/lib/jwtauth.js index 35ddd12..a14c0f3 100644 --- a/lib/jwtauth.js +++ b/lib/jwtauth.js @@ -22,6 +22,7 @@ module.exports = function(req, res, next){ * - the x-access-token header * ...in that order. */ + var token = (req.body && req.body.access_token) || parsed_url.query.access_token || req.headers["x-access-token"]; if (token) { @@ -30,24 +31,25 @@ module.exports = function(req, res, next){ var decoded = jwt.decode(token, app.get('jwtTokenSecret')) if (decoded.exp <= Date.now()) { - res.end('Access token has expired', 400) + res.send('Access token has expired', 400) } UserModel.findOne({ '_id': decoded.iss }, function(err, user){ - if (!err) { - req.user = user + if (!err) { + req.user = user return next() } + + res.send('Not authorized', 401) }) } catch (err) { - return next() + res.send('Not authorized', 401) + // return next() } } else { - - next() - + res.send('Not authorized', 401) } } diff --git a/models/user.js b/models/user.js index e012de1..0fb556d 100644 --- a/models/user.js +++ b/models/user.js @@ -9,7 +9,7 @@ */ var mongoose = require('mongoose'); -var bcrypt = require('bcrypt'); +var bcrypt = require('bcryptjs'); var SALT_WORK_FACTOR = 10; @@ -31,7 +31,6 @@ UserSchema.pre('save', function(next) { // hash the password along with our new salt bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); - // override the cleartext password with the hashed one user.password = hash; next(); diff --git a/package.json b/package.json index e5619e2..96a10e2 100644 --- a/package.json +++ b/package.json @@ -4,11 +4,12 @@ "version": "0.0.1", "private": true, "dependencies": { - "express": "3.x", + "bcryptjs": "^2.3.0", + "body-parser": "^1.15.2", "colors": "0.6.2", - "mongoose": "3.8.8", - "bcrypt": "0.7.7", - "moment": "2.6.0", - "jwt-simple": "0.2.0" + "express": "3.x", + "jwt-simple": "0.2.0", + "moment": "^2.14.1", + "mongoose": "^4.5.7" } } diff --git a/seed.js b/seed.js index 6512036..6bd1870 100644 --- a/seed.js +++ b/seed.js @@ -13,7 +13,10 @@ var UserModel = require('./models/user') /** * Connect to the database */ -mongoose.connect('mongodb://localhost/jwttest'); + +// mongoose.connect('mongodb://localhost/jwttest'); + +mongoose.connect("mongodb://localhost:27017/jwttest"); var db = mongoose.connection; @@ -27,11 +30,10 @@ db.once('open', function callback () { user.save(function(err){ if (err) { - console.log('Could not save user.'.red) + console.log('%s'.red, err) //Explaining error reason. } else { console.log('Database seeded'.green) } - process.exit() })