问题描述
我正在创建一个具有管理员用户的 Web 应用,该用户是唯一可以创建其他用户的用户。我将管理员用户名和密码存储在 .env
文件中并使用 dotenv
包。
我的问题是,当我使用 custom
检查(使用 express-validator
)将用户名和密码与 env 变量进行比较时,它总是触发错误,即使我的所有 console.log()
都在自定义验证中不在终端中显示。
这是我的router
const router = require('express').Router();
const { logAdmin} = require('../../controllers/admin');
const { validateAdminLogIn } = require('../../utils/adminValidation');
// log admin in
router.post('/login',validateAdminLogIn,logAdmin);
和我的adminValidation
const { check,validationResult } = require('express-validator');
exports.validateAdminLogIn = [
check('username').custom((value) => {
if (value !== process.env.ADMIN_USER) {
console.log('no user match') // this doesn't run
return Promise.reject('wrong username or password');
}
}),check('password').custom((value) => {
if (value !== process.env.ADMIN_PASSWORD) {
console.log("passwords don't match") // this never runs
return Promise.reject('wrong username or password');
}
}),(req,res,next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log('there are errors');
console.log(errors);
return res.status(401).json({ errors: errors.array() });
}
console.log('finished validation with no errors'); // never get to here
next();
},];
还有我的 controller
,我还没有做过任何事情
exports.logAdmin = (req,res) => {
// get username and password
const { username,password } = req.body;
// match to the admin credentials
// create token and send it as a cookie using the admin token secret
};
这是我的请求(vs 代码的休息客户端)
### admin
post http://localhost:5000/api/auth/admin/login
Content-Type: application/json
{
"username": "admin","password": "password"
}
这里是错误结果
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 169
ETag: W/"a9-zEKcgYJMgQx5PLgkFguKIPyF/5Q"
Date: Fri,23 Apr 2021 22:35:22 GMT
Connection: close
{
"errors": [
{
"value": "admin","msg": "Invalid value","param": "username","location": "body"
},{
"value": "password","param": "password","location": "body"
}
]
}
非常感谢
解决方法
我已经解决了这个问题,因为我一开始没有承诺要拒绝。如果没有错误,我也不会从自定义验证器函数返回任何内容
所以这是我修复它的方法
check('username')
.custom((value) => {
const username = process.env.ADMIN_USER;
if (value !== username) throw new Error('wrong username or password');
return true;
})
.withMessage('user name error'),check('password').custom((value) => {
const password = process.env.ADMIN_PASSWORD;
if (value !== password) throw new Error('wrong username or password');
return true;
}),(req,res,next) => {
const errors = validationResult(req);
console.log(errors);
if (!errors.isEmpty())
return res.status(401).json({ errors: errors.array() });
console.log('finished validation with no errors');
next();
},