import crypto from 'crypto';

const options = {
    saltLength: 24, // A minimum of 16 is required (see: https://nodejs.org/api/crypto.html)
    hashLength: 60,
    encoding: 'base64',
};

export function hash(password) {
    const randomSalt = crypto.randomBytes(options.saltLength).toString(options.encoding);
    return hashWithSalt(password, randomSalt);
}

export function verify(providedPassword, storedPassword) {
    const salt = storedPassword.split('.')[0];

    return new Promise(resolve => {
        hashWithSalt(providedPassword, salt).then(result => {
            resolve(result === storedPassword);
        });
    });
}

function hashWithSalt(password, salt) {
    return new Promise((resolve, reject) => {
        crypto.scrypt(password, salt, options.hashLength, (err, hash) => {
            if (err) reject(err);
            else resolve(salt + '.' + hash.toString(options.encoding));
        })
    });
}
