我要创建一个关于IT技术的生产应用程序,需要翻译的内容涉及AngularJS和RESTFul API。
现在我已经创建了部分RESTFul API。
这个API将在登录时生成一个用户对象,但是我不想通过HTTP头明文传输密码。
让您了解我的API:
当登录时:
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);
};
目前看来(因为我还不确定如何处理)只需要查找用户名并检查该用户名是否存在。
我的问题很简单,如何对密码进行加密,并在到达API后验证它?