datasquirel/users/logout-user.js
Benjamin Toby d98deb06c5 Updates
2024-12-13 14:08:41 +01:00

109 lines
3.6 KiB
JavaScript

// @ts-check
const http = require("http");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const EJSON = require("../package-shared/utils/ejson");
const {
deleteAuthFile,
} = require("../package-shared/functions/backend/auth/write-auth-files");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
/**
* Logout user
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} [params.encryptedUserString] - Encrypted User String
* @param {http.IncomingMessage & Object<string, any>} [params.request] - Request Object
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
* @param {string} [params.cookieString]
* @param {string} [params.database] - Target database name(slug): optional
* @param {string | number} [params.dsqlUserId]
*
* @returns {{success: boolean, msg: string, cookieNames?: any}}
*/
function logoutUser({
response,
database,
dsqlUserId,
encryptedUserString,
request,
cookieString,
}) {
/**
* 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;
/** @type {string | undefined} */
const decryptedUserJSON = (() => {
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) {
console.log(
"Error getting decrypted User JSON to logout:",
error.message
);
return undefined;
}
})();
if (!decryptedUserJSON) throw new Error("Invalid User");
const userObject =
/** @type {import("../package-shared/types").DATASQUIREL_LoggedInUser | undefined} */ (
EJSON.parse(decryptedUserJSON)
);
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) {
console.log("Logout Error:", error.message);
return {
success: false,
msg: "Logout Failed",
};
}
}
module.exports = logoutUser;