Skip to content

Instantly share code, notes, and snippets.

@t1mofe1
Last active June 25, 2021 10:08
Show Gist options
  • Save t1mofe1/3088db685dd4263944517055c5b52e2c to your computer and use it in GitHub Desktop.
Save t1mofe1/3088db685dd4263944517055c5b52e2c to your computer and use it in GitHub Desktop.
Email verification system
const crypto = require('crypto');
const createError = (field, last = 'provided') => { throw Error(`${field} needs to be ${last}!`); };
const genHash = (secret, email, expiry, separator) => crypto.createHmac('sha256', secret).update(`${email}${separator}${expiry}`).digest('hex');
/**
* @function createHash
* @param {string} email - email
* @param {string|number} secret - your secret (DO NOT PUBLISH IT)
* @param {number|string} expiry - time in ms, when verification hash will be expired
* @param {string} separator - custom separator between hash and expiry time
* @returns {string} hash
*/
function createHash(email, secret, expiry = 60000, separator = '.') {
if (!secret) createError('Secret');
else if (!email) createError('Email');
else if (!separator) createError('Separator');
else if ((!expiry && String(expiry) !== '0') || (isNaN(expiry) && typeof expiry !== 'number')) createError('Expiry', 'a valid number');
const expiryTime = Date.now() + expiry;
return `${genHash(secret, email, expiryTime, separator)}${separator}${expiryTime}`;
}
/**
* @function verifyHash
* @param {string} hash - hash
* @param {string} email - email
* @param {string|number} secret - your secret (DO NOT PUBLISH IT)
* @param {string} separator - custom separator between hash and expiry time
* @returns {boolean} is hash valid
*/
function verifyHash(hash, email, secret, separator = '.') {
if (!hash) createError('Hash');
else if (!secret) createError('Secret');
else if (!email) createError('Email');
else if (!separator) createError('Separator');
if (!hash.match(separator)) return false;
const [baseHash, expiryTime] = hash.split(separator);
if (expiryTime < Date.now()) {
return false;
}
return genHash(secret, email, expiryTime, separator) === baseHash;
}
module.exports = {
createHash,
verifyHash,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment