.save()
有竞争条件。那么,如何应对呢?。
并且,数据库无法保存tokenUser
值。
login.js
var crypto = require('crypto');
var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();
var User = require('../modules/user');
var Token = require('../modules/token');
router.get('/', function(req, res) {
res.render('login', {
title: '登录界面'
});
});
router.post('/', function(req, res) {
User.findOne({
tel: req.body.tel,
})
.exec(function(err, user) {
var md5 = crypto.createHash('md5'),
password = md5.update(req.body.password)
.digest('hex');
if (!user) {
return res.json({
success: false,
message: '认证失败,用户名找不到'
});
} else if (user.hash_password === password) {
return;
} else {
return res.json({
status: 007,
success: false,
message: '没有当前用户'
});
}
});
var tel = req.body.tel;
var user = new User({
tel: tel
});
var md5 = crypto.createHash('md5'),
password = md5.update(req.body.password)
.digest('hex');
user.set("hash_password", password);
user.set("name", req.body.name);
user.set("created_at", Date.now());
var token = jwt.sign(user, 'whuteditor', {
expiresIn: "30 days" // 设置过期时间
});
var tokenUser = new Token({
token: token
});
tokenUser.set("nickname", req.body.name);
tokenUser.save(function(err, token) { //how to deal with??
if (err) {
return res.json({
status: 120,
success: false,
message: "Bad Storage"
});
} else {
res.json({
status: 100,
success: true,
message: 'Enjoy your token!',
token: token
});
}
});
});
module.exports = router;