Refactor Code to typescript

This commit is contained in:
Benjamin Toby
2025-01-10 20:10:28 +01:00
parent 549d0abc02
commit eb0992f28d
270 changed files with 3535 additions and 9062 deletions
-28
View File
@@ -1,28 +0,0 @@
export = addUser;
/**
* Add User to Database
* ============================================
* @async
*
* @param {object} param - Single object passed
* @param {string} [param.key] - FULL ACCESS API Key
* @param {string} [param.database] - Database Name
* @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload
* @param {string} [param.encryptionKey]
* @param {string} [param.encryptionSalt]
* @param {string | number} [param.user_id]
* @param {string | number} [param.apiUserId]
* @param {boolean} [param.useLocal]
*
* @returns { Promise<import("../package-shared/types").AddUserFunctionReturn> }
*/
declare function addUser({ key, payload, database, encryptionKey, user_id, useLocal, apiUserId, }: {
key?: string;
database?: string;
payload: import("../package-shared/types").UserDataPayload;
encryptionKey?: string;
encryptionSalt?: string;
user_id?: string | number;
apiUserId?: string | number;
useLocal?: boolean;
}): Promise<import("../package-shared/types").AddUserFunctionReturn>;
+25 -26
View File
@@ -1,28 +1,27 @@
// @ts-check
import path from "path";
import fs from "fs";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiCreateUser from "../package-shared/functions/api/users/api-create-user";
import {
AddUserFunctionReturn,
UserDataPayload,
} from "../package-shared/types";
const path = require("path");
const fs = require("fs");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiCreateUser = require("../package-shared/functions/api/users/api-create-user");
type Param = {
key?: string;
database?: string;
payload: UserDataPayload;
encryptionKey?: string;
encryptionSalt?: string;
user_id?: string | number;
apiUserId?: string | number;
useLocal?: boolean;
};
/**
* Add User to Database
* ============================================
* @async
*
* @param {object} param - Single object passed
* @param {string} [param.key] - FULL ACCESS API Key
* @param {string} [param.database] - Database Name
* @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload
* @param {string} [param.encryptionKey]
* @param {string} [param.encryptionSalt]
* @param {string | number} [param.user_id]
* @param {string | number} [param.apiUserId]
* @param {boolean} [param.useLocal]
*
* @returns { Promise<import("../package-shared/types").AddUserFunctionReturn> }
* # Add User to Database
*/
async function addUser({
export default async function addUser({
key,
payload,
database,
@@ -30,7 +29,7 @@ async function addUser({
user_id,
useLocal,
apiUserId,
}) {
}: Param): Promise<AddUserFunctionReturn> {
/**
* Check for local DB settings
*
@@ -55,7 +54,9 @@ async function addUser({
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -129,7 +130,5 @@ async function addUser({
httpsRequest.end();
});
return httpResponse;
return httpResponse as AddUserFunctionReturn;
}
module.exports = addUser;
-21
View File
@@ -1,21 +0,0 @@
export = deleteUser;
/**
* # Update User
* @async
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} [params.database] - Target Database
* @param {String | number} params.deletedUserId - Target Database
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/
declare function deleteUser({ key, database, user_id, useLocal, deletedUserId }: {
key?: string;
database?: string;
deletedUserId: string | number;
user_id?: boolean;
useLocal?: boolean;
}): Promise<import("../package-shared/types").UpdateUserFunctionReturn>;
+24 -32
View File
@@ -1,27 +1,27 @@
// @ts-check
import path from "path";
import fs from "fs";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiDeleteUser from "../package-shared/functions/api/users/api-delete-user";
import { UpdateUserFunctionReturn } from "../package-shared/types";
const http = require("http");
const https = require("https");
const path = require("path");
const fs = require("fs");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiUpdateUser = require("../package-shared/functions/api/users/api-update-user");
const apiDeleteUser = require("../package-shared/functions/api/users/api-delete-user");
type Param = {
key?: string;
database?: string;
deletedUserId: string | number;
user_id?: boolean;
useLocal?: boolean;
};
/**
* # Update User
* @async
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} [params.database] - Target Database
* @param {String | number} params.deletedUserId - Target Database
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/
async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
export default async function deleteUser({
key,
database,
user_id,
useLocal,
deletedUserId,
}: Param): Promise<UpdateUserFunctionReturn> {
/**
* Check for local DB settings
*
@@ -41,7 +41,9 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -63,7 +65,7 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
database,
deletedUserId,
@@ -110,17 +112,7 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
);
httpsRequest.write(reqPayload);
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
})) as UpdateUserFunctionReturn;
return httpResponse;
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = deleteUser;
-35
View File
@@ -1,35 +0,0 @@
export = getToken;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* 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.cookieString]
* @param {string} params.encryptionKey - Encryption Key
* @param {string} params.encryptionSalt - Encryption Salt
* @param {string} params.database - Database Name
* @param {boolean} [params.useLocal]
*
* @returns {{ key: string | undefined, csrf: string | undefined }}
*/
declare function getToken({ request, encryptionKey, encryptionSalt, database, useLocal, cookieString, }: {
request?: http.IncomingMessage;
cookieString?: string;
encryptionKey: string;
encryptionSalt: string;
database: string;
useLocal?: boolean;
}): {
key: string | undefined;
csrf: string | undefined;
};
import http = require("http");
-116
View File
@@ -1,116 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Get just the access token for user
* ==============================================================================
* @description This Function takes in a request object and returns a user token
* string and csrf token string
*
* @param {Object} params - Arg
* @param {http.IncomingMessage} [params.request] - Http request object
* @param {string} [params.cookieString]
* @param {string} params.encryptionKey - Encryption Key
* @param {string} params.encryptionSalt - Encryption Salt
* @param {string} params.database - Database Name
* @param {boolean} [params.useLocal]
*
* @returns {{ key: string | undefined, csrf: string | undefined }}
*/
function getToken({
request,
encryptionKey,
encryptionSalt,
database,
useLocal,
cookieString,
}) {
try {
/**
* Grab the payload
*
* @description Grab the payload
*/
const cookies = parseCookies({ request, cookieString });
const keynames = getAuthCookieNames();
const authKeyName = keynames.keyCookieName;
const csrfName = keynames.csrfCookieName;
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;
+96
View File
@@ -0,0 +1,96 @@
import http from "http";
import decrypt from "../package-shared/functions/dsql/decrypt";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../package-shared/utils/backend/parseCookies";
type Param = {
request?: http.IncomingMessage;
cookieString?: string;
encryptionKey: string;
encryptionSalt: string;
database: string;
useLocal?: boolean;
};
type Return = {
key: string | undefined;
csrf: string | undefined;
};
/**
* Get just the access token for user
* ==============================================================================
* @description This Function takes in a request object and returns a user token
* string and csrf token string
*/
export default function getToken({
request,
encryptionKey,
encryptionSalt,
database,
useLocal,
cookieString,
}: Param): Return {
try {
/**
* Grab the payload
*
* @description Grab the payload
*/
const cookies = parseCookies({ request, cookieString });
const keynames = getAuthCookieNames();
const authKeyName = keynames.keyCookieName;
const csrfName = keynames.csrfCookieName;
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,
};
}
}
-31
View File
@@ -1,31 +0,0 @@
export = getUser;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* ==============================================================================
* 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 to get
* @param {string[]} [params.fields] - fields to select
* @param {boolean} [params.apiUserId] - API User ID
* @param {boolean} [params.useLocal] - Whether to use a remote database instead of API
*
* @returns { Promise<import("../package-shared/types").GetUserFunctionReturn>}
*/
declare function getUser({ key, userId, database, fields, apiUserId, useLocal }: {
key: string;
database: string;
userId: number;
fields?: string[];
apiUserId?: boolean;
useLocal?: boolean;
}): Promise<import("../package-shared/types").GetUserFunctionReturn>;
+27 -43
View File
@@ -1,41 +1,29 @@
// @ts-check
import path from "path";
import fs from "fs";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiGetUser from "../package-shared/functions/api/users/api-get-user";
import { GetUserFunctionReturn } from "../package-shared/types";
type Param = {
key: string;
database: string;
userId: number;
fields?: string[];
apiUserId?: boolean;
useLocal?: boolean;
};
/**
* ==============================================================================
* Imports
* ==============================================================================
* # Get User
*/
const path = require("path");
const fs = require("fs");
const https = require("https");
const http = require("http");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiGetUser = require("../package-shared/functions/api/users/api-get-user");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* ==============================================================================
* 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 to get
* @param {string[]} [params.fields] - fields to select
* @param {boolean} [params.apiUserId] - API User ID
* @param {boolean} [params.useLocal] - Whether to use a remote database instead of API
*
* @returns { Promise<import("../package-shared/types").GetUserFunctionReturn>}
*/
async function getUser({ key, userId, database, fields, apiUserId, useLocal }) {
export default async function getUser({
key,
userId,
database,
fields,
apiUserId,
useLocal,
}: Param): Promise<GetUserFunctionReturn> {
/**
* Initialize
*/
@@ -84,7 +72,9 @@ async function getUser({ key, userId, database, fields, apiUserId, useLocal }) {
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -156,11 +146,5 @@ async function getUser({ key, userId, database, fields, apiUserId, useLocal }) {
/** ********************************************** */
/** ********************************************** */
return httpResponse;
return httpResponse as GetUserFunctionReturn;
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = getUser;
-55
View File
@@ -1,55 +0,0 @@
export = loginUser;
/**
* 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 & Object<string, any>} [params.response] - Http response object
* @param {String} [params.encryptionKey] - Encryption Key
* @param {String} [params.encryptionSalt] - Encryption Salt
* @param {boolean} [params.email_login] - Email only Login
* @param {string} [params.email_login_code] - Email login code
* @param {string} [params.temp_code_field] - Database table field name for temporary code
* @param {boolean} [params.token] - Send access key as part of response body?
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.skipPassword]
* @param {boolean} [params.useLocal]
* @param {boolean} [params.skipWriteAuthFile] - Skip writing auth file to `.tmp/login` folder
* @param {string | number} [params.apiUserID] - Required for setting of cookies
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn>}
*/
declare function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, useLocal, apiUserID, skipWriteAuthFile, }: {
key?: string;
database: string;
payload: {
email?: string;
username?: string;
password?: string;
};
additionalFields?: string[];
response?: http.ServerResponse & {
[x: string]: any;
};
encryptionKey?: string;
encryptionSalt?: string;
email_login?: boolean;
email_login_code?: string;
temp_code_field?: string;
token?: boolean;
user_id?: string | number;
skipPassword?: boolean;
useLocal?: boolean;
skipWriteAuthFile?: boolean;
apiUserID?: string | number;
}): Promise<import("../package-shared/types").APILoginFunctionReturn>;
import http = require("http");
+54 -64
View File
@@ -1,52 +1,40 @@
// @ts-check
import http from "http";
import fs from "fs";
import path from "path";
import encrypt from "../package-shared/functions/dsql/encrypt";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiLoginUser from "../package-shared/functions/api/users/api-login";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../package-shared/functions/backend/auth/write-auth-files";
import { APILoginFunctionReturn } from "../package-shared/types";
type Param = {
key?: string;
database: string;
payload: {
email?: string;
username?: string;
password?: string;
};
additionalFields?: string[];
response?: http.ServerResponse & { [s: string]: any };
encryptionKey?: string;
encryptionSalt?: string;
email_login?: boolean;
email_login_code?: string;
temp_code_field?: string;
token?: boolean;
user_id?: string | number;
skipPassword?: boolean;
useLocal?: boolean;
skipWriteAuthFile?: boolean;
apiUserID?: string | number;
};
/**
* ==============================================================================
* Imports
* ==============================================================================
* # Login A user
*/
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const encrypt = require("../package-shared/functions/dsql/encrypt");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiLoginUser = require("../package-shared/functions/api/users/api-login");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const {
writeAuthFile,
} = require("../package-shared/functions/backend/auth/write-auth-files");
/**
* 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 & Object<string, any>} [params.response] - Http response object
* @param {String} [params.encryptionKey] - Encryption Key
* @param {String} [params.encryptionSalt] - Encryption Salt
* @param {boolean} [params.email_login] - Email only Login
* @param {string} [params.email_login_code] - Email login code
* @param {string} [params.temp_code_field] - Database table field name for temporary code
* @param {boolean} [params.token] - Send access key as part of response body?
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.skipPassword]
* @param {boolean} [params.useLocal]
* @param {boolean} [params.skipWriteAuthFile] - Skip writing auth file to `.tmp/login` folder
* @param {string | number} [params.apiUserID] - Required for setting of cookies
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn>}
*/
async function loginUser({
export default async function loginUser({
key,
payload,
database,
@@ -63,7 +51,7 @@ async function loginUser({
useLocal,
apiUserID,
skipWriteAuthFile,
}) {
}: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
@@ -114,9 +102,10 @@ async function loginUser({
*/
/** @type {import("../package-shared/types").APILoginFunctionReturn} */
let httpResponse = {
success: false,
};
let httpResponse: import("../package-shared/types").APILoginFunctionReturn =
{
success: false,
};
/**
* Check for local DB settings
@@ -134,7 +123,9 @@ async function loginUser({
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -168,17 +159,18 @@ async function loginUser({
*/
httpResponse = await new Promise((resolve, reject) => {
/** @type {import("../package-shared/types").PackageUserLoginRequestBody} */
const reqPayload = {
encryptionKey: finalEncryptionKey,
payload,
database,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
skipPassword: skipPassword,
};
const reqPayload: import("../package-shared/types").PackageUserLoginRequestBody =
{
encryptionKey: finalEncryptionKey,
payload,
database,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
skipPassword: skipPassword,
};
const reqPayloadJSON = JSON.stringify(reqPayload);
@@ -270,5 +262,3 @@ async function loginUser({
return httpResponse;
}
module.exports = loginUser;
-31
View File
@@ -1,31 +0,0 @@
export = logoutUser;
/**
* Logout user
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} [params.encryptedUserString] - Encrypted User String
* @param {http.IncomingMessage & Object<string, any>} [params.request] - Request Object
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
* @param {string} [params.cookieString]
* @param {string} [params.database] - Target database name(slug): optional
* @param {string | number} [params.dsqlUserId]
*
* @returns {{success: boolean, msg: string, cookieNames?: any}}
*/
declare function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, }: {
encryptedUserString?: string;
request?: http.IncomingMessage & {
[x: string]: any;
};
response?: http.ServerResponse & {
[x: string]: any;
};
cookieString?: string;
database?: string;
dsqlUserId?: string | number;
}): {
success: boolean;
msg: string;
cookieNames?: any;
};
import http = require("http");
+30 -30
View File
@@ -1,35 +1,37 @@
// @ts-check
import http from "http";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import decrypt from "../package-shared/functions/dsql/decrypt";
import EJSON from "../package-shared/utils/ejson";
import { deleteAuthFile } from "../package-shared/functions/backend/auth/write-auth-files";
import parseCookies from "../package-shared/utils/backend/parseCookies";
import { DATASQUIREL_LoggedInUser } from "../package-shared/types";
const http = require("http");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const EJSON = require("../package-shared/utils/ejson");
const {
deleteAuthFile,
} = require("../package-shared/functions/backend/auth/write-auth-files");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
type Param = {
encryptedUserString?: string;
request?: http.IncomingMessage & { [s: string]: any };
response?: http.ServerResponse & { [s: string]: any };
cookieString?: string;
database?: string;
dsqlUserId?: string | number;
};
type Return = {
success: boolean;
msg: string;
cookieNames?: any;
};
/**
* Logout user
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} [params.encryptedUserString] - Encrypted User String
* @param {http.IncomingMessage & Object<string, any>} [params.request] - Request Object
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
* @param {string} [params.cookieString]
* @param {string} [params.database] - Target database name(slug): optional
* @param {string | number} [params.dsqlUserId]
*
* @returns {{success: boolean, msg: string, cookieNames?: any}}
* # Logout user
*/
function logoutUser({
export default function logoutUser({
response,
database,
dsqlUserId,
encryptedUserString,
request,
cookieString,
}) {
}: Param): Return {
/**
* Check Encryption Keys
*
@@ -44,8 +46,7 @@ function logoutUser({
const csrfName = cookieNames.csrfCookieName;
const oneTimeCodeName = getAuthCookieNames().oneTimeCodeName;
/** @type {string | undefined} */
const decryptedUserJSON = (() => {
const decryptedUserJSON: string | undefined = (() => {
try {
if (request) {
const cookiesObject = parseCookies({
@@ -62,7 +63,7 @@ function logoutUser({
} else {
return undefined;
}
} catch (/** @type {any} */ error) {
} catch (/** @type {any} */ error: any) {
console.log(
"Error getting decrypted User JSON to logout:",
error.message
@@ -74,10 +75,9 @@ function logoutUser({
if (!decryptedUserJSON) throw new Error("Invalid User");
const userObject =
/** @type {import("../package-shared/types").DATASQUIREL_LoggedInUser | undefined} */ (
EJSON.parse(decryptedUserJSON)
);
const userObject = EJSON.parse(
decryptedUserJSON
) as DATASQUIREL_LoggedInUser;
if (!userObject?.csrf_k)
throw new Error("Invalid User. Please check key");
@@ -96,7 +96,7 @@ function logoutUser({
msg: "User Logged Out",
cookieNames,
};
} catch (/** @type {any} */ error) {
} catch (/** @type {any} */ error: any) {
console.log("Logout Error:", error.message);
return {
success: false,
-42
View File
@@ -1,42 +0,0 @@
export = reauthUser;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* ==============================================================================
* Main Function
* ==============================================================================
* @async
*
* @param {object} params - Single Param object containing params
* @param {String} [params.key] - API Key
* @param {String} [params.database]- Target Database slug
* @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
* @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn> }
*/
declare function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, useLocal, }: {
key?: string;
database?: string;
response?: http.ServerResponse;
request?: http.IncomingMessage;
level?: ("deep" | "normal");
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
encryptedUserString?: string;
user_id?: string | number;
useLocal?: boolean;
}): Promise<import("../package-shared/types").APILoginFunctionReturn>;
import http = require("http");
+33 -62
View File
@@ -1,54 +1,37 @@
// @ts-check
import http from "http";
import https from "https";
import fs from "fs";
import path from "path";
import encrypt from "../package-shared/functions/dsql/encrypt";
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const encrypt = require("../package-shared/functions/dsql/encrypt");
const userAuth = require("./user-auth");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiReauthUser = require("../package-shared/functions/api/users/api-reauth-user");
const {
import userAuth from "./user-auth";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiReauthUser from "../package-shared/functions/api/users/api-reauth-user";
import {
writeAuthFile,
deleteAuthFile,
} = require("../package-shared/functions/backend/auth/write-auth-files");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
} from "../package-shared/functions/backend/auth/write-auth-files";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import { APILoginFunctionReturn } from "../package-shared/types";
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
type Param = {
key?: string;
database?: string;
response?: http.ServerResponse;
request?: http.IncomingMessage;
level?: "deep" | "normal";
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
encryptedUserString?: string;
user_id?: string | number;
useLocal?: boolean;
};
/**
* ==============================================================================
* Main Function
* ==============================================================================
* @async
*
* @param {object} params - Single Param object containing params
* @param {String} [params.key] - API Key
* @param {String} [params.database]- Target Database slug
* @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
* @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn> }
* # Reauthorize User
*/
async function reauthUser({
export default async function reauthUser({
key,
database,
response,
@@ -60,7 +43,7 @@ async function reauthUser({
encryptedUserString,
user_id,
useLocal,
}) {
}: Param): Promise<APILoginFunctionReturn> {
/**
* Check Encryption Keys
*
@@ -112,7 +95,9 @@ async function reauthUser({
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -133,7 +118,7 @@ async function reauthUser({
*
* @description make a request to datasquirel.com
*/
httpResponse = await new Promise((resolve, reject) => {
httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
existingUser: existingUser.payload,
database,
@@ -182,13 +167,9 @@ async function reauthUser({
httpsRequest.write(reqPayload);
httpsRequest.end();
});
})) as APILoginFunctionReturn;
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
/**
* Make https request
*
@@ -226,15 +207,5 @@ async function reauthUser({
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = reauthUser;
-41
View File
@@ -1,41 +0,0 @@
export = sendEmailCode;
/**
* Send Email Code to 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 {string} params.email Login Email/Username and Password
* @param {string} [params.temp_code_field_name] - Database table field name for temporary code
* @param {http.ServerResponse & Object<string,any>} [params.response]
* @param {string} [params.mail_domain]
* @param {string} [params.mail_username]
* @param {string} [params.mail_password]
* @param {number} [params.mail_port]
* @param {string} [params.sender]
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* @param {import("../package-shared/types").CookieObject[]} [params.extraCookies]
*
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse>}
*/
declare function sendEmailCode({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, useLocal, response, extraCookies, }: {
key?: string;
database?: string;
email: string;
temp_code_field_name?: string;
response?: http.ServerResponse & {
[x: string]: any;
};
mail_domain?: string;
mail_username?: string;
mail_password?: string;
mail_port?: number;
sender?: string;
user_id?: boolean;
useLocal?: boolean;
extraCookies?: import("../package-shared/types").CookieObject[];
}): Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse>;
import http = require("http");
-172
View File
@@ -1,172 +0,0 @@
// @ts-check
const http = require("http");
const fs = require("fs");
const path = require("path");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiSendEmailCode = require("../package-shared/functions/api/users/api-send-email-code");
/**
* Send Email Code to 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 {string} params.email Login Email/Username and Password
* @param {string} [params.temp_code_field_name] - Database table field name for temporary code
* @param {http.ServerResponse & Object<string,any>} [params.response]
* @param {string} [params.mail_domain]
* @param {string} [params.mail_username]
* @param {string} [params.mail_password]
* @param {number} [params.mail_port]
* @param {string} [params.sender]
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* @param {import("../package-shared/types").CookieObject[]} [params.extraCookies]
*
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse>}
*/
async function sendEmailCode({
key,
email,
database,
temp_code_field_name,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
user_id,
useLocal,
response,
extraCookies,
}) {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
: defaultTempLoginFieldName;
const emailHtml = fs.readFileSync(
path.resolve(__dirname, "../package-shared/html/one-time-code.html"),
"utf-8"
);
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path.resolve(
process.cwd(),
"dsql.schema.json"
);
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
return await apiSendEmailCode({
database: DSQL_DB_NAME,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
useLocal,
response,
extraCookies,
});
} else {
/**
* Make https request
*
* @description make a request to datasquirel.com
*
* @type {import("../package-shared/types").SendOneTimeCodeEmailResponse}
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
email,
database,
email_login_field: emailLoginTempCodeFieldName,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
html: emailHtml,
});
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${
user_id || grabedHostNames.user_id
}/send-email-code`,
},
/**
* Callback Function
*
* @description https request callback
*/
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = sendEmailCode;
+165
View File
@@ -0,0 +1,165 @@
import http from "http";
import fs from "fs";
import path from "path";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiSendEmailCode from "../package-shared/functions/api/users/api-send-email-code";
import { SendOneTimeCodeEmailResponse } from "../package-shared/types";
type Param = {
key?: string;
database?: string;
email: string;
temp_code_field_name?: string;
response?: http.ServerResponse & { [s: string]: any };
mail_domain?: string;
mail_username?: string;
mail_password?: string;
mail_port?: number;
sender?: string;
user_id?: boolean;
useLocal?: boolean;
extraCookies?: import("../package-shared/types").CookieObject[];
};
/**
* # Send Email Code to a User
*/
export default async function sendEmailCode({
key,
email,
database,
temp_code_field_name,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
user_id,
useLocal,
response,
extraCookies,
}: Param): Promise<SendOneTimeCodeEmailResponse> {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
: defaultTempLoginFieldName;
const emailHtml = fs.readFileSync(
path.resolve(__dirname, "../package-shared/html/one-time-code.html"),
"utf-8"
);
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
process.cwd(),
"dsql.schema.json"
);
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
return await apiSendEmailCode({
database: DSQL_DB_NAME,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
useLocal,
response,
extraCookies,
});
} else {
/**
* Make https request
*
* @description make a request to datasquirel.com
*
* @type {import("../package-shared/types").SendOneTimeCodeEmailResponse}
*/
const httpResponse: import("../package-shared/types").SendOneTimeCodeEmailResponse =
await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
email,
database,
email_login_field: emailLoginTempCodeFieldName,
mail_domain,
mail_password,
mail_username,
mail_port,
sender,
html: emailHtml,
});
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${
user_id || grabedHostNames.user_id
}/send-email-code`,
},
/**
* Callback Function
*
* @description https request callback
*/
(res) => {
var str = "";
res.on("data", function (chunk) {
str += chunk;
});
res.on("end", function () {
resolve(JSON.parse(str));
});
res.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
}
-80
View File
@@ -1,80 +0,0 @@
export = githubAuth;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {object} FunctionReturn
* @property {boolean} success - Did the function run successfully?
* @property {{id: number, first_name: string, last_name: string, csrf_k: string, social_id: string} | 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.code - Github access code gotten from the client side
* @param {string?} params.email - Email gotten from the client side if available
* @param {string} params.database - Target database name(slug)
* @param {string} params.clientId - Github client id
* @param {string} params.clientSecret - Github client Secret
* @param {http.ServerResponse} params.response - HTTPS response object
* @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
* @param {Object<string,string|number>} [params.additionalData] - Additional Data to by added on creation of User
* @param {boolean} [params.user_id] - User ID
*
* @returns { Promise<FunctionReturn | undefined> }
*/
declare function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, }: {
key: string;
code: string;
email: string | null;
database: string;
clientId: string;
clientSecret: string;
response: http.ServerResponse;
encryptionKey: string;
encryptionSalt: string;
additionalFields?: string[];
additionalData?: {
[x: string]: string | number;
};
user_id?: boolean;
}): Promise<FunctionReturn | undefined>;
declare namespace githubAuth {
export { FunctionReturn };
}
import http = require("http");
type FunctionReturn = {
/**
* - Did the function run successfully?
*/
success: boolean;
/**
* - Returned User
*/
user: {
id: number;
first_name: string;
last_name: string;
csrf_k: string;
social_id: string;
} | null;
/**
* - Dsql User Id
*/
dsqlUserId?: number;
/**
* - Response message
*/
msg?: string;
};
@@ -1,56 +1,42 @@
// @ts-check
import http from "http";
import fs from "fs";
import path from "path";
import encrypt from "../../package-shared/functions/dsql/encrypt";
import grabHostNames from "../../package-shared/utils/grab-host-names";
import apiGithubLogin from "../../package-shared/functions/api/users/social/api-github-login";
interface FunctionReturn {
success: boolean;
user: {
id: number;
first_name: string;
last_name: string;
csrf_k: string;
social_id: string;
} | null;
dsqlUserId?: number;
msg?: string;
}
type Param = {
key: string;
code: string;
email: string | null;
database: string;
clientId: string;
clientSecret: string;
response: http.ServerResponse;
encryptionKey: string;
encryptionSalt: string;
additionalFields?: string[];
additionalData?: { [s: string]: string | number };
user_id?: boolean;
};
/**
* ==============================================================================
* Imports
* ==============================================================================
* # SERVER FUNCTION: Login with google Function
*/
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const encrypt = require("../../package-shared/functions/dsql/encrypt");
const grabHostNames = require("../../package-shared/utils/grab-host-names");
const apiGithubLogin = require("../../package-shared/functions/api/users/social/api-github-login");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {object} FunctionReturn
* @property {boolean} success - Did the function run successfully?
* @property {{id: number, first_name: string, last_name: string, csrf_k: string, social_id: string} | 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.code - Github access code gotten from the client side
* @param {string?} params.email - Email gotten from the client side if available
* @param {string} params.database - Target database name(slug)
* @param {string} params.clientId - Github client id
* @param {string} params.clientSecret - Github client Secret
* @param {http.ServerResponse} params.response - HTTPS response object
* @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
* @param {Object<string,string|number>} [params.additionalData] - Additional Data to by added on creation of User
* @param {boolean} [params.user_id] - User ID
*
* @returns { Promise<FunctionReturn | undefined> }
*/
async function githubAuth({
export default async function githubAuth({
key,
code,
email,
@@ -63,7 +49,7 @@ async function githubAuth({
additionalFields,
user_id,
additionalData,
}) {
}: Param): Promise<FunctionReturn | undefined> {
/**
* Check inputs
*
@@ -96,10 +82,6 @@ async function githubAuth({
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Initialize HTTP response variable
*/
@@ -127,7 +109,10 @@ async function githubAuth({
DSQL_DB_NAME?.match(/./)
) {
/** @type {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined | undefined} */
let dbSchema;
let dbSchema:
| import("../../package-shared/types").DSQL_DatabaseSchemaType
| undefined
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -153,7 +138,7 @@ async function githubAuth({
* @description make a request to datasquirel.com
* @type {FunctionReturn} - Https response object
*/
httpResponse = await new Promise((resolve, reject) => {
httpResponse = (await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
code,
email,
@@ -215,7 +200,7 @@ async function githubAuth({
);
httpsRequest.write(reqPayload);
httpsRequest.end();
});
})) as any;
}
////////////////////////////////////////
@@ -247,15 +232,5 @@ async function githubAuth({
]);
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return httpResponse;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = githubAuth;
-36
View File
@@ -1,36 +0,0 @@
export = googleAuth;
/**
* 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
* @param {http.ServerResponse} [params.response] - HTTPS response object
* @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
* @param {Object<string,string|number>} [params.additionalData] - Additional Data to by added on creation of User
* @param {string | number} [params.apiUserID] - API user ID
* @param {boolean} [params.useLocal] - Whether to use a remote database instead of API
*
* @returns { Promise<import("../../package-shared/types").APILoginFunctionReturn> }
*/
declare function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, useLocal, }: {
key?: string;
token: string;
database?: string;
response?: http.ServerResponse;
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
additionalData?: {
[x: string]: string | number;
};
apiUserID?: string | number;
useLocal?: boolean;
}): Promise<import("../../package-shared/types").APILoginFunctionReturn>;
import http = require("http");
@@ -1,35 +1,28 @@
// @ts-check
import http from "http";
import encrypt from "../../package-shared/functions/dsql/encrypt";
import grabHostNames from "../../package-shared/utils/grab-host-names";
import apiGoogleLogin from "../../package-shared/functions/api/users/social/api-google-login";
import getAuthCookieNames from "../../package-shared/functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../../package-shared/functions/backend/auth/write-auth-files";
import { APILoginFunctionReturn } from "../../package-shared/types";
const http = require("http");
const encrypt = require("../../package-shared/functions/dsql/encrypt");
const grabHostNames = require("../../package-shared/utils/grab-host-names");
const apiGoogleLogin = require("../../package-shared/functions/api/users/social/api-google-login");
const getAuthCookieNames = require("../../package-shared/functions/backend/cookies/get-auth-cookie-names");
const {
writeAuthFile,
} = require("../../package-shared/functions/backend/auth/write-auth-files");
type Param = {
key?: string;
token: string;
database?: string;
response?: http.ServerResponse;
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
additionalData?: { [s: string]: string | number };
apiUserID?: string | number;
useLocal?: boolean;
};
/**
* 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
* @param {http.ServerResponse} [params.response] - HTTPS response object
* @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
* @param {Object<string,string|number>} [params.additionalData] - Additional Data to by added on creation of User
* @param {string | number} [params.apiUserID] - API user ID
* @param {boolean} [params.useLocal] - Whether to use a remote database instead of API
*
* @returns { Promise<import("../../package-shared/types").APILoginFunctionReturn> }
* # SERVER FUNCTION: Login with google Function
*/
async function googleAuth({
export default async function googleAuth({
key,
token,
database,
@@ -40,7 +33,7 @@ async function googleAuth({
additionalData,
apiUserID,
useLocal,
}) {
}: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
@@ -85,9 +78,10 @@ async function googleAuth({
*/
/** @type {import("../../package-shared/types").APILoginFunctionReturn} */
let httpResponse = {
success: false,
};
let httpResponse: import("../../package-shared/types").APILoginFunctionReturn =
{
success: false,
};
/**
* Check for local DB settings
@@ -207,5 +201,3 @@ async function googleAuth({
return httpResponse;
}
module.exports = googleAuth;
-25
View File
@@ -1,25 +0,0 @@
export = updateUser;
/**
* # Update User
* @async
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} [params.database] - Target Database
* @param {String | number} params.updatedUserId - Target Database
* @param {Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/
declare function updateUser({ key, payload, database, user_id, useLocal, updatedUserId, }: {
key?: string;
database?: string;
updatedUserId: string | number;
payload: {
[x: string]: any;
};
user_id?: boolean;
useLocal?: boolean;
}): Promise<import("../package-shared/types").UpdateUserFunctionReturn>;
+19 -32
View File
@@ -1,34 +1,29 @@
// @ts-check
import path from "path";
import fs from "fs";
import grabHostNames from "../package-shared/utils/grab-host-names";
import apiUpdateUser from "../package-shared/functions/api/users/api-update-user";
import { UpdateUserFunctionReturn } from "../package-shared/types";
const http = require("http");
const https = require("https");
const path = require("path");
const fs = require("fs");
const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiUpdateUser = require("../package-shared/functions/api/users/api-update-user");
type Param = {
key?: string;
database?: string;
updatedUserId: string | number;
payload: { [s: string]: any };
user_id?: boolean;
useLocal?: boolean;
};
/**
* # Update User
* @async
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} [params.database] - Target Database
* @param {String | number} params.updatedUserId - Target Database
* @param {Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/
async function updateUser({
export default async function updateUser({
key,
payload,
database,
user_id,
useLocal,
updatedUserId,
}) {
}: Param): Promise<UpdateUserFunctionReturn> {
/**
* Check for local DB settings
*
@@ -48,7 +43,9 @@ async function updateUser({
useLocal
) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema;
let dbSchema:
| import("../package-shared/types").DSQL_DatabaseSchemaType
| undefined;
try {
const localDbSchemaPath = path.resolve(
@@ -122,15 +119,5 @@ async function updateUser({
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
return httpResponse as UpdateUserFunctionReturn;
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateUser;
-42
View File
@@ -1,42 +0,0 @@
export = userAuth;
/**
* 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 & Object<string, any>} [params.request] - Http request object
* @param {http.IncomingMessage & Object<string, any>} [params.req] - Http request object
* @param {string} [params.cookieString]
* @param {string} [params.encryptedUserString] - Encrypted user string to use instead of getting from cookie header
* @param {string} [params.encryptionKey] - Encryption Key: alt env: DSQL_ENCRYPTION_PASSWORD
* @param {string} [params.encryptionSalt] - Encryption Salt: alt env: DSQL_ENCRYPTION_SALT
* @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security
* @param {string} [params.database] - Database Name (slug)
* @param {string | number} [params.dsqlUserId] - alt env: DSQL_API_USER_ID
* @param {number} [params.expiry] - Expiry time in milliseconds
* @param {string} [params.csrfHeaderName] - Optional. CSRF Header Name
* @param {boolean} [params.csrfHeaderIsValue] - If the csrf value is the name of the request http header
*
* @returns { import("../package-shared/types").AuthenticatedUser }
*/
declare function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry, cookieString, csrfHeaderIsValue, csrfHeaderName, }: {
request?: http.IncomingMessage & {
[x: string]: any;
};
req?: http.IncomingMessage & {
[x: string]: any;
};
cookieString?: string;
encryptedUserString?: string;
encryptionKey?: string;
encryptionSalt?: string;
level?: ("deep" | "normal");
database?: string;
dsqlUserId?: string | number;
expiry?: number;
csrfHeaderName?: string;
csrfHeaderIsValue?: boolean;
}): import("../package-shared/types").AuthenticatedUser;
import http = require("http");
+26 -29
View File
@@ -1,12 +1,11 @@
// @ts-check
const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const {
checkAuthFile,
} = require("../package-shared/functions/backend/auth/write-auth-files");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
import http from "http";
import decrypt from "../package-shared/functions/dsql/decrypt";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import { checkAuthFile } from "../package-shared/functions/backend/auth/write-auth-files";
import parseCookies from "../package-shared/utils/backend/parseCookies";
import { AuthenticatedUser } from "../package-shared/types";
const minuteInMilliseconds = 60000;
const hourInMilliseconds = minuteInMilliseconds * 60;
@@ -15,29 +14,28 @@ const weekInMilliseconds = dayInMilliseconds * 7;
const monthInMilliseconds = dayInMilliseconds * 30;
const yearInMilliseconds = dayInMilliseconds * 365;
type Param = {
request?: http.IncomingMessage & { [s: string]: any };
req?: http.IncomingMessage & { [s: string]: any };
cookieString?: string;
encryptedUserString?: string;
encryptionKey?: string;
encryptionSalt?: string;
level?: "deep" | "normal";
database?: string;
dsqlUserId?: string | number;
expiry?: number;
csrfHeaderName?: string;
csrfHeaderIsValue?: boolean;
};
/**
* 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 & Object<string, any>} [params.request] - Http request object
* @param {http.IncomingMessage & Object<string, any>} [params.req] - Http request object
* @param {string} [params.cookieString]
* @param {string} [params.encryptedUserString] - Encrypted user string to use instead of getting from cookie header
* @param {string} [params.encryptionKey] - Encryption Key: alt env: DSQL_ENCRYPTION_PASSWORD
* @param {string} [params.encryptionSalt] - Encryption Salt: alt env: DSQL_ENCRYPTION_SALT
* @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security
* @param {string} [params.database] - Database Name (slug)
* @param {string | number} [params.dsqlUserId] - alt env: DSQL_API_USER_ID
* @param {number} [params.expiry] - Expiry time in milliseconds
* @param {string} [params.csrfHeaderName] - Optional. CSRF Header Name
* @param {boolean} [params.csrfHeaderIsValue] - If the csrf value is the name of the request http header
*
* @returns { import("../package-shared/types").AuthenticatedUser }
*/
function userAuth({
export default function userAuth({
request,
req,
encryptionKey,
@@ -50,7 +48,7 @@ function userAuth({
cookieString,
csrfHeaderIsValue,
csrfHeaderName,
}) {
}: Param): AuthenticatedUser {
try {
const finalRequest = req || request;
@@ -108,7 +106,8 @@ function userAuth({
*/
/** @type {import("../package-shared/types").DATASQUIREL_LoggedInUser} */
let userObject = JSON.parse(userPayloadJSON);
let userObject: import("../package-shared/types").DATASQUIREL_LoggedInUser =
JSON.parse(userPayloadJSON);
if (!userObject.csrf_k) {
return {
@@ -192,7 +191,7 @@ function userAuth({
success: true,
payload: userObject,
};
} catch (/** @type {any} */ error) {
} catch (/** @type {any} */ error: any) {
/**
* Return User Object
*
@@ -205,5 +204,3 @@ function userAuth({
};
}
}
module.exports = userAuth;
-21
View File
@@ -1,21 +0,0 @@
export = validateTempEmailCode;
/**
* Verify the temp email code sent to the user's email address
* ==============================================================================
* @async
*
* @param {object} params - Single Param object containing params
* @param {http.IncomingMessage & Object<string, any>} [params.request]
* @param {string} [params.cookieString]
* @param {string} [params.email]
*
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>}
*/
declare function validateTempEmailCode({ request, email, cookieString }: {
request?: http.IncomingMessage & {
[x: string]: any;
};
cookieString?: string;
email?: string;
}): Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>;
import http = require("http");
-53
View File
@@ -1,53 +0,0 @@
// @ts-check
const http = require("http");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
const parseCookies = require("../package-shared/utils/backend/parseCookies");
const decrypt = require("../package-shared/functions/dsql/decrypt");
const EJSON = require("../package-shared/utils/ejson");
/**
* Verify the temp email code sent to the user's email address
* ==============================================================================
* @async
*
* @param {object} params - Single Param object containing params
* @param {http.IncomingMessage & Object<string, any>} [params.request]
* @param {string} [params.cookieString]
* @param {string} [params.email]
*
* @returns { Promise<import("../package-shared/types").SendOneTimeCodeEmailResponse | null>}
*/
async function validateTempEmailCode({ request, email, cookieString }) {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload =
/** @type {import("../package-shared/types").SendOneTimeCodeEmailResponse | undefined} */ (
EJSON.parse(encryptedPayload)
);
if (payload?.email && !email) {
return payload;
}
if (payload?.email && payload.email === email) {
return payload;
}
return null;
} catch (/** @type {any} */ error) {
console.log("validateTempEmailCode error:", error.message);
return null;
}
}
module.exports = validateTempEmailCode;
+50
View File
@@ -0,0 +1,50 @@
import http from "http";
import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../package-shared/utils/backend/parseCookies";
import decrypt from "../package-shared/functions/dsql/decrypt";
import EJSON from "../package-shared/utils/ejson";
import { SendOneTimeCodeEmailResponse } from "../package-shared/types";
type Param = {
request?: http.IncomingMessage & { [s: string]: any };
cookieString?: string;
email?: string;
};
/**
* # Verify the temp email code sent to the user's email address
*/
export default async function validateTempEmailCode({
request,
email,
cookieString,
}: Param): Promise<SendOneTimeCodeEmailResponse | null> {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload = EJSON.parse(encryptedPayload) as
| SendOneTimeCodeEmailResponse
| undefined;
if (payload?.email && !email) {
return payload;
}
if (payload?.email && payload.email === email) {
return payload;
}
return null;
} catch (error: any) {
console.log("validateTempEmailCode error:", error.message);
return null;
}
}
-22
View File
@@ -1,22 +0,0 @@
export = validateToken;
/**
* 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("../package-shared/types").DATASQUIREL_LoggedInUser | null}
*/
declare function validateToken({ token, encryptionKey, encryptionSalt }: {
token: string;
encryptionKey: string;
encryptionSalt: string;
level?: ("deep" | "normal") | null;
database: string;
}): import("../package-shared/types").DATASQUIREL_LoggedInUser | null;
@@ -1,23 +1,25 @@
// @ts-check
import http from "http";
import decrypt from "../package-shared/functions/dsql/decrypt";
import { DATASQUIREL_LoggedInUser } from "../package-shared/types";
const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt");
type Param = {
token: string;
encryptionKey: string;
encryptionSalt: string;
level?: ("deep" | "normal") | null;
database: string;
};
/**
* 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("../package-shared/types").DATASQUIREL_LoggedInUser | null}
*/
function validateToken({ token, encryptionKey, encryptionSalt }) {
export default function validateToken({
token,
encryptionKey,
encryptionSalt,
}: Param): DATASQUIREL_LoggedInUser | null {
try {
/**
* Grab the payload
@@ -72,5 +74,3 @@ function validateToken({ token, encryptionKey, encryptionSalt }) {
return null;
}
}
module.exports = validateToken;