Skip to content
Permalink
Browse files

Current to Part 9 - http://brianmajewski.com/2015/02/25/relearning-ba…

  • Loading branch information...
bmajewski committed Feb 26, 2015
1 parent 88039a9 commit dae2b441bf1c718a6000df50679a6b096d70d8c4
Showing with 74 additions and 0 deletions.
  1. +21 −0 app/models/user.js
  2. +51 −0 app/routes/user.js
  3. +2 −0 package.json
@@ -1,5 +1,6 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');


var UserSchema = new Schema({
@@ -9,4 +10,24 @@ var UserSchema = new Schema({
permissions: [String]
});

UserSchema.pre('save', function(next){
var user = this;
if (!user.isModified()){
return next();
}

bcrypt.hash(user.password, null, null, function(err,hash){
if (err) {
return next(err);
}
user.password = hash;
next();
})
});

UserSchema.methods.comparePassword = function(password){
var user = this;
return bcrypt.compareSync(password, user.password);
};

module.exports = mongoose.model('User', UserSchema);
@@ -1,13 +1,64 @@
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var User = require('../models/user');

var superSecret = 'TheAmazingKreskin';

module.exports = function (app, express) {
var userRouter = express.Router();

userRouter.post('/authenticate', function (req, res) {
User.findOne({
username: req.body.username
}).select('name username password').exec(function (err, user) {
if (err) throw err;

if (!user) {
res.json({success: false, message: 'User not found'});
} else {
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({success: false, message: 'Wrong password'});
} else {
var token = jwt.sign({
name: user.name,
username: user.username,
_id: user._id
}, superSecret, {
expiresInMinutes: 1440
});

res.json({
success: true,
message: 'login ok',
token: token,
_id: user._id
});
}
}
});
});

userRouter.get('/', function (req, res) {
res.json({message: 'api is loaded'});
});

userRouter.use(function (req, res, next) {
var token = req.body.token || req.params.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, superSecret, function (err, decoded) {
if (err) {
return res.status(401).send({success: false, message: 'Failed to authenticate token'});
} else {
req.decoded = decoded;
next();
}
})
} else {
return res.status(401).send({success: false, message: 'No token provided'});
}
});

userRouter.route('/users')
.post(function (req, res) {
var user = new User();
@@ -9,8 +9,10 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.12.0",
"express": "^4.11.2",
"jsonwebtoken": "^3.2.2",
"mongoose": "^3.8.23",
"morgan": "^1.5.1"
}

0 comments on commit dae2b44

Please sign in to comment.
You can’t perform that action at this time.