Updates
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").GetReturn>}
|
||||
*/
|
||||
module.exports = async function apiGet({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
}) {
|
||||
if (
|
||||
typeof query == "string" &&
|
||||
(query.match(/^alter|^delete|information_schema|databases|^create/i) ||
|
||||
!query.match(/^select/i))
|
||||
) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
let results;
|
||||
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
queryValuesArray: queryValues,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
(table) => table.tableName === tableName
|
||||
);
|
||||
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
|
||||
if (error) throw error;
|
||||
if (result.error) throw new Error(result.error);
|
||||
|
||||
results = result;
|
||||
|
||||
/** @type {import("../../../types").GetReturn} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
return resObject;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return { success: false, payload: null, error: error.message };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
|
||||
/**
|
||||
* # Post Function For API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {any} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").PostReturn>}
|
||||
*/
|
||||
module.exports = async function apiPost({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
}) {
|
||||
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
if (
|
||||
typeof query === "object" &&
|
||||
query?.action?.match(/^create |^alter |^drop /i)
|
||||
) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
dbSchema: dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
});
|
||||
|
||||
results = result;
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
(table) => table.tableName === tableName
|
||||
);
|
||||
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
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");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - parameters object
|
||||
* @param {any} params.body
|
||||
* @param {import("../../../types").UserType} params.usertype
|
||||
*/
|
||||
module.exports = async function facebookLogin({ usertype, body }) {
|
||||
try {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let socialHashedPassword = hashPassword(body.facebookUserId);
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
social_id,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${body.facebookUserFirstName}',
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${
|
||||
body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()
|
||||
}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'${body.facebookUserId}',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
const newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Send email notifications to admin
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
// handleNodemailer({
|
||||
// to: "",
|
||||
// subject: "New Registered Buyer",
|
||||
// text: "We have a new registered Buyer from facebook",
|
||||
// html: `
|
||||
// <h2>${newFoundUser[0].first_name} ${newFoundUser[0].last_name} just registered from facebook.</h2>
|
||||
// <p>We have a new buyer registration</p>
|
||||
// <div>Name: <b>${newFoundUser[0].first_name} ${newFoundUser[0].last_name}</b></div>
|
||||
// <div>Email: <b>${newFoundUser[0].email}</b></div>
|
||||
// <div>Site: <b>${process.env.DSQL_HOST}</b></div>
|
||||
// `,
|
||||
// }).catch((error) => {
|
||||
// console.log(
|
||||
// "error in mail notification for new Facebook user =>",
|
||||
// error.message
|
||||
// );
|
||||
// });
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
};
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const httpsRequest = require("../../backend/httpsRequest");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* @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|undefined>}
|
||||
*/
|
||||
module.exports = async function githubLogin({ code, clientId, clientSecret }) {
|
||||
/** @type {GithubUserPayload | undefined} */
|
||||
let gitHubUser;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
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.DSQL_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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}&client_secret=${process.env.DSQL_GITHUB_SECRET}&code=${code}`,
|
||||
// body: JSON.stringify({
|
||||
// client_id: process.env.DSQL_GITHUB_ID,
|
||||
// client_secret: process.env.DSQL_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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (!gitHubUser?.email && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(
|
||||
`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`
|
||||
);
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ 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;
|
||||
};
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
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");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string} params.usertype
|
||||
* @param {any} params.foundUser
|
||||
* @param {boolean} params.isSocialValidated
|
||||
* @param {boolean} params.isUserValid
|
||||
* @param {any} params.reqBody
|
||||
* @param {any} params.serverRes
|
||||
* @param {any} params.loginFailureReason
|
||||
*/
|
||||
module.exports = async function googleLogin({
|
||||
usertype,
|
||||
foundUser,
|
||||
isSocialValidated,
|
||||
isUserValid,
|
||||
reqBody,
|
||||
serverRes,
|
||||
loginFailureReason,
|
||||
}) {
|
||||
const client = new OAuth2Client(
|
||||
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
||||
);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
// Or, if multiple clients access the backend:
|
||||
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||
});
|
||||
|
||||
const payload = ticket.getPayload();
|
||||
const userid = payload?.["sub"];
|
||||
|
||||
if (!payload)
|
||||
throw new Error("Google login failed. Credentials invalid");
|
||||
|
||||
isUserValid = Boolean(payload.email_verified);
|
||||
|
||||
if (!isUserValid || !payload || !payload.email_verified) return;
|
||||
|
||||
serverRes.isUserValid = payload.email_verified;
|
||||
isSocialValidated = payload.email_verified;
|
||||
isGoogleAuthValid = payload.email_verified;
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
|
||||
let socialHashedPassword = hashPassword(payload.at_hash || "");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let existinEmail = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`
|
||||
);
|
||||
|
||||
if (existinEmail && existinEmail[0]) {
|
||||
loginFailureReason = "Email Exists Already";
|
||||
isGoogleAuthValid = false;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
loginFailureReason: loginFailureReason,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
newFoundUser = foundUser;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
social_id,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${payload.email?.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
'${payload.picture}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
loginFailureReason = error;
|
||||
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
};
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
// @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");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* @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"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {import("../../../types").HandleSocialDbFunction}
|
||||
*/
|
||||
module.exports = async function handleSocialDb({
|
||||
database,
|
||||
social_id,
|
||||
email,
|
||||
social_platform,
|
||||
payload,
|
||||
res,
|
||||
invitation,
|
||||
supEmail,
|
||||
additionalFields,
|
||||
}) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let existingSocialIdUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `,
|
||||
queryValuesArray: [social_id.toString(), social_platform],
|
||||
});
|
||||
|
||||
if (existingSocialIdUser && existingSocialIdUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingSocialIdUser[0],
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "No Email Present",
|
||||
social_id,
|
||||
social_platform,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: `SELECT * FROM users WHERE email='${finalEmail}'`,
|
||||
});
|
||||
|
||||
if (existingEmailOnly && existingEmailOnly[0]) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "This Email is already taken",
|
||||
alert: true,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`,
|
||||
});
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: payload,
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const socialHashedPassword = encrypt({
|
||||
data: social_id.toString(),
|
||||
});
|
||||
|
||||
/** @type {any} */
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
|
||||
/** @type {any} */
|
||||
const newUser = await addDbEntry({
|
||||
dbContext: database ? "Dsql User" : undefined,
|
||||
paradigm: database ? "Full Access" : undefined,
|
||||
dbFullName: database ? database : "datasquirel",
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: {
|
||||
...data,
|
||||
email: finalEmail,
|
||||
},
|
||||
});
|
||||
|
||||
if (newUser?.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
await addMariadbUser({ userId: newUser.insertId });
|
||||
}
|
||||
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: `SELECT * FROM users WHERE id='${newUser.insertId}'`,
|
||||
});
|
||||
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (supEmail && database?.match(/^datasquirel$/)) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = encrypt({
|
||||
data: JSON.stringify({
|
||||
id: newUser.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
|
||||
handleNodemailer({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs
|
||||
.readFileSync(
|
||||
"./email/send-email-verification-link.html",
|
||||
"utf8"
|
||||
)
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then((mail) => {});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || database?.match(/^datasquirel$/)) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
||||
|
||||
let newUserMediaFolderPath = path.join(
|
||||
STATIC_ROOT,
|
||||
`images/user-images/user-${newUser.insertId}`
|
||||
);
|
||||
|
||||
fs.mkdirSync(newUserSchemaFolderPath);
|
||||
fs.mkdirSync(newUserMediaFolderPath);
|
||||
|
||||
fs.writeFileSync(
|
||||
`${newUserSchemaFolderPath}/main.json`,
|
||||
JSON.stringify([]),
|
||||
"utf8"
|
||||
);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return await loginSocialUser({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} else {
|
||||
console.log(
|
||||
"Social User Failed to insert in 'handleSocialDb.js' backend function =>",
|
||||
newUser
|
||||
);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function => ",
|
||||
newUser: newUser,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
"ERROR in 'handleSocialDb.js' backend function =>",
|
||||
error.message
|
||||
);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
error: 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
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
async function loginSocialUser({
|
||||
user,
|
||||
social_platform,
|
||||
res,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
}) {
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`,
|
||||
});
|
||||
|
||||
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,117 @@
|
||||
// @ts-check
|
||||
|
||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APICreateUserFunction} */
|
||||
module.exports = async function apiCreateUser({
|
||||
encryptionKey,
|
||||
payload,
|
||||
database,
|
||||
userId,
|
||||
}) {
|
||||
const dbFullName = database;
|
||||
|
||||
const hashedPassword = hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
|
||||
payload.password = hashedPassword;
|
||||
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
if (!fields) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(userId),
|
||||
database: database,
|
||||
});
|
||||
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
|
||||
if (!fields) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map(
|
||||
(/** @type {any} */ 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,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
if (existingUser?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
const addUser = await addDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: {
|
||||
...payload,
|
||||
image: "/images/user-preset.png",
|
||||
image_thumbnail: "/images/user-preset-thumbnail.png",
|
||||
},
|
||||
});
|
||||
|
||||
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,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/** @type {import("../../../types").APIGetUserFunction} */
|
||||
module.exports = async function apiGetUser({ fields, dbFullName, userId }) {
|
||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APILoginFunction} */
|
||||
module.exports = async function apiLoginUser({
|
||||
encryptionKey,
|
||||
email,
|
||||
username,
|
||||
password,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field,
|
||||
token,
|
||||
skipPassword,
|
||||
social,
|
||||
}) {
|
||||
const dbFullName = database;
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (
|
||||
email?.match(/ /) ||
|
||||
(username && username?.match(/ /)) ||
|
||||
(password && password?.match(/ /))
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
|
||||
let isSocialValidated = false;
|
||||
let loginFailureReason = null;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
let isPasswordCorrect = false;
|
||||
|
||||
if (foundUser?.[0] && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
} else if (foundUser?.[0] && !email_login) {
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
} else if (
|
||||
foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field
|
||||
) {
|
||||
/** @type {string} */
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
|
||||
if (!tempCode) throw new Error("No code Found!");
|
||||
|
||||
const tempCodeArray = tempCode.split("-");
|
||||
const [code, codeDate] = tempCodeArray;
|
||||
const millisecond15mins = 1000 * 60 * 15;
|
||||
|
||||
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||
throw new Error("Code Expired");
|
||||
}
|
||||
isPasswordCorrect = code === email_login_code;
|
||||
}
|
||||
|
||||
let socialUserValid = false;
|
||||
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (isPasswordCorrect && email_login) {
|
||||
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, ""),
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
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(),
|
||||
};
|
||||
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload:
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ (
|
||||
userPayload
|
||||
),
|
||||
userId: foundUser[0].id,
|
||||
};
|
||||
|
||||
if (
|
||||
additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0
|
||||
) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
return resposeObject;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
* @param {object} param
|
||||
* @param {Object<string, any>} param.existingUser
|
||||
* @param {string} param.database
|
||||
* @param {string | number} [param.userId]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").ApiReauthUserReturn>}
|
||||
*/
|
||||
module.exports = async function apiReauthUser({
|
||||
existingUser,
|
||||
database,
|
||||
userId,
|
||||
additionalFields,
|
||||
}) {
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: 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);
|
||||
|
||||
/** @type {Object<string, string | number | boolean>} */
|
||||
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) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*
|
||||
* @param {object} param
|
||||
* @param {string} param.email
|
||||
* @param {string} param.database
|
||||
* @param {string} [param.email_login_field]
|
||||
* @param {string} [param.mail_domain]
|
||||
* @param {number} [param.mail_port]
|
||||
* @param {string} [param.sender]
|
||||
* @param {string} [param.mail_username]
|
||||
* @param {string} [param.mail_password]
|
||||
* @param {string} param.html
|
||||
*
|
||||
* @returns {Promise<{success: boolean, msg?: string}>}
|
||||
*/
|
||||
module.exports = async function apiSendEmailCode({
|
||||
email,
|
||||
database,
|
||||
email_login_field,
|
||||
mail_domain,
|
||||
mail_port,
|
||||
sender,
|
||||
mail_username,
|
||||
mail_password,
|
||||
html,
|
||||
}) {
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?`,
|
||||
queryValuesArray: [email],
|
||||
database,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
}
|
||||
|
||||
function generateCode() {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
if (foundUser && foundUser[0] && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port || 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
let mailObject = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${
|
||||
sender || "support@datasquirel.com"
|
||||
}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
|
||||
const info = await transporter.sendMail(mailObject);
|
||||
|
||||
if (!info?.accepted) throw new Error("Mail not Sent!");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ?`,
|
||||
queryValuesArray: [tempCode + `-${Date.now()}`, email],
|
||||
database: database,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: "Success",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {{ id: string | number } & Object<string, (string | number | null | undefined)>} params.payload
|
||||
* @param {string} params.dbFullName
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, payload: any }>}
|
||||
*/
|
||||
module.exports = async function apiUpdateUser({ payload, dbFullName }) {
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
if (key?.match(/^date_|^id$/)) return;
|
||||
finalData[key] = payload[key];
|
||||
});
|
||||
|
||||
return finalData;
|
||||
})();
|
||||
|
||||
const updateUser = await updateDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: payload.id,
|
||||
data: data,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
// @ts-check
|
||||
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const githubLogin = require("../../social-login/githubLogin");
|
||||
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");
|
||||
|
||||
/**
|
||||
* # Login with Github
|
||||
* @param {object} param
|
||||
* @param {string} [param.code]
|
||||
* @param {string} [param.clientId]
|
||||
* @param {string} [param.clientSecret]
|
||||
* @param {string} [param.database]
|
||||
* @param {Object<string, any>} [param.additionalFields]
|
||||
* @param {any} [param.res]
|
||||
* @param {string} [param.email]
|
||||
* @param {string | number} [param.userId]
|
||||
*
|
||||
* @returns {Promise<import("../../../../types").APIGoogleLoginFunctionReturn>}
|
||||
*/
|
||||
module.exports = async function apiGithubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
res,
|
||||
email,
|
||||
userId,
|
||||
}) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
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 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,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
social_platform: "github",
|
||||
res: res,
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { success: true, ...loggedInGithubUser, dsqlUserId: userId };
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
// @ts-check
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
|
||||
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
||||
module.exports = async function apiGoogleLogin({
|
||||
clientId,
|
||||
token,
|
||||
database,
|
||||
userId,
|
||||
additionalFields,
|
||||
res,
|
||||
}) {
|
||||
const client = new OAuth2Client(clientId);
|
||||
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: token,
|
||||
audience: clientId,
|
||||
});
|
||||
|
||||
if (!ticket?.getPayload()?.email_verified) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
};
|
||||
}
|
||||
|
||||
const payload = ticket.getPayload();
|
||||
|
||||
if (!payload) throw new Error("No Payload");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
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 = `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 };
|
||||
};
|
||||
Reference in New Issue
Block a user