// @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} [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;