This commit is contained in:
Benjamin Toby
2025-07-10 11:48:20 +01:00
parent a131764e1e
commit 5ab079f687
71 changed files with 1186 additions and 1727 deletions
+30 -66
View File
@@ -1,39 +1,39 @@
import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiCreateUser from "../../functions/api/users/api-create-user";
import { AddUserFunctionReturn, UserDataPayload } from "../../types";
type Param = {
key?: string;
database: string;
payload: UserDataPayload;
encryptionKey?: string;
useLocal?: boolean;
verify?: boolean;
};
import {
AddUserParams,
APICreateUserFunctionParams,
APIResponseObject,
} from "../../types";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
import queryDSQLAPI from "../../functions/api/query-dsql-api";
/**
* # Add User to Database
*/
export default async function addUser({
key,
apiKey,
payload,
database,
encryptionKey,
useLocal,
verify,
}: Param): Promise<AddUserFunctionReturn> {
apiVersion = "v1",
dsqlUserID,
}: AddUserParams): Promise<APIResponseObject> {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const apiAddUserParams: APICreateUserFunctionParams = {
database,
encryptionKey,
payload,
verify,
dsqlUserID,
};
if (useLocal) {
return await apiCreateUser({
database,
encryptionKey,
payload,
verify,
});
return await apiCreateUser(apiAddUserParams);
}
/**
@@ -41,53 +41,17 @@ export default async function addUser({
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
const httpResponse = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "signup",
database,
encryptionKey,
});
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: ``,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
resolve(JSON.parse(str));
});
response.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
apiVersion,
}),
apiKey,
body: apiAddUserParams,
method: "POST",
});
return httpResponse as AddUserFunctionReturn;
return httpResponse;
}
+16 -7
View File
@@ -1,9 +1,10 @@
import grabHostNames from "../../utils/grab-host-names";
import apiDeleteUser from "../../functions/api/users/api-delete-user";
import { UpdateUserFunctionReturn } from "../../types";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
type Param = {
key?: string;
apiKey?: string;
database: string;
deletedUserId: string | number;
useLocal?: boolean;
@@ -14,7 +15,7 @@ type Param = {
* # Update User
*/
export default async function deleteUser({
key,
apiKey,
database,
deletedUserId,
useLocal,
@@ -41,20 +42,28 @@ export default async function deleteUser({
deletedUserId,
});
const finalAPIKey =
apiKey ||
process.env.DSQL_API_KEY ||
process.env.DSQL_FULL_ACCESS_API_KEY;
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
Authorization: finalAPIKey,
},
port,
hostname: host,
path: `/api/${apiVersion}/users/${database}/${deletedUserId}`,
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "delete",
database,
apiVersion,
userID: deletedUserId,
}),
},
/**
+35 -28
View File
@@ -2,28 +2,26 @@ import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiGetUser from "../../functions/api/users/api-get-user";
import { GetUserFunctionReturn } from "../../types";
type Param = {
key: string;
database: string;
userId: number;
fields?: string[];
useLocal?: boolean;
apiVersion?: string;
};
import {
APIGetUserFunctionParams,
GetUserFunctionReturn,
GetUserParams,
} from "../../types";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
/**
* # Get User
*/
export default async function getUser({
key,
apiKey,
userId,
database,
fields,
useLocal,
apiVersion = "v1",
}: Param): Promise<GetUserFunctionReturn> {
dbUserId,
selectAll,
}: GetUserParams): Promise<GetUserFunctionReturn> {
/**
* Initialize
*/
@@ -47,21 +45,19 @@ export default async function getUser({
const updatedFields =
fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
const reqPayload = JSON.stringify({
userId,
database,
fields: [...new Set(updatedFields)],
});
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const getUserParams: APIGetUserFunctionParams = {
userId,
fields: [...new Set(updatedFields)],
database,
dbUserId,
selectAll,
};
if (useLocal) {
return await apiGetUser({
userId,
fields: [...new Set(updatedFields)],
dbFullName: database,
});
return await apiGetUser(getUserParams);
}
/**
@@ -70,20 +66,31 @@ export default async function getUser({
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify(getUserParams);
const finalAPIKey =
apiKey ||
process.env.DSQL_API_KEY ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_READ_ONLY_API_KEY;
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,
Authorization: finalAPIKey,
},
port,
hostname: host,
path: `/api/${apiVersion}/users/${database}/${userId}`,
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "get",
database,
apiVersion,
userID: userId,
}),
},
/**
+47 -101
View File
@@ -1,24 +1,29 @@
import fs from "fs";
import path from "path";
import encrypt from "../../functions/dsql/encrypt";
import grabHostNames from "../../utils/grab-host-names";
import apiLoginUser from "../../functions/api/users/api-login";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
import {
APILoginFunctionReturn,
DSQL_DatabaseSchemaType,
APILoginFunctionParams,
APIResponseObject,
DATASQUIREL_LoggedInUser,
LoginUserParam,
PackageUserLoginRequestBody,
} from "../../types";
import debugLog from "../../utils/logging/debug-log";
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
import queryDSQLAPI from "../../functions/api/query-dsql-api";
function debugFn(log: any, label?: string) {
debugLog({ log, addTime: true, title: "loginUser", label });
}
/**
* # Login A user
*/
export default async function loginUser({
key,
export default async function loginUser<
T extends DATASQUIREL_LoggedInUser = DATASQUIREL_LoggedInUser
>({
apiKey,
payload,
database,
additionalFields,
@@ -29,7 +34,6 @@ export default async function loginUser({
email_login_code,
temp_code_field,
token,
user_id,
skipPassword,
apiUserID,
skipWriteAuthFile,
@@ -37,11 +41,9 @@ export default async function loginUser({
debug,
cleanupTokens,
secureCookie,
request,
useLocal,
}: LoginUserParam): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames;
apiVersion = "v1",
}: LoginUserParam): Promise<APIResponseObject<T | null>> {
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const defaultTempLoginFieldName = "temp_login_code";
@@ -56,10 +58,6 @@ export default async function loginUser({
const finalEncryptionSalt =
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
function debugFn(log: any, label?: string) {
debugLog({ log, addTime: true, title: "loginUser", label });
}
if (!finalEncryptionKey?.match(/.{8,}/)) {
console.log("Encryption key is invalid");
return {
@@ -78,104 +76,48 @@ export default async function loginUser({
};
}
/**
* Check required fields
*
* @description Check required fields
*/
// const isEmailValid = await validateEmail({ email: payload.email });
// if (!payload.email) {
// return {
// success: false,
// payload: null,
// msg: isEmailValid.message,
// };
// }
/**
* Initialize HTTP response variable
*/
let httpResponse: import("../../types").APILoginFunctionReturn = {
let httpResponse: APIResponseObject = {
success: false,
};
const apiLoginParams: APILoginFunctionParams = {
database,
email: payload.email,
username: payload.username,
password: payload.password,
skipPassword,
encryptionKey: finalEncryptionKey,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
dbUserId,
debug,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
if (useLocal) {
httpResponse = await apiLoginUser({
database,
email: payload.email,
username: payload.username,
password: payload.password,
skipPassword,
encryptionKey: finalEncryptionKey,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
dbUserId,
debug,
});
httpResponse = await apiLoginUser(apiLoginParams);
} else {
httpResponse = await new Promise((resolve, reject) => {
const reqPayload: PackageUserLoginRequestBody = {
encryptionKey: finalEncryptionKey,
payload,
httpResponse = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "login",
database,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
skipPassword: skipPassword,
dbUserId: dbUserId || 0,
};
const reqPayloadJSON = JSON.stringify(reqPayload);
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayloadJSON).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
}/login-user`,
},
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayloadJSON);
httpsRequest.end();
apiVersion,
}),
apiKey,
body: apiLoginParams,
method: "POST",
});
}
@@ -183,6 +125,10 @@ export default async function loginUser({
debugFn(httpResponse, "httpResponse");
}
/**
* # Send Response
*/
if (httpResponse?.success) {
let encryptedPayload = encrypt({
data: JSON.stringify(httpResponse.payload),
@@ -199,7 +145,7 @@ export default async function loginUser({
const cookieNames = getAuthCookieNames({
database,
userId: grabedHostNames.user_id,
userId: apiUserID,
});
if (httpResponse.csrf && !skipWriteAuthFile) {
+1 -1
View File
@@ -78,7 +78,7 @@ export default function logoutUser({
} else {
return undefined;
}
} catch (/** @type {any} */ error: any) {
} catch (error: any) {
console.log(
"Error getting decrypted User JSON to logout:",
error.message
-214
View File
@@ -1,214 +0,0 @@
import http from "http";
import userAuth from "./user-auth";
import grabHostNames from "../../utils/grab-host-names";
import { APILoginFunctionReturn } from "../../types";
import loginUser from "./login-user";
type Param = {
key?: string;
database?: string;
response?: http.ServerResponse;
request?: http.IncomingMessage;
level?: "deep" | "normal";
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
encryptedUserString?: string;
user_id?: string | number;
secureCookie?: boolean;
};
/**
* # Reauthorize User
*/
export default async function reauthUser({
key,
database,
response,
request,
level,
encryptionKey,
encryptionSalt,
additionalFields,
encryptedUserString,
user_id,
secureCookie,
}: Param): Promise<APILoginFunctionReturn> {
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
const grabedHostNames = grabHostNames();
// const { host, port, scheme } = grabedHostNames;
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey =
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt =
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const existingUser = userAuth({
database,
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
level,
request,
encryptedUserString,
});
if (!existingUser?.payload?.id) {
return {
success: false,
payload: null,
msg: "Cookie Credentials Invalid",
};
}
return await loginUser({
database: database || "",
payload: {
email: existingUser.payload.email,
},
additionalFields,
skipPassword: true,
response,
request,
user_id,
secureCookie,
key,
});
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* Check for local DB settings
*
* @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;
// 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) {}
// 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`,
// },
// /**
// * Callback Function
// *
// * @description https request callback
// */
// (response) => {
// var str = "";
// response.on("data", function (chunk) {
// str += chunk;
// });
// response.on("end", function () {
// resolve(JSON.parse(str));
// });
// response.on("error", (err) => {
// reject(err);
// });
// }
// );
// 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,
// });
// const cookieNames = getAuthCookieNames({
// database,
// userId: user_id || grabedHostNames.user_id,
// });
// httpResponse["cookieNames"] = cookieNames;
// httpResponse["key"] = String(encryptedPayload);
// 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}`,
// ]);
// if (httpResponse.csrf) {
// deleteAuthFile(String(existingUser.payload.csrf_k));
// writeAuthFile(
// httpResponse.csrf,
// JSON.stringify(httpResponse.payload)
// );
// }
// }
// return httpResponse;
}
@@ -0,0 +1,29 @@
import { ResetPasswordParams, UpdateUserFunctionReturn } from "../../types";
import queryDSQLAPI from "../../functions/api/query-dsql-api";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
import apiResetUserPassword from "../../functions/api/users/api-reset-user-password";
/**
* # Reset User Password
*/
export default async function resetPassword(
params: ResetPasswordParams
): Promise<UpdateUserFunctionReturn> {
if (params.useLocal) {
return await apiResetUserPassword(params);
}
const httpResponse = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "reset-password",
database: params.database,
apiVersion: params.apiVersion,
}),
apiKey: params.apiKey,
body: params,
method: "POST",
});
return httpResponse as UpdateUserFunctionReturn;
}
+38 -104
View File
@@ -1,32 +1,20 @@
import http from "http";
import grabHostNames from "../../utils/grab-host-names";
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
import { SendOneTimeCodeEmailResponse } from "../../types";
type Param = {
key?: string;
database: string;
email: string;
temp_code_field_name?: string;
response?: http.ServerResponse & { [s: string]: any };
mail_domain?: string;
mail_username?: string;
mail_password?: string;
mail_port?: number;
sender?: string;
user_id?: boolean;
extraCookies?: import("../../types").CookieObject[];
useLocal?: boolean;
};
import {
APIResponseObject,
APISendEmailCodeFunctionParams,
SendEmailCodeParams,
} from "../../types";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
import queryDSQLAPI from "../../functions/api/query-dsql-api";
/**
* # Send Email Code to a User
*/
export default async function sendEmailCode(
params: Param
): Promise<SendOneTimeCodeEmailResponse> {
params: SendEmailCodeParams
): Promise<APIResponseObject> {
const {
key,
apiKey,
email,
database,
temp_code_field_name,
@@ -35,15 +23,13 @@ export default async function sendEmailCode(
mail_username,
mail_port,
sender,
user_id,
response,
extraCookies,
useLocal,
apiVersion,
dbUserId,
} = params;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
@@ -51,87 +37,35 @@ export default async function sendEmailCode(
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
console.log("useLocal", useLocal);
const apiSendEmailCodeParams: APISendEmailCodeFunctionParams = {
database,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
response,
extraCookies,
dbUserId,
};
if (useLocal) {
return await apiSendEmailCode({
database,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
response,
extraCookies,
});
return await apiSendEmailCode(apiSendEmailCodeParams);
} else {
/**
* Make https request
*
* @description make a request to datasquirel.com
*
* @type {import("../../types").SendOneTimeCodeEmailResponse}
*/
const httpResponse: import("../../types").SendOneTimeCodeEmailResponse =
await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
email,
database,
email_login_field: emailLoginTempCodeFieldName,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
html: emailHtml,
});
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
}/send-email-code`,
},
/**
* Callback Function
*
* @description https request callback
*/
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
});
const httpResponse: APIResponseObject = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "send-email-code",
database,
apiVersion,
}),
apiKey,
body: apiSendEmailCodeParams,
method: "POST",
});
return httpResponse;
}
+33 -69
View File
@@ -1,36 +1,38 @@
import grabHostNames from "../../utils/grab-host-names";
import apiUpdateUser from "../../functions/api/users/api-update-user";
import { UpdateUserFunctionReturn } from "../../types";
type Param = {
key?: string;
database: string;
updatedUserId: string | number;
payload: { [s: string]: any };
user_id?: boolean;
useLocal?: boolean;
};
import {
ApiUpdateUserParams,
UpdateUserFunctionReturn,
UpdateUserParams,
} from "../../types";
import queryDSQLAPI from "../../functions/api/query-dsql-api";
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
import { DSQL_DATASQUIREL_USERS } from "../../types/dsql";
/**
* # Update User
*/
export default async function updateUser({
key,
export default async function updateUser<
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
[k: string]: any;
}
>({
payload,
database,
user_id,
updatedUserId,
useLocal,
}: Param): Promise<UpdateUserFunctionReturn> {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
apiKey,
apiVersion,
dbUserId,
}: UpdateUserParams<T>): Promise<UpdateUserFunctionReturn> {
const updateUserParams: ApiUpdateUserParams = {
payload: payload,
database,
updatedUserId,
dbUserId,
};
if (useLocal) {
return await apiUpdateUser({
payload: payload,
dbFullName: database,
updatedUserId,
});
return await apiUpdateUser(updateUserParams);
}
/**
@@ -38,54 +40,16 @@ export default async function updateUser({
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
const httpResponse = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "update",
database,
updatedUserId,
});
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
},
port,
hostname: host,
path: `/api/user/${
user_id || grabedHostNames.user_id
}/update-user`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
resolve(JSON.parse(str));
});
response.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
apiVersion,
}),
apiKey,
body: updateUserParams,
method: "POST",
});
return httpResponse as UpdateUserFunctionReturn;
@@ -1,50 +0,0 @@
import http from "http";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";
import decrypt from "../../functions/dsql/decrypt";
import EJSON from "../../utils/ejson";
import { SendOneTimeCodeEmailResponse } from "../../types";
type Param = {
request?: http.IncomingMessage & { [s: string]: any };
cookieString?: string;
email?: string;
};
/**
* # Verify the temp email code sent to the user's email address
*/
export default async function validateTempEmailCode({
request,
email,
cookieString,
}: Param): Promise<SendOneTimeCodeEmailResponse | null> {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload = EJSON.parse(encryptedPayload) as
| SendOneTimeCodeEmailResponse
| undefined;
if (payload?.email && !email) {
return payload;
}
if (payload?.email && payload.email === email) {
return payload;
}
return null;
} catch (error: any) {
console.log("validateTempEmailCode error:", error.message);
return null;
}
}
@@ -1,76 +0,0 @@
import http from "http";
import decrypt from "../../functions/dsql/decrypt";
import { DATASQUIREL_LoggedInUser } from "../../types";
type Param = {
token: string;
encryptionKey: string;
encryptionSalt: string;
level?: ("deep" | "normal") | null;
database: string;
};
/**
* Validate Token
* ======================================
* @description This Function takes in a encrypted token and returns a user object
*/
export default function validateToken({
token,
encryptionKey,
encryptionSalt,
}: Param): DATASQUIREL_LoggedInUser | null {
try {
/**
* Grab the payload
*
* @description Grab the payload
*/
const key = token;
/**
* Grab the payload
*
* @description Grab the payload
*/
let userPayload = decrypt({
encryptedString: key,
encryptionKey,
encryptionSalt,
});
/**
* Grab the payload
*
* @description Grab the payload
*/
if (!userPayload) {
return null;
}
/**
* Grab the payload
*
* @description Grab the payload
*/
let userObject = JSON.parse(userPayload);
if (!userObject.csrf_k) {
return null;
}
/**
* Return User Object
*
* @description Return User Object
*/
return userObject;
} catch (error) {
/**
* Return User Object
*
* @description Return User Object
*/
return null;
}
}