首页 > 解决方案 > 根据参数查找单个用户

问题描述

我正在尝试设置登录到我正在处理的网站。我无法根据他们的登录信息找到用户,因为我的结果总是为空。

这就是我在用户服务中传递用户名和密码的内容。

confirmUser(username: string, password: string) { 
    this.http.get<{ confirmUser: ConfirmUser }>('http://localhost:3000/users?username=' + username.toLowerCase() + '&password=' + password).subscribe(
        // success function
        (response) => {
           console.log(response);
           return; //Only returning here just to check the response before moving on while I debug
           // this.user = response.user;
           // console.log(this.user);
        }
     ),
     (error: any) => {
        console.log(error);
     } 
}

另一方面,我可以使用它来安全地返回所有用户(只要我先删除所需的用户名/密码)

router.get('/', (req, res, next) => {
User.findOne()
.then(user => {
    res.status(200).json({
        message: "Logged in successfully",
        user: user
    });
})
.catch(error => {
    console.log(error);
});
});

当我尝试过滤它以根据用户名查找用户,然后根据传入的密码创建的新哈希检查存储的哈希时,问题就出现了。这是我尝试过的一个例子:

router.get('/', (req, res, next) => {
const hash = bcrypt.hashSync(req.query.password, saltRounds); //Hash the password argument
User.findOne( { username: req.username }).then(user => { //Find based on username

    if (user){ //Check here to match the hashes before returning?
        res.status(200).json({
            confirmUser: ConfirmUser = {
                id: user.id,
                username: user.username    
            }
        });

    } else {
        res.status(401);
    }

})
.catch(error => {
    // returnError(res, error);
});
});

首先,我不完全确定在哪里比较这两个哈希以确保我抓取的是正确的用户,而不是具有相同用户名的用户(尽管我想确保用户名是唯一的可以解决这个问题)

我知道有一种方法可以只返回找到的记录中的特定字段,我相信通过添加一些东西来达到 的效果{username: 1, password: 0},但我也不确定如何实际做到这一点。理想情况下,我想找到与用户名/密码匹配的用户,然后只返回用户的 ID 和用户名来存储以实际登录。完整的用户模型如下:

export class User {
constructor(
    public id: string,
    public firstName: string,
    public lastName: string,
    public username: string,
    public email: string,
    public password: string
) { }
}

confirmUser 对象是一个仅包含这些字段的视图模型:

export class ConfirmUser {
constructor(
    public id: string,
    public username: string,
) { }
}

这可能是一个太多的问题,但我不想留下任何可能有助于解决问题的东西,因为我知道我可能有几个问题需要在这里解决,但我不知道什么做我自己。

标签: node.jsangularmongodbmean-stackbcrypt

解决方案


这是因为你写了。findOne( { username: req.username }).then(user => { //根据用户名查找

可以看出你误用了req.username,没有定义。结果用户为空。

所以使用 req.query.username 或 req.body.username。

基于路线类型


推荐阅读