I am creating an production angularJs
application.
Now ive created parts of my RESTFul
API
this API
generates a user
object on login however i am not keen on sending the password
unhashed / un incrypted over the HTTP header.
To give you some insight of my API
:
on login:
var jwt = require('jwt-simple');
// Route: /login
module.exports = function (express, sequelize, router) {
var DataTypes = require("sequelize");
var crypto = require('crypto');
var User = sequelize.define('user', {
id: DataTypes.INTEGER,
username: DataTypes.STRING,
name: DataTypes.STRING,
organization_id: DataTypes.INTEGER,
type_id: DataTypes.INTEGER,
division_id: DataTypes.INTEGER
}, {
freezeTableName: true,
instanceMethods: {
retrieveByNamePassword: function (username, onSuccess, onError) {
User.find({where: {username: username}}, {raw: true})
.then(onSuccess).catch(onError);
}
}
}
);
router.route('/login')
.post(function (req, res) {
var user = User.build();
var username = req.body.username || '';
var password = req.body.password || '';
if (username == '' || password == '') {
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
user.retrieveByNamePassword(username, function (users) {
if (users) {
// If authentication is success, we will generate a token
// and dispatch it to the client
res.json(genToken(users));
return;
} else {
// If authentication fails, we send a 401 back
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
}, function (error) {
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
});
});
var genToken = function(user) {
var expires = expiresIn(7); // 7 days
var token = jwt.encode({
exp: expires,
user_id: user.id,
organization_id: user.organization_id,
type_id: user.type_id,
division_id: user.division_id
}, require('./config/secret')());
return {
token: token,
expires: expires,
user: user
};
};
var expiresIn = function(numDays) {
var dateObj = new Date();
return dateObj.setDate(dateObj.getDate() + numDays);
};
As you can see right now (Because i am not sure yet how to handle it) am only looking for the username and then checks that the username exists.
My question is fairly simple how do you go around encrypting the password and then validate it once it reaches the API?