Updates
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiCreateUser from "../../functions/api/users/api-create-user";
|
||||
import { AddUserFunctionReturn, UserDataPayload } from "../../types";
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
payload: UserDataPayload;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
user_id?: string | number;
|
||||
apiUserId?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
export default async function addUser({
|
||||
key,
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
user_id,
|
||||
apiUserId,
|
||||
}: Param): Promise<AddUserFunctionReturn> {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const {
|
||||
DSQL_DB_HOST,
|
||||
DSQL_DB_USERNAME,
|
||||
DSQL_DB_PASSWORD,
|
||||
DSQL_DB_NAME,
|
||||
DSQL_API_USER_ID,
|
||||
} = process.env;
|
||||
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
return await apiCreateUser({
|
||||
database: DSQL_DB_NAME,
|
||||
encryptionKey,
|
||||
payload,
|
||||
userId: apiUserId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/add-user`,
|
||||
},
|
||||
|
||||
/**
|
||||
* 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 as AddUserFunctionReturn;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiDeleteUser from "../../functions/api/users/api-delete-user";
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
deletedUserId: string | number;
|
||||
user_id?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default async function deleteUser({
|
||||
key,
|
||||
database,
|
||||
user_id,
|
||||
deletedUserId,
|
||||
}: Param): Promise<UpdateUserFunctionReturn> {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
return await apiDeleteUser({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
deletedUserId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
database,
|
||||
deletedUserId,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/delete-user`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
);
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
})) as UpdateUserFunctionReturn;
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import http from "http";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
|
||||
type Param = {
|
||||
request?: http.IncomingMessage;
|
||||
cookieString?: string;
|
||||
encryptionKey: string;
|
||||
encryptionSalt: string;
|
||||
database: string;
|
||||
};
|
||||
|
||||
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,
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiGetUser from "../../functions/api/users/api-get-user";
|
||||
import { GetUserFunctionReturn } from "../../types";
|
||||
|
||||
type Param = {
|
||||
key: string;
|
||||
database: string;
|
||||
userId: number;
|
||||
fields?: string[];
|
||||
apiUserId?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
export default async function getUser({
|
||||
key,
|
||||
userId,
|
||||
database,
|
||||
fields,
|
||||
apiUserId,
|
||||
}: Param): Promise<GetUserFunctionReturn> {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
const defaultFields = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"email",
|
||||
"username",
|
||||
"image",
|
||||
"image_thumbnail",
|
||||
"verification_status",
|
||||
"date_created",
|
||||
"date_created_code",
|
||||
"date_created_timestamp",
|
||||
"date_updated",
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
|
||||
const updatedFields =
|
||||
fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
return await apiGetUser({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
apiUserId || grabedHostNames.user_id
|
||||
}/get-user`,
|
||||
},
|
||||
|
||||
/**
|
||||
* 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 as GetUserFunctionReturn;
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import http from "http";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiLoginUser from "../../functions/api/users/api-login";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import {
|
||||
APILoginFunctionReturn,
|
||||
DSQL_DatabaseSchemaType,
|
||||
PackageUserLoginRequestBody,
|
||||
} from "../../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;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
apiUserID?: string | number;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default async function loginUser({
|
||||
key,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
response,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
email_login,
|
||||
email_login_code,
|
||||
temp_code_field,
|
||||
token,
|
||||
user_id,
|
||||
skipPassword,
|
||||
apiUserID,
|
||||
skipWriteAuthFile,
|
||||
dbUserId,
|
||||
debug,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
if (!payload.email) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Email Required",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
|
||||
/** @type {import("../../types").APILoginFunctionReturn} */
|
||||
let httpResponse: import("../../types").APILoginFunctionReturn = {
|
||||
success: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
let dbSchema: DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
httpResponse = await apiLoginUser({
|
||||
database: process.env.DSQL_DB_NAME || "",
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
skipPassword,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
} else {
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload: PackageUserLoginRequestBody = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
skipPassword: skipPassword,
|
||||
dbUserId: dbUserId || 0,
|
||||
};
|
||||
|
||||
const reqPayloadJSON = JSON.stringify(reqPayload);
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayloadJSON).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/login-user`,
|
||||
},
|
||||
|
||||
(res) => {
|
||||
var str = "";
|
||||
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log(`loginUser:httpResponse:`, httpResponse);
|
||||
}
|
||||
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
} catch (error) {}
|
||||
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
});
|
||||
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
writeAuthFile(
|
||||
httpResponse.csrf,
|
||||
JSON.stringify(httpResponse.payload)
|
||||
);
|
||||
}
|
||||
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
|
||||
if (debug) {
|
||||
console.log(`loginUser:authKeyName:`, authKeyName);
|
||||
console.log(`loginUser:csrfName:`, csrfName);
|
||||
console.log(`loginUser:encryptedPayload:`, encryptedPayload);
|
||||
}
|
||||
|
||||
response?.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
|
||||
if (debug) {
|
||||
console.log(`loginUser:Response Sent!`);
|
||||
}
|
||||
}
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import http from "http";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import { deleteAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
|
||||
type Param = {
|
||||
encryptedUserString?: string;
|
||||
request?: http.IncomingMessage & { [s: string]: any };
|
||||
response?: http.ServerResponse & { [s: string]: any };
|
||||
cookieString?: string;
|
||||
database?: string;
|
||||
dsqlUserId?: string | number;
|
||||
debug?: boolean;
|
||||
};
|
||||
|
||||
type Return = {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
cookieNames?: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Logout user
|
||||
*/
|
||||
export default function logoutUser({
|
||||
response,
|
||||
database,
|
||||
dsqlUserId,
|
||||
encryptedUserString,
|
||||
request,
|
||||
cookieString,
|
||||
debug,
|
||||
}: Param): Return {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
try {
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("logoutUser:cookieNames", cookieNames);
|
||||
}
|
||||
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
const oneTimeCodeName = cookieNames.oneTimeCodeName;
|
||||
|
||||
const decryptedUserJSON: string | undefined = (() => {
|
||||
try {
|
||||
if (request) {
|
||||
const cookiesObject = parseCookies({
|
||||
request,
|
||||
cookieString,
|
||||
});
|
||||
return decrypt({
|
||||
encryptedString: cookiesObject[authKeyName],
|
||||
});
|
||||
} else if (encryptedUserString) {
|
||||
return decrypt({
|
||||
encryptedString: encryptedUserString,
|
||||
});
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(
|
||||
"Error getting decrypted User JSON to logout:",
|
||||
error.message
|
||||
);
|
||||
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
if (debug) {
|
||||
console.log("logoutUser:decryptedUserJSON", decryptedUserJSON);
|
||||
}
|
||||
|
||||
if (!decryptedUserJSON) throw new Error("Invalid User");
|
||||
|
||||
const userObject = EJSON.parse(
|
||||
decryptedUserJSON
|
||||
) as DATASQUIREL_LoggedInUser;
|
||||
|
||||
if (!userObject?.csrf_k)
|
||||
throw new Error("Invalid User. Please check key");
|
||||
|
||||
response?.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=null;max-age=0`,
|
||||
`${csrfName}=null;max-age=0`,
|
||||
`${oneTimeCodeName}=null;max-age=0`,
|
||||
]);
|
||||
|
||||
const csrf = userObject.csrf_k;
|
||||
deleteAuthFile(csrf);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: "User Logged Out",
|
||||
cookieNames,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.log("Logout Error:", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Logout Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import http from "http";
|
||||
import https from "https";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
|
||||
import userAuth from "./user-auth";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiReauthUser from "../../functions/api/users/api-reauth-user";
|
||||
import {
|
||||
writeAuthFile,
|
||||
deleteAuthFile,
|
||||
} from "../../functions/backend/auth/write-auth-files";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { APILoginFunctionReturn } from "../../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;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
export default async function reauthUser({
|
||||
key,
|
||||
database,
|
||||
response,
|
||||
request,
|
||||
level,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
additionalFields,
|
||||
encryptedUserString,
|
||||
user_id,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
|
||||
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_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
httpResponse = await apiReauthUser({
|
||||
existingUser: existingUser.payload,
|
||||
additionalFields,
|
||||
});
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
existingUser: existingUser.payload,
|
||||
database,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/reauth-user`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
})) as APILoginFunctionReturn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id || grabedHostNames.user_id,
|
||||
});
|
||||
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
|
||||
response?.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
|
||||
if (httpResponse.csrf) {
|
||||
deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
writeAuthFile(
|
||||
httpResponse.csrf,
|
||||
JSON.stringify(httpResponse.payload)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import http from "http";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../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;
|
||||
extraCookies?: import("../../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,
|
||||
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 = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
return await apiSendEmailCode({
|
||||
database: DSQL_DB_NAME,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
*/
|
||||
const httpResponse: import("../../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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import http from "http";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGithubLogin from "../../../functions/api/users/social/api-github-login";
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
export default async function githubAuth({
|
||||
key,
|
||||
code,
|
||||
email,
|
||||
database,
|
||||
clientId,
|
||||
clientSecret,
|
||||
response,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
additionalFields,
|
||||
user_id,
|
||||
additionalData,
|
||||
}: Param): Promise<FunctionReturn | undefined> {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
if (!code || code?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github 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 Github OAUTH client ID",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const {
|
||||
DSQL_DB_HOST,
|
||||
DSQL_DB_USERNAME,
|
||||
DSQL_DB_PASSWORD,
|
||||
DSQL_DB_NAME,
|
||||
DSQL_KEY,
|
||||
DSQL_REF_DB_NAME,
|
||||
DSQL_FULL_SYNC,
|
||||
} = process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./)
|
||||
) {
|
||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||
let dbSchema:
|
||||
| import("../../../types").DSQL_DatabaseSchemaType
|
||||
| undefined
|
||||
| undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
httpResponse = await apiGithubLogin({
|
||||
code,
|
||||
email: email || undefined,
|
||||
clientId,
|
||||
clientSecret,
|
||||
additionalFields,
|
||||
database: DSQL_DB_NAME,
|
||||
additionalData,
|
||||
});
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {FunctionReturn} - Https response object
|
||||
*/
|
||||
httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
code,
|
||||
email,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/github-login`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
resolve({
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Something went wrong",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
);
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
})) as any;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import http from "http";
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
|
||||
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
|
||||
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;
|
||||
debug?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
export default async function googleAuth({
|
||||
key,
|
||||
token,
|
||||
database,
|
||||
response,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
apiUserID,
|
||||
debug,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
|
||||
if (!token || token?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
|
||||
let httpResponse: APILoginFunctionReturn = {
|
||||
success: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
if (debug) {
|
||||
console.log(`Google login with Local Paradigm ...`);
|
||||
}
|
||||
|
||||
httpResponse = await apiGoogleLogin({
|
||||
token,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
} else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {{ success: boolean, user: import("../../../types").DATASQUIREL_LoggedInUser | null, msg?: string, dsqlUserId?: number } | null } - Https response object
|
||||
*/
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
apiUserID || grabedHostNames.user_id
|
||||
}/google-login`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
);
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if (httpResponse?.success && httpResponse?.payload) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||
});
|
||||
|
||||
if (httpResponse.csrf) {
|
||||
writeAuthFile(
|
||||
httpResponse.csrf,
|
||||
JSON.stringify(httpResponse.payload)
|
||||
);
|
||||
}
|
||||
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
|
||||
response?.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
}
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiUpdateUser from "../../functions/api/users/api-update-user";
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
updatedUserId: string | number;
|
||||
payload: { [s: string]: any };
|
||||
user_id?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default async function updateUser({
|
||||
key,
|
||||
payload,
|
||||
database,
|
||||
user_id,
|
||||
updatedUserId,
|
||||
}: Param): Promise<UpdateUserFunctionReturn> {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
process.env;
|
||||
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
if (
|
||||
DSQL_DB_HOST?.match(/./) &&
|
||||
DSQL_DB_USERNAME?.match(/./) &&
|
||||
DSQL_DB_PASSWORD?.match(/./) &&
|
||||
DSQL_DB_NAME?.match(/./) &&
|
||||
global.DSQL_USE_LOCAL
|
||||
) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
} catch (error) {}
|
||||
|
||||
return await apiUpdateUser({
|
||||
payload: payload,
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization:
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${
|
||||
user_id || grabedHostNames.user_id
|
||||
}/update-user`,
|
||||
},
|
||||
|
||||
/**
|
||||
* 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 as UpdateUserFunctionReturn;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import http from "http";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { checkAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import { AuthenticatedUser } from "../../types";
|
||||
import getCsrfHeaderName from "../../actions/get-csrf-header-name";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
|
||||
const minuteInMilliseconds = 60000;
|
||||
const hourInMilliseconds = minuteInMilliseconds * 60;
|
||||
const dayInMilliseconds = hourInMilliseconds * 24;
|
||||
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;
|
||||
debug?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*/
|
||||
export default function userAuth({
|
||||
request,
|
||||
req,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
level,
|
||||
database,
|
||||
dsqlUserId,
|
||||
encryptedUserString,
|
||||
expiry = weekInMilliseconds,
|
||||
cookieString,
|
||||
csrfHeaderName,
|
||||
debug,
|
||||
}: Param): AuthenticatedUser {
|
||||
try {
|
||||
const finalRequest = req || request;
|
||||
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
|
||||
const cookies = parseCookies({
|
||||
request: finalRequest,
|
||||
cookieString,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("userAuth:cookies:", cookies);
|
||||
}
|
||||
|
||||
const keyNames = getAuthCookieNames({
|
||||
userId: user_id,
|
||||
database: database || process.env.DSQL_DB_NAME,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("userAuth:keyNames:", keyNames);
|
||||
}
|
||||
|
||||
const key = encryptedUserString
|
||||
? encryptedUserString
|
||||
: cookies[keyNames.keyCookieName];
|
||||
|
||||
if (debug) {
|
||||
console.log("userAuth:key:", key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayloadJSON = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("userAuth:userPayloadJSON:", userPayloadJSON);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayloadJSON) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't Decrypt cookie",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
|
||||
/** @type {import("../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userObject: import("../../types").DATASQUIREL_LoggedInUser =
|
||||
JSON.parse(userPayloadJSON);
|
||||
|
||||
if (debug) {
|
||||
console.log("userAuth:userObject:", userObject);
|
||||
}
|
||||
|
||||
if (!userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No CSRF_K in decrypted payload",
|
||||
};
|
||||
}
|
||||
|
||||
if (!checkAuthFile(userObject.csrf_k)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Auth file doesn't exist",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (level?.match(/deep/i) && finalRequest) {
|
||||
const finalCsrfHeaderName = csrfHeaderName || getCsrfHeaderName();
|
||||
if (
|
||||
finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "CSRF_K mismatch",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const payloadCreationDate = Number(userObject.date);
|
||||
|
||||
if (
|
||||
Number.isNaN(payloadCreationDate) ||
|
||||
typeof payloadCreationDate !== "number"
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Payload Creation Date is not a number",
|
||||
};
|
||||
}
|
||||
|
||||
const timeElapsed = Date.now() - payloadCreationDate;
|
||||
|
||||
const finalExpiry = process.env.DSQL_SESSION_EXPIRY_TIME
|
||||
? Number(process.env.DSQL_SESSION_EXPIRY_TIME)
|
||||
: expiry;
|
||||
|
||||
if (timeElapsed > finalExpiry) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Session has expired",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: true,
|
||||
payload: userObject,
|
||||
};
|
||||
} catch (error: any) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import http from "http";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import http from "http";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
|
||||
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
|
||||
*/
|
||||
export default function validateToken({
|
||||
token,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}: Param): DATASQUIREL_LoggedInUser | null {
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user