datasquirel/users/logout-user.ts
2025-01-10 20:10:28 +01:00

109 lines
3.2 KiB
TypeScript

import http from "http";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import decrypt from "../package-shared/functions/dsql/decrypt";
import EJSON from "../package-shared/utils/ejson";
import { deleteAuthFile } from "../package-shared/functions/backend/auth/write-auth-files";
import parseCookies from "../package-shared/utils/backend/parseCookies";
import { DATASQUIREL_LoggedInUser } from "../package-shared/types";
type Param = {
encryptedUserString?: string;
request?: http.IncomingMessage & { [s: string]: any };
response?: http.ServerResponse & { [s: string]: any };
cookieString?: string;
database?: string;
dsqlUserId?: string | number;
};
type Return = {
success: boolean;
msg: string;
cookieNames?: any;
};
/**
* # Logout user
*/
export default function logoutUser({
response,
database,
dsqlUserId,
encryptedUserString,
request,
cookieString,
}: Param): Return {
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
try {
const cookieNames = getAuthCookieNames({
database,
userId: dsqlUserId || process.env.DSQL_API_USER_ID,
});
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
const oneTimeCodeName = getAuthCookieNames().oneTimeCodeName;
const decryptedUserJSON: string | undefined = (() => {
try {
if (request) {
const cookiesObject = parseCookies({
request,
cookieString,
});
return decrypt({
encryptedString: cookiesObject[authKeyName],
});
} else if (encryptedUserString) {
return decrypt({
encryptedString: encryptedUserString,
});
} else {
return undefined;
}
} catch (/** @type {any} */ error: any) {
console.log(
"Error getting decrypted User JSON to logout:",
error.message
);
return undefined;
}
})();
if (!decryptedUserJSON) throw new Error("Invalid User");
const userObject = EJSON.parse(
decryptedUserJSON
) as DATASQUIREL_LoggedInUser;
if (!userObject?.csrf_k)
throw new Error("Invalid User. Please check key");
response?.setHeader("Set-Cookie", [
`${authKeyName}=null;max-age=0`,
`${csrfName}=null;max-age=0`,
`${oneTimeCodeName}=null;max-age=0`,
]);
const csrf = userObject.csrf_k;
deleteAuthFile(csrf);
return {
success: true,
msg: "User Logged Out",
cookieNames,
};
} catch (/** @type {any} */ error: any) {
console.log("Logout Error:", error.message);
return {
success: false,
msg: "Logout Failed",
};
}
}
module.exports = logoutUser;