datasquirel/users/validate-temp-email-code.js
Benjamin Toby d98deb06c5 Updates
2024-12-13 14:08:41 +01:00

54 lines
1.8 KiB
JavaScript

// @ts-check
const http = require("http");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const EJSON = require("../package-shared/utils/ejson");
/**
* Verify the temp email code sent to the user's email address
* ==============================================================================
* @async
*
* @param {object} params - Single Param object containing params
* @param {http.IncomingMessage & Object<string, any>} [params.request]
* @param {string} [params.cookieString]
* @param {string} [params.email]
*
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>}
*/
async function validateTempEmailCode({ request, email, cookieString }) {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload =
/** @type {import("../package-shared/types").SendOneTimeCodeEmailResponse | undefined} */ (
EJSON.parse(encryptedPayload)
);
if (payload?.email && !email) {
return payload;
}
if (payload?.email && payload.email === email) {
return payload;
}
return null;
} catch (/** @type {any} */ error) {
console.log("validateTempEmailCode error:", error.message);
return null;
}
}
module.exports = validateTempEmailCode;