// Original file created by Prof.Dr. Matthias Hopf

/*
 * Crypto routines for Authorization
 */

const crypto = require ("crypto");

const defaultHash = "sha256";
const defaultSaltLen = 16;                // More (e.g. 256) for extra paranoia

const mod = {
    encodePwd: function (entry, pwd) {
        return crypto.createHash (entry.hash) .update (entry.salt + ":" + pwd, 'utf8') .digest ('base64');
    },
    checkLocalAuth: function (entry, pwd) {
        if (!entry || !entry._id || !entry.hash || !entry.salt || !entry.hash || !entry.pwd ||
            !pwd   || pwd === '')
            return false;
        return mod.encodePwd (entry, pwd) === entry.pwd;
    },
    fillLocalAuth: function (entry, pwd) {
        if (!entry.hash)
            entry.hash = defaultHash;
        entry.salt = crypto.randomBytes (defaultSaltLen) .toString('base64');
        entry.pwd  = mod.encodePwd (entry, pwd);
    },
}


module.exports = mod;
