datasquirel/users/logout-user.js
Benjamin Toby 8a8257d17e Updates
2024-12-06 12:55:03 +01:00

90 lines
3.0 KiB
JavaScript

// @ts-check
const http = require("http");
const parseCookies = require("../utils/functions/parseCookies");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
/**
* Logout user
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {http.IncomingMessage} params.request - Http request object
* @param {http.ServerResponse} params.response - Http response object
* @param {string} [params.database] - Target database name(slug): optional => If you don't
* include this you will be logged out of all datasquirel websites instead of just the target
* database
*
* @returns {{success: boolean, payload: string}}
*/
function logoutUser({ request, response, database }) {
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
try {
const cookies = parseCookies({ request });
const cookiesKeys = Object.keys(cookies);
const keyNames = getAuthCookieNames();
const keyRegexp = new RegExp(keyNames.keyCookieName);
const csrfRegexp = new RegExp(keyNames.csrfCookieName);
const authKeyName = cookiesKeys.filter((cookieKey) =>
cookieKey.match(keyRegexp)
)[0];
const csrfName = cookiesKeys.filter((cookieKey) =>
cookieKey.match(csrfRegexp)
)[0];
if (authKeyName && csrfName) {
response.setHeader("Set-Cookie", [
`${authKeyName}=null;max-age=0`,
`${csrfName}=null;max-age=0`,
]);
} else {
const allKeys = cookiesKeys.filter((cookieKey) =>
cookieKey.match(/datasquirel_.*_auth_key/)
);
const allCsrfs = cookiesKeys.filter((cookieKey) =>
cookieKey.match(/datasquirel_.*_csrf/)
);
response.setHeader("Set-Cookie", [
...allKeys.map(
(key) =>
`${key}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`
),
...allCsrfs.map(
(csrf) =>
`${csrf}=null;samesite=strict;path=/;HttpOnly=true`
),
`dsqluid=null;samesite=strict;path=/;HttpOnly=true`,
]);
}
return {
success: true,
payload: "User Logged Out",
};
} catch (error) {
console.log(error);
return {
success: false,
payload: "Logout Failed",
};
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = logoutUser;