datasquirel/users/logout-user.js
Benjamin Toby 7bd4b2fe65 Updates
2024-12-08 09:58:57 +01:00

79 lines
2.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");
/**
* Logout user
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} params.encryptedUserString - Encrypted User String
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
* @param {string} [params.database] - Target database name(slug): optional
* @param {string | number} [params.dsqlUserId]
*
* @returns {{success: boolean, payload: string, cookieNames?: any}}
*/
function logoutUser({ response, database, dsqlUserId, encryptedUserString }) {
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
try {
const decryptedUserJSON = decrypt({
encryptedString: encryptedUserString,
});
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");
const cookieNames = getAuthCookieNames({
database,
userId: dsqlUserId || process.env.DSQL_API_USER_ID,
});
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
response?.setHeader("Set-Cookie", [
`${authKeyName}=null;max-age=0`,
`${csrfName}=null;max-age=0`,
]);
const csrf = userObject.csrf_k;
deleteAuthFile(csrf);
return {
success: true,
payload: "User Logged Out",
cookieNames,
};
} catch (error) {
console.log(error);
return {
success: false,
payload: "Logout Failed",
};
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = logoutUser;