Mo1
Mo1

Reputation: 379

Please help me get the hashed password

I'm trying to get the hashed password for the admin.

I've tried to hash the password but I'm failing to insert it into the user object.

import encryptor from '../helpers/password';

let hashed_pswd = 'john123';
const hashPassword= async () => {
    const adminPwd = await encryptor.encryptPassword(hashed_pswd, 10);
    console.log(adminPwd);
}
hashPassword();

export default [
    {
        id: 1,
        first_name: 'john',
        last_name: 'doe',
        email: '[email protected]',
        password: adminPwd,
        address: 'kigali',
        is_admin: true
    }
]

I'm being able to log the hashed password in the console but when I try to send a POST request, I'm getting that the adminPwd is not defined.

Thank you in advance.

Upvotes: 0

Views: 81

Answers (2)

In order to solve this you need to declare adminPwd using let instead of const in global scope or in scope where your export default section can access it.

Refer to modified code snippet:

import encryptor from '../helpers/password';

let hashed_pswd = 'john123';
let adminPwd;
const hashPassword = async () => {
    adminPwd = await encryptor.encryptPassword(hashed_pswd, 10);
            console.log(adminPwd);
            return [
                {
                    id: 1,
                    first_name: 'john',
                    last_name: 'doe',
                    email: '[email protected]',
                    password: adminPwd,
                    address: 'kigali',
                    is_admin: true
                }
            ]
}

export default hashPassword;

Wherever you were importing this, call exported function before using it.

In order to Consume this response you have two options:

  1. In a async function using await keyword

  2. If not consuming within async function use .then method of promise.

Upvotes: -1

Andy
Andy

Reputation: 63524

Since you're using async/await for the hashPassword function you may as well wrap your whole code in one and remove that function. You should rename your hashed_pswd variable to something more meaningful because it's not hashed at that stage. I've called it password.

import encryptor from '../helpers/password';

export default async () => {

  const password = 'john123';
  const hashedPassword = await encryptor.encryptPassword(password, 10);

  return [{
    id: 1,
    first_name: 'john',
    last_name: 'doe',
    email: '[email protected]',
    password: hashedPassword,
    address: 'kigali',
    is_admin: true
  }];

};

And to import that module you'd have to use async to wrap your code because you're returning a promise from that async in getUserData.

import getUserData from './getUserData.mjs';

(async () => {

  console.log(await getUserData());

})();

Upvotes: 3

Related Questions