updates
This commit is contained in:
+153
-153
@@ -1,153 +1,153 @@
|
||||
// @ts-check
|
||||
|
||||
const hashPassword = require("../../functions/hashPassword");
|
||||
const addUsersTableToDb = require("../engine/addUsersTableToDb");
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
const addDbEntry = require("../query/utils/addDbEntry");
|
||||
const runQuery = require("../query/utils/runQuery");
|
||||
|
||||
/**
|
||||
* @typedef {Object} LocalPostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {*} [payload] - GET request results
|
||||
* @property {string} [msg] - Message
|
||||
* @property {string} [error] - Error Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Make a get request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {import("../../users/add-user").UserDataPayload} params.payload - SQL Query
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
|
||||
*
|
||||
* @returns { Promise<LocalPostReturn> } - Return Object
|
||||
*/
|
||||
async function localAddUser({ payload, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* Initialize Variables
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* Hash Password
|
||||
*
|
||||
* @description Hash Password
|
||||
*/
|
||||
if (!payload?.password) {
|
||||
return { success: false, payload: `Password is required to create an account` };
|
||||
}
|
||||
|
||||
const hashedPassword = hashPassword({
|
||||
password: payload.password,
|
||||
encryptionKey,
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
if (!fields) {
|
||||
const newTable = await addUsersTableToDb({ dbSchema });
|
||||
|
||||
console.log(newTable);
|
||||
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
|
||||
if (!fields) {
|
||||
return {
|
||||
success: false,
|
||||
payload: "Could not create users table",
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map((/** @type {*} */ fieldObject) => fieldObject.Field);
|
||||
|
||||
let invalidField = null;
|
||||
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
invalidField = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidField) {
|
||||
return { success: false, payload: `${invalidField} is not a valid field!` };
|
||||
}
|
||||
|
||||
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?${payload.username ? "OR username = ?" : ""}}`,
|
||||
queryValuesArray: payload.username ? [payload.email, payload.username] : [payload.email],
|
||||
database: dbFullName,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
|
||||
if (existingUser && existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: "User Already Exists",
|
||||
};
|
||||
}
|
||||
|
||||
const addUser = await addDbEntry({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: {
|
||||
...payload,
|
||||
image: "/images/user_images/user-preset.png",
|
||||
image_thumbnail: "/images/user_images/user-preset-thumbnail.png",
|
||||
},
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
if (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}'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser?.[0],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
payload: "Could not create user",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////
|
||||
console.log("Error in local add-user Request =>", error.message);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Something went wrong!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localAddUser;
|
||||
// @ts-check
|
||||
|
||||
const hashPassword = require("../../functions/hashPassword");
|
||||
const addUsersTableToDb = require("../engine/addUsersTableToDb");
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
const addDbEntry = require("../query/utils/addDbEntry");
|
||||
const runQuery = require("../query/utils/runQuery");
|
||||
|
||||
/**
|
||||
* @typedef {Object} LocalPostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {*} [payload] - GET request results
|
||||
* @property {string} [msg] - Message
|
||||
* @property {string} [error] - Error Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Make a get request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {import("../../users/add-user").UserDataPayload} params.payload - SQL Query
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
|
||||
*
|
||||
* @returns { Promise<LocalPostReturn> } - Return Object
|
||||
*/
|
||||
async function localAddUser({ payload, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* Initialize Variables
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* Hash Password
|
||||
*
|
||||
* @description Hash Password
|
||||
*/
|
||||
if (!payload?.password) {
|
||||
return { success: false, payload: `Password is required to create an account` };
|
||||
}
|
||||
|
||||
const hashedPassword = hashPassword({
|
||||
password: payload.password,
|
||||
encryptionKey,
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
if (!fields) {
|
||||
const newTable = await addUsersTableToDb({ dbSchema });
|
||||
|
||||
console.log(newTable);
|
||||
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
|
||||
if (!fields) {
|
||||
return {
|
||||
success: false,
|
||||
payload: "Could not create users table",
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map((/** @type {*} */ fieldObject) => fieldObject.Field);
|
||||
|
||||
let invalidField = null;
|
||||
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
invalidField = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidField) {
|
||||
return { success: false, payload: `${invalidField} is not a valid field!` };
|
||||
}
|
||||
|
||||
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?${payload.username ? "OR username = ?" : ""}}`,
|
||||
queryValuesArray: payload.username ? [payload.email, payload.username] : [payload.email],
|
||||
database: dbFullName,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
|
||||
if (existingUser && existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: "User Already Exists",
|
||||
};
|
||||
}
|
||||
|
||||
const addUser = await addDbEntry({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: {
|
||||
...payload,
|
||||
image: "/images/user_images/user-preset.png",
|
||||
image_thumbnail: "/images/user_images/user-preset-thumbnail.png",
|
||||
},
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
if (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}'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser?.[0],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
payload: "Could not create user",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////
|
||||
console.log("Error in local add-user Request =>", error.message);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Something went wrong!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localAddUser;
|
||||
|
||||
+53
-53
@@ -1,53 +1,53 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {number} param0.userId
|
||||
* @param {string[]} param0.fields
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function getLocalUser({ userId, fields, dbSchema }) {
|
||||
/**
|
||||
* GRAB user
|
||||
*
|
||||
* @description GRAB user
|
||||
*/
|
||||
const sanitizedFields = fields.map((fld) => fld.replace(/[^a-z\_]/g, ""));
|
||||
const query = `SELECT ${sanitizedFields.join(",")} FROM users WHERE id = ?`;
|
||||
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId.toString()],
|
||||
database: process.env.DSQL_DB_NAME || "",
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User not found!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = getLocalUser;
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {number} param0.userId
|
||||
* @param {string[]} param0.fields
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function getLocalUser({ userId, fields, dbSchema }) {
|
||||
/**
|
||||
* GRAB user
|
||||
*
|
||||
* @description GRAB user
|
||||
*/
|
||||
const sanitizedFields = fields.map((fld) => fld.replace(/[^a-z\_]/g, ""));
|
||||
const query = `SELECT ${sanitizedFields.join(",")} FROM users WHERE id = ?`;
|
||||
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId.toString()],
|
||||
database: process.env.DSQL_DB_NAME || "",
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User not found!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = getLocalUser;
|
||||
|
||||
+152
-152
@@ -1,152 +1,152 @@
|
||||
// @ts-check
|
||||
|
||||
const hashPassword = require("../../functions/hashPassword");
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {{
|
||||
* email?: string,
|
||||
* username?: string,
|
||||
* password: string,
|
||||
* }} param0.payload
|
||||
* @param {string[]} [param0.additionalFields]
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function loginLocalUser({ payload, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
|
||||
const { email, username, password } = payload;
|
||||
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (email?.match(/ /) || username?.match(/ /) || password?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = hashPassword({
|
||||
password: password,
|
||||
encryptionKey: encryptionKey,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email || "", username || ""],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
let isPasswordCorrect = false;
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
|
||||
let socialUserValid = false;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
|
||||
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
// @ts-ignore
|
||||
userPayload[key] = foundUser?.[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: "0",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in local login-user Request =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Login Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = loginLocalUser;
|
||||
// @ts-check
|
||||
|
||||
const hashPassword = require("../../functions/hashPassword");
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {{
|
||||
* email?: string,
|
||||
* username?: string,
|
||||
* password: string,
|
||||
* }} param0.payload
|
||||
* @param {string[]} [param0.additionalFields]
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function loginLocalUser({ payload, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
|
||||
const { email, username, password } = payload;
|
||||
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (email?.match(/ /) || username?.match(/ /) || password?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = hashPassword({
|
||||
password: password,
|
||||
encryptionKey: encryptionKey,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email || "", username || ""],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
let isPasswordCorrect = false;
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
|
||||
let socialUserValid = false;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
|
||||
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
// @ts-ignore
|
||||
userPayload[key] = foundUser?.[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: "0",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in local login-user Request =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Login Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = loginLocalUser;
|
||||
|
||||
+106
-106
@@ -1,106 +1,106 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {*} param0.existingUser
|
||||
* @param {string[]} [param0.additionalFields]
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function localReauthUser({ existingUser, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* Grab data
|
||||
*
|
||||
* @description Grab data
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
/**
|
||||
* GRAB user
|
||||
*
|
||||
* @description GRAB user
|
||||
*/
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
tableSchema,
|
||||
})
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
|
||||
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
// @ts-ignore
|
||||
userPayload[key] = foundUser?.[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: "0",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in local login-user Request =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Login Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localReauthUser;
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {*} param0.existingUser
|
||||
* @param {string[]} [param0.additionalFields]
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
async function localReauthUser({ existingUser, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* Grab data
|
||||
*
|
||||
* @description Grab data
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
/**
|
||||
* GRAB user
|
||||
*
|
||||
* @description GRAB user
|
||||
*/
|
||||
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
tableSchema,
|
||||
})
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
|
||||
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
// @ts-ignore
|
||||
userPayload[key] = foundUser?.[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: "0",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in local login-user Request =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Login Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localReauthUser;
|
||||
|
||||
+134
-134
@@ -1,134 +1,134 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const encrypt = require("../../../functions/encrypt");
|
||||
const camelJoinedtoCamelSpace = require("../../engine/utils/camelJoinedtoCamelSpace");
|
||||
const githubLogin = require("./utils/githubLogin");
|
||||
const handleSocialDb = require("./utils/handleSocialDb");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
const database = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {http.ServerResponse} params.res - HTTPS response object
|
||||
* @param {string} params.code
|
||||
* @param {string} [params.email]
|
||||
* @param {string} params.clientId
|
||||
* @param {string} params.clientSecret
|
||||
* @param {object} [params.additionalFields]
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema
|
||||
*/
|
||||
async function localGithubAuth({ res, code, email, clientId, clientSecret, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
if (!code || !clientId || !clientSecret) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof code !== "string" || typeof clientId !== "string" || typeof clientSecret !== "string" || typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
|
||||
const targetDbName = database;
|
||||
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = targetName?.match(/ /) ? targetName?.split(" ") : targetName?.match(/\-/) ? targetName?.split("-") : [targetName];
|
||||
|
||||
const payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: camelJoinedtoCamelSpace(nameArray[0]) || "",
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]) || "",
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
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: targetDbName,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
social_platform: "github",
|
||||
res: res,
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
dbSchema: dbSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGithubUser, dsqlUserId: "0" };
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("localGithubAuth error", error.message);
|
||||
|
||||
return { success: false, msg: "Failed!" };
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = localGithubAuth;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const encrypt = require("../../../functions/encrypt");
|
||||
const camelJoinedtoCamelSpace = require("../../engine/utils/camelJoinedtoCamelSpace");
|
||||
const githubLogin = require("./utils/githubLogin");
|
||||
const handleSocialDb = require("./utils/handleSocialDb");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
const database = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {http.ServerResponse} params.res - HTTPS response object
|
||||
* @param {string} params.code
|
||||
* @param {string} [params.email]
|
||||
* @param {string} params.clientId
|
||||
* @param {string} params.clientSecret
|
||||
* @param {object} [params.additionalFields]
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema
|
||||
*/
|
||||
async function localGithubAuth({ res, code, email, clientId, clientSecret, additionalFields, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
if (!code || !clientId || !clientSecret) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof code !== "string" || typeof clientId !== "string" || typeof clientSecret !== "string" || typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
|
||||
const targetDbName = database;
|
||||
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = targetName?.match(/ /) ? targetName?.split(" ") : targetName?.match(/\-/) ? targetName?.split("-") : [targetName];
|
||||
|
||||
const payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: camelJoinedtoCamelSpace(nameArray[0]) || "",
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]) || "",
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
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: targetDbName,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
social_platform: "github",
|
||||
res: res,
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
dbSchema: dbSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGithubUser, dsqlUserId: "0" };
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("localGithubAuth error", error.message);
|
||||
|
||||
return { success: false, msg: "Failed!" };
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = localGithubAuth;
|
||||
|
||||
+169
-169
@@ -1,169 +1,169 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../../../functions/encrypt");
|
||||
const decrypt = require("../../../functions/decrypt");
|
||||
const handleSocialDb = require("./utils/handleSocialDb");
|
||||
const httpsRequest = require("./utils/httpsRequest");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object | null} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
|
||||
* @property {number} [dsqlUserId] - Dsql User Id
|
||||
* @property {string} [msg] - Response message
|
||||
*/
|
||||
|
||||
const database = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {string} params.token - Google access token gotten from the client side
|
||||
* @param {string} params.clientId - Google client id
|
||||
* @param {http.ServerResponse} params.response - HTTPS response object
|
||||
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function localGoogleAuth({ dbSchema, token, clientId, response, additionalFields }) {
|
||||
/**
|
||||
* Send Response
|
||||
*
|
||||
* @description Send a boolean response
|
||||
*/
|
||||
try {
|
||||
/**
|
||||
* Grab User data
|
||||
*
|
||||
* @description Grab User data
|
||||
* @type {{ success: boolean, payload: any, msg: string }}
|
||||
*/
|
||||
const payloadResponse = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "datasquirel.com",
|
||||
path: "/user/grab-google-user-from-token",
|
||||
body: {
|
||||
token: token,
|
||||
clientId: clientId,
|
||||
},
|
||||
headers: {
|
||||
Authorization: process.env.DSQL_API_KEY,
|
||||
},
|
||||
});
|
||||
|
||||
const payload = payloadResponse.payload;
|
||||
|
||||
if (!payloadResponse.success || !payload) {
|
||||
console.log("payloadResponse Failed =>", payloadResponse);
|
||||
return {
|
||||
success: false,
|
||||
msg: "User fetch Error",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
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 targetDbName = database;
|
||||
|
||||
if (!payload) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No payload",
|
||||
};
|
||||
}
|
||||
|
||||
const { given_name, family_name, email, sub, picture, email_verified } = payload;
|
||||
|
||||
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) => {
|
||||
// @ts-ignore
|
||||
payloadObject[key] = additionalFields[key];
|
||||
});
|
||||
}
|
||||
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database: targetDbName,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
res: response,
|
||||
social_id: sub,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGoogleUser, dsqlUserId: "0" };
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User fetch Error",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = localGoogleAuth;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../../../functions/encrypt");
|
||||
const decrypt = require("../../../functions/decrypt");
|
||||
const handleSocialDb = require("./utils/handleSocialDb");
|
||||
const httpsRequest = require("./utils/httpsRequest");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object | null} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
|
||||
* @property {number} [dsqlUserId] - Dsql User Id
|
||||
* @property {string} [msg] - Response message
|
||||
*/
|
||||
|
||||
const database = process.env.DSQL_DB_NAME || "";
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {string} params.token - Google access token gotten from the client side
|
||||
* @param {string} params.clientId - Google client id
|
||||
* @param {http.ServerResponse} params.response - HTTPS response object
|
||||
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function localGoogleAuth({ dbSchema, token, clientId, response, additionalFields }) {
|
||||
/**
|
||||
* Send Response
|
||||
*
|
||||
* @description Send a boolean response
|
||||
*/
|
||||
try {
|
||||
/**
|
||||
* Grab User data
|
||||
*
|
||||
* @description Grab User data
|
||||
* @type {{ success: boolean, payload: any, msg: string }}
|
||||
*/
|
||||
const payloadResponse = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "datasquirel.com",
|
||||
path: "/user/grab-google-user-from-token",
|
||||
body: {
|
||||
token: token,
|
||||
clientId: clientId,
|
||||
},
|
||||
headers: {
|
||||
Authorization: process.env.DSQL_API_KEY,
|
||||
},
|
||||
});
|
||||
|
||||
const payload = payloadResponse.payload;
|
||||
|
||||
if (!payloadResponse.success || !payload) {
|
||||
console.log("payloadResponse Failed =>", payloadResponse);
|
||||
return {
|
||||
success: false,
|
||||
msg: "User fetch Error",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
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 targetDbName = database;
|
||||
|
||||
if (!payload) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No payload",
|
||||
};
|
||||
}
|
||||
|
||||
const { given_name, family_name, email, sub, picture, email_verified } = payload;
|
||||
|
||||
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) => {
|
||||
// @ts-ignore
|
||||
payloadObject[key] = additionalFields[key];
|
||||
});
|
||||
}
|
||||
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database: targetDbName,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
res: response,
|
||||
social_id: sub,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGoogleUser, dsqlUserId: "0" };
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User fetch Error",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = localGoogleAuth;
|
||||
|
||||
@@ -1,164 +1,164 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const httpsRequest = require("./httpsRequest");
|
||||
const dbHandler = require("../../../engine/utils/dbHandler");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* @typedef {object} GithubUserPayload
|
||||
* @property {string} login - Full name merged eg. "JohnDoe"
|
||||
* @property {number} id - github user id
|
||||
* @property {string} node_id - Some other id
|
||||
* @property {string} avatar_url - profile picture
|
||||
* @property {string} gravatar_id - some other id
|
||||
* @property {string} url - Github user URL
|
||||
* @property {string} html_url - User html URL - whatever that means
|
||||
* @property {string} followers_url - Followers URL
|
||||
* @property {string} following_url - Following URL
|
||||
* @property {string} gists_url - Gists URL
|
||||
* @property {string} starred_url - Starred URL
|
||||
* @property {string} subscriptions_url - Subscriptions URL
|
||||
* @property {string} organizations_url - Organizations URL
|
||||
* @property {string} repos_url - Repositories URL
|
||||
* @property {string} received_events_url - Received Events URL
|
||||
* @property {string} type - Common value => "User"
|
||||
* @property {boolean} site_admin - Is site admin or not? Boolean
|
||||
* @property {string} name - More like "username"
|
||||
* @property {string} company - User company
|
||||
* @property {string} blog - User blog URL
|
||||
* @property {string} location - User Location
|
||||
* @property {string} email - User Email
|
||||
* @property {string} hireable - Is user hireable
|
||||
* @property {string} bio - User bio
|
||||
* @property {string} twitter_username - User twitter username
|
||||
* @property {number} public_repos - Number of public repositories
|
||||
* @property {number} public_gists - Number of public gists
|
||||
* @property {number} followers - Number of followers
|
||||
* @property {number} following - Number of following
|
||||
* @property {string} created_at - Date created
|
||||
* @property {string} updated_at - Date updated
|
||||
*/
|
||||
|
||||
/**
|
||||
* Login/signup a github user
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - foundUser if any
|
||||
* @param {string} params.code - github auth token
|
||||
* @param {string} params.clientId - github client Id
|
||||
* @param {string} params.clientSecret - github client Secret
|
||||
*
|
||||
* @returns {Promise<GithubUserPayload|null>}
|
||||
*/
|
||||
async function githubLogin({ code, clientId, clientSecret }) {
|
||||
/** @type {GithubUserPayload | null} */
|
||||
let gitHubUser = null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}`);
|
||||
const response = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
});
|
||||
|
||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
|
||||
// body: JSON.stringify({
|
||||
// client_id: process.env.GITHUB_ID,
|
||||
// client_secret: process.env.GITHUB_SECRET,
|
||||
// code: code,
|
||||
// }),
|
||||
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
|
||||
if (!accessTokenObject?.access_token) {
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const userDataResponse = await httpsRequest({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (!gitHubUser?.email) {
|
||||
const existingGithubUser = await dbHandler({
|
||||
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id= ?`,
|
||||
values: [gitHubUser?.id || ""],
|
||||
});
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0] && gitHubUser) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
console.log("ERROR in githubLogin.js backend function =>", error.message);
|
||||
|
||||
// serverError({
|
||||
// component: "/api/social-login/github-auth/catch-error",
|
||||
// message: error.message,
|
||||
// user: user,
|
||||
// });
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
module.exports = githubLogin;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const httpsRequest = require("./httpsRequest");
|
||||
const dbHandler = require("../../../engine/utils/dbHandler");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* @typedef {object} GithubUserPayload
|
||||
* @property {string} login - Full name merged eg. "JohnDoe"
|
||||
* @property {number} id - github user id
|
||||
* @property {string} node_id - Some other id
|
||||
* @property {string} avatar_url - profile picture
|
||||
* @property {string} gravatar_id - some other id
|
||||
* @property {string} url - Github user URL
|
||||
* @property {string} html_url - User html URL - whatever that means
|
||||
* @property {string} followers_url - Followers URL
|
||||
* @property {string} following_url - Following URL
|
||||
* @property {string} gists_url - Gists URL
|
||||
* @property {string} starred_url - Starred URL
|
||||
* @property {string} subscriptions_url - Subscriptions URL
|
||||
* @property {string} organizations_url - Organizations URL
|
||||
* @property {string} repos_url - Repositories URL
|
||||
* @property {string} received_events_url - Received Events URL
|
||||
* @property {string} type - Common value => "User"
|
||||
* @property {boolean} site_admin - Is site admin or not? Boolean
|
||||
* @property {string} name - More like "username"
|
||||
* @property {string} company - User company
|
||||
* @property {string} blog - User blog URL
|
||||
* @property {string} location - User Location
|
||||
* @property {string} email - User Email
|
||||
* @property {string} hireable - Is user hireable
|
||||
* @property {string} bio - User bio
|
||||
* @property {string} twitter_username - User twitter username
|
||||
* @property {number} public_repos - Number of public repositories
|
||||
* @property {number} public_gists - Number of public gists
|
||||
* @property {number} followers - Number of followers
|
||||
* @property {number} following - Number of following
|
||||
* @property {string} created_at - Date created
|
||||
* @property {string} updated_at - Date updated
|
||||
*/
|
||||
|
||||
/**
|
||||
* Login/signup a github user
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - foundUser if any
|
||||
* @param {string} params.code - github auth token
|
||||
* @param {string} params.clientId - github client Id
|
||||
* @param {string} params.clientSecret - github client Secret
|
||||
*
|
||||
* @returns {Promise<GithubUserPayload|null>}
|
||||
*/
|
||||
async function githubLogin({ code, clientId, clientSecret }) {
|
||||
/** @type {GithubUserPayload | null} */
|
||||
let gitHubUser = null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}`);
|
||||
const response = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
});
|
||||
|
||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
|
||||
// body: JSON.stringify({
|
||||
// client_id: process.env.GITHUB_ID,
|
||||
// client_secret: process.env.GITHUB_SECRET,
|
||||
// code: code,
|
||||
// }),
|
||||
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
|
||||
if (!accessTokenObject?.access_token) {
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const userDataResponse = await httpsRequest({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (!gitHubUser?.email) {
|
||||
const existingGithubUser = await dbHandler({
|
||||
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id= ?`,
|
||||
values: [gitHubUser?.id || ""],
|
||||
});
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0] && gitHubUser) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
console.log("ERROR in githubLogin.js backend function =>", error.message);
|
||||
|
||||
// serverError({
|
||||
// component: "/api/social-login/github-auth/catch-error",
|
||||
// message: error.message,
|
||||
// user: user,
|
||||
// });
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
module.exports = githubLogin;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,105 +1,105 @@
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {{
|
||||
* url?: string,
|
||||
* method: string,
|
||||
* hostname: string,
|
||||
* path?: string,
|
||||
* href?: string,
|
||||
* headers?: object,
|
||||
* body?: object,
|
||||
* }} params - params
|
||||
*/
|
||||
function httpsRequest({ url, method, hostname, path, href, headers, body }) {
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let requestOptions = {
|
||||
method: method,
|
||||
hostname: hostname,
|
||||
port: 443,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
if (path) requestOptions.path = path;
|
||||
if (href) requestOptions.href = href;
|
||||
|
||||
if (headers) requestOptions.headers = headers;
|
||||
if (body) {
|
||||
requestOptions.headers["Content-Type"] = "application/json";
|
||||
requestOptions.headers["Content-Length"] = Buffer.from(reqPayloadString || "").length;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return new Promise((res, rej) => {
|
||||
const httpsRequest = https.request(
|
||||
/* ====== Request Options object ====== */
|
||||
// @ts-ignore
|
||||
url ? url : requestOptions,
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/* ====== Callback function ====== */
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
// ## another chunk of data has been received, so append it to `str`
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
// ## the whole response has been received, so we just print it out here
|
||||
response.on("end", function () {
|
||||
res(str);
|
||||
});
|
||||
|
||||
response.on("error", (error) => {
|
||||
console.log("HTTP response error =>", error.message);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
if (body) httpsRequest.write(reqPayloadString);
|
||||
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
});
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
module.exports = httpsRequest;
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {{
|
||||
* url?: string,
|
||||
* method: string,
|
||||
* hostname: string,
|
||||
* path?: string,
|
||||
* href?: string,
|
||||
* headers?: object,
|
||||
* body?: object,
|
||||
* }} params - params
|
||||
*/
|
||||
function httpsRequest({ url, method, hostname, path, href, headers, body }) {
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let requestOptions = {
|
||||
method: method,
|
||||
hostname: hostname,
|
||||
port: 443,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
if (path) requestOptions.path = path;
|
||||
if (href) requestOptions.href = href;
|
||||
|
||||
if (headers) requestOptions.headers = headers;
|
||||
if (body) {
|
||||
requestOptions.headers["Content-Type"] = "application/json";
|
||||
requestOptions.headers["Content-Length"] = Buffer.from(reqPayloadString || "").length;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return new Promise((res, rej) => {
|
||||
const httpsRequest = https.request(
|
||||
/* ====== Request Options object ====== */
|
||||
// @ts-ignore
|
||||
url ? url : requestOptions,
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/* ====== Callback function ====== */
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
// ## another chunk of data has been received, so append it to `str`
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
// ## the whole response has been received, so we just print it out here
|
||||
response.on("end", function () {
|
||||
res(str);
|
||||
});
|
||||
|
||||
response.on("error", (error) => {
|
||||
console.log("HTTP response error =>", error.message);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
if (body) httpsRequest.write(reqPayloadString);
|
||||
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
});
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
module.exports = httpsRequest;
|
||||
|
||||
+85
-85
@@ -1,85 +1,85 @@
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../query/utils/updateDbEntry");
|
||||
|
||||
/**
|
||||
* @typedef {Object} LocalPostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {*} [payload] - GET request results
|
||||
* @property {string} [msg] - Message
|
||||
* @property {string} [error] - Error Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Make a get request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {*} params.payload - SQL Query
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
|
||||
*
|
||||
* @returns { Promise<LocalPostReturn> } - Return Object
|
||||
*/
|
||||
async function localUpdateUser({ payload, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
/**
|
||||
* Initialize Variables
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const finalData = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
if (key?.match(/^date_|^id$/)) return;
|
||||
// @ts-ignore
|
||||
finalData[key] = payload[key];
|
||||
});
|
||||
|
||||
return finalData;
|
||||
})();
|
||||
|
||||
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
const updateUser = await updateDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: payload.id,
|
||||
data: data,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////
|
||||
console.log("Error in local add-user Request =>", error.message);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Something went wrong!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localUpdateUser;
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../query/utils/updateDbEntry");
|
||||
|
||||
/**
|
||||
* @typedef {Object} LocalPostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {*} [payload] - GET request results
|
||||
* @property {string} [msg] - Message
|
||||
* @property {string} [error] - Error Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Make a get request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {*} params.payload - SQL Query
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
|
||||
*
|
||||
* @returns { Promise<LocalPostReturn> } - Return Object
|
||||
*/
|
||||
async function localUpdateUser({ payload, dbSchema }) {
|
||||
try {
|
||||
/**
|
||||
* User auth
|
||||
*
|
||||
* @description Authenticate user
|
||||
*/
|
||||
/**
|
||||
* Initialize Variables
|
||||
*/
|
||||
const dbFullName = process.env.DSQL_DB_NAME || "";
|
||||
|
||||
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
|
||||
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const finalData = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
if (key?.match(/^date_|^id$/)) return;
|
||||
// @ts-ignore
|
||||
finalData[key] = payload[key];
|
||||
});
|
||||
|
||||
return finalData;
|
||||
})();
|
||||
|
||||
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
|
||||
|
||||
const updateUser = await updateDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: payload.id,
|
||||
data: data,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
} catch (/** @type {*} */ error) {
|
||||
////////////////////////////////////////
|
||||
console.log("Error in local add-user Request =>", error.message);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Something went wrong!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = localUpdateUser;
|
||||
|
||||
Reference in New Issue
Block a user