datasquirel/users/validate-temp-email-code.js

53 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-12-10 14:10:32 +00:00
// @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.email]
*
2024-12-10 14:31:53 +00:00
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>}
2024-12-10 14:10:32 +00:00
*/
async function validateTempEmailCode({ request, email }) {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request });
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) {
2024-12-10 14:31:53 +00:00
return payload;
2024-12-10 14:10:32 +00:00
}
if (payload?.email && payload.email === email) {
2024-12-10 14:31:53 +00:00
return payload;
2024-12-10 14:10:32 +00:00
}
2024-12-10 14:31:53 +00:00
return null;
2024-12-10 14:10:32 +00:00
} catch (/** @type {any} */ error) {
console.log("validateTempEmailCode error:", error.message);
2024-12-10 14:31:53 +00:00
return null;
2024-12-10 14:10:32 +00:00
}
}
module.exports = validateTempEmailCode;