Updates
This commit is contained in:
@@ -17,5 +17,6 @@
|
||||
"onUpdate": "CURRENT_TIMESTAMP",
|
||||
"onUpdateLiteral": "CURRENT_TIMESTAMP",
|
||||
"onDelete": "CURRENT_TIMESTAMP",
|
||||
"onDeleteLiteral": "CURRENT_TIMESTAMP"
|
||||
"onDeleteLiteral": "CURRENT_TIMESTAMP",
|
||||
"encrypted": false
|
||||
}
|
||||
|
||||
@@ -33,8 +33,7 @@
|
||||
},
|
||||
{
|
||||
"fieldName": "password",
|
||||
"dataType": "VARCHAR(250)",
|
||||
"notNullValue": true
|
||||
"dataType": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldName": "image",
|
||||
|
||||
@@ -27,10 +27,9 @@ module.exports = async function apiGet({
|
||||
}) {
|
||||
if (
|
||||
typeof query == "string" &&
|
||||
(query.match(/^alter|^delete|information_schema|databases|^create/i) ||
|
||||
!query.match(/^select/i))
|
||||
query.match(/^alter|^delete|information_schema|databases|^create/i)
|
||||
) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const { hashPassword } = require("../../backend/passwordHash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -44,7 +44,9 @@ module.exports = async function facebookLogin({ usertype, body }) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let socialHashedPassword = hashPassword(body.facebookUserId);
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
|
||||
@@ -13,10 +13,10 @@ const fs = require("fs");
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
|
||||
const { hashPassword } = require("../../backend/passwordHash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const { ServerResponse } = require("http");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -81,7 +81,9 @@ module.exports = async function googleLogin({
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
|
||||
let socialHashedPassword = hashPassword(payload.at_hash || "");
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
@@ -1,19 +1,2 @@
|
||||
declare namespace _exports {
|
||||
export { FunctionReturn };
|
||||
}
|
||||
declare const _exports: import("../../../types").HandleSocialDbFunction;
|
||||
export = _exports;
|
||||
type FunctionReturn = {
|
||||
/**
|
||||
* - Did the operation complete successfully or not?
|
||||
*/
|
||||
success: boolean;
|
||||
/**
|
||||
* - User payload object: or "null"
|
||||
*/
|
||||
user: {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
@@ -1,43 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const { ServerResponse } = require("http");
|
||||
const path = require("path");
|
||||
const addMariadbUser = require("../../backend/addMariadbUser");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the operation complete successfully or not?
|
||||
* @property {{
|
||||
* id: number,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* }|null} user - User payload object: or "null"
|
||||
*/
|
||||
const loginSocialUser = require("./loginSocialUser");
|
||||
|
||||
/**
|
||||
* @type {import("../../../types").HandleSocialDbFunction}
|
||||
@@ -48,43 +18,29 @@ module.exports = async function handleSocialDb({
|
||||
email,
|
||||
social_platform,
|
||||
payload,
|
||||
res,
|
||||
invitation,
|
||||
supEmail,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialIdUserValues = [
|
||||
social_id.toString(),
|
||||
social_platform,
|
||||
];
|
||||
|
||||
let existingSocialIdUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
existingSocialIdUserQuery,
|
||||
existingSocialIdUserValues
|
||||
)
|
||||
: await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingSocialIdUserQuery,
|
||||
queryValuesArray: existingSocialIdUserValues,
|
||||
});
|
||||
let existingSocialIdUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingSocialIdUserQuery,
|
||||
queryValuesArray: existingSocialIdUserValues,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (existingSocialIdUser && existingSocialIdUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingSocialIdUser[0],
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
@@ -92,63 +48,46 @@ module.exports = async function handleSocialDb({
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
social_id,
|
||||
social_platform,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`;
|
||||
|
||||
let existingEmailOnly = useLocal
|
||||
? await LOCAL_DB_HANDLER(existingEmailOnlyQuery)
|
||||
: await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingEmailOnlyQuery,
|
||||
});
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingEmailOnlyQuery,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (existingEmailOnly && existingEmailOnly[0]) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
payload: null,
|
||||
msg: "This Email is already taken",
|
||||
alert: true,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`;
|
||||
const foundUserQueryValues = [finalEmail, social_platform, social_id];
|
||||
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`;
|
||||
|
||||
const foundUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(foundUserQuery)
|
||||
: await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
});
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserQueryValues,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: payload,
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
@@ -156,10 +95,6 @@ module.exports = async function handleSocialDb({
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const socialHashedPassword = encrypt({
|
||||
data: social_id.toString(),
|
||||
});
|
||||
@@ -200,24 +135,19 @@ module.exports = async function handleSocialDb({
|
||||
|
||||
const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`;
|
||||
|
||||
const newUserQueried = useLocal
|
||||
? await LOCAL_DB_HANDLER(newUserQueriedQuery)
|
||||
: await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: newUserQueriedQuery,
|
||||
});
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: newUserQueriedQuery,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (supEmail && database?.match(/^datasquirel$/)) {
|
||||
/**
|
||||
* Send email Verification
|
||||
@@ -246,15 +176,15 @@ module.exports = async function handleSocialDb({
|
||||
}).then((mail) => {});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return null;
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,23 +210,14 @@ module.exports = async function handleSocialDb({
|
||||
);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return await loginSocialUser({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} else {
|
||||
console.log(
|
||||
"Social User Failed to insert in 'handleSocialDb.js' backend function =>",
|
||||
@@ -305,15 +226,10 @@ module.exports = async function handleSocialDb({
|
||||
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function => ",
|
||||
newUser: newUser,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
"ERROR in 'handleSocialDb.js' backend function =>",
|
||||
@@ -322,126 +238,8 @@ module.exports = async function handleSocialDb({
|
||||
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
error: error.message,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - function parameters inside an object
|
||||
* @param {{
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* email: string,
|
||||
* social_id: string|number,
|
||||
* }} params.user - user object
|
||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
||||
* @param {ServerResponse} [params.res] - Https response object
|
||||
* @param {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {object} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
async function loginSocialUser({
|
||||
user,
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`;
|
||||
|
||||
const foundUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(foundUserQuery)
|
||||
: await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
});
|
||||
|
||||
if (!foundUser?.[0])
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
};
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {any} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
type: foundUser[0].type || "",
|
||||
stripe_id: foundUser[0].stripe_id || "",
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
||||
Object.keys(additionalFields).forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
let encryptedPayload = encrypt({ data: JSON.stringify(userPayload) });
|
||||
|
||||
const { keyCookieName, csrfCookieName } = getAuthCookieNames();
|
||||
|
||||
if (res?.setHeader) {
|
||||
res.setHeader("Set-Cookie", [
|
||||
`${keyCookieName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfCookieName}=${csrfKey};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (invitation && (!database || database?.match(/^datasquirel$/))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: userPayload,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export = loginSocialUser;
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - function parameters inside an object
|
||||
* @param {{
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* email: string,
|
||||
* social_id: string|number,
|
||||
* }} params.user - user object
|
||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
||||
* @param {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
declare function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: {
|
||||
user: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
social_id: string | number;
|
||||
};
|
||||
social_platform: string;
|
||||
invitation?: any;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
||||
@@ -0,0 +1,104 @@
|
||||
// @ts-check
|
||||
|
||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
||||
const { ServerResponse } = require("http");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - function parameters inside an object
|
||||
* @param {{
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* email: string,
|
||||
* social_id: string|number,
|
||||
* }} params.user - user object
|
||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
||||
* @param {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
async function loginSocialUser({
|
||||
user,
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!foundUser?.[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields?.[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
if (invitation && (!database || database?.match(/^datasquirel$/))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = loginSocialUser;
|
||||
@@ -1,8 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const updateUsersTableSchema = require("../../backend/updateUsersTableSchema");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
@@ -42,27 +42,30 @@ module.exports = async function apiCreateUser({
|
||||
|
||||
payload.password = hashedPassword;
|
||||
|
||||
let fields = useLocal
|
||||
? await LOCAL_DB_HANDLER(`SHOW COLUMNS FROM users`)
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
const fieldsQuery = `SHOW COLUMNS FROM users`;
|
||||
|
||||
if (!fields) {
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!fields?.[0]) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(userId),
|
||||
database: database,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
payload: payload,
|
||||
});
|
||||
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
|
||||
if (!fields) {
|
||||
if (!fields?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
@@ -78,8 +81,13 @@ module.exports = async function apiCreateUser({
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
invalidField = key;
|
||||
break;
|
||||
await updateUsersTableSchema({
|
||||
userId: Number(userId),
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,14 +98,18 @@ module.exports = async function apiCreateUser({
|
||||
};
|
||||
}
|
||||
|
||||
const existingUserQuery = `SELECT * FROM users WHERE email = ?${
|
||||
payload.username ? " OR username = ?" : ""
|
||||
}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?${
|
||||
payload.username ? " OR username = ?" : ""
|
||||
}`,
|
||||
queryValuesArray: payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email],
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (existingUser?.[0]) {
|
||||
@@ -121,9 +133,12 @@ module.exports = async function apiCreateUser({
|
||||
});
|
||||
|
||||
if (addUser?.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`;
|
||||
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
declare function _exports({ dbFullName, deletedUserId, useLocal, }: {
|
||||
dbFullName: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
result?: any;
|
||||
msg?: string;
|
||||
}>;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,52 @@
|
||||
// @ts-check
|
||||
|
||||
const deleteDbEntry = require("../../backend/db/deleteDbEntry");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.deletedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, result?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiDeleteUser({
|
||||
dbFullName,
|
||||
deletedUserId,
|
||||
useLocal,
|
||||
}) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!existingUser?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
|
||||
const deleteUser = await deleteDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
// @ts-check
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/** @type {import("../../../types").APIGetUserFunction} */
|
||||
@@ -12,13 +11,12 @@ module.exports = async function apiGetUser({
|
||||
}) {
|
||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||
|
||||
let foundUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(query, [userId])
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const { writeAuthFile } = require("../../backend/auth/write-auth-files");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
@@ -50,16 +51,12 @@ module.exports = async function apiLoginUser({
|
||||
})
|
||||
: null;
|
||||
|
||||
let foundUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
`SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
[email, username]
|
||||
)
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
@@ -107,16 +104,12 @@ module.exports = async function apiLoginUser({
|
||||
}
|
||||
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
`UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`,
|
||||
["", email, username]
|
||||
)
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: ["", email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: ["", email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
|
||||
let csrfKey =
|
||||
@@ -144,6 +137,7 @@ module.exports = async function apiLoginUser({
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
@@ -152,6 +146,7 @@ module.exports = async function apiLoginUser({
|
||||
userPayload
|
||||
),
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
|
||||
if (
|
||||
|
||||
+2
-3
@@ -1,10 +1,9 @@
|
||||
declare function _exports({ existingUser, database, userId, additionalFields, useLocal, }: {
|
||||
declare function _exports({ existingUser, database, additionalFields, useLocal, }: {
|
||||
existingUser: {
|
||||
[x: string]: any;
|
||||
};
|
||||
database: string;
|
||||
userId?: string | number;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").ApiReauthUserReturn>;
|
||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
||||
export = _exports;
|
||||
|
||||
@@ -9,16 +9,14 @@ const nodemailer = require("nodemailer");
|
||||
* @param {object} param
|
||||
* @param {Object<string, any>} param.existingUser
|
||||
* @param {string} param.database
|
||||
* @param {string | number} [param.userId]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {boolean} [param.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").ApiReauthUserReturn>}
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
module.exports = async function apiReauthUser({
|
||||
existingUser,
|
||||
database,
|
||||
userId,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
@@ -55,7 +53,7 @@ module.exports = async function apiReauthUser({
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {Object<string, string | number | boolean>} */
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
@@ -94,6 +92,6 @@ module.exports = async function apiReauthUser({
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -47,13 +47,12 @@ module.exports = async function apiSendEmailCode({
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
|
||||
let foundUser = useLocal
|
||||
? await LOCAL_DB_HANDLER(foundUserQuery, foundUserValues)
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
});
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -105,13 +104,12 @@ module.exports = async function apiSendEmailCode({
|
||||
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${Date.now()}`, email];
|
||||
|
||||
let setTempCode = useLocal
|
||||
? await LOCAL_DB_HANDLER(setTempCodeQuery, setTempCodeValues)
|
||||
: await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database: database,
|
||||
});
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database: database,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+6
-5
@@ -1,13 +1,14 @@
|
||||
declare function _exports({ payload, dbFullName, useLocal, }: {
|
||||
declare function _exports({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: {
|
||||
payload: {
|
||||
id: string | number;
|
||||
} & {
|
||||
[x: string]: (string | number | null | undefined);
|
||||
[x: string]: any;
|
||||
};
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
payload: any;
|
||||
payload?: any;
|
||||
msg?: string;
|
||||
}>;
|
||||
export = _exports;
|
||||
|
||||
@@ -1,33 +1,83 @@
|
||||
// @ts-check
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {{ id: string | number } & Object<string, (string | number | null | undefined)>} params.payload
|
||||
* @param {Object<string, any>} params.payload
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.updatedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, payload: any }>}
|
||||
* @returns {Promise<{ success: boolean, payload?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiUpdateUser({
|
||||
payload,
|
||||
dbFullName,
|
||||
updatedUserId,
|
||||
useLocal,
|
||||
dbSchema,
|
||||
}) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!existingUser?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
|
||||
const targetTableSchema = (() => {
|
||||
try {
|
||||
const targetDatabaseSchema = dbSchema?.tables?.find(
|
||||
(tbl) => tbl.tableName == "users"
|
||||
);
|
||||
return targetDatabaseSchema;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
if (key?.match(/^date_|^id$/)) return;
|
||||
finalData[key] = payload[key];
|
||||
const targetFieldSchema = targetTableSchema?.fields?.find(
|
||||
(field) => field.fieldName == key
|
||||
);
|
||||
|
||||
if (key?.match(/^date_|^id$|^uuid$/)) return;
|
||||
let value = payload[key];
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt({ data: value });
|
||||
}
|
||||
|
||||
finalData[key] = value;
|
||||
});
|
||||
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = hashPassword({ password: finalData.password });
|
||||
}
|
||||
|
||||
return finalData;
|
||||
})();
|
||||
|
||||
@@ -37,7 +87,7 @@ module.exports = async function apiUpdateUser({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: payload.id,
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
@@ -3,9 +3,7 @@ declare function _exports({ code, clientId, clientSecret, database, additionalFi
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
database?: string;
|
||||
additionalFields?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
additionalFields?: string[];
|
||||
res?: any;
|
||||
email?: string;
|
||||
userId?: string | number;
|
||||
|
||||
@@ -11,7 +11,7 @@ const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpa
|
||||
* @param {string} [param.clientId]
|
||||
* @param {string} [param.clientSecret]
|
||||
* @param {string} [param.database]
|
||||
* @param {Object<string, any>} [param.additionalFields]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {any} [param.res]
|
||||
* @param {string} [param.email]
|
||||
* @param {string | number} [param.userId]
|
||||
@@ -84,19 +84,11 @@ module.exports = async function apiGithubLogin({
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
|
||||
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
||||
Object.keys(additionalFields).forEach((key) => {
|
||||
// @ts-ignore
|
||||
payload[key] = additionalFields[key];
|
||||
});
|
||||
}
|
||||
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
social_platform: "github",
|
||||
res: res,
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
@@ -106,5 +98,5 @@ module.exports = async function apiGithubLogin({
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { success: true, ...loggedInGithubUser, dsqlUserId: userId };
|
||||
return { ...loggedInGithubUser };
|
||||
};
|
||||
|
||||
@@ -1,88 +1,96 @@
|
||||
// @ts-check
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
const https = require("https");
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const EJSON = require("../../../../utils/ejson");
|
||||
|
||||
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
||||
module.exports = async function apiGoogleLogin({
|
||||
clientId,
|
||||
token,
|
||||
database,
|
||||
userId,
|
||||
additionalFields,
|
||||
res,
|
||||
}) {
|
||||
const client = new OAuth2Client(clientId);
|
||||
try {
|
||||
/** @type {import("../../../../types").GoogleOauth2User | undefined} */
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request(
|
||||
{
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(/** @type {any} */ (EJSON.parse(data)));
|
||||
});
|
||||
}
|
||||
)
|
||||
.end();
|
||||
});
|
||||
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: token,
|
||||
audience: clientId,
|
||||
});
|
||||
if (!gUser?.email_verified) throw new Error("No Google User.");
|
||||
|
||||
if (!ticket?.getPayload()?.email_verified) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!database || typeof database != "string" || database?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: undefined,
|
||||
msg: "Please provide a database slug(database name in lowercase with no spaces)",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
|
||||
/** @type {Object<string, any>} */
|
||||
const payloadObject = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
social_id: sub,
|
||||
social_platform: "google",
|
||||
image: picture,
|
||||
image_thumbnail: picture,
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
}
|
||||
|
||||
const payload = ticket.getPayload();
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
social_id: sub,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
if (!payload) throw new Error("No Payload");
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return { ...loggedInGoogleUser };
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||
|
||||
if (!database || typeof database != "string" || database?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: undefined,
|
||||
msg: "Please provide a database slug(database name in lowercase with no spaces)",
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const targetDbName = `datasquirel_user_${userId}_${database}`;
|
||||
|
||||
const { given_name, family_name, email, sub, picture, email_verified } =
|
||||
payload;
|
||||
|
||||
/** @type {Object<string, any>} */
|
||||
const payloadObject = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
social_id: sub,
|
||||
social_platform: "google",
|
||||
image: picture,
|
||||
image_thumbnail: picture,
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
|
||||
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
||||
Object.keys(additionalFields).forEach((key) => {
|
||||
payloadObject[key] = additionalFields[key];
|
||||
});
|
||||
}
|
||||
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
res,
|
||||
database: targetDbName,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
social_id: sub,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { success: true, ...loggedInGoogleUser, dsqlUserId: userId };
|
||||
};
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
declare function _exports({ query, user }: {
|
||||
declare function _exports({ query, user, useLocal }: {
|
||||
query: {
|
||||
invite: number;
|
||||
database_access: string;
|
||||
priviledge: string;
|
||||
email: string;
|
||||
};
|
||||
user: import("../../types").UserType;
|
||||
useLocal?: boolean;
|
||||
user: import("../../types").DATASQUIREL_LoggedInUser;
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -3,13 +3,7 @@
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
@@ -27,32 +21,23 @@ const addDbEntry = require("./db/addDbEntry");
|
||||
* @param {string} params.query.priviledge - String containing databases priviledges
|
||||
* @param {string} params.query.email - Inviting user email address
|
||||
*
|
||||
* @param {import("../../types").UserType} params.user - invited user object
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../types").DATASQUIREL_LoggedInUser} params.user - invited user object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/ // @ts-ignore
|
||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
|
||||
const lastInviteTimeArray = await DB_HANDLER(
|
||||
`SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
|
||||
// if (lastInviteTimeArray && lastInviteTimeArray[0]?.date_created_code) {
|
||||
// const timeSinceLastInvite = Date.now() - parseInt(lastInviteTimeArray[0].date_created_code);
|
||||
// if (timeSinceLastInvite > 21600000) {
|
||||
// throw new Error("Invitation expired");
|
||||
// }
|
||||
// } else if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
// throw new Error("No Invitation Found");
|
||||
// }
|
||||
const lastInviteTimeArray = await finalDbHandler(
|
||||
lastInviteTimeQuery,
|
||||
lastInviteTimeValues
|
||||
);
|
||||
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
@@ -62,14 +47,16 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const invitingUserDb = await DB_HANDLER(
|
||||
`SELECT first_name,last_name,email FROM users WHERE id=?`,
|
||||
[invite]
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
|
||||
const invitingUserDb = await finalDbHandler(
|
||||
invitingUserDbQuery,
|
||||
invitingUserDbValues
|
||||
);
|
||||
|
||||
if (invitingUserDb?.[0]) {
|
||||
const existingUserUser = await DB_HANDLER(
|
||||
const existingUserUser = await finalDbHandler(
|
||||
`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`,
|
||||
[invite, user.id, email]
|
||||
);
|
||||
@@ -77,25 +64,6 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
if (existingUserUser?.[0]) {
|
||||
console.log("User already added");
|
||||
} else {
|
||||
// const newUserUser = await DB_HANDLER(
|
||||
// `INSERT IGNORE INTO user_users
|
||||
// (user_id, invited_user_id, database_access, first_name, last_name, phone, email, username, user_type, user_priviledge)
|
||||
// VALUES
|
||||
// (?,?,?,?,?,?,?,?,?,?)
|
||||
// )`,
|
||||
// [
|
||||
// invite,
|
||||
// user.id,
|
||||
// database_access,
|
||||
// user.first_name,
|
||||
// user.last_name,
|
||||
// user.phone,
|
||||
// user.email,
|
||||
// user.username,
|
||||
// "admin",
|
||||
// priviledge,
|
||||
// ]
|
||||
// );
|
||||
addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
@@ -113,20 +81,19 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const dbTableData = await DB_HANDLER(
|
||||
const dbTableData = await finalDbHandler(
|
||||
`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
// @ts-ignore
|
||||
const clearEntries = await DB_HANDLER(
|
||||
const clearEntries = await finalDbHandler(
|
||||
`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`,
|
||||
[invite, user.id]
|
||||
);
|
||||
@@ -154,17 +121,13 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const inviteAccepted = await DB_HANDLER(
|
||||
const inviteAccepted = await finalDbHandler(
|
||||
`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
+4
-1
@@ -1,6 +1,9 @@
|
||||
declare function _exports({ userId, database, useLocal, }: {
|
||||
declare function _exports({ userId, database, useLocal, payload, }: {
|
||||
userId: number;
|
||||
database: string;
|
||||
useLocal?: boolean;
|
||||
payload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -10,6 +10,7 @@ const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const grabNewUsersTableSchema = require("./grabNewUsersTableSchema");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
@@ -18,6 +19,7 @@ const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {Object<string, any>} [params.payload] - payload object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
@@ -25,39 +27,30 @@ module.exports = async function addUsersTableToDb({
|
||||
userId,
|
||||
database,
|
||||
useLocal,
|
||||
payload,
|
||||
}) {
|
||||
/**
|
||||
* Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
const dbFullName = `datasquirel_user_${userId}_${database}`;
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/
|
||||
const dbFullName = database;
|
||||
|
||||
const userPreset = grabNewUsersTableSchema({ payload });
|
||||
if (!userPreset) throw new Error("Couldn't Get User Preset!");
|
||||
|
||||
const userSchemaData = grabUserSchemaData({ userId });
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabase = userSchemaData.filter(
|
||||
(db) => db.dbSlug === database
|
||||
)[0];
|
||||
let targetDatabase = userSchemaData.find(
|
||||
(db) => db.dbFullName === database
|
||||
);
|
||||
|
||||
let existingTableIndex;
|
||||
// @ts-ignore
|
||||
let existingTable = targetDatabase.tables.filter((table, index) => {
|
||||
if (table.tableName === "users") {
|
||||
existingTableIndex = index;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
|
||||
if (existingTable && existingTable[0] && existingTableIndex) {
|
||||
let existingTableIndex = targetDatabase?.tables.findIndex(
|
||||
(table) => table.tableName === "users"
|
||||
);
|
||||
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
} else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
@@ -65,6 +58,7 @@ module.exports = async function addUsersTableToDb({
|
||||
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
/** @type {any[] | null} */
|
||||
const targetDb = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
@@ -75,14 +69,14 @@ module.exports = async function addUsersTableToDb({
|
||||
[userId, database]
|
||||
);
|
||||
|
||||
if (targetDb && targetDb[0]) {
|
||||
if (targetDb?.[0]) {
|
||||
const newTableEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: database,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
@@ -97,6 +91,8 @@ module.exports = async function addUsersTableToDb({
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export function grabAuthDirs(): {
|
||||
root: string;
|
||||
auth: string;
|
||||
};
|
||||
export function initAuthFiles(): boolean;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
* @param {string} name
|
||||
* @param {string} data
|
||||
*/
|
||||
export function writeAuthFile(name: string, data: string): boolean;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function getAuthFile(name: string): string;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function deleteAuthFile(name: string): void;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function checkAuthFile(name: string): boolean;
|
||||
@@ -0,0 +1,90 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const grabAuthDirs = () => {
|
||||
const ROOT_DIR = path.resolve(process.cwd(), "./.tmp");
|
||||
const AUTH_DIR = path.join(ROOT_DIR, "logins");
|
||||
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
|
||||
const initAuthFiles = () => {
|
||||
try {
|
||||
const authDirs = grabAuthDirs();
|
||||
|
||||
if (!fs.existsSync(authDirs.root))
|
||||
fs.mkdirSync(authDirs.root, { recursive: true });
|
||||
if (!fs.existsSync(authDirs.auth))
|
||||
fs.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Write Auth Files
|
||||
* @param {string} name
|
||||
* @param {string} data
|
||||
*/
|
||||
const writeAuthFile = (name, data) => {
|
||||
initAuthFiles();
|
||||
try {
|
||||
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error writing Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Get Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
try {
|
||||
const authFilePath = path.join(grabAuthDirs().auth, name);
|
||||
return fs.readFileSync(authFilePath, "utf-8");
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
try {
|
||||
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
try {
|
||||
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error checking Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
exports.getAuthFile = getAuthFile;
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
@@ -1,4 +1,7 @@
|
||||
declare function _exports(): {
|
||||
declare function _exports(params?: {
|
||||
database?: string;
|
||||
userId?: string | number;
|
||||
}): {
|
||||
keyCookieName: string;
|
||||
csrfCookieName: string;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
module.exports = function getAuthCookieNames() {
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {string} [params.database]
|
||||
* @param {string | number} [params.userId]
|
||||
*
|
||||
* @returns {{ keyCookieName: string, csrfCookieName: string }}
|
||||
*/
|
||||
module.exports = function getAuthCookieNames(params) {
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
|
||||
const keyCookieName = cookiesPrefix + cookiesKeyName;
|
||||
const csrfCookieName = cookiesPrefix + cookiesCSRFName;
|
||||
let keyCookieName = cookiesPrefix;
|
||||
if (params?.userId) keyCookieName += `user_${params.userId}_`;
|
||||
if (params?.database) keyCookieName += `${params.database}_`;
|
||||
keyCookieName += cookiesKeyName;
|
||||
|
||||
let csrfCookieName = cookiesPrefix;
|
||||
if (params?.userId) csrfCookieName += `user_${params.userId}_`;
|
||||
if (params?.database) csrfCookieName += `${params.database}_`;
|
||||
csrfCookieName += cookiesCSRFName;
|
||||
|
||||
return {
|
||||
keyCookieName,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
declare function _exports(params?: {
|
||||
payload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): import("../../types").DSQL_TableSchemaType | null;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,54 @@
|
||||
// @ts-check
|
||||
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {Object<string,any>} [params.payload] - fields to add to the table
|
||||
*
|
||||
* @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabNewUsersTableSchema(params) {
|
||||
try {
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const defaultFields = require("../../data/defaultFields.json");
|
||||
|
||||
const supplementalFields = params?.payload
|
||||
? grabSchemaFieldsFromData({
|
||||
data: params?.payload,
|
||||
excludeData: defaultFields,
|
||||
excludeFields: userPreset.fields,
|
||||
})
|
||||
: [];
|
||||
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
|
||||
console.log("allFields", allFields);
|
||||
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
...defaultFields.slice(2),
|
||||
];
|
||||
|
||||
userPreset.fields = [...finalFields];
|
||||
|
||||
return userPreset;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabNewUsersTableSchema",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
declare function _exports({ data, fields, excludeData, excludeFields, }: {
|
||||
data?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
fields?: string[];
|
||||
excludeData?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
excludeFields?: import("../../types").DSQL_FieldSchemaType[];
|
||||
}): import("../../types").DSQL_FieldSchemaType[];
|
||||
export = _exports;
|
||||
@@ -0,0 +1,94 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {Object<string,any>} [params.data]
|
||||
* @param {string[]} [params.fields]
|
||||
* @param {Object<string,any>} [params.excludeData]
|
||||
* @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields]
|
||||
*
|
||||
* @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabSchemaFieldsFromData({
|
||||
data,
|
||||
fields,
|
||||
excludeData,
|
||||
excludeFields,
|
||||
}) {
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const finalFields = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
let filteredFields = [];
|
||||
|
||||
if (data && Object.keys(data)?.[0]) {
|
||||
filteredFields = Object.keys(data);
|
||||
}
|
||||
|
||||
if (fields) {
|
||||
filteredFields = [...filteredFields, ...fields];
|
||||
filteredFields = [...new Set(filteredFields)];
|
||||
}
|
||||
|
||||
filteredFields = filteredFields
|
||||
.filter(
|
||||
(fld) => !excludeData || !Object.keys(excludeData).includes(fld)
|
||||
)
|
||||
.filter(
|
||||
(fld) =>
|
||||
!excludeFields ||
|
||||
!excludeFields.find((exlFld) => exlFld.fieldName == fld)
|
||||
);
|
||||
|
||||
filteredFields.forEach((fld) => {
|
||||
const value = data ? data[fld] : null;
|
||||
|
||||
if (typeof value == "string") {
|
||||
const newField =
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||
});
|
||||
|
||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||
newField.richText = true;
|
||||
}
|
||||
|
||||
finalFields.push(newField);
|
||||
} else if (typeof value == "number") {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "INT",
|
||||
})
|
||||
);
|
||||
} else {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "VARCHAR(255)",
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return finalFields;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabSchemaFieldsFromData.js",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
//
|
||||
|
||||
/**
|
||||
* # Password Hash function
|
||||
* @param {string} password
|
||||
* @returns
|
||||
*/
|
||||
function hashPassword(password) {
|
||||
const hmac = createHmac(
|
||||
"sha512",
|
||||
process.env.DSQL_ENCRYPTION_PASSWORD || ""
|
||||
);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
}
|
||||
|
||||
exports.hashPassword = hashPassword;
|
||||
|
||||
// export const comparePasswords = async (password) => {
|
||||
// const hmac = createHmac("sha512", process.env.DSQL_ENCRYPTION_PASSWORD);
|
||||
// hmac.update(password);
|
||||
// let hashed = hmac.digest("base64");
|
||||
|
||||
// let dbPass = await global.DB_HANDLER(`SELECT * FROM users WHERE password = '${hashed}'`);
|
||||
// console.log(dbPass);
|
||||
// return dbPass;
|
||||
// };
|
||||
@@ -1,24 +1,11 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const { IncomingMessage } = require("http");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* # Server Error
|
||||
*
|
||||
* @param {{
|
||||
* user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
|
||||
* message: string,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
declare function _exports({ userId, database, newFields, newPayload, }: {
|
||||
userId: number | string;
|
||||
database: string;
|
||||
newFields?: string[];
|
||||
newPayload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,80 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {number | string} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {string[]} [params.newFields] - new fields to add to the users table
|
||||
* @param {Object<string, any>} [params.newPayload]
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function updateUsersTableSchema({
|
||||
userId,
|
||||
database,
|
||||
newFields,
|
||||
newPayload,
|
||||
}) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
|
||||
const userSchemaData = grabUserSchemaData({ userId });
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabaseIndex = userSchemaData.findIndex(
|
||||
(db) => db.dbFullName === database
|
||||
);
|
||||
|
||||
if (targetDatabaseIndex < 0) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
|
||||
let existingTableIndex = userSchemaData[
|
||||
targetDatabaseIndex
|
||||
]?.tables.findIndex((table) => table.tableName === "users");
|
||||
|
||||
const usersTable =
|
||||
userSchemaData[targetDatabaseIndex].tables[existingTableIndex];
|
||||
|
||||
if (!usersTable?.fields?.[0]) throw new Error("Users Table Not Found!");
|
||||
|
||||
const additionalFields = grabSchemaFieldsFromData({
|
||||
fields: newFields,
|
||||
data: newPayload,
|
||||
});
|
||||
|
||||
const spliceStartIndex = usersTable.fields.findIndex(
|
||||
(field) => field.fieldName === "date_created"
|
||||
);
|
||||
const finalSpliceStartIndex =
|
||||
spliceStartIndex >= 0 ? spliceStartIndex : 0;
|
||||
|
||||
usersTable.fields.splice(finalSpliceStartIndex, 0, ...additionalFields);
|
||||
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,8 @@
|
||||
declare function _exports({ queryString, queryValuesArray, database, tableSchema, }: {
|
||||
declare function _exports({ queryString, queryValuesArray, database, tableSchema, useLocal, }: {
|
||||
queryString: string;
|
||||
queryValuesArray?: any[];
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -5,6 +5,7 @@ const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
@@ -15,6 +16,7 @@ const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB
|
||||
* @param {*[]} [params.queryValuesArray] - Values Array
|
||||
* @param {string} [params.database] - Database name
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
module.exports = async function varDatabaseDbHandler({
|
||||
@@ -22,6 +24,7 @@ module.exports = async function varDatabaseDbHandler({
|
||||
queryValuesArray,
|
||||
database,
|
||||
tableSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
@@ -31,7 +34,11 @@ module.exports = async function varDatabaseDbHandler({
|
||||
const isMaster = database?.match(/^datasquirel$/) ? true : false;
|
||||
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
const FINAL_DB_HANDLER = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
: DSQL_USER_DB_HANDLER;
|
||||
|
||||
let results;
|
||||
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
declare function _exports({ password, encryptionKey }: {
|
||||
password: string;
|
||||
encryptionKey: string;
|
||||
encryptionKey?: string;
|
||||
}): string;
|
||||
export = _exports;
|
||||
|
||||
@@ -1,13 +1,3 @@
|
||||
/** # MODULE TRACE
|
||||
======================================================================
|
||||
* Detected 4 files that call this module. The files are listed below:
|
||||
======================================================================
|
||||
* `require` Statement Found in [add-user.js] => file:///d:\GitHub\dsql\engine\user\add-user.js
|
||||
* `require` Statement Found in [login-user.js] => file:///d:\GitHub\dsql\engine\user\login-user.js
|
||||
* `require` Statement Found in [googleLogin.js] => file:///d:\GitHub\dsql\engine\user\social\utils\googleLogin.js
|
||||
* `require` Statement Found in [update-user.js] => file:///d:\GitHub\dsql\engine\user\update-user.js
|
||||
==== MODULE TRACE END ==== */
|
||||
|
||||
// @ts-check
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
@@ -16,11 +6,18 @@ const { createHmac } = require("crypto");
|
||||
* # Hash password Function
|
||||
* @param {object} param0
|
||||
* @param {string} param0.password - Password to hash
|
||||
* @param {string} param0.encryptionKey - Encryption key
|
||||
* @param {string} [param0.encryptionKey] - Encryption key
|
||||
* @returns {string}
|
||||
*/
|
||||
module.exports = function hashPassword({ password, encryptionKey }) {
|
||||
const hmac = createHmac("sha512", encryptionKey);
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
throw new Error("Encryption key is invalid");
|
||||
}
|
||||
|
||||
const hmac = createHmac("sha512", finalEncryptionKey);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
export = createDbFromSchema;
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* =============================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} [params.userId] - User ID or null
|
||||
* @param {string} [params.targetDatabase] - User Database full name
|
||||
|
||||
@@ -16,7 +16,7 @@ const execFlag = process.argv.find((arg) => arg === "--exec");
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* =============================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} [params.userId] - User ID or null
|
||||
* @param {string} [params.targetDatabase] - User Database full name
|
||||
|
||||
@@ -96,6 +96,8 @@ module.exports = async function createTable({
|
||||
////////////////////////////////////////
|
||||
|
||||
let primaryKeySet = false;
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
let foreignKeys = [];
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -130,8 +132,7 @@ module.exports = async function createTable({
|
||||
|
||||
if (foreignKey) {
|
||||
foreignKeys.push({
|
||||
fieldName: fieldName,
|
||||
...foreignKey,
|
||||
...column,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -161,14 +162,14 @@ module.exports = async function createTable({
|
||||
|
||||
if (foreignKeys[0]) {
|
||||
foreignKeys.forEach((foreighKey, index, array) => {
|
||||
const {
|
||||
fieldName,
|
||||
destinationTableName,
|
||||
destinationTableColumnName,
|
||||
cascadeDelete,
|
||||
cascadeUpdate,
|
||||
foreignKeyName,
|
||||
} = foreighKey;
|
||||
const fieldName = foreighKey.fieldName;
|
||||
const destinationTableName =
|
||||
foreighKey.foreignKey?.destinationTableName;
|
||||
const destinationTableColumnName =
|
||||
foreighKey.foreignKey?.destinationTableColumnName;
|
||||
const cascadeDelete = foreighKey.foreignKey?.cascadeDelete;
|
||||
const cascadeUpdate = foreighKey.foreignKey?.cascadeUpdate;
|
||||
const foreignKeyName = foreighKey.foreignKey?.foreignKeyName;
|
||||
|
||||
const comma = (() => {
|
||||
if (index === foreignKeys.length - 1) return "";
|
||||
|
||||
@@ -60,6 +60,9 @@ module.exports = async function updateTable({
|
||||
* @description Initial setup
|
||||
*/
|
||||
|
||||
/** @type {any[]} */
|
||||
let errorLogs = [];
|
||||
|
||||
/**
|
||||
* @description Initialize table info array. This value will be
|
||||
* changing depending on if a field is renamed or not.
|
||||
@@ -530,7 +533,7 @@ module.exports = async function updateTable({
|
||||
foreignKeyName,
|
||||
} = foreignKey;
|
||||
|
||||
const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${
|
||||
const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)${
|
||||
cascadeDelete ? " ON DELETE CASCADE" : ""
|
||||
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
|
||||
// const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}` + ",";
|
||||
@@ -541,6 +544,10 @@ module.exports = async function updateTable({
|
||||
database: dbFullName,
|
||||
queryString: finalQueryString,
|
||||
});
|
||||
|
||||
if (!addForeignKey?.serverStatus) {
|
||||
errorLogs.push(addForeignKey);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
Vendored
+102
-53
@@ -1,4 +1,3 @@
|
||||
import type { ServerResponse } from "http";
|
||||
import { Editor } from "tinymce";
|
||||
export type DSQL_DatabaseFullName = string;
|
||||
export interface DSQL_DatabaseSchemaType {
|
||||
@@ -165,7 +164,8 @@ export interface SerializeQueryParams {
|
||||
query: any;
|
||||
}
|
||||
export type DATASQUIREL_LoggedInUser = {
|
||||
id?: number;
|
||||
id: number;
|
||||
uuid?: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
@@ -174,32 +174,13 @@ export type DATASQUIREL_LoggedInUser = {
|
||||
username?: string;
|
||||
image?: string;
|
||||
image_thumbnail?: string;
|
||||
address?: string;
|
||||
city?: string;
|
||||
state?: string;
|
||||
country?: string;
|
||||
zip_code?: string;
|
||||
social_login?: number;
|
||||
social_platform?: string;
|
||||
social_id?: string;
|
||||
more_user_data?: string;
|
||||
verification_status?: number;
|
||||
loan_officer_id?: number;
|
||||
is_admin?: number;
|
||||
admin_level?: number;
|
||||
admin_permissions?: string;
|
||||
uuid?: string;
|
||||
temp_login_code?: string;
|
||||
date_created?: string;
|
||||
date_created_code?: number;
|
||||
date_created_timestamp?: string;
|
||||
date_updated?: string;
|
||||
date_updated_code?: number;
|
||||
date_updated_timestamp?: string;
|
||||
csrf_k?: string;
|
||||
logged_in_status?: boolean;
|
||||
date?: number;
|
||||
more_data?: any;
|
||||
csrf_k: string;
|
||||
logged_in_status: boolean;
|
||||
date: number;
|
||||
} & {
|
||||
[key: string]: any;
|
||||
};
|
||||
@@ -208,6 +189,7 @@ export interface AuthenticatedUser {
|
||||
payload: DATASQUIREL_LoggedInUser | null;
|
||||
msg?: string;
|
||||
userId?: number;
|
||||
cookieNames?: any;
|
||||
}
|
||||
export interface SuccessUserObject {
|
||||
id: number;
|
||||
@@ -322,25 +304,7 @@ export interface PostInsertReturn {
|
||||
protocol41: boolean;
|
||||
changedRows: number;
|
||||
}
|
||||
export interface UserType {
|
||||
id: number;
|
||||
stripe_id?: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
bio?: string;
|
||||
username?: string;
|
||||
image: string;
|
||||
image_thumbnail: string;
|
||||
social_id?: string;
|
||||
verification_status?: number;
|
||||
social_platform?: string;
|
||||
social_login?: number;
|
||||
date?: number;
|
||||
phone?: number | string;
|
||||
csrf_k: string;
|
||||
logged_in_status: boolean;
|
||||
}
|
||||
export type UserType = DATASQUIREL_LoggedInUser;
|
||||
export interface ApiKeyDef {
|
||||
name: string;
|
||||
scope: string;
|
||||
@@ -1061,6 +1025,10 @@ export type APILoginFunctionReturn = {
|
||||
msg?: string;
|
||||
payload?: DATASQUIREL_LoggedInUser | null;
|
||||
userId?: number | string;
|
||||
key?: string;
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
cookieNames?: any;
|
||||
};
|
||||
export type APILoginFunction = (params: APILoginFunctionParams) => Promise<APILoginFunctionReturn>;
|
||||
export type APICreateUserFunctionParams = {
|
||||
@@ -1085,14 +1053,9 @@ export type APIGetUserFunction = (params: APIGetUserFunctionParams) => Promise<G
|
||||
* API Google Login Function
|
||||
*/
|
||||
export type APIGoogleLoginFunctionParams = {
|
||||
clientId: string;
|
||||
token: string;
|
||||
database: string;
|
||||
userId: string | number;
|
||||
additionalFields?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
res: any;
|
||||
additionalFields?: string[];
|
||||
};
|
||||
export type APIGoogleLoginFunctionReturn = {
|
||||
dsqlUserId?: number | string;
|
||||
@@ -1107,15 +1070,14 @@ export type HandleSocialDbFunctionParams = {
|
||||
email: string;
|
||||
social_platform: string;
|
||||
payload: any;
|
||||
res?: ServerResponse;
|
||||
invitation?: any;
|
||||
supEmail?: string;
|
||||
additionalFields?: object;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
export type HandleSocialDbFunctionReturn = {
|
||||
success: boolean;
|
||||
user?: null;
|
||||
user?: DATASQUIREL_LoggedInUser | null;
|
||||
msg?: string;
|
||||
social_id?: string | number;
|
||||
social_platform?: string;
|
||||
@@ -1137,7 +1099,7 @@ export type HandleSocialDbFunctionReturn = {
|
||||
*
|
||||
* @returns {Promise<HandleSocialDbFunctionReturn>} - Response object
|
||||
*/
|
||||
export type HandleSocialDbFunction = (params: HandleSocialDbFunctionParams) => Promise<HandleSocialDbFunctionReturn>;
|
||||
export type HandleSocialDbFunction = (params: HandleSocialDbFunctionParams) => Promise<APILoginFunctionReturn>;
|
||||
export type ApiReauthUserReturn = {
|
||||
success: boolean;
|
||||
payload?: {
|
||||
@@ -1146,4 +1108,91 @@ export type ApiReauthUserReturn = {
|
||||
msg?: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
export type GoogleAccessTokenObject = {
|
||||
access_token: string;
|
||||
token_type: "Bearer";
|
||||
expires_in: number;
|
||||
scope: string;
|
||||
authuser: string;
|
||||
prompt: string;
|
||||
};
|
||||
export type GoogleOauth2User = {
|
||||
sub: string;
|
||||
name: string;
|
||||
given_name: string;
|
||||
family_name: string;
|
||||
picture: string;
|
||||
email: string;
|
||||
email_verified: boolean;
|
||||
};
|
||||
export interface AceEditorOptions {
|
||||
animatedScroll?: boolean;
|
||||
autoScrollEditorIntoView?: boolean;
|
||||
behavioursEnabled?: boolean;
|
||||
copyWithEmptySelection?: boolean;
|
||||
cursorStyle?: "ace" | "slim" | "smooth" | "wide";
|
||||
customScrollbar?: boolean;
|
||||
displayIndentGuides?: boolean;
|
||||
dragDelay?: number;
|
||||
dragEnabled?: boolean;
|
||||
enableAutoIndent?: boolean;
|
||||
enableBasicAutocompletion?: boolean | any[];
|
||||
enableKeyboardAccessibility?: boolean;
|
||||
enableLiveAutocompletion?: boolean | any[];
|
||||
enableMobileMenu?: boolean;
|
||||
enableMultiselect?: boolean;
|
||||
enableSnippets?: boolean;
|
||||
fadeFoldWidgets?: boolean;
|
||||
firstLineNumber?: number;
|
||||
fixedWidthGutter?: boolean;
|
||||
focusTimeout?: number;
|
||||
foldStyle?: "markbegin" | "markbeginend" | "manual";
|
||||
fontFamily?: string;
|
||||
fontSize?: number;
|
||||
hScrollBarAlwaysVisible?: boolean;
|
||||
hasCssTransforms?: boolean;
|
||||
highlightActiveLine?: boolean;
|
||||
highlightGutterLine?: boolean;
|
||||
highlightIndentGuides?: boolean;
|
||||
highlightSelectedWord?: boolean;
|
||||
indentedSoftWrap?: boolean;
|
||||
keyboardHandler?: string;
|
||||
liveAutocompletionDelay?: number;
|
||||
liveAutocompletionThreshold?: number;
|
||||
maxLines?: number;
|
||||
maxPixelHeight?: number;
|
||||
mergeUndoDeltas?: boolean | "always";
|
||||
minLines?: number;
|
||||
mode?: string;
|
||||
navigateWithinSoftTabs?: boolean;
|
||||
newLineMode?: AceAjax.NewLineMode;
|
||||
overwrite?: boolean;
|
||||
placeholder?: string;
|
||||
printMargin?: number | boolean;
|
||||
printMarginColumn?: number;
|
||||
readOnly?: boolean;
|
||||
relativeLineNumbers?: boolean;
|
||||
scrollPastEnd?: number;
|
||||
scrollSpeed?: number;
|
||||
selectionStyle?: string;
|
||||
session?: any;
|
||||
showFoldWidgets?: boolean;
|
||||
showFoldedAnnotations?: boolean;
|
||||
showGutter?: boolean;
|
||||
showInvisibles?: boolean;
|
||||
showLineNumbers?: boolean;
|
||||
showPrintMargin?: boolean;
|
||||
tabSize?: number;
|
||||
textInputAriaLabel?: string;
|
||||
theme?: string;
|
||||
tooltipFollowsMouse?: boolean;
|
||||
useSoftTabs?: boolean;
|
||||
useSvgGutterIcons?: boolean;
|
||||
useWorker?: boolean;
|
||||
vScrollBarAlwaysVisible?: boolean;
|
||||
value?: string;
|
||||
wrap?: number | boolean | "off" | "free" | "printmargin";
|
||||
wrapBehavioursEnabled?: boolean;
|
||||
wrapMethod?: "code" | "text" | "auto";
|
||||
}
|
||||
export {};
|
||||
|
||||
+105
-68
@@ -3,12 +3,6 @@ import type { IncomingMessage, ServerResponse } from "http";
|
||||
import { Editor } from "tinymce";
|
||||
export type DSQL_DatabaseFullName = string;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
export interface DSQL_DatabaseSchemaType {
|
||||
dbName: string;
|
||||
dbSlug: string;
|
||||
@@ -26,8 +20,6 @@ export interface DSQL_ChildrenDatabaseObject {
|
||||
dbFullName: string;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_TableSchemaType {
|
||||
tableName: string;
|
||||
tableFullName: string;
|
||||
@@ -48,8 +40,6 @@ export interface DSQL_ChildrenTablesType {
|
||||
tableNameFull?: string;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_FieldSchemaType {
|
||||
fieldName?: string;
|
||||
originName?: string;
|
||||
@@ -92,8 +82,6 @@ export interface DSQL_ForeignKeyType {
|
||||
cascadeUpdate?: boolean;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_IndexSchemaType {
|
||||
indexName?: string;
|
||||
indexType?: string;
|
||||
@@ -118,8 +106,6 @@ export interface DSQL_MYSQL_SHOW_INDEXES_Type {
|
||||
Comment: string;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_MYSQL_SHOW_COLUMNS_Type {
|
||||
Field: string;
|
||||
Type: string;
|
||||
@@ -129,16 +115,12 @@ export interface DSQL_MYSQL_SHOW_COLUMNS_Type {
|
||||
Extra: string;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_MYSQL_FOREIGN_KEYS_Type {
|
||||
CONSTRAINT_NAME: string;
|
||||
CONSTRAINT_SCHEMA: string;
|
||||
TABLE_NAME: string;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
export interface DSQL_MYSQL_user_databases_Type {
|
||||
id: number;
|
||||
user_id: number;
|
||||
@@ -215,7 +197,8 @@ export interface SerializeQueryParams {
|
||||
// @ts-check
|
||||
|
||||
export type DATASQUIREL_LoggedInUser = {
|
||||
id?: number;
|
||||
id: number;
|
||||
uuid?: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
@@ -224,32 +207,13 @@ export type DATASQUIREL_LoggedInUser = {
|
||||
username?: string;
|
||||
image?: string;
|
||||
image_thumbnail?: string;
|
||||
address?: string;
|
||||
city?: string;
|
||||
state?: string;
|
||||
country?: string;
|
||||
zip_code?: string;
|
||||
social_login?: number;
|
||||
social_platform?: string;
|
||||
social_id?: string;
|
||||
more_user_data?: string;
|
||||
verification_status?: number;
|
||||
loan_officer_id?: number;
|
||||
is_admin?: number;
|
||||
admin_level?: number;
|
||||
admin_permissions?: string;
|
||||
uuid?: string;
|
||||
temp_login_code?: string;
|
||||
date_created?: string;
|
||||
date_created_code?: number;
|
||||
date_created_timestamp?: string;
|
||||
date_updated?: string;
|
||||
date_updated_code?: number;
|
||||
date_updated_timestamp?: string;
|
||||
csrf_k?: string;
|
||||
logged_in_status?: boolean;
|
||||
date?: number;
|
||||
more_data?: any;
|
||||
csrf_k: string;
|
||||
logged_in_status: boolean;
|
||||
date: number;
|
||||
} & {
|
||||
[key: string]: any;
|
||||
};
|
||||
@@ -259,6 +223,7 @@ export interface AuthenticatedUser {
|
||||
payload: DATASQUIREL_LoggedInUser | null;
|
||||
msg?: string;
|
||||
userId?: number;
|
||||
cookieNames?: any;
|
||||
}
|
||||
|
||||
export interface SuccessUserObject {
|
||||
@@ -391,25 +356,7 @@ export interface PostInsertReturn {
|
||||
changedRows: number;
|
||||
}
|
||||
|
||||
export interface UserType {
|
||||
id: number;
|
||||
stripe_id?: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
bio?: string;
|
||||
username?: string;
|
||||
image: string;
|
||||
image_thumbnail: string;
|
||||
social_id?: string;
|
||||
verification_status?: number;
|
||||
social_platform?: string;
|
||||
social_login?: number;
|
||||
date?: number;
|
||||
phone?: number | string;
|
||||
csrf_k: string;
|
||||
logged_in_status: boolean;
|
||||
}
|
||||
export type UserType = DATASQUIREL_LoggedInUser;
|
||||
|
||||
export interface ApiKeyDef {
|
||||
name: string;
|
||||
@@ -1278,6 +1225,10 @@ export type APILoginFunctionReturn = {
|
||||
msg?: string;
|
||||
payload?: DATASQUIREL_LoggedInUser | null;
|
||||
userId?: number | string;
|
||||
key?: string;
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
cookieNames?: any;
|
||||
};
|
||||
export type APILoginFunction = (
|
||||
params: APILoginFunctionParams
|
||||
@@ -1313,12 +1264,9 @@ export type APIGetUserFunction = (
|
||||
* API Google Login Function
|
||||
*/
|
||||
export type APIGoogleLoginFunctionParams = {
|
||||
clientId: string;
|
||||
token: string;
|
||||
database: string;
|
||||
userId: string | number;
|
||||
additionalFields?: { [key: string]: any };
|
||||
res: any;
|
||||
additionalFields?: string[];
|
||||
};
|
||||
|
||||
export type APIGoogleLoginFunctionReturn = {
|
||||
@@ -1338,16 +1286,15 @@ export type HandleSocialDbFunctionParams = {
|
||||
email: string;
|
||||
social_platform: string;
|
||||
payload: any;
|
||||
res?: ServerResponse;
|
||||
invitation?: any;
|
||||
supEmail?: string;
|
||||
additionalFields?: object;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
export type HandleSocialDbFunctionReturn = {
|
||||
success: boolean;
|
||||
user?: null;
|
||||
user?: DATASQUIREL_LoggedInUser | null;
|
||||
msg?: string;
|
||||
social_id?: string | number;
|
||||
social_platform?: string;
|
||||
@@ -1372,7 +1319,7 @@ export type HandleSocialDbFunctionReturn = {
|
||||
*/
|
||||
export type HandleSocialDbFunction = (
|
||||
params: HandleSocialDbFunctionParams
|
||||
) => Promise<HandleSocialDbFunctionReturn>;
|
||||
) => Promise<APILoginFunctionReturn>;
|
||||
|
||||
export type ApiReauthUserReturn = {
|
||||
success: boolean;
|
||||
@@ -1380,3 +1327,93 @@ export type ApiReauthUserReturn = {
|
||||
msg?: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
|
||||
export type GoogleAccessTokenObject = {
|
||||
access_token: string;
|
||||
token_type: "Bearer";
|
||||
expires_in: number;
|
||||
scope: string;
|
||||
authuser: string;
|
||||
prompt: string;
|
||||
};
|
||||
|
||||
export type GoogleOauth2User = {
|
||||
sub: string;
|
||||
name: string;
|
||||
given_name: string;
|
||||
family_name: string;
|
||||
picture: string;
|
||||
email: string;
|
||||
email_verified: boolean;
|
||||
};
|
||||
|
||||
export interface AceEditorOptions {
|
||||
animatedScroll?: boolean;
|
||||
autoScrollEditorIntoView?: boolean;
|
||||
behavioursEnabled?: boolean;
|
||||
copyWithEmptySelection?: boolean;
|
||||
cursorStyle?: "ace" | "slim" | "smooth" | "wide";
|
||||
customScrollbar?: boolean;
|
||||
displayIndentGuides?: boolean;
|
||||
dragDelay?: number;
|
||||
dragEnabled?: boolean;
|
||||
enableAutoIndent?: boolean;
|
||||
enableBasicAutocompletion?: boolean | any[];
|
||||
enableKeyboardAccessibility?: boolean;
|
||||
enableLiveAutocompletion?: boolean | any[];
|
||||
enableMobileMenu?: boolean;
|
||||
enableMultiselect?: boolean;
|
||||
enableSnippets?: boolean;
|
||||
fadeFoldWidgets?: boolean;
|
||||
firstLineNumber?: number;
|
||||
fixedWidthGutter?: boolean;
|
||||
focusTimeout?: number;
|
||||
foldStyle?: "markbegin" | "markbeginend" | "manual";
|
||||
fontFamily?: string;
|
||||
fontSize?: number;
|
||||
hScrollBarAlwaysVisible?: boolean;
|
||||
hasCssTransforms?: boolean;
|
||||
highlightActiveLine?: boolean;
|
||||
highlightGutterLine?: boolean;
|
||||
highlightIndentGuides?: boolean;
|
||||
highlightSelectedWord?: boolean;
|
||||
indentedSoftWrap?: boolean;
|
||||
keyboardHandler?: string;
|
||||
liveAutocompletionDelay?: number;
|
||||
liveAutocompletionThreshold?: number;
|
||||
maxLines?: number;
|
||||
maxPixelHeight?: number;
|
||||
mergeUndoDeltas?: boolean | "always";
|
||||
minLines?: number;
|
||||
mode?: string;
|
||||
navigateWithinSoftTabs?: boolean;
|
||||
newLineMode?: AceAjax.NewLineMode;
|
||||
overwrite?: boolean;
|
||||
placeholder?: string;
|
||||
printMargin?: number | boolean;
|
||||
printMarginColumn?: number;
|
||||
readOnly?: boolean;
|
||||
relativeLineNumbers?: boolean;
|
||||
scrollPastEnd?: number;
|
||||
scrollSpeed?: number;
|
||||
selectionStyle?: string;
|
||||
session?: any;
|
||||
showFoldWidgets?: boolean;
|
||||
showFoldedAnnotations?: boolean;
|
||||
showGutter?: boolean;
|
||||
showInvisibles?: boolean;
|
||||
showLineNumbers?: boolean;
|
||||
showPrintMargin?: boolean;
|
||||
tabSize?: number;
|
||||
textInputAriaLabel?: string;
|
||||
theme?: string;
|
||||
tooltipFollowsMouse?: boolean;
|
||||
useSoftTabs?: boolean;
|
||||
useSvgGutterIcons?: boolean;
|
||||
useWorker?: boolean;
|
||||
vScrollBarAlwaysVisible?: boolean;
|
||||
value?: string;
|
||||
wrap?: number | boolean | "off" | "free" | "printmargin";
|
||||
wrapBehavioursEnabled?: boolean;
|
||||
wrapMethod?: "code" | "text" | "auto";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user