Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

-- Hello JWT #25

Merged
merged 1 commit into from
Oct 13, 2015
Merged
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
73 changes: 73 additions & 0 deletions app/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// app/models/user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var _ = require('lodash');

var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
},
lastName: {
type: String,
trim: true,
default: '',
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
trim: true,
unique: true,
},
password: {
type: String,
default: '',
require: true
},
created: {
type: Date,
default: Date.now
},
});

/**
* Hook a pre save method to hash the user password
*/
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next()
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if(err) return next(err);
// set the hashed password back on our user document
user.password = hash;
//user.save();
next();
});
});
});

// User methods

/**
* Validate user password on singin and compare with hased password stored in DB
*/

UserSchema.methods.validateUserPassword = function(plainPassword, cb) {
var user = this;
bcrypt.compare(plainPassword, user.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};

// TODO: check if user with email already exist

module.exports = mongoose.model('User', UserSchema);
51 changes: 51 additions & 0 deletions app/routes/sessions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
var express = require('express');
var router = express.Router(); // get an instance of the express Router
var _ = require('lodash');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens

var config = require('../../config/config');
var User = require('../models/user');

// on routes that end in /things
// ----------------------------------------------------
router.route('/')

// Authenticate the user and return user token (accessed at POST http://localhost:8080/sessions)
.post(function(req, res) {
if(req.body.email && req.body.password) {
// Find the user
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if(!user){
// User with this email does not exist
res.json({status:404, message: 'Authentication failed. User not found.' });
}
// Validate user password
user.validateUserPassword(req.body.password,function (err, isMatch) {
if(err){
res.json({status:401, message: 'Unauthorized.' });
}
if(isMatch){
// Generate user token
var token = jwt.sign(user, config.secretToken, {
expiresInMinutes: config.userTokenExpirePeriod
});
res.json({status:200, token: token, message: 'Authentication succeeded.' });
} else {
res.json({status:401, message: 'Unauthorized.' });
}
});
})
}
else {
// Email or password are not provided
res.json({status:400, message: 'Bad request.' });
}

});

// export router module
module.exports = router;

2 changes: 1 addition & 1 deletion app/routes/status.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ router.route('/')

// get the status (accessed at GET http://localhost:8080/status)
.get(function(req, res) {
var stat = {"status":"OK"}
var stat = {"status":"OK"};
res.send(stat);
});

Expand Down
42 changes: 42 additions & 0 deletions app/routes/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
var express = require('express');
var router = express.Router(); // get an instance of the express Router
var _ = require('lodash');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens

var config = require('../../config/config');
var User = require('../models/user');

// on routes that end in /things
// ----------------------------------------------------
router.route('/')

// create a new user account and return user token (accessed at POST http://localhost:8080/users)
.post(function(req, res) {

if (!req.body.email || !req.body.password) { // Check for email and password in request
return res.json({status:400, message: 'Bad request.' });
}
//TODO: Check if user with this email already exist
var user = new User({
email: req.body.email,
password: req.body.password
});
// save the user and generate token
user.save(function(err) {
if (err)
res.send(err);
// Create user token
var token = jwt.sign(user, config.secretToken, {
expiresInMinutes: config.userTokenExpirePeriod
});
res.json({
status: 200,
message: 'Account created!',
token: token
});
});
});

// export router module
module.exports = router;

4 changes: 3 additions & 1 deletion config/development.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@
"port" : "27017",
"name" : "test"
},
"port" : "8080"
"port" : "8080",
"secretToken": "VelikaSrbija",
"userTokenExpirePeriod": "10080"
}
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
"dependencies": {
"express": "~4.0.0",
"mongoose": "~3.6.13",
"body-parser": "~1.0.1"
"body-parser": "~1.0.1",
"jsonwebtoken": "~5.0.5",
"bcrypt": "~0.8.5",
"lodash": "~3.10.1"
},
"devDependencies": {
"gulp-jshint": "^1.11.2",
Expand Down
3 changes: 3 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ var port = process.env.PORT || config.port; // set our port
// =============================================================================
app.use('/status', require('./app/routes/status'));
app.use('/devices', require('./app/routes/devices'));
app.use('/users', require('./app/routes/users'));
app.use('/sessions', require('./app/routes/sessions'));



// START THE SERVER
Expand Down