updates
This commit is contained in:
+134
-134
@@ -1,134 +1,134 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const localAddUser = require("../engine/user/add-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} UserDataPayload
|
||||
* @property {string} first_name - First Name *Required
|
||||
* @property {string} last_name - Last Name *Required
|
||||
* @property {string} email - Email *Required
|
||||
* @property {string} password - Password *Required
|
||||
* @property {string?} username - Username (Optional)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Add User to Database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} props - Single object passed
|
||||
* @param {string} props.key - FULL ACCESS API Key
|
||||
* @param {string} props.database - Database Name
|
||||
* @param {UserDataPayload} props.payload - User Data Payload
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function addUser({ key, payload, database }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await localAddUser({
|
||||
dbSchema: dbSchema,
|
||||
payload: payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = addUser;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const localAddUser = require("../engine/user/add-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} UserDataPayload
|
||||
* @property {string} first_name - First Name *Required
|
||||
* @property {string} last_name - Last Name *Required
|
||||
* @property {string} email - Email *Required
|
||||
* @property {string} password - Password *Required
|
||||
* @property {string?} username - Username (Optional)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Add User to Database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} props - Single object passed
|
||||
* @param {string} props.key - FULL ACCESS API Key
|
||||
* @param {string} props.database - Database Name
|
||||
* @param {UserDataPayload} props.payload - User Data Payload
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function addUser({ key, payload, database }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await localAddUser({
|
||||
dbSchema: dbSchema,
|
||||
payload: payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = addUser;
|
||||
|
||||
+106
-106
@@ -1,106 +1,106 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
const parseCookies = require("../utils/functions/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
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns {{ key: string | undefined, csrf: string | undefined }}
|
||||
*/
|
||||
function getToken({ request, encryptionKey, encryptionSalt, database }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = parseCookies({ request });
|
||||
const dsqluid = cookies.dsqluid;
|
||||
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`;
|
||||
|
||||
const key = cookies[authKeyName];
|
||||
const csrf = cookies[csrfName];
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return { key, csrf };
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
key: undefined,
|
||||
csrf: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = getToken;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
const parseCookies = require("../utils/functions/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
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns {{ key: string | undefined, csrf: string | undefined }}
|
||||
*/
|
||||
function getToken({ request, encryptionKey, encryptionSalt, database }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = parseCookies({ request });
|
||||
const dsqluid = cookies.dsqluid;
|
||||
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`;
|
||||
|
||||
const key = cookies[authKeyName];
|
||||
const csrf = cookies[csrfName];
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return { key, csrf };
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
key: undefined,
|
||||
csrf: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = getToken;
|
||||
|
||||
+144
-144
@@ -1,144 +1,144 @@
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const getLocalUser = require("../engine/user/get-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {{
|
||||
* id: number,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* username: string,
|
||||
* email: string,
|
||||
* phone: string,
|
||||
* social_id: [string],
|
||||
* image: string,
|
||||
* image_thumbnail: string,
|
||||
* verification_status: [number=0],
|
||||
* }} payload - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string[]} [params.fields] - fields to select
|
||||
*
|
||||
* @returns { Promise<FunctionReturn>}
|
||||
*/
|
||||
async function getUser({ key, userId, database, fields }) {
|
||||
/**
|
||||
* 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)],
|
||||
});
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await getLocalUser({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = getUser;
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const getLocalUser = require("../engine/user/get-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {{
|
||||
* id: number,
|
||||
* first_name: string,
|
||||
* last_name: string,
|
||||
* username: string,
|
||||
* email: string,
|
||||
* phone: string,
|
||||
* social_id: [string],
|
||||
* image: string,
|
||||
* image_thumbnail: string,
|
||||
* verification_status: [number=0],
|
||||
* }} payload - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string[]} [params.fields] - fields to select
|
||||
*
|
||||
* @returns { Promise<FunctionReturn>}
|
||||
*/
|
||||
async function getUser({ key, userId, database, fields }) {
|
||||
/**
|
||||
* 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)],
|
||||
});
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await getLocalUser({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = getUser;
|
||||
|
||||
+204
-204
@@ -1,204 +1,204 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../functions/encrypt");
|
||||
const loginLocalUser = require("../engine/user/login-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} AuthenticatedUser
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload of the response
|
||||
* @property {string} [msg] - An optional message
|
||||
* @property {number} [userId] - An optional message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Login A user
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - FULL ACCESS API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {{
|
||||
* email?: string,
|
||||
* username?: string,
|
||||
* password: string,
|
||||
* }} params.payload Login Email/Username and Password
|
||||
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {String} params.encryptionKey - Encryption Key
|
||||
* @param {String} params.encryptionSalt - Encryption Salt
|
||||
*
|
||||
* @returns { Promise<AuthenticatedUser>}
|
||||
*/
|
||||
async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
if (!encryptionKey?.match(/./))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Key Required",
|
||||
};
|
||||
|
||||
if (!encryptionSalt?.match(/./))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Salt Required",
|
||||
};
|
||||
|
||||
if (encryptionKey.length < 24)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Key must be at least 24 characters",
|
||||
};
|
||||
|
||||
if (encryptionSalt.length < 8)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Salt must be at least 8 characters",
|
||||
};
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await loginLocalUser({
|
||||
payload,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {{ success: boolean, payload: import("../types/user.td").DATASQUIREL_LoggedInUser | null, userId?: number, msg?: string }}
|
||||
*/
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/login-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();
|
||||
});
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
const { userId } = httpResponse;
|
||||
|
||||
const authKeyName = `datasquirel_${userId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${userId}_${database}_csrf`;
|
||||
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = loginUser;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../functions/encrypt");
|
||||
const loginLocalUser = require("../engine/user/login-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} AuthenticatedUser
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload of the response
|
||||
* @property {string} [msg] - An optional message
|
||||
* @property {number} [userId] - An optional message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Login A user
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - FULL ACCESS API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {{
|
||||
* email?: string,
|
||||
* username?: string,
|
||||
* password: string,
|
||||
* }} params.payload Login Email/Username and Password
|
||||
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {String} params.encryptionKey - Encryption Key
|
||||
* @param {String} params.encryptionSalt - Encryption Salt
|
||||
*
|
||||
* @returns { Promise<AuthenticatedUser>}
|
||||
*/
|
||||
async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
if (!encryptionKey?.match(/./))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Key Required",
|
||||
};
|
||||
|
||||
if (!encryptionSalt?.match(/./))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Salt Required",
|
||||
};
|
||||
|
||||
if (encryptionKey.length < 24)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Key must be at least 24 characters",
|
||||
};
|
||||
|
||||
if (encryptionSalt.length < 8)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption Salt must be at least 8 characters",
|
||||
};
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await loginLocalUser({
|
||||
payload,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {{ success: boolean, payload: import("../types/user.td").DATASQUIREL_LoggedInUser | null, userId?: number, msg?: string }}
|
||||
*/
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/login-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();
|
||||
});
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
const { userId } = httpResponse;
|
||||
|
||||
const authKeyName = `datasquirel_${userId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${userId}_${database}_csrf`;
|
||||
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = loginUser;
|
||||
|
||||
+74
-74
@@ -1,74 +1,74 @@
|
||||
// @ts-check
|
||||
|
||||
const http = require("http");
|
||||
const parseCookies = require("../utils/functions/parseCookies");
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {string} [params.database] - Target database name(slug): optional => If you don't
|
||||
* include this you will be logged out of all datasquirel websites instead of just the target
|
||||
* database
|
||||
*
|
||||
* @returns {{success: boolean, payload: string}}
|
||||
*/
|
||||
function logoutUser({ request, response, database }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
try {
|
||||
const cookies = parseCookies({ request });
|
||||
const cookiesKeys = Object.keys(cookies);
|
||||
|
||||
const dbUid = cookies.dsqluid;
|
||||
const keyRegexp = new RegExp(`datasquirel_${dbUid}_${database}_auth_key`);
|
||||
const csrfRegexp = new RegExp(`datasquirel_${dbUid}_${database}_csrf`);
|
||||
|
||||
const authKeyName = cookiesKeys.filter((cookieKey) => cookieKey.match(keyRegexp))[0];
|
||||
const csrfName = cookiesKeys.filter((cookieKey) => cookieKey.match(csrfRegexp))[0];
|
||||
|
||||
if (authKeyName && csrfName) {
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=null;samesite=strict;path=/;HttpOnly=true`, `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]);
|
||||
} else {
|
||||
const allKeys = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_auth_key/));
|
||||
const allCsrfs = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_csrf/));
|
||||
|
||||
response.setHeader("Set-Cookie", [...allKeys.map((key) => `${key}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`), ...allCsrfs.map((csrf) => `${csrf}=null;samesite=strict;path=/;HttpOnly=true`), `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: "User Logged Out",
|
||||
};
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: "Logout Failed",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = logoutUser;
|
||||
// @ts-check
|
||||
|
||||
const http = require("http");
|
||||
const parseCookies = require("../utils/functions/parseCookies");
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {string} [params.database] - Target database name(slug): optional => If you don't
|
||||
* include this you will be logged out of all datasquirel websites instead of just the target
|
||||
* database
|
||||
*
|
||||
* @returns {{success: boolean, payload: string}}
|
||||
*/
|
||||
function logoutUser({ request, response, database }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
try {
|
||||
const cookies = parseCookies({ request });
|
||||
const cookiesKeys = Object.keys(cookies);
|
||||
|
||||
const dbUid = cookies.dsqluid;
|
||||
const keyRegexp = new RegExp(`datasquirel_${dbUid}_${database}_auth_key`);
|
||||
const csrfRegexp = new RegExp(`datasquirel_${dbUid}_${database}_csrf`);
|
||||
|
||||
const authKeyName = cookiesKeys.filter((cookieKey) => cookieKey.match(keyRegexp))[0];
|
||||
const csrfName = cookiesKeys.filter((cookieKey) => cookieKey.match(csrfRegexp))[0];
|
||||
|
||||
if (authKeyName && csrfName) {
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=null;samesite=strict;path=/;HttpOnly=true`, `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]);
|
||||
} else {
|
||||
const allKeys = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_auth_key/));
|
||||
const allCsrfs = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_csrf/));
|
||||
|
||||
response.setHeader("Set-Cookie", [...allKeys.map((key) => `${key}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`), ...allCsrfs.map((csrf) => `${csrf}=null;samesite=strict;path=/;HttpOnly=true`), `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: "User Logged Out",
|
||||
};
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: "Logout Failed",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = logoutUser;
|
||||
|
||||
+190
-190
@@ -1,190 +1,190 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../functions/encrypt");
|
||||
|
||||
const userAuth = require("./user-auth");
|
||||
const localReauthUser = require("../engine/user/reauth-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload
|
||||
* @property {string} [msg] - Response Message
|
||||
* @property {number} [userId] - user ID
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {("deep" | "normal")} [params.level] - Authentication level
|
||||
* @param {String} params.encryptionKey - Encryption Key
|
||||
* @param {String} params.encryptionSalt - Encryption Salt
|
||||
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
level,
|
||||
request,
|
||||
});
|
||||
|
||||
if (!existingUser?.payload?.id) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await localReauthUser({
|
||||
existingUser: existingUser.payload,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
} 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 = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
const { userId } = httpResponse;
|
||||
|
||||
const authKeyName = `datasquirel_${userId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${userId}_${database}_csrf`;
|
||||
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=${httpResponse.payload.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = reauthUser;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../functions/encrypt");
|
||||
|
||||
const userAuth = require("./user-auth");
|
||||
const localReauthUser = require("../engine/user/reauth-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload
|
||||
* @property {string} [msg] - Response Message
|
||||
* @property {number} [userId] - user ID
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {http.ServerResponse} params.response - Http response object
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {("deep" | "normal")} [params.level] - Authentication level
|
||||
* @param {String} params.encryptionKey - Encryption Key
|
||||
* @param {String} params.encryptionSalt - Encryption Salt
|
||||
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
level,
|
||||
request,
|
||||
});
|
||||
|
||||
if (!existingUser?.payload?.id) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await localReauthUser({
|
||||
existingUser: existingUser.payload,
|
||||
additionalFields,
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
} 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 = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
const { userId } = httpResponse;
|
||||
|
||||
const authKeyName = `datasquirel_${userId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${userId}_${database}_csrf`;
|
||||
|
||||
response.setHeader("Set-Cookie", [`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=${httpResponse.payload.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`]);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = reauthUser;
|
||||
|
||||
+251
-251
File diff suppressed because it is too large
Load Diff
+239
-239
@@ -1,239 +1,239 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../../functions/encrypt");
|
||||
const localGoogleAuth = require("../../engine/user/social/google-auth");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object | null} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
|
||||
* @property {number} [dsqlUserId] - Dsql User Id
|
||||
* @property {string} [msg] - Response message
|
||||
*/
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {string} params.key - API full access key
|
||||
* @param {string} params.token - Google access token gotten from the client side
|
||||
* @param {string} params.database - Target database name(slug)
|
||||
* @param {string} params.clientId - Google client id
|
||||
* @param {http.ServerResponse} params.response - HTTPS response object
|
||||
* @param {string} params.encryptionKey - Encryption key
|
||||
* @param {string} params.encryptionSalt - Encryption salt
|
||||
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function googleAuth({ key, token, database, clientId, response, encryptionKey, encryptionSalt, additionalFields }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!key || key?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter API full access Key",
|
||||
};
|
||||
}
|
||||
|
||||
if (!token || token?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
|
||||
if (!database || database?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
|
||||
if (!clientId || clientId?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Google OAUTH client ID",
|
||||
};
|
||||
}
|
||||
|
||||
if (!response || !response?.setHeader) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid HTTPS response object",
|
||||
};
|
||||
}
|
||||
|
||||
if (!encryptionKey || encryptionKey?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid encryption key",
|
||||
};
|
||||
}
|
||||
|
||||
if (!encryptionSalt || encryptionSalt?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid encryption salt",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await localGoogleAuth({
|
||||
dbSchema: dbSchema,
|
||||
token,
|
||||
clientId,
|
||||
additionalFields,
|
||||
response: response,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {{ success: boolean, user: import("../../types/user.td").DATASQUIREL_LoggedInUser | null, msg?: string, dsqlUserId?: number } | null } - Https response object
|
||||
*/
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
clientId,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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?.success && 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;Secure=true`, `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${dsqlUserId};samesite=strict;path=/;HttpOnly=true`, `datasquirel_social_id=${user.social_id};samesite=strict;path=/`]);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = googleAuth;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const encrypt = require("../../functions/encrypt");
|
||||
const localGoogleAuth = require("../../engine/user/social/google-auth");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object | null} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
|
||||
* @property {number} [dsqlUserId] - Dsql User Id
|
||||
* @property {string} [msg] - Response message
|
||||
*/
|
||||
|
||||
/**
|
||||
* SERVER FUNCTION: Login with google Function
|
||||
* ==============================================================================
|
||||
*
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - main params object
|
||||
* @param {string} params.key - API full access key
|
||||
* @param {string} params.token - Google access token gotten from the client side
|
||||
* @param {string} params.database - Target database name(slug)
|
||||
* @param {string} params.clientId - Google client id
|
||||
* @param {http.ServerResponse} params.response - HTTPS response object
|
||||
* @param {string} params.encryptionKey - Encryption key
|
||||
* @param {string} params.encryptionSalt - Encryption salt
|
||||
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn> }
|
||||
*/
|
||||
async function googleAuth({ key, token, database, clientId, response, encryptionKey, encryptionSalt, additionalFields }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!key || key?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter API full access Key",
|
||||
};
|
||||
}
|
||||
|
||||
if (!token || token?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
|
||||
if (!database || database?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
|
||||
if (!clientId || clientId?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Google OAUTH client ID",
|
||||
};
|
||||
}
|
||||
|
||||
if (!response || !response?.setHeader) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid HTTPS response object",
|
||||
};
|
||||
}
|
||||
|
||||
if (!encryptionKey || encryptionKey?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid encryption key",
|
||||
};
|
||||
}
|
||||
|
||||
if (!encryptionSalt || encryptionSalt?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide a valid encryption salt",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 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_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
httpResponse = await localGoogleAuth({
|
||||
dbSchema: dbSchema,
|
||||
token,
|
||||
clientId,
|
||||
additionalFields,
|
||||
response: response,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {{ success: boolean, user: import("../../types/user.td").DATASQUIREL_LoggedInUser | null, msg?: string, dsqlUserId?: number } | null } - Https response object
|
||||
*/
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
clientId,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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?.success && 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;Secure=true`, `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, `dsqluid=${dsqlUserId};samesite=strict;path=/;HttpOnly=true`, `datasquirel_social_id=${user.social_id};samesite=strict;path=/`]);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = googleAuth;
|
||||
|
||||
+126
-126
@@ -1,126 +1,126 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const localUpdateUser = require("../engine/user/update-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - API Key
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {{ id: number }} params.payload - User Object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn>}
|
||||
*/
|
||||
async function updateUser({ key, payload, database }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await localUpdateUser({
|
||||
dbSchema: dbSchema,
|
||||
payload: payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = updateUser;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const localUpdateUser = require("../engine/user/update-user");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - Payload
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - API Key
|
||||
* @param {String} params.key - API Key
|
||||
* @param {String} params.database - Target Database
|
||||
* @param {{ id: number }} params.payload - User Object
|
||||
*
|
||||
* @returns { Promise<FunctionReturn>}
|
||||
*/
|
||||
async function updateUser({ key, payload, database }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC } = process.env;
|
||||
|
||||
if (DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && DSQL_DB_NAME?.match(/./)) {
|
||||
/** @type {import("../types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
console.log("Reading from local database ...");
|
||||
|
||||
if (dbSchema) {
|
||||
return await localUpdateUser({
|
||||
dbSchema: dbSchema,
|
||||
payload: payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
});
|
||||
|
||||
const httpsRequest = https.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
port: 443,
|
||||
hostname: "datasquirel.com",
|
||||
path: `/api/user/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();
|
||||
});
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = updateUser;
|
||||
|
||||
+143
-143
@@ -1,143 +1,143 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
const parseCookies = require("../utils/functions/parseCookies");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} AuthenticatedUserObject
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload
|
||||
* @property {string | unknown} [msg] - Response Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns { AuthenticatedUserObject }
|
||||
*/
|
||||
function userAuth({ request, encryptionKey, encryptionSalt, level, database }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = parseCookies({ request });
|
||||
const dsqluid = cookies.dsqluid;
|
||||
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`;
|
||||
|
||||
const key = cookies[authKeyName];
|
||||
const csrf = cookies[csrfName];
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't Decrypt cookie",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No CSRF_K in decrypted payload",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (level?.match(/deep/i) && !csrf?.match(new RegExp(`${userObject.csrf_k}`))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "CSRF_K requested but does not match payload",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: true,
|
||||
payload: userObject,
|
||||
};
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = userAuth;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
const parseCookies = require("../utils/functions/parseCookies");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} AuthenticatedUserObject
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {import("../types/user.td").DATASQUIREL_LoggedInUser | null} payload - Payload
|
||||
* @property {string | unknown} [msg] - Response Message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {http.IncomingMessage} params.request - Http request object
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns { AuthenticatedUserObject }
|
||||
*/
|
||||
function userAuth({ request, encryptionKey, encryptionSalt, level, database }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = parseCookies({ request });
|
||||
const dsqluid = cookies.dsqluid;
|
||||
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`;
|
||||
|
||||
const key = cookies[authKeyName];
|
||||
const csrf = cookies[csrfName];
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't Decrypt cookie",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No CSRF_K in decrypted payload",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (level?.match(/deep/i) && !csrf?.match(new RegExp(`${userObject.csrf_k}`))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "CSRF_K requested but does not match payload",
|
||||
};
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: true,
|
||||
payload: userObject,
|
||||
};
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = userAuth;
|
||||
|
||||
+96
-96
@@ -1,96 +1,96 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Validate Token
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {string} params.token - Encrypted Token
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {("deep" | "normal")?} [params.level] - Optional. "Deep" value indicates an extra layer of security
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns { import("../types/user.td").DATASQUIREL_LoggedInUser | null}
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const key = token;
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return userObject;
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = validateToken;
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const http = require("http");
|
||||
const decrypt = require("../functions/decrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Validate Token
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {string} params.token - Encrypted Token
|
||||
* @param {string} params.encryptionKey - Encryption Key
|
||||
* @param {string} params.encryptionSalt - Encryption Salt
|
||||
* @param {("deep" | "normal")?} [params.level] - Optional. "Deep" value indicates an extra layer of security
|
||||
* @param {string} params.database - Database Name
|
||||
*
|
||||
* @returns { import("../types/user.td").DATASQUIREL_LoggedInUser | null}
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const key = token;
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return userObject;
|
||||
} catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = validateToken;
|
||||
|
||||
Reference in New Issue
Block a user