所以我试着建立一个非常基本的用户登录。我正在尝试创建一个用户,然后使用这些凭据登录并返回一个JSON令牌。我被困的地方是试图比较密码,然后发送回复。
步骤:
创建用户:
登录
用户模型
email:{
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}用户路由
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
// Create User
...
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash("superSecret", salt, function(err, hash) {
user.password = hash;
user.save();
res.json({success: true, message: 'Create user successful'});
});
});
...
// Login
...
bcrypt.compare(req.body.password, 'superSecret', function(err, res) {
if(req.body.password != user.password){
res.json({success: false, message: 'passwords do not match'});
} else {
// Send JWT
}
});所以这里的两个问题是,我不能发送响应,也不能比较密码。只要完全停留在这一点上,任何帮助都将不胜感激。
发布于 2016-10-17 01:57:58
正如在文档中所描述的,您应该像这样使用bcrypt.compare:
bcrypt.compare(req.body.password, user.password, function(err, res) {
if (err){
// handle error
}
if (res) {
// Send JWT
} else {
// response is OutgoingMessage object that server response http request
return response.json({success: false, message: 'passwords do not match'});
}
});这是一个关于用猫鼬进行密码认证(第1部分):bcrypt的很好的帖子
发布于 2019-05-08 13:04:29
如果我们在浏览器()中使用bcryptjs,那么您可以添加bcryptjs来完成这个任务。
CDN - https://cdn.jsdelivr.net/npm/bcryptjs@2.4.3/dist/bcrypt.js
示例-
-(在标签中添加上述CDN )
JS-
var bcrypt = dcodeIO.bcrypt;
/** One way, can't decrypt but can compare */
var salt = bcrypt.genSaltSync(10);
/** Encrypt password */
bcrypt.hash('anypassword', salt, (err, res) => {
console.log('hash', res)
hash = res
compare(hash)
});
/** Compare stored password with new encrypted password */
function compare(encrypted) {
bcrypt.compare('aboveusedpassword', encrypted, (err, res) => {
// res == true or res == false
console.log('Compared result', res, hash)
})
}如果您想在Nodejs中执行同样的操作,请使用
/**导入库如下所示,并使用与上面编写的相同的函数*/
var bcrypt = require('bcryptjs')发布于 2019-10-30 10:36:30
//required files
const express = require('express')
const router = express.Router();
//bcryptjs
const bcrypt = require('bcryptjs')
//User modal of mongoDB
const User = require('../../models/User')
//Post request for login
router.post('/', (req, res) => {
//email and password
const email = req.body.email
const password = req.body.password
//find user exist or not
User.findOne({ email })
.then(user => {
//if user not exist than return status 400
if (!user) return res.status(400).json({ msg: "User not exist" })
//if user exist than compare password
//password comes from the user
//user.password comes from the database
bcrypt.compare(password, user.password, (err, data) => {
//if error than throw error
if (err) throw err
//if both match than you can do anything
if (data) {
return res.status(200).json({ msg: "Login success" })
} else {
return res.status(401).json({ msg: "Invalid credencial" })
}
})
})
})
module.exports = routerhttps://stackoverflow.com/questions/40076638
复制相似问题