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;
}
}
+59 -2
View File
@@ -1,3 +1,60 @@
const user = {};
import addUser from "../../actions/users/add-user";
import getUser from "../../actions/users/get-user";
import loginUser from "../../actions/users/login-user";
import logoutUser from "../../actions/users/logout-user";
import resetPassword from "../../actions/users/reset-password";
import sendEmailCode from "../../actions/users/send-email-code";
import updateUser from "../../actions/users/update-user";
import userAuth from "../../actions/users/user-auth";
export default user;
import {
AddUserParams,
GetUserParams,
LoginUserParam,
ResetPasswordParams,
SendEmailCodeParams,
UpdateUserParams,
} from "../../types";
type Params = {
local?: boolean;
};
export default function user(params?: Params) {
return {
auth: {
login: params?.local
? async (_: LoginUserParam) => {
return await loginUser({ ..._, useLocal: true });
}
: loginUser,
get: params?.local
? async (_: GetUserParams) => {
return await getUser({ ..._, useLocal: true });
}
: getUser,
signup: params?.local
? async (_: AddUserParams) => {
return await addUser({ ..._, useLocal: true });
}
: addUser,
sendEmailCode: params?.local
? async (_: SendEmailCodeParams) => {
return await sendEmailCode({ ..._, useLocal: true });
}
: sendEmailCode,
update: params?.local
? async (_: UpdateUserParams) => {
return await updateUser({ ..._, useLocal: true });
}
: updateUser,
resetPassword: params?.local
? async (_: ResetPasswordParams) => {
return await resetPassword({ ..._, useLocal: true });
}
: resetPassword,
logout: logoutUser,
auth: userAuth,
},
};
}
@@ -1,5 +1,5 @@
import { grabPrimaryRequiredDbSchema } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
import { APICreateUserFunctionParams } from "../../../types";
import { APICreateUserFunctionParams, APIResponseObject } from "../../../types";
import addUsersTableToDb from "../../backend/addUsersTableToDb";
import addDbEntry from "../../backend/db/addDbEntry";
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
@@ -15,9 +15,9 @@ export default async function apiCreateUser({
encryptionKey,
payload,
database,
userId,
dsqlUserID,
verify,
}: APICreateUserFunctionParams) {
}: APICreateUserFunctionParams): Promise<APIResponseObject> {
const finalEncryptionKey =
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
@@ -39,8 +39,8 @@ export default async function apiCreateUser({
const targetDbSchema = grabPrimaryRequiredDbSchema({
dbSlug: database,
userId,
dbId: userId ? undefined : 1,
userId: dsqlUserID,
dbId: dsqlUserID ? undefined : 1,
});
if (!targetDbSchema?.id) {
@@ -77,23 +77,19 @@ export default async function apiCreateUser({
if (!fields?.[0]) {
const newTable = await addUsersTableToDb({
userId,
userId: dsqlUserID,
database: dbFullName,
payload: payload,
dbId: targetDbSchema.id,
});
fields = (await dbHandler({
query: fieldsQuery,
database: dbFullName,
})) as any[];
}
if (!fields?.[0]) {
return {
success: false,
msg: "Could not create users table",
};
if (!newTable) {
return {
success: false,
msg: "Could not create users table",
payload: null,
};
}
}
const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field);
@@ -104,7 +100,7 @@ export default async function apiCreateUser({
const key = Object.keys(payload)[i];
if (!fieldsTitles.includes(key)) {
await updateUsersTableSchema({
userId,
userId: dsqlUserID,
database: dbFullName,
newPayload: {
[key]: payload[key],
@@ -177,15 +173,13 @@ export default async function apiCreateUser({
})) as any[];
return {
success: true,
...addUser,
payload: newlyAddedUser[0],
};
} else {
return {
success: false,
...addUser,
msg: "Could not create user",
sqlResult: addUser,
payload: null,
};
}
}
@@ -2,6 +2,7 @@ import {
APIGetUserFunctionParams,
GetUserFunctionReturn,
} from "../../../types";
import grabDbFullName from "../../../utils/grab-db-full-name";
import dbHandler from "../../backend/dbHandler";
/**
@@ -9,19 +10,18 @@ import dbHandler from "../../backend/dbHandler";
*/
export default async function apiGetUser({
fields,
dbFullName,
database,
userId,
dbUserId,
selectAll,
}: APIGetUserFunctionParams): Promise<GetUserFunctionReturn> {
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
const finalDbName = grabDbFullName({ dbName: database, userId: dbUserId });
const query = `SELECT ${fields.join(
","
)} FROM ${finalDbName}.users WHERE id=?`;
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
const selectFields = selectAll ? "*" : fields?.[0] ? fields.join(",") : "*";
let foundUser = (await dbHandler({
query,
values: [API_USER_ID],
query: `SELECT ${selectFields} FROM users WHERE id=?`,
values: [userId],
database: finalDbName,
})) as any[];
@@ -1,6 +1,6 @@
import {
APILoginFunctionParams,
APILoginFunctionReturn,
APIResponseObject,
DATASQUIREL_LoggedInUser,
} from "../../../types";
import grabDbFullName from "../../../utils/grab-db-full-name";
@@ -24,7 +24,7 @@ export default async function apiLoginUser({
social,
dbUserId,
debug,
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
}: APILoginFunctionParams): Promise<APIResponseObject> {
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
if (!dbFullName) {
@@ -181,7 +181,7 @@ export default async function apiLoginUser({
console.log("apiLoginUser:Sending Response Object ...");
}
const resposeObject: APILoginFunctionReturn = {
const resposeObject: APIResponseObject = {
success: true,
msg: "Login Successful",
payload: userPayload,
@@ -0,0 +1,53 @@
import updateDbEntry from "../../backend/db/updateDbEntry";
import hashPassword from "../../dsql/hashPassword";
import dbHandler from "../../backend/dbHandler";
import { APIResponseObject, ResetPasswordParams } from "../../../types";
import grabDbFullName from "../../../utils/grab-db-full-name";
import { DSQL_DATASQUIREL_USERS } from "../../../types/dsql";
/**
* # Update API User Function
*/
export default async function apiResetUserPassword({
updatedUserId,
database,
dbUserId,
newPassword,
encryptionKey,
}: ResetPasswordParams): Promise<APIResponseObject> {
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
const existingUserValues = [updatedUserId];
const existingUser = (await dbHandler({
query: existingUserQuery,
values: existingUserValues,
database: dbFullName,
})) as any[];
if (!existingUser?.[0]) {
return {
success: false,
msg: "User not found",
};
}
const newPasswordHashed = hashPassword({
password: newPassword,
encryptionKey,
});
const updateUser = await updateDbEntry<DSQL_DATASQUIREL_USERS>({
dbFullName,
tableName: "users",
identifierColumnName: "id",
identifierValue: updatedUserId,
data: { password: newPasswordHashed },
});
return {
success: true,
payload: updateUser,
};
}
@@ -1,24 +1,14 @@
import dbHandler from "../../backend/dbHandler";
import nodemailer, { SendMailOptions } from "nodemailer";
import http from "http";
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
import encrypt from "../../dsql/encrypt";
import serializeCookies from "../../../utils/serialize-cookies";
import { CookieObject, SendOneTimeCodeEmailResponse } from "../../../types";
type Param = {
email: string;
database: string;
email_login_field?: string;
mail_domain?: string;
mail_port?: number;
sender?: string;
mail_username?: string;
mail_password?: string;
html: string;
response?: http.ServerResponse & { [s: string]: any };
extraCookies?: CookieObject[];
};
import {
APIResponseObject,
APISendEmailCodeFunctionParams,
CookieObject,
} from "../../../types";
import grabDbFullName from "../../../utils/grab-db-full-name";
/**
* # Send Email Login Code
@@ -35,22 +25,26 @@ export default async function apiSendEmailCode({
html,
response,
extraCookies,
}: Param): Promise<SendOneTimeCodeEmailResponse> {
dbUserId,
}: APISendEmailCodeFunctionParams): Promise<APIResponseObject> {
if (email?.match(/ /)) {
return {
success: false,
msg: "Invalid Email/Password format",
};
}
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
const createdAt = Date.now();
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
const foundUserValues = [email];
let foundUser = (await dbHandler({
query: foundUserQuery,
values: foundUserValues,
database,
database: dbFullName,
})) as any[];
if (!foundUser || !foundUser[0]) {
@@ -88,10 +82,11 @@ export default async function apiSendEmailCode({
let mailObject: SendMailOptions = {};
mailObject["from"] = `"Datasquirel SSO" <${
sender || "support@datasquirel.com"
}>`;
mailObject["sender"] = sender || "support@datasquirel.com";
const finalSender =
sender || process.env.DSQL_MAIL_EMAIL || "support@datasquirel.com";
mailObject["from"] = `"Datasquirel SSO" <${finalSender}>`;
mailObject["sender"] = finalSender;
mailObject["to"] = email;
mailObject["subject"] = "One Time Login Code";
mailObject["html"] = html.replace(/{{code}}/, tempCode);
@@ -100,23 +95,22 @@ export default async function apiSendEmailCode({
if (!info?.accepted) throw new Error("Mail not Sent!");
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
await dbHandler({
query: setTempCodeQuery,
values: setTempCodeValues,
database,
database: dbFullName,
});
const resObject: import("../../../types").SendOneTimeCodeEmailResponse =
{
success: true,
code: tempCode,
email: email,
createdAt,
msg: "Success",
};
const resObject: APIResponseObject = {
success: true,
code: tempCode,
email: email,
createdAt,
msg: "Success",
};
if (response) {
const cookieKeyNames = getAuthCookieNames();
@@ -1,28 +1,22 @@
// @ts-check
import updateDbEntry from "../../backend/db/updateDbEntry";
import encrypt from "../../dsql/encrypt";
import hashPassword from "../../dsql/hashPassword";
import dbHandler from "../../backend/dbHandler";
type Param = {
payload: { [s: string]: any };
dbFullName: string;
updatedUserId: string | number;
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
};
type Return = { success: boolean; payload?: any; msg?: string };
import { APIResponseObject, ApiUpdateUserParams } from "../../../types";
import grabDbFullName from "../../../utils/grab-db-full-name";
/**
* # Update API User Function
*/
export default async function apiUpdateUser({
payload,
dbFullName,
updatedUserId,
dbSchema,
}: Param): Promise<Return> {
database,
dbUserId,
}: ApiUpdateUserParams): Promise<APIResponseObject> {
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
const existingUserValues = [updatedUserId];
@@ -53,8 +47,7 @@ export default async function apiUpdateUser({
}
})();
/** @type {any} */
const finalData: any = {};
const finalData: { [s: string]: any } = {};
reqBodyKeys.forEach((key) => {
const targetFieldSchema = targetTableSchema?.fields?.find(
@@ -23,10 +23,8 @@ export default async function addUsersTableToDb({
database,
payload,
dbId,
}: Param): Promise<any> {
}: Param): Promise<boolean> {
try {
const dbFullName = database;
const userPreset = grabNewUsersTableSchema({ payload });
if (!userPreset) throw new Error("Couldn't Get User Preset!");
@@ -51,32 +49,13 @@ export default async function addUsersTableToDb({
writeUpdatedDbSchema({ dbSchema: targetDatabase, userId });
const targetDb = (await dbHandler({
query: `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
values: [userId, database],
})) as any[];
if (targetDb?.[0]) {
const newTableEntry = await addDbEntry({
dbFullName: "datasquirel",
tableName: "user_database_tables",
data: {
user_id: userId,
db_id: targetDb[0].id,
db_slug: targetDatabase.dbSlug,
table_name: "Users",
table_slug: "users",
},
});
}
const dbShellUpdate = await createDbFromSchema({
userId,
targetDatabase: dbFullName,
dbId,
});
return `Done!`;
} catch (/** @type {any} */ error: any) {
return dbShellUpdate;
} catch (error: any) {
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
serverError({
@@ -84,6 +63,7 @@ export default async function addUsersTableToDb({
message: error.message,
user: { id: userId },
});
return error.message;
return false;
}
}
@@ -20,12 +20,8 @@ export default function grabNewUsersTableSchema(params: {
})
: [];
console.log("supplementalFields", supplementalFields);
const allFields = [...userPreset.fields, ...supplementalFields];
console.log("allFields", allFields);
const finalFields = [
...defaultFields.slice(0, 2),
...allFields,
@@ -35,7 +31,7 @@ export default function grabNewUsersTableSchema(params: {
userPreset.fields = [...finalFields];
return userPreset;
} catch (/** @type {any} */ error: any) {
} catch (error: any) {
console.log(`grabNewUsersTableSchema.ts ERROR: ${error.message}`);
serverError({
+1 -1
View File
@@ -31,7 +31,7 @@ export default function decrypt({
keyLen,
algorithm,
bufferAllocSize,
} = grabKeys({ encryptionKey });
} = grabKeys({ encryptionKey, encryptionSalt });
if (!encrptKey?.match(/.{8,}/)) {
if (debug) console.log("Decrption key is invalid");
+1 -1
View File
@@ -29,7 +29,7 @@ export default function encrypt({
keyLen,
algorithm,
bufferAllocSize,
} = grabKeys({ encryptionKey });
} = grabKeys({ encryptionKey, encryptionSalt });
if (!encrptKey?.match(/.{8,}/)) {
console.log("Encryption key is invalid");
+138 -6
View File
@@ -226,7 +226,6 @@ export interface DSQL_MYSQL_user_databases_Type {
export interface PackageUserLoginRequestBody {
encryptionKey: string;
payload: any;
database: string;
additionalFields?: string[];
email_login?: boolean;
email_login_code?: string;
@@ -1139,7 +1138,7 @@ export type APICreateUserFunctionParams = {
encryptionKey?: string;
payload: any;
database: string;
userId?: string | number;
dsqlUserID?: string | number;
verify?: boolean;
};
@@ -1152,8 +1151,10 @@ export type APICreateUserFunction = (
*/
export type APIGetUserFunctionParams = {
fields: string[];
dbFullName: string;
database: string;
userId: string | number;
dbUserId?: string | number;
selectAll?: boolean;
};
/**
@@ -1613,6 +1614,14 @@ export type APIResponseObject<T extends any = any> = {
debug?: any;
batchPayload?: any[][] | null;
errorData?: any;
token?: string;
csrf?: string;
cookieNames?: any;
key?: string;
userId?: string | number;
code?: string;
createdAt?: number;
email?: string;
};
export const UserTypes = ["su", "admin"] as const;
@@ -1903,7 +1912,7 @@ export type DefaultEntryType = {
export const IndexTypes = ["regular", "full_text"] as const;
export type LoginUserParam = {
key?: string;
apiKey?: string;
database: string;
payload: {
email?: string;
@@ -1919,7 +1928,6 @@ export type LoginUserParam = {
email_login_code?: string;
temp_code_field?: string;
token?: boolean;
user_id?: string | number;
skipPassword?: boolean;
debug?: boolean;
skipWriteAuthFile?: boolean;
@@ -1928,6 +1936,7 @@ export type LoginUserParam = {
cleanupTokens?: boolean;
secureCookie?: boolean;
useLocal?: boolean;
apiVersion?: string;
};
export const UserSelectFields = [
@@ -2163,7 +2172,13 @@ export type SiteConfigMaxscale = {
admin_port: number;
};
export const APIParadigms = ["crud", "media", "sql", "schema"] as const;
export const APIParadigms = [
"crud",
"media",
"sql",
"schema",
"users",
] as const;
export const AppVersions = [
{
@@ -2319,3 +2334,120 @@ export type GrabUserResourceParams<T extends { [k: string]: any } = any> = {
isSuperUser?: boolean;
targetID?: string | number;
};
export const UserAPIParadigms = ["auth", "crud"] as const;
export const UserAPIAuthActions = [
"login",
"get",
"signup",
"update",
"logout",
"refresh",
"verify",
"send-verification",
"delete",
"send-email-code",
"reset-password",
] as const;
export type GrabUserAPIPathParams = {
apiVersion?: string;
paradigm?: (typeof UserAPIParadigms)[number];
action?: (typeof UserAPIAuthActions)[number];
database?: string;
userID?: string | number;
};
export type GetUserParams = {
apiKey?: string;
database: string;
userId: number | string;
fields?: string[];
useLocal?: boolean;
apiVersion?: string;
dbUserId?: string | number;
selectAll?: boolean;
};
export type AddUserParams = {
apiKey?: string;
database: string;
payload: UserDataPayload;
encryptionKey?: string;
useLocal?: boolean;
verify?: boolean;
apiVersion?: string;
dsqlUserID?: string | number;
};
export type APISendEmailCodeFunctionParams = {
email: string;
database: string;
email_login_field?: string;
mail_domain?: string;
mail_port?: number;
sender?: string;
mail_username?: string;
mail_password?: string;
/**
* HTML string with {{code}} placeholder for the code
*/
html: string;
response?: ServerResponse & { [s: string]: any };
extraCookies?: CookieObject[];
dbUserId?: string | number;
};
export type SendEmailCodeParams = {
apiKey?: string;
database: string;
email: string;
temp_code_field_name?: string;
response?: ServerResponse & { [s: string]: any };
mail_domain?: string;
mail_username?: string;
mail_password?: string;
mail_port?: number;
sender?: string;
extraCookies?: CookieObject[];
useLocal?: boolean;
apiVersion?: string;
dbUserId?: string | number;
};
export type UpdateUserParams<
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
[k: string]: any;
}
> = {
apiKey?: string;
database: string;
updatedUserId: string | number;
payload: T;
useLocal?: boolean;
apiVersion?: string;
dbUserId?: string | number;
};
export type ResetPasswordParams = {
apiKey?: string;
newPassword: string;
database: string;
updatedUserId: string | number;
useLocal?: boolean;
apiVersion?: string;
dbUserId?: string | number;
encryptionKey?: string;
};
export type ApiUpdateUserParams<
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
[k: string]: any;
}
> = {
payload: T;
database: string;
updatedUserId: string | number;
dbSchema?: DSQL_DatabaseSchemaType;
dbUserId?: string | number;
};
@@ -0,0 +1,31 @@
import { GrabUserAPIPathParams } from "../../../types";
export default function grabUserDSQLAPIPath({
apiVersion,
paradigm,
action,
database,
userID,
}: GrabUserAPIPathParams) {
const finalAPIVersion = process.env.DSQL_API_VERSION || apiVersion || "v1";
const finalParadigm = paradigm || "auth";
const finalAction = action || "login";
const finalDatabase = database || "datasquirel";
let finalPath = `/api/${finalAPIVersion}/users/${finalParadigm}/${finalDatabase}`;
switch (paradigm) {
case "auth":
finalPath += `/${finalAction}`;
if (userID) {
finalPath += `/${userID}`;
}
break;
default:
break;
}
return finalPath;
}