根据参数查找单个用户

时间:2020-07-24 20:25:47

标签: node.js angular mongodb mean-stack bcrypt

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

这是我在用户服务中提供的用户名和密码。

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,
) { }
}

这可能是一个问题太多,但我不想遗漏任何可能有助于解决问题的方法,因为我知道我可能有几个问题需要在这里解决,但是我处于为自己做事而茫然。

1 个答案:

答案 0 :(得分:1)

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

可以看出您错误地使用了req.username,该名称未定义。 结果,用户为空。

因此,请使用req.query.username或req.body.username。

基于路线类型