我正在开发一个网络应用,我想尝试使用JWT
进行用户身份验证和密码恢复。我需要JWT
来验证我的数据库中的有效用户。我试过这个:
login.js :
var User = require("../model/user/registerSchema").User;
var bcrypt = require('bcrypt');
var utils = require('../util/util'),
config = require('../config'),
jwt = require('jsonwebtoken');
/* Login Route. */
route = (app)=>{
//POST
app.post ('/login', (req, res) => {
let {userName, password} = req.body;
if (!utils.noEmptyParams(req.body)) res.json({success: false, message: config.messages.NO_DATA});
else
User.findOne({userName, password}, {password: 0})
.exec()
.then(user => {
if (user) {
user = JSON.parse(JSON.stringify(user));
jwt.sign(user, config.jwt.secret, config.jwt.options, (err, token) => {
res.json({
success: true,
user,
token,
});
});
} else {
res.json({success: false, message: config.messages.INVALID_CREDENTIALS});
}
})
.catch(error => {
utils.error(error);
res.json({success: false});
});
});
}
module.exports.route = route;
registerSchema.js
var mongoose = require("mongoose"),
db = global.db,
bcrypt = require('bcrypt');
var User = new mongoose.Schema();
// MONGOOSE MODEL CONFIGURATION
const RegisterSchema = new mongoose.Schema({
access:{
type: String,
required:[true, 'please select proffession']
},
phone: {
type: String,
required: [true, 'Please add a username'],
unique: true
},
firstName: {
type: String,
required: [true, 'Please enter your firstname']
},
lastName: {
type: String,
required: [true, 'Please add your last name']
},
password: {
type: String,
required: [true, 'Please add a password']
},
userName: {
type: String,
required: [true, 'Please add an email address'],
unique: true
},
companyName: {
type: String
},
});
RegisterSchema.pre('save', function(next){
var user = this;
bcrypt.hash(user.password, 10, function(err, hash){
if(err){
return next(err);
}
user.password= hash;
next()
})
})
module.exports = mongoose.model('User', RegisterSchema);
我正在运行Node版本:v9.4.0,我正在使用邮递员进行测试。当我尝试发布需求字段时,
{
"userName": "njksdnf@fds.com",
"password": "1234567"
}
我收到了这个错误:
TypeError: Cannot read property 'findOne' of undefined
at app.post (/home/user/Home/Node/Routers/login.js:19:18)
我见过WT-user-authentication-API-bolilerplate ,但似乎没有完全帮助。
关于我如何解决它以及如何在这种情况下使用JWT
进行密码恢复的任何想法?
答案 0 :(得分:0)
对于
TypeError: Cannot read property 'findOne' of undefined
at app.post (/home/user/Home/Node/Routers/login.js:19:18)
从邮递员那里得到了,这一切都归功于评论中的Striped。移除.User
为我做了全部魔术。
现在让我的代码成为:
var User = require("../model/user/registerSchema");
而不是:
var User = require("../model/user/registerSchema").User;
还有问题"关于如何在这种情况下使用JWT
进行密码恢复的任何想法?