Roll Back compile version

This commit is contained in:
Benjamin Toby
2025-07-05 16:14:11 +01:00
parent 4f4eb44a98
commit 728183b827
251 changed files with 10169 additions and 7458 deletions
+86 -69
View File
@@ -1,81 +1,98 @@
import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiCreateUser from "../../functions/api/users/api-create-user";
"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 = addUser;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
/**
* # Add User to Database
*/
export default async function addUser({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return await apiCreateUser({
database: DSQL_DB_NAME,
encryptionKey,
payload,
userId: apiUserId,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
database,
encryptionKey,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
},
function addUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
/**
* Callback Function
* Check for local DB settings
*
* @description https request callback
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return yield (0, api_create_user_1.default)({
database: DSQL_DB_NAME,
encryptionKey,
payload,
userId: apiUserId,
});
response.on("end", function () {
resolve(JSON.parse(str));
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
database,
encryptionKey,
});
response.on("error", (err) => {
reject(err);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
httpsRequest.write(reqPayload);
httpsRequest.end();
return httpResponse;
});
return httpResponse;
}
+85 -68
View File
@@ -1,78 +1,95 @@
import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiDeleteUser from "../../functions/api/users/api-delete-user";
"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 = deleteUser;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
/**
* # Update User
*/
export default async function deleteUser({ key, database, user_id, deletedUserId, }) {
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return await apiDeleteUser({
dbFullName: DSQL_DB_NAME,
deletedUserId,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
database,
deletedUserId,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
},
function deleteUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, database, user_id, deletedUserId, }) {
/**
* Callback Function
* Check for local DB settings
*
* @description https request callback
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return yield (0, api_delete_user_1.default)({
dbFullName: DSQL_DB_NAME,
deletedUserId,
});
response.on("end", function () {
resolve(JSON.parse(str));
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = (yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
database,
deletedUserId,
});
response.on("error", (err) => {
reject(err);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
},
/**
* 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);
});
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
return httpResponse;
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
return httpResponse;
});
}
+13 -7
View File
@@ -1,13 +1,19 @@
import decrypt from "../../functions/dsql/decrypt";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getToken;
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
/**
* Get just the access token for user
* ==============================================================================
* @description This Function takes in a request object and returns a user token
* string and csrf token string
*/
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
var _a;
try {
/**
@@ -15,8 +21,8 @@ export default function getToken({ request, encryptionKey, encryptionSalt, cooki
*
* @description Grab the payload
*/
const cookies = parseCookies({ request, cookieString });
const keynames = getAuthCookieNames();
const cookies = (0, parseCookies_1.default)({ request, cookieString });
const keynames = (0, get_auth_cookie_names_1.default)();
const authKeyName = keynames.keyCookieName;
const csrfName = keynames.csrfCookieName;
const key = cookies[authKeyName];
@@ -26,7 +32,7 @@ export default function getToken({ request, encryptionKey, encryptionSalt, cooki
*
* @description Grab the payload
*/
let userPayload = decrypt({
let userPayload = (0, decrypt_1.default)({
encryptedString: key,
encryptionKey,
encryptionSalt,
+112 -95
View File
@@ -1,103 +1,120 @@
import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiGetUser from "../../functions/api/users/api-get-user";
"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 = getUser;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
/**
* # Get User
*/
export default async function getUser({ key, userId, database, fields, apiUserId, }) {
/**
* Initialize
*/
const defaultFields = [
"id",
"first_name",
"last_name",
"email",
"username",
"image",
"image_thumbnail",
"verification_status",
"date_created",
"date_created_code",
"date_created_timestamp",
"date_updated",
"date_updated_code",
"date_updated_timestamp",
];
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
const reqPayload = JSON.stringify({
userId,
database,
fields: [...new Set(updatedFields)],
});
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return await apiGetUser({
userId,
fields: [...new Set(updatedFields)],
dbFullName: DSQL_DB_NAME,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
},
function getUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, userId, database, fields, apiUserId, }) {
/**
* Callback Function
*
* @description https request callback
* Initialize
*/
(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 defaultFields = [
"id",
"first_name",
"last_name",
"email",
"username",
"image",
"image_thumbnail",
"verification_status",
"date_created",
"date_created_code",
"date_created_timestamp",
"date_updated",
"date_updated_code",
"date_updated_timestamp",
];
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
const reqPayload = JSON.stringify({
userId,
database,
fields: [...new Set(updatedFields)],
});
httpsRequest.write(reqPayload);
httpsRequest.end();
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return yield (0, api_get_user_1.default)({
userId,
fields: [...new Set(updatedFields)],
dbFullName: DSQL_DB_NAME,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
}
+182 -165
View File
@@ -1,183 +1,200 @@
import fs from "fs";
import path from "path";
import encrypt from "../../functions/dsql/encrypt";
import grabHostNames from "../../utils/grab-host-names";
import apiLoginUser from "../../functions/api/users/api-login";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
import debugLog from "../../utils/logging/debug-log";
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
"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 = loginUser;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
/**
* # Login A user
*/
export default async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
var _a, _b, _c;
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = email_login
? temp_code_field
function loginUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
var _b, _c, _d;
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = email_login
? temp_code_field
: defaultTempLoginFieldName
: undefined;
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
function debugFn(log, label) {
debugLog({ log, addTime: true, title: "loginUser", label });
}
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Check required fields
*
* @description Check required fields
*/
// const isEmailValid = await validateEmail({ email: payload.email });
// if (!payload.email) {
// return {
// success: false,
// payload: null,
// msg: isEmailValid.message,
// };
// }
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
? temp_code_field
: defaultTempLoginFieldName
: undefined;
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
function debugFn(log, label) {
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
}
catch (error) { }
httpResponse = await apiLoginUser({
database: database || process.env.DSQL_DB_NAME || "",
email: payload.email,
username: payload.username,
password: payload.password,
skipPassword,
encryptionKey: finalEncryptionKey,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
dbUserId,
debug,
});
}
else {
httpResponse = await new Promise((resolve, reject) => {
const reqPayload = {
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Check required fields
*
* @description Check required fields
*/
// const isEmailValid = await validateEmail({ email: payload.email });
// if (!payload.email) {
// return {
// success: false,
// payload: null,
// msg: isEmailValid.message,
// };
// }
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
httpResponse = yield (0, api_login_1.default)({
database: database || process.env.DSQL_DB_NAME || "",
email: payload.email,
username: payload.username,
password: payload.password,
skipPassword,
encryptionKey: finalEncryptionKey,
payload,
database,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
skipPassword: skipPassword,
dbUserId: dbUserId || 0,
};
const reqPayloadJSON = JSON.stringify(reqPayload);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayloadJSON).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
}, (res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
dbUserId,
debug,
});
httpsRequest.write(reqPayloadJSON);
httpsRequest.end();
});
}
if (debug) {
debugFn(httpResponse, "httpResponse");
}
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
let encryptedPayload = encrypt({
data: JSON.stringify(httpResponse.payload),
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
});
try {
if (token && encryptedPayload)
httpResponse["token"] = encryptedPayload;
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Login User HTTP Response Error`, error);
else {
httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = {
encryptionKey: finalEncryptionKey,
payload,
database,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
skipPassword: skipPassword,
dbUserId: dbUserId || 0,
};
const reqPayloadJSON = JSON.stringify(reqPayload);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayloadJSON).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
}, (res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
});
httpsRequest.write(reqPayloadJSON);
httpsRequest.end();
});
}
const cookieNames = getAuthCookieNames({
database,
userId: grabedHostNames.user_id,
});
if (httpResponse.csrf && !skipWriteAuthFile) {
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.id)
? { userId: httpResponse.payload.id }
: undefined);
}
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
if (debug) {
debugFn(authKeyName, "authKeyName");
debugFn(csrfName, "csrfName");
debugFn(encryptedPayload, "encryptedPayload");
debugFn(httpResponse, "httpResponse");
}
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
if (debug) {
debugFn("Response Sent!");
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
let encryptedPayload = (0, encrypt_1.default)({
data: JSON.stringify(httpResponse.payload),
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
});
try {
if (token && encryptedPayload)
httpResponse["token"] = encryptedPayload;
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Login User HTTP Response Error`, error);
}
const cookieNames = (0, get_auth_cookie_names_1.default)({
database,
userId: grabedHostNames.user_id,
});
if (httpResponse.csrf && !skipWriteAuthFile) {
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.id)
? { userId: httpResponse.payload.id }
: undefined);
}
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
if (debug) {
debugFn(authKeyName, "authKeyName");
debugFn(csrfName, "csrfName");
debugFn(encryptedPayload, "encryptedPayload");
}
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
if (debug) {
debugFn("Response Sent!");
}
}
}
return httpResponse;
return httpResponse;
});
}
+22 -16
View File
@@ -1,14 +1,20 @@
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import decrypt from "../../functions/dsql/decrypt";
import EJSON from "../../utils/ejson";
import { deleteAuthFile } from "../../functions/backend/auth/write-auth-files";
import parseCookies from "../../utils/backend/parseCookies";
import grabHostNames from "../../utils/grab-host-names";
import debugLog from "../../utils/logging/debug-log";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = logoutUser;
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const ejson_1 = __importDefault(require("../../utils/ejson"));
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
/**
* # Logout user
*/
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
var _a;
/**
* Check Encryption Keys
@@ -16,13 +22,13 @@ export default function logoutUser({ response, database, dsqlUserId, encryptedUs
* @description Check Encryption Keys
*/
try {
const { user_id } = grabHostNames({ userId: dsqlUserId });
const cookieNames = getAuthCookieNames({
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
const cookieNames = (0, get_auth_cookie_names_1.default)({
database,
userId: user_id,
});
function debugFn(log, label) {
debugLog({ log, addTime: true, title: "logoutUser", label });
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
}
if (debug) {
debugFn(cookieNames, "cookieNames");
@@ -33,16 +39,16 @@ export default function logoutUser({ response, database, dsqlUserId, encryptedUs
const decryptedUserJSON = (() => {
try {
if (request) {
const cookiesObject = parseCookies({
const cookiesObject = (0, parseCookies_1.default)({
request,
cookieString,
});
return decrypt({
return (0, decrypt_1.default)({
encryptedString: cookiesObject[authKeyName],
});
}
else if (encryptedUserString) {
return decrypt({
return (0, decrypt_1.default)({
encryptedString: encryptedUserString,
});
}
@@ -60,7 +66,7 @@ export default function logoutUser({ response, database, dsqlUserId, encryptedUs
}
if (!decryptedUserJSON)
throw new Error("Invalid User");
const userObject = EJSON.parse(decryptedUserJSON);
const userObject = ejson_1.default.parse(decryptedUserJSON);
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
throw new Error("Invalid User. Please check key");
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
@@ -69,7 +75,7 @@ export default function logoutUser({ response, database, dsqlUserId, encryptedUs
`${oneTimeCodeName}=null;max-age=0`,
]);
const csrf = userObject.csrf_k;
deleteAuthFile(csrf);
(0, write_auth_files_1.deleteAuthFile)(csrf);
return {
success: true,
msg: "User Logged Out",
+174 -157
View File
@@ -1,162 +1,179 @@
import userAuth from "./user-auth";
import grabHostNames from "../../utils/grab-host-names";
import loginUser from "./login-user";
"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 = reauthUser;
const user_auth_1 = __importDefault(require("./user-auth"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const login_user_1 = __importDefault(require("./login-user"));
/**
* # Reauthorize User
*/
export default async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
var _a;
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
const grabedHostNames = grabHostNames();
// const { host, port, scheme } = grabedHostNames;
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const existingUser = userAuth({
database,
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
level,
request,
encryptedUserString,
function reauthUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
var _b;
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
const grabedHostNames = (0, grab_host_names_1.default)();
// const { host, port, scheme } = grabedHostNames;
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const existingUser = (0, user_auth_1.default)({
database,
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
level,
request,
encryptedUserString,
});
if (!((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _b === void 0 ? void 0 : _b.id)) {
return {
success: false,
payload: null,
msg: "Cookie Credentials Invalid",
};
}
return yield (0, login_user_1.default)({
database: database || "",
payload: {
email: existingUser.payload.email,
},
additionalFields,
skipPassword: true,
response,
request,
user_id,
secureCookie,
key,
});
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
// process.env;
// if (
// DSQL_DB_HOST?.match(/./) &&
// DSQL_DB_USERNAME?.match(/./) &&
// DSQL_DB_PASSWORD?.match(/./) &&
// DSQL_DB_NAME?.match(/./) &&
// global.DSQL_USE_LOCAL
// ) {
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
// try {
// const localDbSchemaPath = path.resolve(
// process.cwd(),
// "dsql.schema.json"
// );
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
// } catch (error) {}
// httpResponse = await apiReauthUser({
// existingUser: existingUser.payload,
// additionalFields,
// });
// } else {
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// httpResponse = (await new Promise((resolve, reject) => {
// const reqPayload = JSON.stringify({
// existingUser: existingUser.payload,
// database,
// additionalFields,
// });
// const httpsRequest = scheme.request(
// {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Content-Length": Buffer.from(reqPayload).length,
// Authorization:
// key ||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
// process.env.DSQL_API_KEY,
// },
// port,
// hostname: host,
// path: `/api/user/${
// user_id || grabedHostNames.user_id
// }/reauth-user`,
// },
// /**
// * 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);
// });
// }
// );
// httpsRequest.write(reqPayload);
// httpsRequest.end();
// })) as APILoginFunctionReturn;
// }
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// if (httpResponse?.success) {
// let encryptedPayload = encrypt({
// data: JSON.stringify(httpResponse.payload),
// encryptionKey: finalEncryptionKey,
// encryptionSalt: finalEncryptionSalt,
// });
// const cookieNames = getAuthCookieNames({
// database,
// userId: user_id || grabedHostNames.user_id,
// });
// httpResponse["cookieNames"] = cookieNames;
// httpResponse["key"] = String(encryptedPayload);
// const authKeyName = cookieNames.keyCookieName;
// const csrfName = cookieNames.csrfCookieName;
// response?.setHeader("Set-Cookie", [
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
// secureCookie ? ";Secure=true" : ""
// }`,
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
// ]);
// if (httpResponse.csrf) {
// deleteAuthFile(String(existingUser.payload.csrf_k));
// writeAuthFile(
// httpResponse.csrf,
// JSON.stringify(httpResponse.payload)
// );
// }
// }
// return httpResponse;
});
if (!((_a = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _a === void 0 ? void 0 : _a.id)) {
return {
success: false,
payload: null,
msg: "Cookie Credentials Invalid",
};
}
return await loginUser({
database: database || "",
payload: {
email: existingUser.payload.email,
},
additionalFields,
skipPassword: true,
response,
request,
user_id,
secureCookie,
key,
});
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
// process.env;
// if (
// DSQL_DB_HOST?.match(/./) &&
// DSQL_DB_USERNAME?.match(/./) &&
// DSQL_DB_PASSWORD?.match(/./) &&
// DSQL_DB_NAME?.match(/./) &&
// global.DSQL_USE_LOCAL
// ) {
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
// try {
// const localDbSchemaPath = path.resolve(
// process.cwd(),
// "dsql.schema.json"
// );
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
// } catch (error) {}
// httpResponse = await apiReauthUser({
// existingUser: existingUser.payload,
// additionalFields,
// });
// } else {
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// httpResponse = (await new Promise((resolve, reject) => {
// const reqPayload = JSON.stringify({
// existingUser: existingUser.payload,
// database,
// additionalFields,
// });
// const httpsRequest = scheme.request(
// {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Content-Length": Buffer.from(reqPayload).length,
// Authorization:
// key ||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
// process.env.DSQL_API_KEY,
// },
// port,
// hostname: host,
// path: `/api/user/${
// user_id || grabedHostNames.user_id
// }/reauth-user`,
// },
// /**
// * 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);
// });
// }
// );
// httpsRequest.write(reqPayload);
// httpsRequest.end();
// })) as APILoginFunctionReturn;
// }
// /**
// * Make https request
// *
// * @description make a request to datasquirel.com
// */
// if (httpResponse?.success) {
// let encryptedPayload = encrypt({
// data: JSON.stringify(httpResponse.payload),
// encryptionKey: finalEncryptionKey,
// encryptionSalt: finalEncryptionSalt,
// });
// const cookieNames = getAuthCookieNames({
// database,
// userId: user_id || grabedHostNames.user_id,
// });
// httpResponse["cookieNames"] = cookieNames;
// httpResponse["key"] = String(encryptedPayload);
// const authKeyName = cookieNames.keyCookieName;
// const csrfName = cookieNames.csrfCookieName;
// response?.setHeader("Set-Cookie", [
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
// secureCookie ? ";Secure=true" : ""
// }`,
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
// ]);
// if (httpResponse.csrf) {
// deleteAuthFile(String(existingUser.payload.csrf_k));
// writeAuthFile(
// httpResponse.csrf,
// JSON.stringify(httpResponse.payload)
// );
// }
// }
// return httpResponse;
}
+101 -84
View File
@@ -1,104 +1,121 @@
import fs from "fs";
import path from "path";
import grabHostNames from "../../utils/grab-host-names";
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
"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 = sendEmailCode;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
/**
* # Send Email Code to a User
*/
export default async function sendEmailCode(params) {
const { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, } = params;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
: defaultTempLoginFieldName;
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return await apiSendEmailCode({
database: DSQL_DB_NAME,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
response,
extraCookies,
});
}
else {
function sendEmailCode(params) {
return __awaiter(this, void 0, void 0, function* () {
const { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, } = params;
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
: defaultTempLoginFieldName;
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
/**
* Make https request
* Check for local DB settings
*
* @description make a request to datasquirel.com
*
* @type {import("../../types").SendOneTimeCodeEmailResponse}
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return yield (0, api_send_email_code_1.default)({
database: DSQL_DB_NAME,
email,
database,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_username,
mail_port,
mail_username,
sender,
html: emailHtml,
response,
extraCookies,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
},
}
else {
/**
* Callback Function
* Make https request
*
* @description https request callback
* @description make a request to datasquirel.com
*
* @type {import("../../types").SendOneTimeCodeEmailResponse}
*/
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
email,
database,
email_login_field: emailLoginTempCodeFieldName,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
html: emailHtml,
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
},
/**
* Callback Function
*
* @description https request callback
*/
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
return httpResponse;
}
});
}
+162 -145
View File
@@ -1,156 +1,173 @@
import fs from "fs";
import path from "path";
import encrypt from "../../../functions/dsql/encrypt";
import grabHostNames from "../../../utils/grab-host-names";
import apiGithubLogin from "../../../functions/api/users/social/api-github-login";
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
"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 = githubAuth;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
/**
* # SERVER FUNCTION: Login with google Function
*/
export default async function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
/**
* Check inputs
*
* @description Check inputs
*/
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github Access Token",
};
}
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
return {
success: false,
user: null,
msg: "Please provide database slug name you want to access",
};
}
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github OAUTH client ID",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
function githubAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
/**
* Check inputs
*
* @description Check inputs
*/
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github Access Token",
};
}
catch (error) { }
httpResponse = await apiGithubLogin({
code,
email: email || undefined,
clientId,
clientSecret,
additionalFields,
database: DSQL_DB_NAME,
additionalData,
});
}
else {
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
return {
success: false,
user: null,
msg: "Please provide database slug name you want to access",
};
}
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github OAUTH client ID",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
httpResponse = yield (0, api_github_login_1.default)({
code,
email: email || undefined,
clientId,
clientSecret,
additionalFields,
database: DSQL_DB_NAME,
additionalData,
});
}
else {
/**
* Make https request
*
* @description make a request to datasquirel.com
* @type {FunctionReturn} - Https response object
*/
httpResponse = (yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
code,
email,
clientId,
clientSecret,
database,
additionalFields,
additionalData,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
var _a;
try {
resolve(JSON.parse(str));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
resolve({
success: false,
user: null,
msg: "Something went wrong",
});
}
});
response.on("error", (err) => {
reject(err);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Make https request
*
* @description make a request to datasquirel.com
* @type {FunctionReturn} - Https response object
*/
httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
code,
email,
clientId,
clientSecret,
database,
additionalFields,
additionalData,
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
let encryptedPayload = (0, encrypt_1.default)({
data: JSON.stringify(httpResponse.user),
encryptionKey,
encryptionSalt,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
var _a;
try {
resolve(JSON.parse(str));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
resolve({
success: false,
user: null,
msg: "Something went wrong",
});
}
});
response.on("error", (err) => {
reject(err);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
let encryptedPayload = encrypt({
data: JSON.stringify(httpResponse.user),
encryptionKey,
encryptionSalt,
});
const { user, dsqlUserId } = httpResponse;
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
}
return httpResponse;
const { user, dsqlUserId } = httpResponse;
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
}
return httpResponse;
});
}
+151 -134
View File
@@ -1,144 +1,161 @@
import encrypt from "../../../functions/dsql/encrypt";
import grabHostNames from "../../../utils/grab-host-names";
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
"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 = googleAuth;
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
const get_auth_cookie_names_1 = __importDefault(require("../../../functions/backend/cookies/get-auth-cookie-names"));
const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-files");
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
/**
* # SERVER FUNCTION: Login with google Function
*/
export default async function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
var _a;
const grabedHostNames = grabHostNames({
userId: apiUserID || process.env.DSQL_API_USER_ID,
});
const { host, port, scheme, user_id } = grabedHostNames;
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Check inputs
*
* @description Check inputs
*/
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
return {
success: false,
payload: null,
msg: "Please enter Google Access Token",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
if (debug) {
console.log(`Google login with Local Paradigm ...`);
}
httpResponse = await apiGoogleLogin({
token,
additionalFields,
additionalData,
debug,
function googleAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
var _b;
const grabedHostNames = (0, grab_host_names_1.default)({
userId: apiUserID || process.env.DSQL_API_USER_ID,
});
}
else {
httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
const { host, port, scheme, user_id } = grabedHostNames;
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Check inputs
*
* @description Check inputs
*/
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
return {
success: false,
payload: null,
msg: "Please enter Google Access Token",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
if (debug) {
console.log(`Google login with Local Paradigm ...`);
}
httpResponse = yield (0, api_google_login_1.default)({
token,
database,
additionalFields,
additionalData,
debug,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
let encryptedPayload = encrypt({
data: JSON.stringify(httpResponse.payload),
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
});
const cookieNames = getAuthCookieNames({
database,
userId: user_id,
});
if (httpResponse.csrf) {
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload));
}
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${(_a = httpResponse.payload) === null || _a === void 0 ? void 0 : _a.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
]);
}
return httpResponse;
else {
httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
token,
database,
additionalFields,
additionalData,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
let encryptedPayload = (0, encrypt_1.default)({
data: JSON.stringify(httpResponse.payload),
encryptionKey: finalEncryptionKey,
encryptionSalt: finalEncryptionSalt,
});
const cookieNames = (0, get_auth_cookie_names_1.default)({
database,
userId: user_id,
});
if (httpResponse.csrf) {
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload));
}
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
]);
}
return httpResponse;
});
}
+86 -69
View File
@@ -1,81 +1,98 @@
import path from "path";
import fs from "fs";
import grabHostNames from "../../utils/grab-host-names";
import apiUpdateUser from "../../functions/api/users/api-update-user";
"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 = updateUser;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_update_user_1 = __importDefault(require("../../functions/api/users/api-update-user"));
/**
* # Update User
*/
export default async function updateUser({ key, payload, database, user_id, updatedUserId, }) {
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return await apiUpdateUser({
payload: payload,
dbFullName: DSQL_DB_NAME,
updatedUserId,
dbSchema,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
database,
updatedUserId,
});
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
},
function updateUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, user_id, updatedUserId, }) {
/**
* Callback Function
* Check for local DB settings
*
* @description https request callback
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
global.DSQL_USE_LOCAL) {
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
return yield (0, api_update_user_1.default)({
payload: payload,
dbFullName: DSQL_DB_NAME,
updatedUserId,
dbSchema,
});
response.on("end", function () {
resolve(JSON.parse(str));
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
payload,
database,
updatedUserId,
});
response.on("error", (err) => {
reject(err);
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY ||
key,
},
port,
hostname: host,
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
httpsRequest.write(reqPayload);
httpsRequest.end();
return httpResponse;
});
return httpResponse;
}
+25 -19
View File
@@ -1,10 +1,16 @@
import decrypt from "../../functions/dsql/decrypt";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import { checkAuthFile } from "../../functions/backend/auth/write-auth-files";
import parseCookies from "../../utils/backend/parseCookies";
import getCsrfHeaderName from "../../actions/get-csrf-header-name";
import grabHostNames from "../../utils/grab-host-names";
import debugLog from "../../utils/logging/debug-log";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = userAuth;
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
const get_csrf_header_name_1 = __importDefault(require("../../actions/get-csrf-header-name"));
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
const minuteInMilliseconds = 60000;
const hourInMilliseconds = minuteInMilliseconds * 60;
const dayInMilliseconds = hourInMilliseconds * 24;
@@ -17,28 +23,28 @@ const yearInMilliseconds = dayInMilliseconds * 365;
* @description This Function takes in a request object and returns a user object
* with the user's data
*/
export default function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
var _a;
try {
const finalRequest = req || request;
const { user_id } = grabHostNames({ userId: dsqlUserId });
const cookies = parseCookies({
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
const cookies = (0, parseCookies_1.default)({
request: finalRequest,
cookieString,
});
if (debug) {
debugLog({
(0, debug_log_1.default)({
log: cookies,
addTime: true,
label: "userAuth:cookies",
});
}
const keyNames = getAuthCookieNames({
const keyNames = (0, get_auth_cookie_names_1.default)({
userId: user_id,
database: database || process.env.DSQL_DB_NAME,
});
if (debug) {
debugLog({
(0, debug_log_1.default)({
log: keyNames,
addTime: true,
label: "userAuth:keyNames",
@@ -48,7 +54,7 @@ export default function userAuth({ request, req, encryptionKey, encryptionSalt,
? encryptedUserString
: cookies[keyNames.keyCookieName];
if (debug) {
debugLog({
(0, debug_log_1.default)({
log: key,
addTime: true,
label: "userAuth:key",
@@ -59,13 +65,13 @@ export default function userAuth({ request, req, encryptionKey, encryptionSalt,
*
* @description Grab the payload
*/
let userPayloadJSON = decrypt({
let userPayloadJSON = (0, decrypt_1.default)({
encryptedString: key,
encryptionKey,
encryptionSalt,
});
if (debug) {
debugLog({
(0, debug_log_1.default)({
log: userPayloadJSON,
addTime: true,
label: "userAuth:userPayloadJSON",
@@ -86,7 +92,7 @@ export default function userAuth({ request, req, encryptionKey, encryptionSalt,
}
let userObject = JSON.parse(userPayloadJSON);
if (debug) {
debugLog({
(0, debug_log_1.default)({
log: userObject,
addTime: true,
label: "userAuth:userObject",
@@ -100,7 +106,7 @@ export default function userAuth({ request, req, encryptionKey, encryptionSalt,
cookieNames: keyNames,
};
}
if (!skipFileCheck && !checkAuthFile(userObject.csrf_k)) {
if (!skipFileCheck && !(0, write_auth_files_1.checkAuthFile)(userObject.csrf_k)) {
return {
success: false,
payload: null,
@@ -114,7 +120,7 @@ export default function userAuth({ request, req, encryptionKey, encryptionSalt,
* @description Grab the payload
*/
if ((level === null || level === void 0 ? void 0 : level.match(/deep/i)) && finalRequest) {
const finalCsrfHeaderName = csrfHeaderName || getCsrfHeaderName();
const finalCsrfHeaderName = csrfHeaderName || (0, get_csrf_header_name_1.default)();
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
return {
success: false,
+43 -26
View File
@@ -1,32 +1,49 @@
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";
import decrypt from "../../functions/dsql/decrypt";
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 = validateTempEmailCode;
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const ejson_1 = __importDefault(require("../../utils/ejson"));
/**
* # Verify the temp email code sent to the user's email address
*/
export default async function validateTempEmailCode({ request, email, cookieString, }) {
var _a;
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload = EJSON.parse(encryptedPayload);
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
return payload;
function validateTempEmailCode(_a) {
return __awaiter(this, arguments, void 0, function* ({ request, email, cookieString, }) {
var _b;
try {
const keyNames = (0, get_auth_cookie_names_1.default)();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = (0, parseCookies_1.default)({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = (0, decrypt_1.default)({
encryptedString: encryptedOneTimeCode,
});
const payload = ejson_1.default.parse(encryptedPayload);
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
return payload;
}
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
return payload;
}
return null;
}
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
return payload;
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Validate Temp Email Code Error`, error);
console.log("validateTempEmailCode error:", error.message);
return null;
}
return null;
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Validate Temp Email Code Error`, error);
console.log("validateTempEmailCode error:", error.message);
return null;
}
});
}
+9 -3
View File
@@ -1,10 +1,16 @@
import decrypt from "../../functions/dsql/decrypt";
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = validateToken;
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
/**
* Validate Token
* ======================================
* @description This Function takes in a encrypted token and returns a user object
*/
export default function validateToken({ token, encryptionKey, encryptionSalt, }) {
function validateToken({ token, encryptionKey, encryptionSalt, }) {
var _a;
try {
/**
@@ -18,7 +24,7 @@ export default function validateToken({ token, encryptionKey, encryptionSalt, })
*
* @description Grab the payload
*/
let userPayload = decrypt({
let userPayload = (0, decrypt_1.default)({
encryptedString: key,
encryptionKey,
encryptionSalt,