Benjamin Nielsen
Benjamin Nielsen

Reputation: 139

Using 'pgcrypt' inside node.js application

Im wondering how i can use the pgcrypt extension inside my Node.js application to hash my passwords when i insert a user into the database. Might be a simple solution, but i cant figure out how to use theese PG extensions inside applications...

As an example this is my query to create an admin table, and insert an admin to the table. Now i would like to hash the password.

function createAdmin(){
    var usertypeid = null;
    const type = "adm";
    pool.query(`INSERT INTO usertype(type) VALUES ($1) RETURNING userTypeId;`, [type], function (error, results) {
        if (error){
            throw error;
        } else{
            usertypeid = results.rows[0].usertypeid;
            console.log(usertypeid);
            insertAdmin();
        }
    });

    function insertAdmin(){
        pool.query(`
                    INSERT INTO users(
                    usertypeid, userName, email, password)
                    VALUES($1, 'admin', '[email protected]', crypt('admin'), gen_salt('bf'));`, [usertypeid]);
    }
}

Upvotes: 1

Views: 239

Answers (1)

jjanes
jjanes

Reputation: 44227

VALUES($1, 'admin', '[email protected]', crypt('admin'), gen_salt('bf'))

It would be nice if you give us the error message.

crypt takes two arguments. You are calling with one, then passing the salt as an extra 5th column to an INSERT which needs exactly 4 columns. Adjust your parentheses.

VALUES($1, 'admin', '[email protected]', crypt('admin', gen_salt('bf')))

Also, using the default work factor for bf is probably too low, but that would be a separate issue.

Upvotes: 1

Related Questions