// @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} [params.request] - Request Object * @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, request, }) { /** * 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; /** @type {string | undefined} */ const decryptedUserJSON = (() => { try { if (request) { const cookiesObject = parseCookies({ request }); 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`, ]); 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;