datasquirel/users/validate-temp-email-code.ts
2025-01-10 20:10:28 +01:00

51 lines
1.6 KiB
TypeScript

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