Updates
This commit is contained in:
@@ -20,6 +20,6 @@ export default function apiCreateUser({ encryptionKey, payload, database, userId
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
sqlResult: import("../../../types").PostInsertReturn | null;
|
||||
sqlResult: import("../../../types").APIResponseObject<import("../../../types").PostInsertReturn>;
|
||||
payload: null;
|
||||
}>;
|
||||
|
||||
+126
-129
@@ -1,143 +1,140 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
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 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"));
|
||||
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";
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, }) {
|
||||
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 hashedPassword = (0, hashPassword_1.default)({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
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,
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
}
|
||||
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({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
});
|
||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
}
|
||||
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],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
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,
|
||||
}
|
||||
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,
|
||||
database: dbFullName,
|
||||
});
|
||||
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 (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.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,
|
||||
};
|
||||
}
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+26
-43
@@ -1,48 +1,31 @@
|
||||
"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"));
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
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: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
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])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = await deleteDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
}
|
||||
|
||||
+19
-36
@@ -1,41 +1,24 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
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: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
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]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
|
||||
+145
-153
@@ -1,162 +1,154 @@
|
||||
"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"));
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
/**
|
||||
* # API 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 });
|
||||
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;
|
||||
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) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
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 = ?`,
|
||||
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) {
|
||||
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,
|
||||
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;
|
||||
});
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
+52
-69
@@ -1,75 +1,58 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
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(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
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: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
});
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
}
|
||||
|
||||
+104
-121
@@ -1,132 +1,115 @@
|
||||
"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"));
|
||||
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";
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
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",
|
||||
};
|
||||
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)];
|
||||
}
|
||||
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,
|
||||
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,
|
||||
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)];
|
||||
/** @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");
|
||||
}
|
||||
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,
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
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;
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
});
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+58
-75
@@ -1,81 +1,64 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
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"));
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
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 (!(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 = (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,
|
||||
};
|
||||
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;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = hashPassword({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = await updateDbEntry({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
}
|
||||
|
||||
+5
-11
@@ -1,18 +1,12 @@
|
||||
"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, }) {
|
||||
import EJSON from "../../../../../utils/ejson";
|
||||
import encrypt from "../../../../dsql/encrypt";
|
||||
export default function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
const encryptObject = {
|
||||
email,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const encryptStr = (0, encrypt_1.default)({
|
||||
data: ejson_1.default.stringify(encryptObject),
|
||||
const encryptStr = encrypt({
|
||||
data: EJSON.stringify(encryptObject),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
+31
-47
@@ -1,52 +1,36 @@
|
||||
"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"));
|
||||
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
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 });
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
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 };
|
||||
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,
|
||||
});
|
||||
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,88 +1,71 @@
|
||||
"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"));
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||
/**
|
||||
* # API Login with Github
|
||||
*/
|
||||
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,
|
||||
export default async function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
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 (typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = (targetName === 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,89 +1,72 @@
|
||||
"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"));
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
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);
|
||||
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);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user