UNPKG

@perfood/couch-auth

Version:

Easy and secure authentication for CouchDB/Cloudant. Based on SuperLogin, updated and rewritten in Typescript.

60 lines (59 loc) 2.54 kB
'use strict'; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SessionHashing = void 0; const couch_pwd_1 = __importDefault(require("@sl-nx/couch-pwd")); class SessionHashing { constructor(config) { this.iterations = config.security?.sessionHashing?.iterations || 1000; this.pbkdf2Prf = config.security?.sessionHashing?.pbkdf2Prf || 'sha256'; this.keyLength = config.security?.sessionHashing?.keyLength || (this.pbkdf2Prf === 'sha' ? 20 : 32); this.saltLength = config.security?.sessionHashing?.saltLength || 16; this.pwdCouch = SessionHashing.createPwdModule(this.iterations, this.keyLength, this.saltLength, this.pbkdf2Prf); } // Function for hashing _users passwords hashSessionPassword(password) { return new Promise((resolve, reject) => { this.pwdCouch.hash(password, (err, salt, hash) => { if (err) { return reject(err); } return resolve({ salt: salt, derived_key: hash, password_scheme: 'pbkdf2', pbkdf2_prf: this.pbkdf2Prf, iterations: this.iterations }); }); }); } verifySessionPassword(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 = SessionHashing.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 resolve(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.SessionHashing = SessionHashing; SessionHashing.invalidErr = { status: 401, message: 'invalid token' };