Roll Back compile version
This commit is contained in:
+81
-64
@@ -1,73 +1,90 @@
|
||||
import path from "path";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import serializeQuery from "../../utils/serialize-query";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = queryDSQLAPI;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const serialize_query_1 = __importDefault(require("../../utils/serialize-query"));
|
||||
/**
|
||||
* # Query DSQL API
|
||||
*/
|
||||
export default async function queryDSQLAPI({ body, query, useDefault, path: passedPath, method, apiKey, }) {
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = body ? JSON.stringify(body) : undefined;
|
||||
let headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: apiKey ||
|
||||
(!method || method == "GET" || method == "get"
|
||||
? process.env.DSQL_READ_ONLY_API_KEY
|
||||
: undefined) ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
};
|
||||
if (reqPayload) {
|
||||
headers["Content-Length"] = Buffer.from(reqPayload).length;
|
||||
}
|
||||
let finalPath = path.join("/", passedPath);
|
||||
if (query) {
|
||||
const queryString = serializeQuery(query);
|
||||
finalPath += `${queryString}`;
|
||||
}
|
||||
const httpsRequest = scheme.request({
|
||||
method: method || "GET",
|
||||
headers,
|
||||
port,
|
||||
hostname: host,
|
||||
path: finalPath,
|
||||
},
|
||||
function queryDSQLAPI(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ body, query, useDefault, path: passedPath, method, apiKey, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Callback Function
|
||||
* Make https request
|
||||
*
|
||||
* @description https request callback
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = body ? JSON.stringify(body) : undefined;
|
||||
let headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: apiKey ||
|
||||
(!method || method == "GET" || method == "get"
|
||||
? process.env.DSQL_READ_ONLY_API_KEY
|
||||
: undefined) ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
};
|
||||
if (reqPayload) {
|
||||
headers["Content-Length"] = Buffer.from(reqPayload).length;
|
||||
}
|
||||
let finalPath = path_1.default.join("/", passedPath);
|
||||
if (query) {
|
||||
const queryString = (0, serialize_query_1.default)(query);
|
||||
finalPath += `${queryString}`;
|
||||
}
|
||||
const httpsRequest = scheme.request({
|
||||
method: method || "GET",
|
||||
headers,
|
||||
port,
|
||||
hostname: host,
|
||||
path: finalPath,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
if (reqPayload) {
|
||||
httpsRequest.write(reqPayload);
|
||||
}
|
||||
httpsRequest.end();
|
||||
});
|
||||
if (reqPayload) {
|
||||
httpsRequest.write(reqPayload);
|
||||
}
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+82
-65
@@ -1,74 +1,91 @@
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import apiGetGrabQueryAndValues from "../../../utils/grab-query-and-values";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGet;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const grab_query_and_values_1 = __importDefault(require("../../../utils/grab-query-and-values"));
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*/
|
||||
export default async function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _a, _b;
|
||||
const queryAndValues = apiGetGrabQueryAndValues({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
function apiGet(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _b, _c;
|
||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_a = dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_b = dbSchema.tables) === null || _b === void 0 ? void 0 : _b.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+90
-73
@@ -1,80 +1,97 @@
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiPost;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
/**
|
||||
* # Post Function For API
|
||||
*/
|
||||
export default async function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _a, _b;
|
||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
if (typeof query === "object" &&
|
||||
((_a = query === null || query === void 0 ? void 0 : query.action) === null || _a === void 0 ? void 0 : _a.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
debugLog({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
function apiPost(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _b, _c;
|
||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
if (typeof query === "object" &&
|
||||
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
}
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+44
-27
@@ -1,19 +1,35 @@
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import serverError from "../../backend/serverError";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = facebookLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
export default 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} (
|
||||
function facebookLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) {
|
||||
try {
|
||||
const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@@ -33,8 +49,8 @@ export default async function facebookLogin({ usertype, body, }) {
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
@@ -46,16 +62,17 @@ export default async function facebookLogin({ usertype, body, }) {
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
const newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
const newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+56
-39
@@ -1,45 +1,62 @@
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import httpsRequest from "../../backend/httpsRequest";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = githubLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest"));
|
||||
/**
|
||||
* # Login/signup a github user
|
||||
*/
|
||||
export default async function githubLogin({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
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);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : 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 === null || gitHubUser === void 0 ? void 0 : 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;
|
||||
function githubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
try {
|
||||
const response = yield (0, httpsRequest_1.default)({
|
||||
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);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||
return gitHubUser;
|
||||
}
|
||||
const userDataResponse = yield (0, httpsRequest_1.default)({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||
const existingGithubUser = yield (0, DB_HANDLER_1.default)(`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.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
});
|
||||
}
|
||||
|
||||
+88
-71
@@ -1,66 +1,82 @@
|
||||
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";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = googleLogin;
|
||||
const google_auth_library_1 = require("google-auth-library");
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # Google Login
|
||||
*/
|
||||
export default async function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _a, _b;
|
||||
const client = new OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.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 === null || payload === void 0 ? void 0 : 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({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
function googleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _b, _c;
|
||||
const client = new google_auth_library_1.OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
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} (
|
||||
try {
|
||||
const ticket = yield client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.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 === null || payload === void 0 ? void 0 : 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 = (0, hashPassword_1.default)({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let existinEmail = yield (0, DB_HANDLER_1.default)(`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 = yield (0, DB_HANDLER_1.default)(`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 = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@@ -79,7 +95,7 @@ export default async function googleLogin({ usertype, foundUser, isSocialValidat
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${(_a = payload.email) === null || _a === void 0 ? void 0 : _a.replace(/@.*/, "")}',
|
||||
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
@@ -91,17 +107,18 @@ export default async function googleLogin({ usertype, foundUser, isSocialValidat
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
});
|
||||
}
|
||||
|
||||
+193
-176
@@ -1,201 +1,218 @@
|
||||
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 grabDirNames from "../../../utils/backend/names/grab-dir-names";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = handleSocialDb;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const loginSocialUser_1 = __importDefault(require("./loginSocialUser"));
|
||||
const grab_dir_names_1 = __importDefault(require("../../../utils/backend/names/grab-dir-names"));
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
export default async function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _a, _b;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
let existingSocialUser = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = encrypt({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = await addDbEntry({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
if ((_a = newUser === null || newUser === void 0 ? void 0 : newUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
await addMariadbUser({ userId: newUser.payload.insertId });
|
||||
function handleSocialDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _b, _c;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.payload.insertId}'`;
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
let existingSocialUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = encrypt({
|
||||
data: JSON.stringify({
|
||||
id: newUser.payload.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
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(() => { });
|
||||
}
|
||||
const { STATIC_ROOT } = grabDirNames();
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.payload.insertId}`;
|
||||
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||
fs.mkdirSync(newUserSchemaFolderPath);
|
||||
fs.mkdirSync(newUserMediaFolderPath);
|
||||
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
return await loginSocialUser({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = (0, encrypt_1.default)({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = yield (0, addDbEntry_1.default)({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
if ((_b = newUser === null || newUser === void 0 ? void 0 : newUser.payload) === null || _b === void 0 ? void 0 : _b.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
yield (0, addMariadbUser_1.default)({ userId: newUser.payload.insertId });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.payload.insertId}'`;
|
||||
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
debug,
|
||||
});
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = (0, encrypt_1.default)({
|
||||
data: JSON.stringify({
|
||||
id: newUser.payload.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
(0, handleNodemailer_1.default)({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs_1.default
|
||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const { STATIC_ROOT } = (0, grab_dir_names_1.default)();
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.payload.insertId}`;
|
||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
||||
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
}
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Handle Social DB Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Handle Social DB Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,64 +1,81 @@
|
||||
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginSocialUser;
|
||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*/
|
||||
export default async function loginSocialUser({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||
const foundUserValues = [user.email];
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't find Social User.",
|
||||
function loginSocialUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||
const foundUserValues = [user.email];
|
||||
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't find Social User.",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uuid: foundUser[0].uuid,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uuid: foundUser[0].uuid,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||
(0, addAdminUserOnLogin_1.default)({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
+142
-125
@@ -1,140 +1,157 @@
|
||||
import { findDbNameInSchemaDir } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
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";
|
||||
import validateEmail from "../../email/fns/validate-email";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiCreateUser;
|
||||
const grab_required_database_schemas_1 = require("../../../shell/createDbFromSchema/grab-required-database-schemas");
|
||||
const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const validate_email_1 = __importDefault(require("../../email/fns/validate-email"));
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
export default async function apiCreateUser({ encryptionKey, payload, database, userId, }) {
|
||||
var _a;
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No encryption key provided",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Encryption key must be at least 8 characters long",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const targetDbSchema = findDbNameInSchemaDir({
|
||||
dbName: dbFullName,
|
||||
userId,
|
||||
});
|
||||
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "targetDbSchema not found",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = hashPassword({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, }) {
|
||||
var _b;
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No encryption key provided",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Encryption key must be at least 8 characters long",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const targetDbSchema = (0, grab_required_database_schemas_1.findDbNameInSchemaDir)({
|
||||
dbName: dbFullName,
|
||||
userId,
|
||||
});
|
||||
fields = await varDatabaseDbHandler({
|
||||
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "targetDbSchema not found",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = (0, hashPassword_1.default)({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
const fieldsTitles = fields.map((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)) {
|
||||
await updateUsersTableSchema({
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = await validateEmail({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = await addDbEntry({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset-thumbnail.png" }),
|
||||
});
|
||||
if ((_a = addUser === null || addUser === void 0 ? void 0 : addUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.payload.insertId}'`;
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: newlyAddedUserQuery,
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
const fieldsTitles = fields.map((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)) {
|
||||
yield (0, updateUsersTableSchema_1.default)({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = yield (0, validate_email_1.default)({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset-thumbnail.png" }),
|
||||
});
|
||||
if ((_b = addUser === null || addUser === void 0 ? void 0 : addUser.payload) === null || _b === void 0 ? void 0 : _b.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.payload.insertId}'`;
|
||||
const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+41
-24
@@ -1,31 +1,48 @@
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiDeleteUser;
|
||||
const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default async function apiDeleteUser({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
function apiDeleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
}
|
||||
const deleteUser = await deleteDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
}
|
||||
|
||||
+35
-18
@@ -1,24 +1,41 @@
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGetUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
export default async function apiGetUser({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
function apiGetUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+162
-145
@@ -1,154 +1,171 @@
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiLoginUser;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default async function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
console.log(`Database Full Name couldn't be grabbed`);
|
||||
return {
|
||||
success: false,
|
||||
msg: `Database Full Name couldn't be grabbed`,
|
||||
};
|
||||
}
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
}
|
||||
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||
function apiLoginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
console.log(`Database Full Name couldn't be grabbed`);
|
||||
return {
|
||||
success: false,
|
||||
msg: `Database Full Name couldn't be grabbed`,
|
||||
};
|
||||
}
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? (0, hashPassword_1.default)({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
}
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uid: foundUser[0].uid,
|
||||
uuid: foundUser[0].uuid,
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return resposeObject;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
}
|
||||
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uid: foundUser[0].uid,
|
||||
uuid: foundUser[0].uuid,
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return resposeObject;
|
||||
});
|
||||
}
|
||||
|
||||
+70
-53
@@ -1,58 +1,75 @@
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiReauthUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
export default async function apiReauthUser({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
function apiReauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}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);
|
||||
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(),
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+123
-106
@@ -1,115 +1,132 @@
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import nodemailer from "nodemailer";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../utils/serialize-cookies";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiSendEmailCode;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
export default async function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
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)];
|
||||
function apiSendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
return code;
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
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,
|
||||
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 === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
});
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = getAuthCookieNames();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = encrypt({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
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 === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer_1.default.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
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,
|
||||
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 = yield transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database,
|
||||
});
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = (0, serialize_cookies_1.default)({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+73
-56
@@ -1,64 +1,81 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiUpdateUser;
|
||||
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const targetTableSchema = (() => {
|
||||
var _a;
|
||||
try {
|
||||
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||
return targetDatabaseSchema;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||
return;
|
||||
let value = payload[key];
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = encrypt({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
function apiUpdateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = hashPassword({ password: finalData.password });
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = await updateDbEntry({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const targetTableSchema = (() => {
|
||||
var _a;
|
||||
try {
|
||||
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||
return targetDatabaseSchema;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||
return;
|
||||
let value = payload[key];
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
}
|
||||
|
||||
+11
-5
@@ -1,12 +1,18 @@
|
||||
import EJSON from "../../../../../utils/ejson";
|
||||
import encrypt from "../../../../dsql/encrypt";
|
||||
export default function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = encryptReserPasswordUrl;
|
||||
const ejson_1 = __importDefault(require("../../../../../utils/ejson"));
|
||||
const encrypt_1 = __importDefault(require("../../../../dsql/encrypt"));
|
||||
function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
const encryptObject = {
|
||||
email,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const encryptStr = encrypt({
|
||||
data: EJSON.stringify(encryptObject),
|
||||
const encryptStr = (0, encrypt_1.default)({
|
||||
data: ejson_1.default.stringify(encryptObject),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
+48
-31
@@ -1,36 +1,53 @@
|
||||
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiSendResetPasswordLink;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default async function apiSendResetPasswordLink({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Couldn't get database full name`,
|
||||
};
|
||||
}
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
function apiSendResetPasswordLink(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Couldn't get database full name`,
|
||||
};
|
||||
}
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -1,71 +1,88 @@
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGithubLogin;
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const githubLogin_1 = __importDefault(require("../../social-login/githubLogin"));
|
||||
const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace"));
|
||||
/**
|
||||
* # API Login with Github
|
||||
*/
|
||||
export default async function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
function apiGithubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
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 = yield (0, githubLogin_1.default)({
|
||||
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 === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||
: [targetName];
|
||||
let payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]),
|
||||
last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
}
|
||||
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 (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
});
|
||||
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 === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||
: [targetName];
|
||||
let 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 (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
}
|
||||
|
||||
@@ -1,72 +1,89 @@
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGoogleLogin;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
export default async function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
try {
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request({
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(EJSON.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
let 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 (additionalData) {
|
||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||
function apiGoogleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
try {
|
||||
const gUser = yield new Promise((resolve, reject) => {
|
||||
https_1.default
|
||||
.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(ejson_1.default.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
let 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 (additionalData) {
|
||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||
}
|
||||
const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
}
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user