This commit is contained in:
Benjamin Toby
2025-05-12 10:47:47 +01:00
parent 07c2186b98
commit 674af34355
9 changed files with 268 additions and 231 deletions
+123 -119
View File
@@ -1,18 +1,8 @@
import http from "http";
import fs from "fs";
import path from "path";
import encrypt from "../../functions/dsql/encrypt";
import userAuth from "./user-auth";
import grabHostNames from "../../utils/grab-host-names";
import apiReauthUser from "../../functions/api/users/api-reauth-user";
import {
writeAuthFile,
deleteAuthFile,
} from "../../functions/backend/auth/write-auth-files";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import { APILoginFunctionReturn } from "../../types";
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
import loginUser from "./login-user";
type Param = {
key?: string;
@@ -50,8 +40,8 @@ export default async function reauthUser({
* @description Check Encryption Keys
*/
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
// const { host, port, scheme } = grabedHostNames;
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey =
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
@@ -75,6 +65,20 @@ export default async function reauthUser({
};
}
return await loginUser({
database: database || "",
payload: {
email: existingUser.payload.email,
},
additionalFields,
skipPassword: true,
response,
request,
user_id,
secureCookie,
key,
});
/**
* Initialize HTTP response variable
*/
@@ -85,126 +89,126 @@ export default async function reauthUser({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
// process.env;
if (
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
global.DSQL_USE_LOCAL
) {
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
// if (
// DSQL_DB_HOST?.match(/./) &&
// DSQL_DB_USERNAME?.match(/./) &&
// DSQL_DB_PASSWORD?.match(/./) &&
// DSQL_DB_NAME?.match(/./) &&
// global.DSQL_USE_LOCAL
// ) {
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
try {
const localDbSchemaPath = path.resolve(
process.cwd(),
"dsql.schema.json"
);
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
// try {
// const localDbSchemaPath = path.resolve(
// process.cwd(),
// "dsql.schema.json"
// );
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
// } catch (error) {}
httpResponse = await apiReauthUser({
existingUser: existingUser.payload,
additionalFields,
});
} else {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
existingUser: existingUser.payload,
database,
additionalFields,
});
// httpResponse = await apiReauthUser({
// existingUser: existingUser.payload,
// additionalFields,
// });
// } else {
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// httpResponse = (await new Promise((resolve, reject) => {
// const reqPayload = JSON.stringify({
// existingUser: existingUser.payload,
// database,
// additionalFields,
// });
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${
user_id || grabedHostNames.user_id
}/reauth-user`,
},
// const httpsRequest = scheme.request(
// {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Content-Length": Buffer.from(reqPayload).length,
// Authorization:
// key ||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
// process.env.DSQL_API_KEY,
// },
// port,
// hostname: host,
// path: `/api/user/${
// user_id || grabedHostNames.user_id
// }/reauth-user`,
// },
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
// /**
// * Callback Function
// *
// * @description https request callback
// */
// (response) => {
// var str = "";
response.on("data", function (chunk) {
str += chunk;
});
// response.on("data", function (chunk) {
// str += chunk;
// });
response.on("end", function () {
resolve(JSON.parse(str));
});
// response.on("end", function () {
// resolve(JSON.parse(str));
// });
response.on("error", (err) => {
reject(err);
});
}
);
// response.on("error", (err) => {
// reject(err);
// });
// }
// );
httpsRequest.write(reqPayload);
httpsRequest.end();
})) as APILoginFunctionReturn;
}
// httpsRequest.write(reqPayload);
// httpsRequest.end();
// })) as APILoginFunctionReturn;
// }
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if (httpResponse?.success) {
let encryptedPayload = encrypt({
data: JSON.stringify(httpResponse.payload),
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
});
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// if (httpResponse?.success) {
// let encryptedPayload = encrypt({
// data: JSON.stringify(httpResponse.payload),
// encryptionKey: finalEncryptionKey,
// encryptionSalt: finalEncryptionSalt,
// });
const cookieNames = getAuthCookieNames({
database,
userId: user_id || grabedHostNames.user_id,
});
// const cookieNames = getAuthCookieNames({
// database,
// userId: user_id || grabedHostNames.user_id,
// });
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);
// httpResponse["cookieNames"] = cookieNames;
// httpResponse["key"] = String(encryptedPayload);
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
// const authKeyName = cookieNames.keyCookieName;
// const csrfName = cookieNames.csrfCookieName;
response?.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
secureCookie ? ";Secure=true" : ""
}`,
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
// response?.setHeader("Set-Cookie", [
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
// secureCookie ? ";Secure=true" : ""
// }`,
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
// ]);
if (httpResponse.csrf) {
deleteAuthFile(String(existingUser.payload.csrf_k));
writeAuthFile(
httpResponse.csrf,
JSON.stringify(httpResponse.payload)
);
}
}
// if (httpResponse.csrf) {
// deleteAuthFile(String(existingUser.payload.csrf_k));
// writeAuthFile(
// httpResponse.csrf,
// JSON.stringify(httpResponse.payload)
// );
// }
// }
return httpResponse;
// return httpResponse;
}