Refactor Code to typescript
This commit is contained in:
-9
@@ -1,9 +0,0 @@
|
||||
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
|
||||
query: string;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").GetReturn>;
|
||||
export = _exports;
|
||||
+20
-19
@@ -1,30 +1,29 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
|
||||
type Param = {
|
||||
query: string;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # 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]
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").GetReturn>}
|
||||
*/
|
||||
module.exports = async function apiGet({
|
||||
export default async function apiGet({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<import("../../../types").GetReturn> {
|
||||
if (
|
||||
typeof query == "string" &&
|
||||
query.match(/^alter|^delete|information_schema|databases|^create/i)
|
||||
@@ -51,7 +50,9 @@ module.exports = async function apiGet({
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
let tableSchema:
|
||||
| import("../../../types").DSQL_TableSchemaType
|
||||
| undefined;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
@@ -77,14 +78,14 @@ module.exports = async function apiGet({
|
||||
results = result;
|
||||
|
||||
/** @type {import("../../../types").GetReturn} */
|
||||
const resObject = {
|
||||
const resObject: import("../../../types").GetReturn = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
return resObject;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
@@ -92,4 +93,4 @@ module.exports = async function apiGet({
|
||||
|
||||
return { success: false, payload: null, error: error.message };
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
|
||||
query: any;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").PostReturn>;
|
||||
export = _exports;
|
||||
+21
-22
@@ -1,30 +1,28 @@
|
||||
// @ts-check
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
type Param = {
|
||||
query: any;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # 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]
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").PostReturn>}
|
||||
*/
|
||||
module.exports = async function apiPost({
|
||||
export default async function apiPost({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<PostReturn> {
|
||||
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
@@ -37,7 +35,7 @@ module.exports = async function apiPost({
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
let results;
|
||||
let results: any;
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
@@ -59,7 +57,9 @@ module.exports = async function apiPost({
|
||||
if (error) throw error;
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
let tableSchema:
|
||||
| import("../../../types").DSQL_TableSchemaType
|
||||
| undefined;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
@@ -76,6 +76,7 @@ module.exports = async function apiPost({
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
@@ -86,9 +87,7 @@ module.exports = async function apiPost({
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
@@ -100,4 +99,4 @@ module.exports = async function apiPost({
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* 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({
|
||||
password: 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_DB_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,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
import { UserType } from "../../../types";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import serverError from "../../backend/serverError";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
export default async function facebookLogin({
|
||||
usertype,
|
||||
body,
|
||||
}: {
|
||||
body: any;
|
||||
usertype: UserType;
|
||||
}) {
|
||||
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({
|
||||
password: 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}'`
|
||||
);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
declare namespace _exports {
|
||||
export { GithubUserPayload };
|
||||
}
|
||||
declare function _exports({ code, clientId, clientSecret }: {
|
||||
code: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
}): Promise<GithubUserPayload | null | undefined>;
|
||||
export = _exports;
|
||||
type GithubUserPayload = {
|
||||
/**
|
||||
* - Full name merged eg. "JohnDoe"
|
||||
*/
|
||||
login: string;
|
||||
/**
|
||||
* - github user id
|
||||
*/
|
||||
id: number;
|
||||
/**
|
||||
* - Some other id
|
||||
*/
|
||||
node_id: string;
|
||||
/**
|
||||
* - profile picture
|
||||
*/
|
||||
avatar_url: string;
|
||||
/**
|
||||
* - some other id
|
||||
*/
|
||||
gravatar_id: string;
|
||||
/**
|
||||
* - Github user URL
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* - User html URL - whatever that means
|
||||
*/
|
||||
html_url: string;
|
||||
/**
|
||||
* - Followers URL
|
||||
*/
|
||||
followers_url: string;
|
||||
/**
|
||||
* - Following URL
|
||||
*/
|
||||
following_url: string;
|
||||
/**
|
||||
* - Gists URL
|
||||
*/
|
||||
gists_url: string;
|
||||
/**
|
||||
* - Starred URL
|
||||
*/
|
||||
starred_url: string;
|
||||
/**
|
||||
* - Subscriptions URL
|
||||
*/
|
||||
subscriptions_url: string;
|
||||
/**
|
||||
* - Organizations URL
|
||||
*/
|
||||
organizations_url: string;
|
||||
/**
|
||||
* - Repositories URL
|
||||
*/
|
||||
repos_url: string;
|
||||
/**
|
||||
* - Received Events URL
|
||||
*/
|
||||
received_events_url: string;
|
||||
/**
|
||||
* - Common value => "User"
|
||||
*/
|
||||
type: string;
|
||||
/**
|
||||
* - Is site admin or not? Boolean
|
||||
*/
|
||||
site_admin: boolean;
|
||||
/**
|
||||
* - More like "username"
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* - User company
|
||||
*/
|
||||
company: string;
|
||||
/**
|
||||
* - User blog URL
|
||||
*/
|
||||
blog: string;
|
||||
/**
|
||||
* - User Location
|
||||
*/
|
||||
location: string;
|
||||
/**
|
||||
* - User Email
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* - Is user hireable
|
||||
*/
|
||||
hireable: string;
|
||||
/**
|
||||
* - User bio
|
||||
*/
|
||||
bio: string;
|
||||
/**
|
||||
* - User twitter username
|
||||
*/
|
||||
twitter_username: string;
|
||||
/**
|
||||
* - Number of public repositories
|
||||
*/
|
||||
public_repos: number;
|
||||
/**
|
||||
* - Number of public gists
|
||||
*/
|
||||
public_gists: number;
|
||||
/**
|
||||
* - Number of followers
|
||||
*/
|
||||
followers: number;
|
||||
/**
|
||||
* - Number of following
|
||||
*/
|
||||
following: number;
|
||||
/**
|
||||
* - Date created
|
||||
*/
|
||||
created_at: string;
|
||||
/**
|
||||
* - Date updated
|
||||
*/
|
||||
updated_at: string;
|
||||
};
|
||||
@@ -1,160 +0,0 @@
|
||||
// @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;
|
||||
};
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import httpsRequest from "../../backend/httpsRequest";
|
||||
|
||||
export interface GithubUserPayload {
|
||||
login: string;
|
||||
id: number;
|
||||
node_id: string;
|
||||
avatar_url: string;
|
||||
gravatar_id: string;
|
||||
url: string;
|
||||
html_url: string;
|
||||
followers_url: string;
|
||||
following_url: string;
|
||||
gists_url: string;
|
||||
starred_url: string;
|
||||
subscriptions_url: string;
|
||||
organizations_url: string;
|
||||
repos_url: string;
|
||||
received_events_url: string;
|
||||
type: string;
|
||||
site_admin: boolean;
|
||||
name: string;
|
||||
company: string;
|
||||
blog: string;
|
||||
location: string;
|
||||
email: string;
|
||||
hireable: string;
|
||||
bio: string;
|
||||
twitter_username: string;
|
||||
public_repos: number;
|
||||
public_gists: number;
|
||||
followers: number;
|
||||
following: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
type Param = {
|
||||
code: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Login/signup a github user
|
||||
*/
|
||||
export default async function githubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
}: Param): Promise<GithubUserPayload | null | undefined> {
|
||||
let gitHubUser: GithubUserPayload | undefined;
|
||||
|
||||
try {
|
||||
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",
|
||||
});
|
||||
|
||||
const accessTokenObject = JSON.parse(response as string);
|
||||
|
||||
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 as string);
|
||||
|
||||
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: any) {
|
||||
console.log(
|
||||
"ERROR in githubLogin.js backend function =>",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
return gitHubUser;
|
||||
}
|
||||
+20
-49
@@ -1,44 +1,23 @@
|
||||
// @ts-check
|
||||
import fs from "fs";
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import serverError from "../../backend/serverError";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
type Param = {
|
||||
usertype: string;
|
||||
foundUser: any;
|
||||
isSocialValidated: boolean;
|
||||
isUserValid: boolean;
|
||||
reqBody: any;
|
||||
serverRes: any;
|
||||
loginFailureReason: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
* # Google Login
|
||||
*/
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
|
||||
const serverError = require("../../backend/serverError");
|
||||
const { ServerResponse } = require("http");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* 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({
|
||||
export default async function googleLogin({
|
||||
usertype,
|
||||
foundUser,
|
||||
isSocialValidated,
|
||||
@@ -46,7 +25,7 @@ module.exports = async function googleLogin({
|
||||
reqBody,
|
||||
serverRes,
|
||||
loginFailureReason,
|
||||
}) {
|
||||
}: Param) {
|
||||
const client = new OAuth2Client(
|
||||
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
||||
);
|
||||
@@ -156,11 +135,7 @@ module.exports = async function googleLogin({
|
||||
newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
@@ -172,9 +147,5 @@ module.exports = async function googleLogin({
|
||||
isSocialValidated = false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
};
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _exports: import("../../../types").HandleSocialDbFunction;
|
||||
export = _exports;
|
||||
+19
-18
@@ -1,18 +1,20 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
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 loginSocialUser = require("./loginSocialUser");
|
||||
import fs from "fs";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import path from "path";
|
||||
import addMariadbUser from "../../backend/addMariadbUser";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import loginSocialUser from "./loginSocialUser";
|
||||
import {
|
||||
APILoginFunctionReturn,
|
||||
HandleSocialDbFunctionParams,
|
||||
} from "../../../types";
|
||||
|
||||
/**
|
||||
* @type {import("../../../types").HandleSocialDbFunction}
|
||||
* # Handle Social DB
|
||||
*/
|
||||
module.exports = async function handleSocialDb({
|
||||
export default async function handleSocialDb({
|
||||
database,
|
||||
social_id,
|
||||
email,
|
||||
@@ -22,7 +24,7 @@ module.exports = async function handleSocialDb({
|
||||
supEmail,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
}: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
try {
|
||||
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialIdUserValues = [
|
||||
@@ -99,8 +101,7 @@ module.exports = async function handleSocialDb({
|
||||
data: social_id.toString(),
|
||||
});
|
||||
|
||||
/** @type {any} */
|
||||
const data = {
|
||||
const data: { [k: string]: any } = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
@@ -173,7 +174,7 @@ module.exports = async function handleSocialDb({
|
||||
)
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then((mail) => {});
|
||||
}).then(() => {});
|
||||
}
|
||||
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
@@ -230,7 +231,7 @@ module.exports = async function handleSocialDb({
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||
};
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
"ERROR in 'handleSocialDb.js' backend function =>",
|
||||
error.message
|
||||
@@ -242,4 +243,4 @@ module.exports = async function handleSocialDb({
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
export = loginSocialUser;
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - function parameters inside an object
|
||||
* @param {{
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* email: string,
|
||||
* social_id: string|number,
|
||||
* }} params.user - user object
|
||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
||||
* @param {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
declare function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: {
|
||||
user: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
social_id: string | number;
|
||||
};
|
||||
social_platform: string;
|
||||
invitation?: any;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
||||
+20
-29
@@ -1,42 +1,35 @@
|
||||
// @ts-check
|
||||
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
|
||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
||||
const { ServerResponse } = require("http");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
type Param = {
|
||||
user: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
social_id: string | number;
|
||||
};
|
||||
social_platform: string;
|
||||
invitation?: any;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - function parameters inside an object
|
||||
* @param {{
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* email: string,
|
||||
* social_id: string|number,
|
||||
* }} params.user - user object
|
||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
||||
* @param {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
async function loginSocialUser({
|
||||
export default async function loginSocialUser({
|
||||
user,
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||
|
||||
@@ -59,7 +52,7 @@ async function loginSocialUser({
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -92,7 +85,7 @@ async function loginSocialUser({
|
||||
}
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
let result = {
|
||||
let result: import("../../../types").APILoginFunctionReturn = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
@@ -100,5 +93,3 @@ async function loginSocialUser({
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = loginSocialUser;
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _exports: import("../../../types").APICreateUserFunction;
|
||||
export = _exports;
|
||||
+13
-12
@@ -1,19 +1,22 @@
|
||||
// @ts-check
|
||||
|
||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const updateUsersTableSchema = require("../../backend/updateUsersTableSchema");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
import { APICreateUserFunctionParams } from "../../../types";
|
||||
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
/** @type {import("../../../types").APICreateUserFunction} */
|
||||
module.exports = async function apiCreateUser({
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
export default async function apiCreateUser({
|
||||
encryptionKey,
|
||||
payload,
|
||||
database,
|
||||
userId,
|
||||
useLocal,
|
||||
}) {
|
||||
}: APICreateUserFunctionParams) {
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
|
||||
@@ -73,9 +76,7 @@ module.exports = async function apiCreateUser({
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map(
|
||||
(/** @type {any} */ fieldObject) => fieldObject.Field
|
||||
);
|
||||
const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field);
|
||||
|
||||
let invalidField = null;
|
||||
|
||||
@@ -159,4 +160,4 @@ module.exports = async function apiCreateUser({
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
declare function _exports({ dbFullName, deletedUserId, useLocal, }: {
|
||||
dbFullName: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
result?: any;
|
||||
msg?: string;
|
||||
}>;
|
||||
export = _exports;
|
||||
+11
-13
@@ -1,23 +1,21 @@
|
||||
// @ts-check
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
const deleteDbEntry = require("../../backend/db/deleteDbEntry");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
type Return = { success: boolean; result?: any; msg?: string };
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.deletedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, result?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiDeleteUser({
|
||||
export default async function apiDeleteUser({
|
||||
dbFullName,
|
||||
deletedUserId,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<Return> {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
|
||||
@@ -49,4 +47,4 @@ module.exports = async function apiDeleteUser({
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _exports: import("../../../types").APIGetUserFunction;
|
||||
export = _exports;
|
||||
+11
-7
@@ -1,14 +1,18 @@
|
||||
// @ts-check
|
||||
import {
|
||||
APIGetUserFunctionParams,
|
||||
GetUserFunctionReturn,
|
||||
} from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/** @type {import("../../../types").APIGetUserFunction} */
|
||||
module.exports = async function apiGetUser({
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
export default async function apiGetUser({
|
||||
fields,
|
||||
dbFullName,
|
||||
userId,
|
||||
useLocal,
|
||||
}) {
|
||||
}: APIGetUserFunctionParams): Promise<GetUserFunctionReturn> {
|
||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
|
||||
@@ -30,4 +34,4 @@ module.exports = async function apiGetUser({
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _exports: import("../../../types").APILoginFunction;
|
||||
export = _exports;
|
||||
+16
-16
@@ -1,10 +1,15 @@
|
||||
// @ts-check
|
||||
import {
|
||||
APILoginFunctionParams,
|
||||
APILoginFunctionReturn,
|
||||
DATASQUIREL_LoggedInUser,
|
||||
} from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APILoginFunction} */
|
||||
module.exports = async function apiLoginUser({
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default async function apiLoginUser({
|
||||
encryptionKey,
|
||||
email,
|
||||
username,
|
||||
@@ -18,7 +23,7 @@ module.exports = async function apiLoginUser({
|
||||
skipPassword,
|
||||
social,
|
||||
useLocal,
|
||||
}) {
|
||||
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
const dbFullName = database;
|
||||
|
||||
/**
|
||||
@@ -115,8 +120,7 @@ module.exports = async function apiLoginUser({
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -135,14 +139,10 @@ module.exports = async function apiLoginUser({
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
const resposeObject = {
|
||||
const resposeObject: APILoginFunctionReturn = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload:
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ (
|
||||
userPayload
|
||||
),
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
@@ -158,4 +158,4 @@ module.exports = async function apiLoginUser({
|
||||
}
|
||||
|
||||
return resposeObject;
|
||||
};
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
declare function _exports({ existingUser, database, additionalFields, useLocal, }: {
|
||||
existingUser: {
|
||||
[x: string]: any;
|
||||
};
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
||||
export = _exports;
|
||||
+12
-28
@@ -1,25 +1,22 @@
|
||||
// @ts-check
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
type Param = {
|
||||
existingUser: { [s: string]: any };
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
* @param {object} param
|
||||
* @param {Object<string, any>} param.existingUser
|
||||
* @param {string} [param.database]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {boolean} [param.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
module.exports = async function apiReauthUser({
|
||||
export default async function apiReauthUser({
|
||||
existingUser,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
@@ -30,10 +27,6 @@ module.exports = async function apiReauthUser({
|
||||
})
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
@@ -41,17 +34,13 @@ module.exports = async function apiReauthUser({
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -80,15 +69,10 @@ module.exports = async function apiReauthUser({
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
declare function _exports({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
html: string;
|
||||
useLocal?: boolean;
|
||||
response?: http.ServerResponse & {
|
||||
[x: string]: any;
|
||||
};
|
||||
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
||||
}): Promise<import("../../../types").SendOneTimeCodeEmailResponse>;
|
||||
export = _exports;
|
||||
import http = require("http");
|
||||
+51
-46
@@ -1,32 +1,30 @@
|
||||
// @ts-check
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import nodemailer, { SendMailOptions } from "nodemailer";
|
||||
import http from "http";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../utils/serialize-cookies";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../../types";
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
const http = require("http");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const serializeCookies = require("../../../utils/serialize-cookies");
|
||||
type Param = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
html: string;
|
||||
useLocal?: boolean;
|
||||
response?: http.ServerResponse & { [s: string]: any };
|
||||
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
||||
};
|
||||
|
||||
/**
|
||||
* # 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
|
||||
* @param {boolean} [param.useLocal]
|
||||
* @param {http.ServerResponse & Object<string,any>} [param.response]
|
||||
* @param {import("../../../../package-shared/types").CookieObject[]} [param.extraCookies]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").SendOneTimeCodeEmailResponse>}
|
||||
*/
|
||||
module.exports = async function apiSendEmailCode({
|
||||
export default async function apiSendEmailCode({
|
||||
email,
|
||||
database,
|
||||
email_login_field,
|
||||
@@ -39,7 +37,7 @@ module.exports = async function apiSendEmailCode({
|
||||
useLocal,
|
||||
response,
|
||||
extraCookies,
|
||||
}) {
|
||||
}: Param): Promise<SendOneTimeCodeEmailResponse> {
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -83,7 +81,11 @@ module.exports = async function apiSendEmailCode({
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port || process.env.DSQL_MAIL_PORT || 465,
|
||||
port: mail_port
|
||||
? mail_port
|
||||
: process.env.DSQL_MAIL_PORT
|
||||
? Number(process.env.DSQL_MAIL_PORT)
|
||||
: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
@@ -91,7 +93,7 @@ module.exports = async function apiSendEmailCode({
|
||||
},
|
||||
});
|
||||
|
||||
let mailObject = {};
|
||||
let mailObject: SendMailOptions = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${
|
||||
sender || "support@datasquirel.com"
|
||||
@@ -116,13 +118,14 @@ module.exports = async function apiSendEmailCode({
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
const resObject: import("../../../types").SendOneTimeCodeEmailResponse =
|
||||
{
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
|
||||
if (response) {
|
||||
const cookieKeyNames = getAuthCookieNames();
|
||||
@@ -139,19 +142,21 @@ module.exports = async function apiSendEmailCode({
|
||||
}
|
||||
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
const oneTimeCookieObject: import("../../../../package-shared/types").CookieObject =
|
||||
{
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const cookiesObjectArray: import("../../../../package-shared/types").CookieObject[] =
|
||||
extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
@@ -167,4 +172,4 @@ module.exports = async function apiSendEmailCode({
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
declare function _exports({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: {
|
||||
payload: {
|
||||
[x: string]: any;
|
||||
};
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
payload?: any;
|
||||
msg?: string;
|
||||
}>;
|
||||
export = _exports;
|
||||
+18
-17
@@ -1,29 +1,30 @@
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
type Param = {
|
||||
payload: { [s: string]: any };
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
};
|
||||
|
||||
type Return = { success: boolean; payload?: any; msg?: string };
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {Object<string, any>} params.payload
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.updatedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, payload?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiUpdateUser({
|
||||
export default async function apiUpdateUser({
|
||||
payload,
|
||||
dbFullName,
|
||||
updatedUserId,
|
||||
useLocal,
|
||||
dbSchema,
|
||||
}) {
|
||||
}: Param): Promise<Return> {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
|
||||
@@ -56,7 +57,7 @@ module.exports = async function apiUpdateUser({
|
||||
})();
|
||||
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
const finalData: any = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
const targetFieldSchema = targetTableSchema?.fields?.find(
|
||||
@@ -95,4 +96,4 @@ module.exports = async function apiUpdateUser({
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
declare function _exports({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: {
|
||||
code?: string;
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: {
|
||||
[x: string]: string | number;
|
||||
};
|
||||
email?: string;
|
||||
}): Promise<import("../../../../types").APILoginFunctionReturn>;
|
||||
export = _exports;
|
||||
+17
-18
@@ -1,23 +1,22 @@
|
||||
// @ts-check
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||
import { APILoginFunctionReturn } from "../../../../types";
|
||||
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const githubLogin = require("../../social-login/githubLogin");
|
||||
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");
|
||||
type Param = {
|
||||
code?: string;
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: { [s: string]: string | number };
|
||||
email?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Login with Github
|
||||
* @param {object} param
|
||||
* @param {string} [param.code]
|
||||
* @param {string} [param.clientId]
|
||||
* @param {string} [param.clientSecret]
|
||||
* @param {string} [param.database]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {Object<string,string|number>} [param.additionalData]
|
||||
* @param {string} [param.email]
|
||||
*
|
||||
* @returns {Promise<import("../../../../types").APILoginFunctionReturn>}
|
||||
* # API Login with Github
|
||||
*/
|
||||
module.exports = async function apiGithubLogin({
|
||||
export default async function apiGithubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
@@ -25,7 +24,7 @@ module.exports = async function apiGithubLogin({
|
||||
additionalFields,
|
||||
email,
|
||||
additionalData,
|
||||
}) {
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -101,4 +100,4 @@ module.exports = async function apiGithubLogin({
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGithubUser };
|
||||
};
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _exports: import("../../../../types").APIGoogleLoginFunction;
|
||||
export = _exports;
|
||||
+40
-34
@@ -1,41 +1,47 @@
|
||||
// @ts-check
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
import {
|
||||
APIGoogleLoginFunctionParams,
|
||||
APILoginFunctionReturn,
|
||||
GoogleOauth2User,
|
||||
} from "../../../../types";
|
||||
|
||||
const https = require("https");
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const EJSON = require("../../../../utils/ejson");
|
||||
|
||||
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
||||
module.exports = async function apiGoogleLogin({
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
export default async function apiGoogleLogin({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
}) {
|
||||
}: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
try {
|
||||
/** @type {import("../../../../types").GoogleOauth2User | undefined} */
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request(
|
||||
{
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
const gUser: GoogleOauth2User | undefined = await new Promise(
|
||||
(resolve, reject) => {
|
||||
https
|
||||
.request(
|
||||
{
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(/** @type {any} */ (EJSON.parse(data)));
|
||||
});
|
||||
}
|
||||
)
|
||||
.end();
|
||||
});
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(EJSON.parse(data) as any);
|
||||
});
|
||||
}
|
||||
)
|
||||
.end();
|
||||
}
|
||||
);
|
||||
|
||||
if (!gUser?.email_verified) throw new Error("No Google User.");
|
||||
|
||||
@@ -60,7 +66,7 @@ module.exports = async function apiGoogleLogin({
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
|
||||
/** @type {Object<string, any>} */
|
||||
let payloadObject = {
|
||||
let payloadObject: { [s: string]: any } = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
@@ -89,7 +95,7 @@ module.exports = async function apiGoogleLogin({
|
||||
////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGoogleUser };
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||
|
||||
return {
|
||||
@@ -98,4 +104,4 @@ module.exports = async function apiGoogleLogin({
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user