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