Last active
June 25, 2021 10:08
-
-
Save t1mofe1/3088db685dd4263944517055c5b52e2c to your computer and use it in GitHub Desktop.
Email verification system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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