Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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)
})
12 changes: 7 additions & 5 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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,
Expand All @@ -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 {
Expand Down
16 changes: 9 additions & 7 deletions lib/jwtauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
}
}
3 changes: 1 addition & 2 deletions models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var bcrypt = require('bcryptjs');

var SALT_WORK_FACTOR = 10;

Expand All @@ -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();
Expand Down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
8 changes: 5 additions & 3 deletions seed.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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()
})

Expand Down