@perfood/couch-auth
Version:
Easy and secure authentication for CouchDB/Cloudant. Based on SuperLogin, updated and rewritten in Typescript.
79 lines (78 loc) • 3.08 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserHashing = void 0;
const couch_pwd_1 = __importDefault(require("@sl-nx/couch-pwd"));
const user_hashing_legacy_1 = require("./user-hashing-legacy");
/**
* Class for hashing and verifying sl-user passwords
*/
class UserHashing {
constructor(config) {
this.legacy = new user_hashing_legacy_1.UserHashingLegacy(config);
this.iterations = config.security?.userHashing?.iterations || 600000;
this.pbkdf2Prf = config.security?.userHashing?.pbkdf2Prf || 'sha256';
this.keyLength = config.security?.userHashing?.keyLength || (this.pbkdf2Prf === 'sha' ? 20 : 32);
this.saltLength = config.security?.userHashing?.saltLength || 16;
this.pwdCouch = UserHashing.createPwdModule(this.iterations, this.keyLength, this.saltLength, this.pbkdf2Prf);
}
isUpgradeNeeded(hashObj) {
if (hashObj.iterations === undefined) {
return true;
}
if (hashObj.iterations < this.iterations) {
return true;
}
if ((hashObj.pbkdf2_prf || 'sha') !== this.pbkdf2Prf) {
return true;
}
return false;
}
hashUserPassword(password) {
return new Promise((resolve, reject) => {
this.pwdCouch.hash(password, (err, salt, hash) => {
if (err) {
return reject(err);
}
return resolve({
created: Date.now(),
salt: salt,
derived_key: hash,
password_scheme: 'pbkdf2',
pbkdf2_prf: this.pbkdf2Prf,
iterations: this.iterations
});
});
});
}
verifyUserPassword(hashObj, pw) {
if (hashObj.iterations === undefined) {
return this.legacy.verifyUserPassword(hashObj, pw);
}
return new Promise((resolve, reject) => {
const iterations = hashObj.iterations || 10;
const digest = hashObj.pbkdf2_prf || 'sha';
const length = digest === 'sha' ? 20 : 32;
const pwdCouch = UserHashing.createPwdModule(iterations, length, 16, digest);
const salt = hashObj.salt;
const derived_key = hashObj.derived_key;
pwdCouch.hash(pw, salt, (err, hash) => {
if (err) {
return reject(err);
}
else if (hash !== derived_key) {
return reject(false);
}
else {
return resolve(true);
}
});
});
}
static createPwdModule(iterations, keyLength, saltLength, digest) {
return new couch_pwd_1.default(iterations, keyLength, saltLength, 'hex', digest === 'sha' ? 'sha1' : digest);
}
}
exports.UserHashing = UserHashing;