Updates
This commit is contained in:
parent
a131764e1e
commit
5ab079f687
50
dist/index.d.ts
vendored
50
dist/index.d.ts
vendored
@ -9,18 +9,6 @@ declare global {
|
||||
import get from "./package-shared/actions/get";
|
||||
import post from "./package-shared/actions/post";
|
||||
import getSchema from "./package-shared/actions/get-schema";
|
||||
import createUser from "./package-shared/actions/users/add-user";
|
||||
import updateUser from "./package-shared/actions/users/update-user";
|
||||
import loginUser from "./package-shared/actions/users/login-user";
|
||||
import sendEmailCode from "./package-shared/actions/users/send-email-code";
|
||||
import logoutUser from "./package-shared/actions/users/logout-user";
|
||||
import userAuth from "./package-shared/actions/users/user-auth";
|
||||
import reAuthUser from "./package-shared/actions/users/reauth-user";
|
||||
import getUser from "./package-shared/actions/users/get-user";
|
||||
import loginWithGoogle from "./package-shared/actions/users/social/google-auth";
|
||||
import loginWithGithub from "./package-shared/actions/users/social/github-auth";
|
||||
import getToken from "./package-shared/actions/users/get-token";
|
||||
import validateToken from "./package-shared/actions/users/validate-token";
|
||||
import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator";
|
||||
import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator";
|
||||
import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator";
|
||||
@ -30,8 +18,6 @@ import connDbHandler from "./package-shared/utils/db/conn-db-handler";
|
||||
import encrypt from "./package-shared/functions/dsql/encrypt";
|
||||
import decrypt from "./package-shared/functions/dsql/decrypt";
|
||||
import hashPassword from "./package-shared/functions/dsql/hashPassword";
|
||||
import validateTempEmailCode from "./package-shared/actions/users/validate-temp-email-code";
|
||||
import deleteUser from "./package-shared/actions/users/delete-user";
|
||||
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
|
||||
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
|
||||
import debugLog from "./package-shared/utils/logging/debug-log";
|
||||
@ -58,6 +44,18 @@ declare const datasquirel: {
|
||||
add: typeof import("./package-shared/api/media/post").default;
|
||||
delete: typeof import("./package-shared/api/media/delete").default;
|
||||
};
|
||||
user: {
|
||||
auth: {
|
||||
login: (_: import("./package-shared/types").LoginUserParam) => Promise<import("./package-shared/types").APIResponseObject<import("./package-shared/types").DATASQUIREL_LoggedInUser | null>>;
|
||||
get: (_: import("./package-shared/types").GetUserParams) => Promise<import("./package-shared/types").GetUserFunctionReturn>;
|
||||
signup: (_: import("./package-shared/types").AddUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||
sendEmailCode: (_: import("./package-shared/types").SendEmailCodeParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||
update: (_: import("./package-shared/types").UpdateUserParams) => Promise<import("./package-shared/types").UpdateUserFunctionReturn>;
|
||||
resetPassword: (_: import("./package-shared/types").ResetPasswordParams) => Promise<import("./package-shared/types").UpdateUserFunctionReturn>;
|
||||
logout: typeof import("./package-shared/actions/users/logout-user").default;
|
||||
auth: typeof import("./package-shared/actions/users/user-auth").default;
|
||||
};
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Get Action
|
||||
@ -68,21 +66,15 @@ declare const datasquirel: {
|
||||
*/
|
||||
post: typeof post;
|
||||
user: {
|
||||
createUser: typeof createUser;
|
||||
deleteUser: typeof deleteUser;
|
||||
loginUser: typeof loginUser;
|
||||
sendEmailCode: typeof sendEmailCode;
|
||||
logoutUser: typeof logoutUser;
|
||||
userAuth: typeof userAuth;
|
||||
reAuthUser: typeof reAuthUser;
|
||||
updateUser: typeof updateUser;
|
||||
getUser: typeof getUser;
|
||||
getToken: typeof getToken;
|
||||
validateToken: typeof validateToken;
|
||||
validateTempEmailCode: typeof validateTempEmailCode;
|
||||
social: {
|
||||
loginWithGoogle: typeof loginWithGoogle;
|
||||
loginWithGithub: typeof loginWithGithub;
|
||||
auth: {
|
||||
login: (_: import("./package-shared/types").LoginUserParam) => Promise<import("./package-shared/types").APIResponseObject<import("./package-shared/types").DATASQUIREL_LoggedInUser | null>>;
|
||||
get: (_: import("./package-shared/types").GetUserParams) => Promise<import("./package-shared/types").GetUserFunctionReturn>;
|
||||
signup: (_: import("./package-shared/types").AddUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||
sendEmailCode: (_: import("./package-shared/types").SendEmailCodeParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||
update: (_: import("./package-shared/types").UpdateUserParams) => Promise<import("./package-shared/types").UpdateUserFunctionReturn>;
|
||||
resetPassword: (_: import("./package-shared/types").ResetPasswordParams) => Promise<import("./package-shared/types").UpdateUserFunctionReturn>;
|
||||
logout: typeof import("./package-shared/actions/users/logout-user").default;
|
||||
auth: typeof import("./package-shared/actions/users/user-auth").default;
|
||||
};
|
||||
};
|
||||
getSchema: typeof getSchema;
|
||||
|
54
dist/index.js
vendored
54
dist/index.js
vendored
@ -6,18 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const get_1 = __importDefault(require("./package-shared/actions/get"));
|
||||
const post_1 = __importDefault(require("./package-shared/actions/post"));
|
||||
const get_schema_1 = __importDefault(require("./package-shared/actions/get-schema"));
|
||||
const add_user_1 = __importDefault(require("./package-shared/actions/users/add-user"));
|
||||
const update_user_1 = __importDefault(require("./package-shared/actions/users/update-user"));
|
||||
const login_user_1 = __importDefault(require("./package-shared/actions/users/login-user"));
|
||||
const send_email_code_1 = __importDefault(require("./package-shared/actions/users/send-email-code"));
|
||||
const logout_user_1 = __importDefault(require("./package-shared/actions/users/logout-user"));
|
||||
const user_auth_1 = __importDefault(require("./package-shared/actions/users/user-auth"));
|
||||
const reauth_user_1 = __importDefault(require("./package-shared/actions/users/reauth-user"));
|
||||
const get_user_1 = __importDefault(require("./package-shared/actions/users/get-user"));
|
||||
const google_auth_1 = __importDefault(require("./package-shared/actions/users/social/google-auth"));
|
||||
const github_auth_1 = __importDefault(require("./package-shared/actions/users/social/github-auth"));
|
||||
const get_token_1 = __importDefault(require("./package-shared/actions/users/get-token"));
|
||||
const validate_token_1 = __importDefault(require("./package-shared/actions/users/validate-token"));
|
||||
const client_1 = __importDefault(require("./client"));
|
||||
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
|
||||
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
|
||||
@ -28,42 +16,42 @@ const conn_db_handler_1 = __importDefault(require("./package-shared/utils/db/con
|
||||
const encrypt_1 = __importDefault(require("./package-shared/functions/dsql/encrypt"));
|
||||
const decrypt_1 = __importDefault(require("./package-shared/functions/dsql/decrypt"));
|
||||
const hashPassword_1 = __importDefault(require("./package-shared/functions/dsql/hashPassword"));
|
||||
const validate_temp_email_code_1 = __importDefault(require("./package-shared/actions/users/validate-temp-email-code"));
|
||||
const delete_user_1 = __importDefault(require("./package-shared/actions/users/delete-user"));
|
||||
const crud_1 = __importDefault(require("./package-shared/utils/data-fetching/crud"));
|
||||
const method_crud_1 = __importDefault(require("./package-shared/utils/data-fetching/method-crud"));
|
||||
const debug_log_1 = __importDefault(require("./package-shared/utils/logging/debug-log"));
|
||||
const parse_env_1 = __importDefault(require("./package-shared/utils/parse-env"));
|
||||
const crud_2 = __importDefault(require("./package-shared/api/crud"));
|
||||
const user_1 = __importDefault(require("./package-shared/api/user"));
|
||||
const media_1 = __importDefault(require("./package-shared/api/media"));
|
||||
const dbHandler_1 = __importDefault(require("./package-shared/functions/backend/dbHandler"));
|
||||
/**
|
||||
* User Functions Object
|
||||
*/
|
||||
const user = {
|
||||
createUser: add_user_1.default,
|
||||
deleteUser: delete_user_1.default,
|
||||
loginUser: login_user_1.default,
|
||||
sendEmailCode: send_email_code_1.default,
|
||||
logoutUser: logout_user_1.default,
|
||||
userAuth: user_auth_1.default,
|
||||
reAuthUser: reauth_user_1.default,
|
||||
updateUser: update_user_1.default,
|
||||
getUser: get_user_1.default,
|
||||
getToken: get_token_1.default,
|
||||
validateToken: validate_token_1.default,
|
||||
validateTempEmailCode: validate_temp_email_code_1.default,
|
||||
social: {
|
||||
loginWithGoogle: google_auth_1.default,
|
||||
loginWithGithub: github_auth_1.default,
|
||||
},
|
||||
};
|
||||
// const user = {
|
||||
// createUser: createUser,
|
||||
// deleteUser,
|
||||
// loginUser: loginUser,
|
||||
// sendEmailCode: sendEmailCode,
|
||||
// logoutUser: logoutUser,
|
||||
// userAuth: userAuth,
|
||||
// reAuthUser: reAuthUser,
|
||||
// updateUser: updateUser,
|
||||
// getUser: getUser,
|
||||
// getToken: getToken,
|
||||
// validateToken: validateToken,
|
||||
// validateTempEmailCode,
|
||||
// social: {
|
||||
// loginWithGoogle: loginWithGoogle,
|
||||
// loginWithGithub: loginWithGithub,
|
||||
// },
|
||||
// };
|
||||
/**
|
||||
* API Functions Object
|
||||
*/
|
||||
const api = {
|
||||
crud: crud_2.default,
|
||||
media: media_1.default,
|
||||
user: (0, user_1.default)(),
|
||||
};
|
||||
/**
|
||||
* SQL Utils
|
||||
@ -90,7 +78,7 @@ const datasquirel = {
|
||||
* Post Action
|
||||
*/
|
||||
post: post_1.default,
|
||||
user,
|
||||
user: (0, user_1.default)({ local: true }),
|
||||
getSchema: get_schema_1.default,
|
||||
client: client_1.default,
|
||||
sql,
|
||||
|
13
dist/package-shared/actions/users/add-user.d.ts
vendored
13
dist/package-shared/actions/users/add-user.d.ts
vendored
@ -1,14 +1,5 @@
|
||||
import { AddUserFunctionReturn, UserDataPayload } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
payload: UserDataPayload;
|
||||
encryptionKey?: string;
|
||||
useLocal?: boolean;
|
||||
verify?: boolean;
|
||||
};
|
||||
import { AddUserParams, APIResponseObject } from "../../types";
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
export default function addUser({ key, payload, database, encryptionKey, useLocal, verify, }: Param): Promise<AddUserFunctionReturn>;
|
||||
export {};
|
||||
export default function addUser({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion, dsqlUserID, }: AddUserParams): Promise<APIResponseObject>;
|
||||
|
56
dist/package-shared/actions/users/add-user.js
vendored
56
dist/package-shared/actions/users/add-user.js
vendored
@ -15,64 +15,40 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUser;
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
function addUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, encryptionKey, useLocal, verify, }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion = "v1", dsqlUserID, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (useLocal) {
|
||||
return yield (0, api_create_user_1.default)({
|
||||
const apiAddUserParams = {
|
||||
database,
|
||||
encryptionKey,
|
||||
payload,
|
||||
verify,
|
||||
});
|
||||
dsqlUserID,
|
||||
};
|
||||
if (useLocal) {
|
||||
return yield (0, api_create_user_1.default)(apiAddUserParams);
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "signup",
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiAddUserParams,
|
||||
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: ``,
|
||||
},
|
||||
/**
|
||||
* 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;
|
||||
});
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
@ -9,5 +9,5 @@ type Param = {
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default function deleteUser({ key, database, deletedUserId, useLocal, apiVersion, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||
export default function deleteUser({ apiKey, database, deletedUserId, useLocal, apiVersion, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||
export {};
|
||||
|
18
dist/package-shared/actions/users/delete-user.js
vendored
18
dist/package-shared/actions/users/delete-user.js
vendored
@ -15,11 +15,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = deleteUser;
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function deleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, deletedUserId, useLocal, apiVersion = "v1", }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ apiKey, database, deletedUserId, useLocal, apiVersion = "v1", }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (useLocal) {
|
||||
@ -38,18 +39,25 @@ function deleteUser(_a) {
|
||||
database,
|
||||
deletedUserId,
|
||||
});
|
||||
const finalAPIKey = apiKey ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY;
|
||||
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,
|
||||
Authorization: finalAPIKey,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/${apiVersion}/users/${database}/${deletedUserId}`,
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "delete",
|
||||
database,
|
||||
apiVersion,
|
||||
userID: deletedUserId,
|
||||
}),
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
|
13
dist/package-shared/actions/users/get-user.d.ts
vendored
13
dist/package-shared/actions/users/get-user.d.ts
vendored
@ -1,14 +1,5 @@
|
||||
import { GetUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key: string;
|
||||
database: string;
|
||||
userId: number;
|
||||
fields?: string[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
};
|
||||
import { GetUserFunctionReturn, GetUserParams } from "../../types";
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
export default function getUser({ key, userId, database, fields, useLocal, apiVersion, }: Param): Promise<GetUserFunctionReturn>;
|
||||
export {};
|
||||
export default function getUser({ apiKey, userId, database, fields, useLocal, apiVersion, dbUserId, selectAll, }: GetUserParams): Promise<GetUserFunctionReturn>;
|
||||
|
36
dist/package-shared/actions/users/get-user.js
vendored
36
dist/package-shared/actions/users/get-user.js
vendored
@ -15,11 +15,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getUser;
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
function getUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, userId, database, fields, useLocal, apiVersion = "v1", }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ apiKey, userId, database, fields, useLocal, apiVersion = "v1", dbUserId, selectAll, }) {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
@ -40,19 +41,17 @@ function getUser(_a) {
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (useLocal) {
|
||||
return yield (0, api_get_user_1.default)({
|
||||
const getUserParams = {
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: database,
|
||||
});
|
||||
database,
|
||||
dbUserId,
|
||||
selectAll,
|
||||
};
|
||||
if (useLocal) {
|
||||
return yield (0, api_get_user_1.default)(getUserParams);
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
@ -60,18 +59,27 @@ function getUser(_a) {
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(getUserParams);
|
||||
const finalAPIKey = apiKey ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY;
|
||||
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,
|
||||
Authorization: finalAPIKey,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/${apiVersion}/users/${database}/${userId}`,
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "get",
|
||||
database,
|
||||
apiVersion,
|
||||
userID: userId,
|
||||
}),
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { APILoginFunctionReturn, LoginUserParam } from "../../types";
|
||||
import { APIResponseObject, DATASQUIREL_LoggedInUser, LoginUserParam } from "../../types";
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, useLocal, }: LoginUserParam): Promise<APILoginFunctionReturn>;
|
||||
export default function loginUser<T extends DATASQUIREL_LoggedInUser = DATASQUIREL_LoggedInUser>({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion, }: LoginUserParam): Promise<APIResponseObject<T | null>>;
|
||||
|
94
dist/package-shared/actions/users/login-user.js
vendored
94
dist/package-shared/actions/users/login-user.js
vendored
@ -14,20 +14,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginUser;
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
function loginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, useLocal, }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion = "v1", }) {
|
||||
var _b, _c;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
@ -37,9 +39,6 @@ function loginUser(_a) {
|
||||
: undefined;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
@ -56,32 +55,13 @@ function loginUser(_a) {
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
success: false,
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
if (useLocal) {
|
||||
httpResponse = yield (0, api_login_1.default)({
|
||||
const apiLoginParams = {
|
||||
database,
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
@ -95,54 +75,34 @@ function loginUser(_a) {
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
if (useLocal) {
|
||||
httpResponse = yield (0, api_login_1.default)(apiLoginParams);
|
||||
}
|
||||
else {
|
||||
httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
httpResponse = yield (0, query_dsql_api_1.default)({
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "login",
|
||||
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({
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiLoginParams,
|
||||
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) {
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
}
|
||||
/**
|
||||
* # Send Response
|
||||
*/
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
@ -158,7 +118,7 @@ function loginUser(_a) {
|
||||
}
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
userId: apiUserID,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.id)
|
||||
|
@ -55,7 +55,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
catch (error) {
|
||||
console.log("Error getting decrypted User JSON to logout:", error.message);
|
||||
return undefined;
|
||||
}
|
||||
|
@ -1,20 +0,0 @@
|
||||
import http from "http";
|
||||
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;
|
||||
secureCookie?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
export default function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
179
dist/package-shared/actions/users/reauth-user.js
vendored
179
dist/package-shared/actions/users/reauth-user.js
vendored
@ -1,179 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = reauthUser;
|
||||
const user_auth_1 = __importDefault(require("./user-auth"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const login_user_1 = __importDefault(require("./login-user"));
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
function reauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const existingUser = (0, user_auth_1.default)({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
if (!((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _b === void 0 ? void 0 : _b.id)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
return yield (0, login_user_1.default)({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// return httpResponse;
|
||||
});
|
||||
}
|
5
dist/package-shared/actions/users/reset-password.d.ts
vendored
Normal file
5
dist/package-shared/actions/users/reset-password.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
import { ResetPasswordParams, UpdateUserFunctionReturn } from "../../types";
|
||||
/**
|
||||
* # Reset User Password
|
||||
*/
|
||||
export default function resetPassword(params: ResetPasswordParams): Promise<UpdateUserFunctionReturn>;
|
40
dist/package-shared/actions/users/reset-password.js
vendored
Normal file
40
dist/package-shared/actions/users/reset-password.js
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = resetPassword;
|
||||
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
const api_reset_user_password_1 = __importDefault(require("../../functions/api/users/api-reset-user-password"));
|
||||
/**
|
||||
* # Reset User Password
|
||||
*/
|
||||
function resetPassword(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (params.useLocal) {
|
||||
return yield (0, api_reset_user_password_1.default)(params);
|
||||
}
|
||||
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "reset-password",
|
||||
database: params.database,
|
||||
apiVersion: params.apiVersion,
|
||||
}),
|
||||
apiKey: params.apiKey,
|
||||
body: params,
|
||||
method: "POST",
|
||||
});
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
@ -1,24 +1,5 @@
|
||||
import http from "http";
|
||||
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[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
import { APIResponseObject, SendEmailCodeParams } from "../../types";
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
export default function sendEmailCode(params: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export {};
|
||||
export default function sendEmailCode(params: SendEmailCodeParams): Promise<APIResponseObject>;
|
||||
|
@ -13,24 +13,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sendEmailCode;
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
function sendEmailCode(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, useLocal, } = params;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const { apiKey, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, response, extraCookies, useLocal, apiVersion, dbUserId, } = params;
|
||||
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>`;
|
||||
console.log("useLocal", useLocal);
|
||||
if (useLocal) {
|
||||
return yield (0, api_send_email_code_1.default)({
|
||||
const apiSendEmailCodeParams = {
|
||||
database,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
@ -42,60 +39,22 @@ function sendEmailCode(params) {
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
dbUserId,
|
||||
};
|
||||
if (useLocal) {
|
||||
return yield (0, api_send_email_code_1.default)(apiSendEmailCodeParams);
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
email,
|
||||
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "send-email-code",
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
html: emailHtml,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiSendEmailCodeParams,
|
||||
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;
|
||||
}
|
||||
|
@ -1,16 +1,8 @@
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
payload: {
|
||||
[s: string]: any;
|
||||
};
|
||||
user_id?: boolean;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
import { UpdateUserFunctionReturn, UpdateUserParams } from "../../types";
|
||||
import { DSQL_DATASQUIREL_USERS } from "../../types/dsql";
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default function updateUser({ key, payload, database, user_id, updatedUserId, useLocal, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||
export {};
|
||||
export default function updateUser<T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}>({ payload, database, updatedUserId, useLocal, apiKey, apiVersion, dbUserId, }: UpdateUserParams<T>): Promise<UpdateUserFunctionReturn>;
|
||||
|
61
dist/package-shared/actions/users/update-user.js
vendored
61
dist/package-shared/actions/users/update-user.js
vendored
@ -13,65 +13,38 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateUser;
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_update_user_1 = __importDefault(require("../../functions/api/users/api-update-user"));
|
||||
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function updateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, user_id, updatedUserId, useLocal, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (useLocal) {
|
||||
return yield (0, api_update_user_1.default)({
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, database, updatedUserId, useLocal, apiKey, apiVersion, dbUserId, }) {
|
||||
const updateUserParams = {
|
||||
payload: payload,
|
||||
dbFullName: database,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
dbUserId,
|
||||
};
|
||||
if (useLocal) {
|
||||
return yield (0, api_update_user_1.default)(updateUserParams);
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||
path: (0, grab_api_path_1.default)({
|
||||
paradigm: "auth",
|
||||
action: "update",
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: updateUserParams,
|
||||
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;
|
||||
});
|
||||
|
@ -1,14 +0,0 @@
|
||||
import http from "http";
|
||||
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 function validateTempEmailCode({ request, email, cookieString, }: Param): Promise<SendOneTimeCodeEmailResponse | null>;
|
||||
export {};
|
@ -1,47 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateTempEmailCode;
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
/**
|
||||
* # Verify the temp email code sent to the user's email address
|
||||
*/
|
||||
function validateTempEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ request, email, cookieString, }) {
|
||||
try {
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||
const encryptedPayload = (0, decrypt_1.default)({
|
||||
encryptedString: encryptedOneTimeCode,
|
||||
});
|
||||
const payload = ejson_1.default.parse(encryptedPayload);
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||
return payload;
|
||||
}
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
|
||||
return payload;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
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;
|
||||
export {};
|
@ -1,63 +0,0 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
/**
|
||||
* Validate Token
|
||||
* ======================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const key = token;
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
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;
|
||||
}
|
||||
}
|
21
dist/package-shared/api/user/index.d.ts
vendored
21
dist/package-shared/api/user/index.d.ts
vendored
@ -1,2 +1,19 @@
|
||||
declare const user: {};
|
||||
export default user;
|
||||
import logoutUser from "../../actions/users/logout-user";
|
||||
import userAuth from "../../actions/users/user-auth";
|
||||
import { AddUserParams, GetUserParams, LoginUserParam, ResetPasswordParams, SendEmailCodeParams, UpdateUserParams } from "../../types";
|
||||
type Params = {
|
||||
local?: boolean;
|
||||
};
|
||||
export default function user(params?: Params): {
|
||||
auth: {
|
||||
login: (_: LoginUserParam) => Promise<import("../../types").APIResponseObject<import("../../types").DATASQUIREL_LoggedInUser | null>>;
|
||||
get: (_: GetUserParams) => Promise<import("../../types").GetUserFunctionReturn>;
|
||||
signup: (_: AddUserParams) => Promise<import("../../types").APIResponseObject>;
|
||||
sendEmailCode: (_: SendEmailCodeParams) => Promise<import("../../types").APIResponseObject>;
|
||||
update: (_: UpdateUserParams) => Promise<import("../../types").UpdateUserFunctionReturn>;
|
||||
resetPassword: (_: ResetPasswordParams) => Promise<import("../../types").UpdateUserFunctionReturn>;
|
||||
logout: typeof logoutUser;
|
||||
auth: typeof userAuth;
|
||||
};
|
||||
};
|
||||
export {};
|
||||
|
59
dist/package-shared/api/user/index.js
vendored
59
dist/package-shared/api/user/index.js
vendored
@ -1,4 +1,61 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const user = {};
|
||||
exports.default = user;
|
||||
const add_user_1 = __importDefault(require("../../actions/users/add-user"));
|
||||
const get_user_1 = __importDefault(require("../../actions/users/get-user"));
|
||||
const login_user_1 = __importDefault(require("../../actions/users/login-user"));
|
||||
const logout_user_1 = __importDefault(require("../../actions/users/logout-user"));
|
||||
const reset_password_1 = __importDefault(require("../../actions/users/reset-password"));
|
||||
const send_email_code_1 = __importDefault(require("../../actions/users/send-email-code"));
|
||||
const update_user_1 = __importDefault(require("../../actions/users/update-user"));
|
||||
const user_auth_1 = __importDefault(require("../../actions/users/user-auth"));
|
||||
function user(params) {
|
||||
return {
|
||||
auth: {
|
||||
login: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, login_user_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: login_user_1.default,
|
||||
get: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, get_user_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: get_user_1.default,
|
||||
signup: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, add_user_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: add_user_1.default,
|
||||
sendEmailCode: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, send_email_code_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: send_email_code_1.default,
|
||||
update: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, update_user_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: update_user_1.default,
|
||||
resetPassword: (params === null || params === void 0 ? void 0 : params.local)
|
||||
? (_) => __awaiter(this, void 0, void 0, function* () {
|
||||
return yield (0, reset_password_1.default)(Object.assign(Object.assign({}, _), { useLocal: true }));
|
||||
})
|
||||
: reset_password_1.default,
|
||||
logout: logout_user_1.default,
|
||||
auth: user_auth_1.default,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
@ -1,25 +1,5 @@
|
||||
import { APICreateUserFunctionParams } from "../../../types";
|
||||
import { APICreateUserFunctionParams, APIResponseObject } from "../../../types";
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
export default function apiCreateUser({ encryptionKey, payload, database, userId, verify, }: APICreateUserFunctionParams): Promise<{
|
||||
success: boolean;
|
||||
msg: string;
|
||||
payload?: undefined;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string | undefined;
|
||||
payload: null;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
payload: any;
|
||||
msg?: undefined;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
sqlResult: import("../../../types").APIResponseObject<import("../../../types").PostInsertReturn>;
|
||||
payload: null;
|
||||
}>;
|
||||
export default function apiCreateUser({ encryptionKey, payload, database, dsqlUserID, verify, }: APICreateUserFunctionParams): Promise<APIResponseObject>;
|
||||
|
@ -24,7 +24,7 @@ const validate_email_1 = __importDefault(require("../../email/fns/validate-email
|
||||
* # API Create User
|
||||
*/
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, verify, }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, dsqlUserID, verify, }) {
|
||||
var _b;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
@ -43,8 +43,8 @@ function apiCreateUser(_a) {
|
||||
}
|
||||
const targetDbSchema = (0, grab_required_database_schemas_1.grabPrimaryRequiredDbSchema)({
|
||||
dbSlug: database,
|
||||
userId,
|
||||
dbId: userId ? undefined : 1,
|
||||
userId: dsqlUserID,
|
||||
dbId: dsqlUserID ? undefined : 1,
|
||||
});
|
||||
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||
return {
|
||||
@ -73,29 +73,26 @@ function apiCreateUser(_a) {
|
||||
}));
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
userId,
|
||||
userId: dsqlUserID,
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
fields = (yield (0, dbHandler_1.default)({
|
||||
query: fieldsQuery,
|
||||
database: dbFullName,
|
||||
}));
|
||||
}
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
if (!newTable) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
const fieldsTitles = fields.map((fieldObject) => fieldObject.Field);
|
||||
let invalidField = null;
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
yield (0, updateUsersTableSchema_1.default)({
|
||||
userId,
|
||||
userId: dsqlUserID,
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
@ -148,18 +145,10 @@ function apiCreateUser(_a) {
|
||||
values: [],
|
||||
database: dbFullName,
|
||||
}));
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
return Object.assign(Object.assign({}, addUser), { payload: newlyAddedUser[0] });
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
return Object.assign(Object.assign({}, addUser), { msg: "Could not create user" });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -2,4 +2,4 @@ import { APIGetUserFunctionParams, GetUserFunctionReturn } from "../../../types"
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
export default function apiGetUser({ fields, dbFullName, userId, }: APIGetUserFunctionParams): Promise<GetUserFunctionReturn>;
|
||||
export default function apiGetUser({ fields, database, userId, dbUserId, selectAll, }: APIGetUserFunctionParams): Promise<GetUserFunctionReturn>;
|
||||
|
@ -13,18 +13,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGetUser;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
const dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
function apiGetUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
return __awaiter(this, arguments, void 0, function* ({ fields, database, userId, dbUserId, selectAll, }) {
|
||||
const finalDbName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const selectFields = selectAll ? "*" : (fields === null || fields === void 0 ? void 0 : fields[0]) ? fields.join(",") : "*";
|
||||
let foundUser = (yield (0, dbHandler_1.default)({
|
||||
query,
|
||||
values: [API_USER_ID],
|
||||
query: `SELECT ${selectFields} FROM users WHERE id=?`,
|
||||
values: [userId],
|
||||
database: finalDbName,
|
||||
}));
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { APILoginFunctionParams, APILoginFunctionReturn } from "../../../types";
|
||||
import { APILoginFunctionParams, APIResponseObject } from "../../../types";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }: APILoginFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
export default function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }: APILoginFunctionParams): Promise<APIResponseObject>;
|
||||
|
5
dist/package-shared/functions/api/users/api-reset-user-password.d.ts
vendored
Normal file
5
dist/package-shared/functions/api/users/api-reset-user-password.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
import { APIResponseObject, ResetPasswordParams } from "../../../types";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default function apiResetUserPassword({ updatedUserId, database, dbUserId, newPassword, encryptionKey, }: ResetPasswordParams): Promise<APIResponseObject>;
|
55
dist/package-shared/functions/api/users/api-reset-user-password.js
vendored
Normal file
55
dist/package-shared/functions/api/users/api-reset-user-password.js
vendored
Normal file
@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiResetUserPassword;
|
||||
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiResetUserPassword(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ updatedUserId, database, dbUserId, newPassword, encryptionKey, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = (yield (0, dbHandler_1.default)({
|
||||
query: existingUserQuery,
|
||||
values: existingUserValues,
|
||||
database: dbFullName,
|
||||
}));
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const newPasswordHashed = (0, hashPassword_1.default)({
|
||||
password: newPassword,
|
||||
encryptionKey,
|
||||
});
|
||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: { password: newPasswordHashed },
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
});
|
||||
}
|
@ -1,22 +1,5 @@
|
||||
import http from "http";
|
||||
import { CookieObject, SendOneTimeCodeEmailResponse } from "../../../types";
|
||||
type Param = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
html: string;
|
||||
response?: http.ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
extraCookies?: CookieObject[];
|
||||
};
|
||||
import { APIResponseObject, APISendEmailCodeFunctionParams } from "../../../types";
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
export default function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export {};
|
||||
export default function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, dbUserId, }: APISendEmailCodeFunctionParams): Promise<APIResponseObject>;
|
||||
|
@ -18,24 +18,26 @@ const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
function apiSendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, dbUserId, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = (yield (0, dbHandler_1.default)({
|
||||
query: foundUserQuery,
|
||||
values: foundUserValues,
|
||||
database,
|
||||
database: dbFullName,
|
||||
}));
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
@ -67,20 +69,21 @@ function apiSendEmailCode(_a) {
|
||||
},
|
||||
});
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
const finalSender = sender || process.env.DSQL_MAIL_EMAIL || "support@datasquirel.com";
|
||||
mailObject["from"] = `"Datasquirel SSO" <${finalSender}>`;
|
||||
mailObject["sender"] = finalSender;
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
const info = yield transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
yield (0, dbHandler_1.default)({
|
||||
query: setTempCodeQuery,
|
||||
values: setTempCodeValues,
|
||||
database,
|
||||
database: dbFullName,
|
||||
});
|
||||
const resObject = {
|
||||
success: true,
|
||||
|
@ -1,18 +1,5 @@
|
||||
type Param = {
|
||||
payload: {
|
||||
[s: string]: any;
|
||||
};
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
};
|
||||
type Return = {
|
||||
success: boolean;
|
||||
payload?: any;
|
||||
msg?: string;
|
||||
};
|
||||
import { APIResponseObject, ApiUpdateUserParams } from "../../../types";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }: Param): Promise<Return>;
|
||||
export {};
|
||||
export default function apiUpdateUser({ payload, updatedUserId, dbSchema, database, dbUserId, }: ApiUpdateUserParams): Promise<APIResponseObject>;
|
||||
|
@ -1,5 +1,4 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
@ -18,11 +17,13 @@ const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiUpdateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, updatedUserId, dbSchema, database, dbUserId, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = (yield (0, dbHandler_1.default)({
|
||||
@ -48,7 +49,6 @@ function apiUpdateUser(_a) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
|
@ -9,5 +9,5 @@ type Param = {
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function addUsersTableToDb({ userId, database, payload, dbId, }: Param): Promise<any>;
|
||||
export default function addUsersTableToDb({ userId, database, payload, dbId, }: Param): Promise<boolean>;
|
||||
export {};
|
||||
|
@ -14,18 +14,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUsersTableToDb;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
||||
const grab_required_database_schemas_1 = require("../../shell/createDbFromSchema/grab-required-database-schemas");
|
||||
const dbHandler_1 = __importDefault(require("./dbHandler"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function addUsersTableToDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, payload, dbId, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
@ -44,37 +41,20 @@ function addUsersTableToDb(_a) {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
(0, grab_required_database_schemas_1.writeUpdatedDbSchema)({ dbSchema: targetDatabase, userId });
|
||||
const targetDb = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
values: [userId, database],
|
||||
}));
|
||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||
const newTableEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
dbId,
|
||||
});
|
||||
return `Done!`;
|
||||
return dbShellUpdate;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
catch (error) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -20,9 +20,7 @@ function grabNewUsersTableSchema(params) {
|
||||
excludeFields: userPreset.fields,
|
||||
})
|
||||
: [];
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
console.log("allFields", allFields);
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
@ -31,7 +29,7 @@ function grabNewUsersTableSchema(params) {
|
||||
userPreset.fields = [...finalFields];
|
||||
return userPreset;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
catch (error) {
|
||||
console.log(`grabNewUsersTableSchema.ts ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "grabNewUsersTableSchema",
|
||||
|
@ -17,7 +17,7 @@ function decrypt({ encryptedString, encryptionKey, encryptionSalt, debug, }) {
|
||||
console.log("Encrypted string is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = (0, grab_keys_1.default)({ encryptionKey });
|
||||
const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = (0, grab_keys_1.default)({ encryptionKey, encryptionSalt });
|
||||
if (!(encrptKey === null || encrptKey === void 0 ? void 0 : encrptKey.match(/.{8,}/))) {
|
||||
if (debug)
|
||||
console.log("Decrption key is invalid");
|
||||
|
@ -16,7 +16,7 @@ function encrypt({ data, encryptionKey, encryptionSalt, }) {
|
||||
console.log("Encryption string is invalid");
|
||||
return data;
|
||||
}
|
||||
const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = (0, grab_keys_1.default)({ encryptionKey });
|
||||
const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = (0, grab_keys_1.default)({ encryptionKey, encryptionSalt });
|
||||
if (!(encrptKey === null || encrptKey === void 0 ? void 0 : encrptKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return data;
|
||||
|
117
dist/package-shared/types/index.d.ts
vendored
117
dist/package-shared/types/index.d.ts
vendored
@ -189,7 +189,6 @@ export interface DSQL_MYSQL_user_databases_Type {
|
||||
export interface PackageUserLoginRequestBody {
|
||||
encryptionKey: string;
|
||||
payload: any;
|
||||
database: string;
|
||||
additionalFields?: string[];
|
||||
email_login?: boolean;
|
||||
email_login_code?: string;
|
||||
@ -940,7 +939,7 @@ export type APICreateUserFunctionParams = {
|
||||
encryptionKey?: string;
|
||||
payload: any;
|
||||
database: string;
|
||||
userId?: string | number;
|
||||
dsqlUserID?: string | number;
|
||||
verify?: boolean;
|
||||
};
|
||||
export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Promise<AddUserFunctionReturn>;
|
||||
@ -949,8 +948,10 @@ export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Pro
|
||||
*/
|
||||
export type APIGetUserFunctionParams = {
|
||||
fields: string[];
|
||||
dbFullName: string;
|
||||
database: string;
|
||||
userId: string | number;
|
||||
dbUserId?: string | number;
|
||||
selectAll?: boolean;
|
||||
};
|
||||
/**
|
||||
* API Google Login Function
|
||||
@ -1393,6 +1394,14 @@ export type APIResponseObject<T extends any = any> = {
|
||||
debug?: any;
|
||||
batchPayload?: any[][] | null;
|
||||
errorData?: any;
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
cookieNames?: any;
|
||||
key?: string;
|
||||
userId?: string | number;
|
||||
code?: string;
|
||||
createdAt?: number;
|
||||
email?: string;
|
||||
};
|
||||
export declare const UserTypes: readonly ["su", "admin"];
|
||||
export declare const SignUpParadigms: readonly [{
|
||||
@ -1553,7 +1562,7 @@ export type DefaultEntryType = {
|
||||
};
|
||||
export declare const IndexTypes: readonly ["regular", "full_text"];
|
||||
export type LoginUserParam = {
|
||||
key?: string;
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
payload: {
|
||||
email?: string;
|
||||
@ -1573,7 +1582,6 @@ export type LoginUserParam = {
|
||||
email_login_code?: string;
|
||||
temp_code_field?: string;
|
||||
token?: boolean;
|
||||
user_id?: string | number;
|
||||
skipPassword?: boolean;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
@ -1582,6 +1590,7 @@ export type LoginUserParam = {
|
||||
cleanupTokens?: boolean;
|
||||
secureCookie?: boolean;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
};
|
||||
export declare const UserSelectFields: readonly [{
|
||||
readonly field: "first_name";
|
||||
@ -1732,7 +1741,7 @@ export type SiteConfigMaxscale = {
|
||||
read_only_port: number;
|
||||
admin_port: number;
|
||||
};
|
||||
export declare const APIParadigms: readonly ["crud", "media", "sql", "schema"];
|
||||
export declare const APIParadigms: readonly ["crud", "media", "sql", "schema", "users"];
|
||||
export declare const AppVersions: readonly [{
|
||||
readonly title: "Community";
|
||||
readonly value: "community";
|
||||
@ -1798,4 +1807,100 @@ export type GrabUserResourceParams<T extends {
|
||||
isSuperUser?: boolean;
|
||||
targetID?: string | number;
|
||||
};
|
||||
export declare const UserAPIParadigms: readonly ["auth", "crud"];
|
||||
export declare const UserAPIAuthActions: readonly ["login", "get", "signup", "update", "logout", "refresh", "verify", "send-verification", "delete", "send-email-code", "reset-password"];
|
||||
export type GrabUserAPIPathParams = {
|
||||
apiVersion?: string;
|
||||
paradigm?: (typeof UserAPIParadigms)[number];
|
||||
action?: (typeof UserAPIAuthActions)[number];
|
||||
database?: string;
|
||||
userID?: string | number;
|
||||
};
|
||||
export type GetUserParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
userId: number | string;
|
||||
fields?: string[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
selectAll?: boolean;
|
||||
};
|
||||
export type AddUserParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
payload: UserDataPayload;
|
||||
encryptionKey?: string;
|
||||
useLocal?: boolean;
|
||||
verify?: boolean;
|
||||
apiVersion?: string;
|
||||
dsqlUserID?: string | number;
|
||||
};
|
||||
export type APISendEmailCodeFunctionParams = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
/**
|
||||
* HTML string with {{code}} placeholder for the code
|
||||
*/
|
||||
html: string;
|
||||
response?: ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
extraCookies?: CookieObject[];
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
export type SendEmailCodeParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
email: string;
|
||||
temp_code_field_name?: string;
|
||||
response?: ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
mail_domain?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
extraCookies?: CookieObject[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
export type UpdateUserParams<T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}> = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
payload: T;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
export type ResetPasswordParams = {
|
||||
apiKey?: string;
|
||||
newPassword: string;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
encryptionKey?: string;
|
||||
};
|
||||
export type ApiUpdateUserParams<T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}> = {
|
||||
payload: T;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
export {};
|
||||
|
24
dist/package-shared/types/index.js
vendored
24
dist/package-shared/types/index.js
vendored
@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TargetMediaParadigms = exports.EnvKeys = exports.AppVersions = exports.APIParadigms = exports.UserSQLPermissions = exports.SQLPermissions = exports.InvitedUserSelectFields = exports.DelegatedUserSelectFields = exports.UserSelectFields = exports.IndexTypes = exports.DefaultSQLValuesLiteral = exports.CurrentlyEditedFieldActions = exports.VideoMimeTypes = exports.FileMimeTypes = exports.ImageMimeTypes = exports.MediaTypes = exports.DockerComposeServices = exports.DatasquirelWindowEvents = exports.WebSocketEvents = exports.QueueJobTypes = exports.SignUpParadigms = exports.UserTypes = exports.QueryFields = exports.DsqlCrudActions = exports.DataCrudRequestMethodsLowerCase = exports.DataCrudRequestMethods = exports.ServerQueryEqualities = exports.ServerQueryOperators = exports.TextFieldTypesArray = exports.UsersOmitedFields = void 0;
|
||||
exports.UserAPIAuthActions = exports.UserAPIParadigms = exports.TargetMediaParadigms = exports.EnvKeys = exports.AppVersions = exports.APIParadigms = exports.UserSQLPermissions = exports.SQLPermissions = exports.InvitedUserSelectFields = exports.DelegatedUserSelectFields = exports.UserSelectFields = exports.IndexTypes = exports.DefaultSQLValuesLiteral = exports.CurrentlyEditedFieldActions = exports.VideoMimeTypes = exports.FileMimeTypes = exports.ImageMimeTypes = exports.MediaTypes = exports.DockerComposeServices = exports.DatasquirelWindowEvents = exports.WebSocketEvents = exports.QueueJobTypes = exports.SignUpParadigms = exports.UserTypes = exports.QueryFields = exports.DsqlCrudActions = exports.DataCrudRequestMethodsLowerCase = exports.DataCrudRequestMethods = exports.ServerQueryEqualities = exports.ServerQueryOperators = exports.TextFieldTypesArray = exports.UsersOmitedFields = void 0;
|
||||
exports.UsersOmitedFields = [
|
||||
"password",
|
||||
"social_id",
|
||||
@ -287,7 +287,13 @@ exports.UserSQLPermissions = [
|
||||
"UPDATE",
|
||||
"USAGE",
|
||||
];
|
||||
exports.APIParadigms = ["crud", "media", "sql", "schema"];
|
||||
exports.APIParadigms = [
|
||||
"crud",
|
||||
"media",
|
||||
"sql",
|
||||
"schema",
|
||||
"users",
|
||||
];
|
||||
exports.AppVersions = [
|
||||
{
|
||||
title: "Community",
|
||||
@ -386,3 +392,17 @@ exports.EnvKeys = [
|
||||
"DSQL_ARCJET_KEY",
|
||||
];
|
||||
exports.TargetMediaParadigms = ["info", "preview"];
|
||||
exports.UserAPIParadigms = ["auth", "crud"];
|
||||
exports.UserAPIAuthActions = [
|
||||
"login",
|
||||
"get",
|
||||
"signup",
|
||||
"update",
|
||||
"logout",
|
||||
"refresh",
|
||||
"verify",
|
||||
"send-verification",
|
||||
"delete",
|
||||
"send-email-code",
|
||||
"reset-password",
|
||||
];
|
||||
|
2
dist/package-shared/utils/backend/users/grab-api-path.d.ts
vendored
Normal file
2
dist/package-shared/utils/backend/users/grab-api-path.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
import { GrabUserAPIPathParams } from "../../../types";
|
||||
export default function grabUserDSQLAPIPath({ apiVersion, paradigm, action, database, userID, }: GrabUserAPIPathParams): string;
|
21
dist/package-shared/utils/backend/users/grab-api-path.js
vendored
Normal file
21
dist/package-shared/utils/backend/users/grab-api-path.js
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabUserDSQLAPIPath;
|
||||
function grabUserDSQLAPIPath({ apiVersion, paradigm, action, database, userID, }) {
|
||||
const finalAPIVersion = process.env.DSQL_API_VERSION || apiVersion || "v1";
|
||||
const finalParadigm = paradigm || "auth";
|
||||
const finalAction = action || "login";
|
||||
const finalDatabase = database || "datasquirel";
|
||||
let finalPath = `/api/${finalAPIVersion}/users/${finalParadigm}/${finalDatabase}`;
|
||||
switch (paradigm) {
|
||||
case "auth":
|
||||
finalPath += `/${finalAction}`;
|
||||
if (userID) {
|
||||
finalPath += `/${userID}`;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return finalPath;
|
||||
}
|
54
index.ts
54
index.ts
@ -14,18 +14,6 @@ import getSchema from "./package-shared/actions/get-schema";
|
||||
|
||||
import createUser from "./package-shared/actions/users/add-user";
|
||||
import updateUser from "./package-shared/actions/users/update-user";
|
||||
import loginUser from "./package-shared/actions/users/login-user";
|
||||
import sendEmailCode from "./package-shared/actions/users/send-email-code";
|
||||
import logoutUser from "./package-shared/actions/users/logout-user";
|
||||
|
||||
import userAuth from "./package-shared/actions/users/user-auth";
|
||||
import reAuthUser from "./package-shared/actions/users/reauth-user";
|
||||
import getUser from "./package-shared/actions/users/get-user";
|
||||
|
||||
import loginWithGoogle from "./package-shared/actions/users/social/google-auth";
|
||||
import loginWithGithub from "./package-shared/actions/users/social/github-auth";
|
||||
import getToken from "./package-shared/actions/users/get-token";
|
||||
import validateToken from "./package-shared/actions/users/validate-token";
|
||||
|
||||
import datasquirelClient from "./client";
|
||||
import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator";
|
||||
@ -37,38 +25,37 @@ import connDbHandler from "./package-shared/utils/db/conn-db-handler";
|
||||
import encrypt from "./package-shared/functions/dsql/encrypt";
|
||||
import decrypt from "./package-shared/functions/dsql/decrypt";
|
||||
import hashPassword from "./package-shared/functions/dsql/hashPassword";
|
||||
import validateTempEmailCode from "./package-shared/actions/users/validate-temp-email-code";
|
||||
import deleteUser from "./package-shared/actions/users/delete-user";
|
||||
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
|
||||
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
|
||||
import debugLog from "./package-shared/utils/logging/debug-log";
|
||||
import { ErrorCallback } from "./package-shared/types";
|
||||
import parseEnv from "./package-shared/utils/parse-env";
|
||||
import crud from "./package-shared/api/crud";
|
||||
import user from "./package-shared/api/user";
|
||||
import media from "./package-shared/api/media";
|
||||
import dbHandler from "./package-shared/functions/backend/dbHandler";
|
||||
|
||||
/**
|
||||
* User Functions Object
|
||||
*/
|
||||
const user = {
|
||||
createUser: createUser,
|
||||
deleteUser,
|
||||
loginUser: loginUser,
|
||||
sendEmailCode: sendEmailCode,
|
||||
logoutUser: logoutUser,
|
||||
userAuth: userAuth,
|
||||
reAuthUser: reAuthUser,
|
||||
updateUser: updateUser,
|
||||
getUser: getUser,
|
||||
getToken: getToken,
|
||||
validateToken: validateToken,
|
||||
validateTempEmailCode,
|
||||
social: {
|
||||
loginWithGoogle: loginWithGoogle,
|
||||
loginWithGithub: loginWithGithub,
|
||||
},
|
||||
};
|
||||
// const user = {
|
||||
// createUser: createUser,
|
||||
// deleteUser,
|
||||
// loginUser: loginUser,
|
||||
// sendEmailCode: sendEmailCode,
|
||||
// logoutUser: logoutUser,
|
||||
// userAuth: userAuth,
|
||||
// reAuthUser: reAuthUser,
|
||||
// updateUser: updateUser,
|
||||
// getUser: getUser,
|
||||
// getToken: getToken,
|
||||
// validateToken: validateToken,
|
||||
// validateTempEmailCode,
|
||||
// social: {
|
||||
// loginWithGoogle: loginWithGoogle,
|
||||
// loginWithGithub: loginWithGithub,
|
||||
// },
|
||||
// };
|
||||
|
||||
/**
|
||||
* API Functions Object
|
||||
@ -76,6 +63,7 @@ const user = {
|
||||
const api = {
|
||||
crud,
|
||||
media,
|
||||
user: user(),
|
||||
};
|
||||
|
||||
/**
|
||||
@ -104,7 +92,7 @@ const datasquirel = {
|
||||
* Post Action
|
||||
*/
|
||||
post,
|
||||
user,
|
||||
user: user({ local: true }),
|
||||
getSchema,
|
||||
client: datasquirelClient,
|
||||
sql,
|
||||
|
@ -1,39 +1,39 @@
|
||||
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;
|
||||
useLocal?: boolean;
|
||||
verify?: boolean;
|
||||
};
|
||||
import {
|
||||
AddUserParams,
|
||||
APICreateUserFunctionParams,
|
||||
APIResponseObject,
|
||||
} from "../../types";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
export default async function addUser({
|
||||
key,
|
||||
apiKey,
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
useLocal,
|
||||
verify,
|
||||
}: Param): Promise<AddUserFunctionReturn> {
|
||||
apiVersion = "v1",
|
||||
dsqlUserID,
|
||||
}: AddUserParams): Promise<APIResponseObject> {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
if (useLocal) {
|
||||
return await apiCreateUser({
|
||||
const apiAddUserParams: APICreateUserFunctionParams = {
|
||||
database,
|
||||
encryptionKey,
|
||||
payload,
|
||||
verify,
|
||||
});
|
||||
dsqlUserID,
|
||||
};
|
||||
|
||||
if (useLocal) {
|
||||
return await apiCreateUser(apiAddUserParams);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -41,53 +41,17 @@ export default async function addUser({
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
const httpResponse = await queryDSQLAPI({
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "signup",
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiAddUserParams,
|
||||
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: ``,
|
||||
},
|
||||
|
||||
/**
|
||||
* 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;
|
||||
return httpResponse;
|
||||
}
|
||||
|
@ -1,9 +1,10 @@
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiDeleteUser from "../../functions/api/users/api-delete-user";
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
@ -14,7 +15,7 @@ type Param = {
|
||||
* # Update User
|
||||
*/
|
||||
export default async function deleteUser({
|
||||
key,
|
||||
apiKey,
|
||||
database,
|
||||
deletedUserId,
|
||||
useLocal,
|
||||
@ -41,20 +42,28 @@ export default async function deleteUser({
|
||||
deletedUserId,
|
||||
});
|
||||
|
||||
const finalAPIKey =
|
||||
apiKey ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY;
|
||||
|
||||
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,
|
||||
Authorization: finalAPIKey,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/${apiVersion}/users/${database}/${deletedUserId}`,
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "delete",
|
||||
database,
|
||||
apiVersion,
|
||||
userID: deletedUserId,
|
||||
}),
|
||||
},
|
||||
|
||||
/**
|
||||
|
@ -2,28 +2,26 @@ 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[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
};
|
||||
import {
|
||||
APIGetUserFunctionParams,
|
||||
GetUserFunctionReturn,
|
||||
GetUserParams,
|
||||
} from "../../types";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
export default async function getUser({
|
||||
key,
|
||||
apiKey,
|
||||
userId,
|
||||
database,
|
||||
fields,
|
||||
useLocal,
|
||||
apiVersion = "v1",
|
||||
}: Param): Promise<GetUserFunctionReturn> {
|
||||
dbUserId,
|
||||
selectAll,
|
||||
}: GetUserParams): Promise<GetUserFunctionReturn> {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
@ -47,21 +45,19 @@ export default async function getUser({
|
||||
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;
|
||||
|
||||
if (useLocal) {
|
||||
return await apiGetUser({
|
||||
const getUserParams: APIGetUserFunctionParams = {
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: database,
|
||||
});
|
||||
database,
|
||||
dbUserId,
|
||||
selectAll,
|
||||
};
|
||||
|
||||
if (useLocal) {
|
||||
return await apiGetUser(getUserParams);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -70,20 +66,31 @@ export default async function getUser({
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(getUserParams);
|
||||
|
||||
const finalAPIKey =
|
||||
apiKey ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY;
|
||||
|
||||
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,
|
||||
Authorization: finalAPIKey,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/${apiVersion}/users/${database}/${userId}`,
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "get",
|
||||
database,
|
||||
apiVersion,
|
||||
userID: userId,
|
||||
}),
|
||||
},
|
||||
|
||||
/**
|
||||
|
@ -1,24 +1,29 @@
|
||||
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,
|
||||
APILoginFunctionParams,
|
||||
APIResponseObject,
|
||||
DATASQUIREL_LoggedInUser,
|
||||
LoginUserParam,
|
||||
PackageUserLoginRequestBody,
|
||||
} from "../../types";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
|
||||
function debugFn(log: any, label?: string) {
|
||||
debugLog({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default async function loginUser({
|
||||
key,
|
||||
export default async function loginUser<
|
||||
T extends DATASQUIREL_LoggedInUser = DATASQUIREL_LoggedInUser
|
||||
>({
|
||||
apiKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
@ -29,7 +34,6 @@ export default async function loginUser({
|
||||
email_login_code,
|
||||
temp_code_field,
|
||||
token,
|
||||
user_id,
|
||||
skipPassword,
|
||||
apiUserID,
|
||||
skipWriteAuthFile,
|
||||
@ -37,11 +41,9 @@ export default async function loginUser({
|
||||
debug,
|
||||
cleanupTokens,
|
||||
secureCookie,
|
||||
request,
|
||||
useLocal,
|
||||
}: LoginUserParam): Promise<APILoginFunctionReturn> {
|
||||
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
apiVersion = "v1",
|
||||
}: LoginUserParam): Promise<APIResponseObject<T | null>> {
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
@ -56,10 +58,6 @@ export default async function loginUser({
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
|
||||
function debugFn(log: any, label?: string) {
|
||||
debugLog({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
@ -78,36 +76,15 @@ export default async function loginUser({
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
|
||||
let httpResponse: import("../../types").APILoginFunctionReturn = {
|
||||
let httpResponse: APIResponseObject = {
|
||||
success: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
if (useLocal) {
|
||||
httpResponse = await apiLoginUser({
|
||||
const apiLoginParams: APILoginFunctionParams = {
|
||||
database,
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
@ -121,61 +98,26 @@ export default async function loginUser({
|
||||
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(
|
||||
{
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
if (useLocal) {
|
||||
httpResponse = await apiLoginUser(apiLoginParams);
|
||||
} else {
|
||||
httpResponse = await queryDSQLAPI({
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "login",
|
||||
database,
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiLoginParams,
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
@ -183,6 +125,10 @@ export default async function loginUser({
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
}
|
||||
|
||||
/**
|
||||
* # Send Response
|
||||
*/
|
||||
|
||||
if (httpResponse?.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
@ -199,7 +145,7 @@ export default async function loginUser({
|
||||
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
userId: apiUserID,
|
||||
});
|
||||
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
|
@ -78,7 +78,7 @@ export default function logoutUser({
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
"Error getting decrypted User JSON to logout:",
|
||||
error.message
|
||||
|
@ -1,214 +0,0 @@
|
||||
import http from "http";
|
||||
import userAuth from "./user-auth";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import { APILoginFunctionReturn } from "../../types";
|
||||
import loginUser from "./login-user";
|
||||
|
||||
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;
|
||||
secureCookie?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
export default async function reauthUser({
|
||||
key,
|
||||
database,
|
||||
response,
|
||||
request,
|
||||
level,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
additionalFields,
|
||||
encryptedUserString,
|
||||
user_id,
|
||||
secureCookie,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
|
||||
if (!existingUser?.payload?.id) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
|
||||
return await loginUser({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
// return httpResponse;
|
||||
}
|
29
package-shared/actions/users/reset-password.ts
Normal file
29
package-shared/actions/users/reset-password.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { ResetPasswordParams, UpdateUserFunctionReturn } from "../../types";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
import apiResetUserPassword from "../../functions/api/users/api-reset-user-password";
|
||||
|
||||
/**
|
||||
* # Reset User Password
|
||||
*/
|
||||
export default async function resetPassword(
|
||||
params: ResetPasswordParams
|
||||
): Promise<UpdateUserFunctionReturn> {
|
||||
if (params.useLocal) {
|
||||
return await apiResetUserPassword(params);
|
||||
}
|
||||
|
||||
const httpResponse = await queryDSQLAPI({
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "reset-password",
|
||||
database: params.database,
|
||||
apiVersion: params.apiVersion,
|
||||
}),
|
||||
apiKey: params.apiKey,
|
||||
body: params,
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
return httpResponse as UpdateUserFunctionReturn;
|
||||
}
|
@ -1,32 +1,20 @@
|
||||
import http from "http";
|
||||
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[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
import {
|
||||
APIResponseObject,
|
||||
APISendEmailCodeFunctionParams,
|
||||
SendEmailCodeParams,
|
||||
} from "../../types";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
export default async function sendEmailCode(
|
||||
params: Param
|
||||
): Promise<SendOneTimeCodeEmailResponse> {
|
||||
params: SendEmailCodeParams
|
||||
): Promise<APIResponseObject> {
|
||||
const {
|
||||
key,
|
||||
apiKey,
|
||||
email,
|
||||
database,
|
||||
temp_code_field_name,
|
||||
@ -35,15 +23,13 @@ export default async function sendEmailCode(
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
user_id,
|
||||
response,
|
||||
extraCookies,
|
||||
useLocal,
|
||||
apiVersion,
|
||||
dbUserId,
|
||||
} = params;
|
||||
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||
? temp_code_field_name
|
||||
@ -51,10 +37,7 @@ export default async function sendEmailCode(
|
||||
|
||||
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>`;
|
||||
|
||||
console.log("useLocal", useLocal);
|
||||
|
||||
if (useLocal) {
|
||||
return await apiSendEmailCode({
|
||||
const apiSendEmailCodeParams: APISendEmailCodeFunctionParams = {
|
||||
database,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
@ -66,71 +49,22 @@ export default async function sendEmailCode(
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
dbUserId,
|
||||
};
|
||||
|
||||
if (useLocal) {
|
||||
return await apiSendEmailCode(apiSendEmailCodeParams);
|
||||
} 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,
|
||||
const httpResponse: APIResponseObject = await queryDSQLAPI({
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "send-email-code",
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
html: emailHtml,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: apiSendEmailCodeParams,
|
||||
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;
|
||||
|
@ -1,36 +1,38 @@
|
||||
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;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
import {
|
||||
ApiUpdateUserParams,
|
||||
UpdateUserFunctionReturn,
|
||||
UpdateUserParams,
|
||||
} from "../../types";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
||||
import { DSQL_DATASQUIREL_USERS } from "../../types/dsql";
|
||||
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default async function updateUser({
|
||||
key,
|
||||
export default async function updateUser<
|
||||
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}
|
||||
>({
|
||||
payload,
|
||||
database,
|
||||
user_id,
|
||||
updatedUserId,
|
||||
useLocal,
|
||||
}: Param): Promise<UpdateUserFunctionReturn> {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
apiKey,
|
||||
apiVersion,
|
||||
dbUserId,
|
||||
}: UpdateUserParams<T>): Promise<UpdateUserFunctionReturn> {
|
||||
const updateUserParams: ApiUpdateUserParams = {
|
||||
payload: payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
dbUserId,
|
||||
};
|
||||
|
||||
if (useLocal) {
|
||||
return await apiUpdateUser({
|
||||
payload: payload,
|
||||
dbFullName: database,
|
||||
updatedUserId,
|
||||
});
|
||||
return await apiUpdateUser(updateUserParams);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -38,54 +40,16 @@ export default async function updateUser({
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
const httpResponse = await queryDSQLAPI({
|
||||
path: grabUserDSQLAPIPath({
|
||||
paradigm: "auth",
|
||||
action: "update",
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
|
||||
const httpsRequest = scheme.request(
|
||||
{
|
||||
apiVersion,
|
||||
}),
|
||||
apiKey,
|
||||
body: updateUserParams,
|
||||
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;
|
||||
|
@ -1,50 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -1,3 +1,60 @@
|
||||
const user = {};
|
||||
import addUser from "../../actions/users/add-user";
|
||||
import getUser from "../../actions/users/get-user";
|
||||
import loginUser from "../../actions/users/login-user";
|
||||
import logoutUser from "../../actions/users/logout-user";
|
||||
import resetPassword from "../../actions/users/reset-password";
|
||||
import sendEmailCode from "../../actions/users/send-email-code";
|
||||
import updateUser from "../../actions/users/update-user";
|
||||
import userAuth from "../../actions/users/user-auth";
|
||||
|
||||
export default user;
|
||||
import {
|
||||
AddUserParams,
|
||||
GetUserParams,
|
||||
LoginUserParam,
|
||||
ResetPasswordParams,
|
||||
SendEmailCodeParams,
|
||||
UpdateUserParams,
|
||||
} from "../../types";
|
||||
|
||||
type Params = {
|
||||
local?: boolean;
|
||||
};
|
||||
|
||||
export default function user(params?: Params) {
|
||||
return {
|
||||
auth: {
|
||||
login: params?.local
|
||||
? async (_: LoginUserParam) => {
|
||||
return await loginUser({ ..._, useLocal: true });
|
||||
}
|
||||
: loginUser,
|
||||
get: params?.local
|
||||
? async (_: GetUserParams) => {
|
||||
return await getUser({ ..._, useLocal: true });
|
||||
}
|
||||
: getUser,
|
||||
signup: params?.local
|
||||
? async (_: AddUserParams) => {
|
||||
return await addUser({ ..._, useLocal: true });
|
||||
}
|
||||
: addUser,
|
||||
sendEmailCode: params?.local
|
||||
? async (_: SendEmailCodeParams) => {
|
||||
return await sendEmailCode({ ..._, useLocal: true });
|
||||
}
|
||||
: sendEmailCode,
|
||||
update: params?.local
|
||||
? async (_: UpdateUserParams) => {
|
||||
return await updateUser({ ..._, useLocal: true });
|
||||
}
|
||||
: updateUser,
|
||||
resetPassword: params?.local
|
||||
? async (_: ResetPasswordParams) => {
|
||||
return await resetPassword({ ..._, useLocal: true });
|
||||
}
|
||||
: resetPassword,
|
||||
logout: logoutUser,
|
||||
auth: userAuth,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { grabPrimaryRequiredDbSchema } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
import { APICreateUserFunctionParams } from "../../../types";
|
||||
import { APICreateUserFunctionParams, APIResponseObject } from "../../../types";
|
||||
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
@ -15,9 +15,9 @@ export default async function apiCreateUser({
|
||||
encryptionKey,
|
||||
payload,
|
||||
database,
|
||||
userId,
|
||||
dsqlUserID,
|
||||
verify,
|
||||
}: APICreateUserFunctionParams) {
|
||||
}: APICreateUserFunctionParams): Promise<APIResponseObject> {
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
|
||||
@ -39,8 +39,8 @@ export default async function apiCreateUser({
|
||||
|
||||
const targetDbSchema = grabPrimaryRequiredDbSchema({
|
||||
dbSlug: database,
|
||||
userId,
|
||||
dbId: userId ? undefined : 1,
|
||||
userId: dsqlUserID,
|
||||
dbId: dsqlUserID ? undefined : 1,
|
||||
});
|
||||
|
||||
if (!targetDbSchema?.id) {
|
||||
@ -77,24 +77,20 @@ export default async function apiCreateUser({
|
||||
|
||||
if (!fields?.[0]) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId,
|
||||
userId: dsqlUserID,
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
|
||||
fields = (await dbHandler({
|
||||
query: fieldsQuery,
|
||||
database: dbFullName,
|
||||
})) as any[];
|
||||
}
|
||||
|
||||
if (!fields?.[0]) {
|
||||
if (!newTable) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field);
|
||||
|
||||
@ -104,7 +100,7 @@ export default async function apiCreateUser({
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
await updateUsersTableSchema({
|
||||
userId,
|
||||
userId: dsqlUserID,
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
@ -177,15 +173,13 @@ export default async function apiCreateUser({
|
||||
})) as any[];
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...addUser,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
...addUser,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -2,6 +2,7 @@ import {
|
||||
APIGetUserFunctionParams,
|
||||
GetUserFunctionReturn,
|
||||
} from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import dbHandler from "../../backend/dbHandler";
|
||||
|
||||
/**
|
||||
@ -9,19 +10,18 @@ import dbHandler from "../../backend/dbHandler";
|
||||
*/
|
||||
export default async function apiGetUser({
|
||||
fields,
|
||||
dbFullName,
|
||||
database,
|
||||
userId,
|
||||
dbUserId,
|
||||
selectAll,
|
||||
}: APIGetUserFunctionParams): Promise<GetUserFunctionReturn> {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const finalDbName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
const query = `SELECT ${fields.join(
|
||||
","
|
||||
)} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const selectFields = selectAll ? "*" : fields?.[0] ? fields.join(",") : "*";
|
||||
|
||||
let foundUser = (await dbHandler({
|
||||
query,
|
||||
values: [API_USER_ID],
|
||||
query: `SELECT ${selectFields} FROM users WHERE id=?`,
|
||||
values: [userId],
|
||||
database: finalDbName,
|
||||
})) as any[];
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
import {
|
||||
APILoginFunctionParams,
|
||||
APILoginFunctionReturn,
|
||||
APIResponseObject,
|
||||
DATASQUIREL_LoggedInUser,
|
||||
} from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
@ -24,7 +24,7 @@ export default async function apiLoginUser({
|
||||
social,
|
||||
dbUserId,
|
||||
debug,
|
||||
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
}: APILoginFunctionParams): Promise<APIResponseObject> {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
if (!dbFullName) {
|
||||
@ -181,7 +181,7 @@ export default async function apiLoginUser({
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
|
||||
const resposeObject: APILoginFunctionReturn = {
|
||||
const resposeObject: APIResponseObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
|
@ -0,0 +1,53 @@
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import dbHandler from "../../backend/dbHandler";
|
||||
import { APIResponseObject, ResetPasswordParams } from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import { DSQL_DATASQUIREL_USERS } from "../../../types/dsql";
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default async function apiResetUserPassword({
|
||||
updatedUserId,
|
||||
database,
|
||||
dbUserId,
|
||||
newPassword,
|
||||
encryptionKey,
|
||||
}: ResetPasswordParams): Promise<APIResponseObject> {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
|
||||
const existingUser = (await dbHandler({
|
||||
query: existingUserQuery,
|
||||
values: existingUserValues,
|
||||
database: dbFullName,
|
||||
})) as any[];
|
||||
|
||||
if (!existingUser?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
|
||||
const newPasswordHashed = hashPassword({
|
||||
password: newPassword,
|
||||
encryptionKey,
|
||||
});
|
||||
|
||||
const updateUser = await updateDbEntry<DSQL_DATASQUIREL_USERS>({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: { password: newPasswordHashed },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
}
|
@ -1,24 +1,14 @@
|
||||
import dbHandler from "../../backend/dbHandler";
|
||||
import nodemailer, { SendMailOptions } from "nodemailer";
|
||||
import http from "http";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../utils/serialize-cookies";
|
||||
import { CookieObject, SendOneTimeCodeEmailResponse } from "../../../types";
|
||||
|
||||
type Param = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
html: string;
|
||||
response?: http.ServerResponse & { [s: string]: any };
|
||||
extraCookies?: CookieObject[];
|
||||
};
|
||||
import {
|
||||
APIResponseObject,
|
||||
APISendEmailCodeFunctionParams,
|
||||
CookieObject,
|
||||
} from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
@ -35,22 +25,26 @@ export default async function apiSendEmailCode({
|
||||
html,
|
||||
response,
|
||||
extraCookies,
|
||||
}: Param): Promise<SendOneTimeCodeEmailResponse> {
|
||||
dbUserId,
|
||||
}: APISendEmailCodeFunctionParams): Promise<APIResponseObject> {
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
const createdAt = Date.now();
|
||||
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
|
||||
let foundUser = (await dbHandler({
|
||||
query: foundUserQuery,
|
||||
values: foundUserValues,
|
||||
database,
|
||||
database: dbFullName,
|
||||
})) as any[];
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
@ -88,10 +82,11 @@ export default async function apiSendEmailCode({
|
||||
|
||||
let mailObject: SendMailOptions = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${
|
||||
sender || "support@datasquirel.com"
|
||||
}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
const finalSender =
|
||||
sender || process.env.DSQL_MAIL_EMAIL || "support@datasquirel.com";
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${finalSender}>`;
|
||||
mailObject["sender"] = finalSender;
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
@ -100,17 +95,16 @@ export default async function apiSendEmailCode({
|
||||
|
||||
if (!info?.accepted) throw new Error("Mail not Sent!");
|
||||
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
|
||||
await dbHandler({
|
||||
query: setTempCodeQuery,
|
||||
values: setTempCodeValues,
|
||||
database,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
const resObject: import("../../../types").SendOneTimeCodeEmailResponse =
|
||||
{
|
||||
const resObject: APIResponseObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
|
@ -1,28 +1,22 @@
|
||||
// @ts-check
|
||||
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import dbHandler from "../../backend/dbHandler";
|
||||
|
||||
type Param = {
|
||||
payload: { [s: string]: any };
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
};
|
||||
|
||||
type Return = { success: boolean; payload?: any; msg?: string };
|
||||
import { APIResponseObject, ApiUpdateUserParams } from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default async function apiUpdateUser({
|
||||
payload,
|
||||
dbFullName,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
}: Param): Promise<Return> {
|
||||
database,
|
||||
dbUserId,
|
||||
}: ApiUpdateUserParams): Promise<APIResponseObject> {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
|
||||
@ -53,8 +47,7 @@ export default async function apiUpdateUser({
|
||||
}
|
||||
})();
|
||||
|
||||
/** @type {any} */
|
||||
const finalData: any = {};
|
||||
const finalData: { [s: string]: any } = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
const targetFieldSchema = targetTableSchema?.fields?.find(
|
||||
|
@ -23,10 +23,8 @@ export default async function addUsersTableToDb({
|
||||
database,
|
||||
payload,
|
||||
dbId,
|
||||
}: Param): Promise<any> {
|
||||
}: Param): Promise<boolean> {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
|
||||
const userPreset = grabNewUsersTableSchema({ payload });
|
||||
if (!userPreset) throw new Error("Couldn't Get User Preset!");
|
||||
|
||||
@ -51,32 +49,13 @@ export default async function addUsersTableToDb({
|
||||
|
||||
writeUpdatedDbSchema({ dbSchema: targetDatabase, userId });
|
||||
|
||||
const targetDb = (await dbHandler({
|
||||
query: `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
values: [userId, database],
|
||||
})) as any[];
|
||||
|
||||
if (targetDb?.[0]) {
|
||||
const newTableEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
dbId,
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
return dbShellUpdate;
|
||||
} catch (error: any) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
@ -84,6 +63,7 @@ export default async function addUsersTableToDb({
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -20,12 +20,8 @@ export default function grabNewUsersTableSchema(params: {
|
||||
})
|
||||
: [];
|
||||
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
|
||||
console.log("allFields", allFields);
|
||||
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
@ -35,7 +31,7 @@ export default function grabNewUsersTableSchema(params: {
|
||||
userPreset.fields = [...finalFields];
|
||||
|
||||
return userPreset;
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
} catch (error: any) {
|
||||
console.log(`grabNewUsersTableSchema.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
|
@ -31,7 +31,7 @@ export default function decrypt({
|
||||
keyLen,
|
||||
algorithm,
|
||||
bufferAllocSize,
|
||||
} = grabKeys({ encryptionKey });
|
||||
} = grabKeys({ encryptionKey, encryptionSalt });
|
||||
|
||||
if (!encrptKey?.match(/.{8,}/)) {
|
||||
if (debug) console.log("Decrption key is invalid");
|
||||
|
@ -29,7 +29,7 @@ export default function encrypt({
|
||||
keyLen,
|
||||
algorithm,
|
||||
bufferAllocSize,
|
||||
} = grabKeys({ encryptionKey });
|
||||
} = grabKeys({ encryptionKey, encryptionSalt });
|
||||
|
||||
if (!encrptKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
|
@ -226,7 +226,6 @@ export interface DSQL_MYSQL_user_databases_Type {
|
||||
export interface PackageUserLoginRequestBody {
|
||||
encryptionKey: string;
|
||||
payload: any;
|
||||
database: string;
|
||||
additionalFields?: string[];
|
||||
email_login?: boolean;
|
||||
email_login_code?: string;
|
||||
@ -1139,7 +1138,7 @@ export type APICreateUserFunctionParams = {
|
||||
encryptionKey?: string;
|
||||
payload: any;
|
||||
database: string;
|
||||
userId?: string | number;
|
||||
dsqlUserID?: string | number;
|
||||
verify?: boolean;
|
||||
};
|
||||
|
||||
@ -1152,8 +1151,10 @@ export type APICreateUserFunction = (
|
||||
*/
|
||||
export type APIGetUserFunctionParams = {
|
||||
fields: string[];
|
||||
dbFullName: string;
|
||||
database: string;
|
||||
userId: string | number;
|
||||
dbUserId?: string | number;
|
||||
selectAll?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@ -1613,6 +1614,14 @@ export type APIResponseObject<T extends any = any> = {
|
||||
debug?: any;
|
||||
batchPayload?: any[][] | null;
|
||||
errorData?: any;
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
cookieNames?: any;
|
||||
key?: string;
|
||||
userId?: string | number;
|
||||
code?: string;
|
||||
createdAt?: number;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
export const UserTypes = ["su", "admin"] as const;
|
||||
@ -1903,7 +1912,7 @@ export type DefaultEntryType = {
|
||||
export const IndexTypes = ["regular", "full_text"] as const;
|
||||
|
||||
export type LoginUserParam = {
|
||||
key?: string;
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
payload: {
|
||||
email?: string;
|
||||
@ -1919,7 +1928,6 @@ export type LoginUserParam = {
|
||||
email_login_code?: string;
|
||||
temp_code_field?: string;
|
||||
token?: boolean;
|
||||
user_id?: string | number;
|
||||
skipPassword?: boolean;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
@ -1928,6 +1936,7 @@ export type LoginUserParam = {
|
||||
cleanupTokens?: boolean;
|
||||
secureCookie?: boolean;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
};
|
||||
|
||||
export const UserSelectFields = [
|
||||
@ -2163,7 +2172,13 @@ export type SiteConfigMaxscale = {
|
||||
admin_port: number;
|
||||
};
|
||||
|
||||
export const APIParadigms = ["crud", "media", "sql", "schema"] as const;
|
||||
export const APIParadigms = [
|
||||
"crud",
|
||||
"media",
|
||||
"sql",
|
||||
"schema",
|
||||
"users",
|
||||
] as const;
|
||||
|
||||
export const AppVersions = [
|
||||
{
|
||||
@ -2319,3 +2334,120 @@ export type GrabUserResourceParams<T extends { [k: string]: any } = any> = {
|
||||
isSuperUser?: boolean;
|
||||
targetID?: string | number;
|
||||
};
|
||||
|
||||
export const UserAPIParadigms = ["auth", "crud"] as const;
|
||||
export const UserAPIAuthActions = [
|
||||
"login",
|
||||
"get",
|
||||
"signup",
|
||||
"update",
|
||||
"logout",
|
||||
"refresh",
|
||||
"verify",
|
||||
"send-verification",
|
||||
"delete",
|
||||
"send-email-code",
|
||||
"reset-password",
|
||||
] as const;
|
||||
|
||||
export type GrabUserAPIPathParams = {
|
||||
apiVersion?: string;
|
||||
paradigm?: (typeof UserAPIParadigms)[number];
|
||||
action?: (typeof UserAPIAuthActions)[number];
|
||||
database?: string;
|
||||
userID?: string | number;
|
||||
};
|
||||
|
||||
export type GetUserParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
userId: number | string;
|
||||
fields?: string[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
selectAll?: boolean;
|
||||
};
|
||||
|
||||
export type AddUserParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
payload: UserDataPayload;
|
||||
encryptionKey?: string;
|
||||
useLocal?: boolean;
|
||||
verify?: boolean;
|
||||
apiVersion?: string;
|
||||
dsqlUserID?: string | number;
|
||||
};
|
||||
|
||||
export type APISendEmailCodeFunctionParams = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
/**
|
||||
* HTML string with {{code}} placeholder for the code
|
||||
*/
|
||||
html: string;
|
||||
response?: ServerResponse & { [s: string]: any };
|
||||
extraCookies?: CookieObject[];
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
||||
export type SendEmailCodeParams = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
email: string;
|
||||
temp_code_field_name?: string;
|
||||
response?: ServerResponse & { [s: string]: any };
|
||||
mail_domain?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
extraCookies?: CookieObject[];
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
||||
export type UpdateUserParams<
|
||||
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}
|
||||
> = {
|
||||
apiKey?: string;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
payload: T;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
||||
export type ResetPasswordParams = {
|
||||
apiKey?: string;
|
||||
newPassword: string;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
apiVersion?: string;
|
||||
dbUserId?: string | number;
|
||||
encryptionKey?: string;
|
||||
};
|
||||
|
||||
export type ApiUpdateUserParams<
|
||||
T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||
[k: string]: any;
|
||||
}
|
||||
> = {
|
||||
payload: T;
|
||||
database: string;
|
||||
updatedUserId: string | number;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
31
package-shared/utils/backend/users/grab-api-path.ts
Normal file
31
package-shared/utils/backend/users/grab-api-path.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { GrabUserAPIPathParams } from "../../../types";
|
||||
|
||||
export default function grabUserDSQLAPIPath({
|
||||
apiVersion,
|
||||
paradigm,
|
||||
action,
|
||||
database,
|
||||
userID,
|
||||
}: GrabUserAPIPathParams) {
|
||||
const finalAPIVersion = process.env.DSQL_API_VERSION || apiVersion || "v1";
|
||||
const finalParadigm = paradigm || "auth";
|
||||
const finalAction = action || "login";
|
||||
|
||||
const finalDatabase = database || "datasquirel";
|
||||
|
||||
let finalPath = `/api/${finalAPIVersion}/users/${finalParadigm}/${finalDatabase}`;
|
||||
|
||||
switch (paradigm) {
|
||||
case "auth":
|
||||
finalPath += `/${finalAction}`;
|
||||
if (userID) {
|
||||
finalPath += `/${userID}`;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return finalPath;
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@moduletrace/datasquirel",
|
||||
"version": "4.9.6",
|
||||
"version": "4.9.7",
|
||||
"description": "Cloud-based SQL data management tool",
|
||||
"main": "dist/index.js",
|
||||
"bin": {
|
||||
|
Loading…
Reference in New Issue
Block a user