首页 > 解决方案 > 为什么我在数据库中的密码不等于请求正文中的密码?

问题描述

我尝试在 Nestjs 中为我的 API 进行登录,因此当用户通过请求正文发送数据时,我捕获数据并使用 typeorm 的查询构建器,然后在确认是否用户存在我创建一个新的比较块,我不知道代码不起作用的原因,如果我使用https://bcrypt-generator.com/比较数据库中的哈希密码和请求正文的密码,这是真的,但在我的代码中它不起作用


async login(userRO: UserRO) {
        const { email, password } = userRO;
        const user = await getRepository(User)
            .createQueryBuilder('user')
            .where('user.email = :email', {email})
            .getOne();
        if (!user) {
            throw new HttpException(
                'Usuario no es correcto',
                HttpStatus.BAD_REQUEST,
            );
        }
        // hashPassword = $2y$12$ZvWFRLVoS2gxyCjLkCbOZuN7NKfYrpT6cWxSJaeiVr0PnPBeoI8GS
        // password = pepito09
        const pass = await bcrypt.compare(password, user.password);
        if (!pass) { // this always throw an error
            throw new HttpException(
                'Contraseña incorrecta',
                HttpStatus.BAD_REQUEST,
            );
        }
        const rol = await getRepository(Rol)
            .createQueryBuilder('rol')
            .select('rol.name')
            .leftJoinAndSelect(User, 'user', 'user.rolId = rol.id')
            .where('user.email = :email', { email })
            .getOne();
        if (!rol) {
            throw new HttpException(
                'Rol no encontrado',
                HttpStatus.NOT_FOUND,
            );
        }
        const type = this.typeUser(rol.name) ;
        const payload = { email: user.email, id: user.id, rol: rol.name };
        return {
            access_token: this.jwtService.sign(payload),
            type,
        };
    }

因此,如果数据库中的密码和请求正文中的密码相等,我希望关于密码的比较块抛出 true,否则返回 false。此刻,总是抛出 true

标签: mysqlbcryptnestjstypeorm

解决方案


推荐阅读