Convert all SecurityClient API calls to hooks except auth

This commit is contained in:
Tuan Dang
2023-08-10 17:19:23 +07:00
parent 78802409bd
commit 2dba7847b6
45 changed files with 179 additions and 1377 deletions
@@ -8,10 +8,9 @@ import { useSubscription, useWorkspace } from "@app/context";
import updateUserProjectPermission from "@app/ee/api/memberships/UpdateUserProjectPermission";
import {
useDeleteUserFromWorkspace,
useUpdateUserWorkspaceRole
} from "@app/hooks/api";
import getLatestFileKey from "@app/pages/api/workspace/getLatestFileKey";
import uploadKeys from "@app/pages/api/workspace/uploadKeys";
useGetUserWsKey,
useUpdateUserWorkspaceRole,
useUploadWsKey} from "@app/hooks/api";
import { decryptAssymmetric, encryptAssymmetric } from "../../utilities/cryptography/crypto";
import guidGenerator from "../../utilities/randomId";
@@ -42,7 +41,10 @@ type EnvironmentProps = {
const ProjectUsersTable = ({ userData, changeData, myUser, filter, isUserListLoading }: Props) => {
const { currentWorkspace } = useWorkspace();
const { subscription } = useSubscription();
const { data: wsKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
const { mutateAsync: deleteUserFromWorkspaceMutateAsync } = useDeleteUserFromWorkspace();
const { mutateAsync: uploadWsKeyMutateAsync } = useUploadWsKey();
const { mutateAsync: updateUserWorkspaceRoleMutateAsync } = useUpdateUserWorkspaceRole();
// const [roleSelected, setRoleSelected] = useState(
// Array(userData?.length).fill(userData.map((user) => user.role))
@@ -151,26 +153,31 @@ const ProjectUsersTable = ({ userData, changeData, myUser, filter, isUserListLoa
}, [userData, myUser, currentWorkspace]);
const grantAccess = async (id: string, publicKey: string) => {
const result = await getLatestFileKey({ workspaceId });
if (wsKey) {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string;
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string;
// assymmetrically decrypt symmetric key with local private key
const key = decryptAssymmetric({
ciphertext: wsKey.encryptedKey,
nonce: wsKey.nonce,
publicKey: wsKey.sender.publicKey,
privateKey: PRIVATE_KEY
});
// assymmetrically decrypt symmetric key with local private key
const key = decryptAssymmetric({
ciphertext: result.latestKey.encryptedKey,
nonce: result.latestKey.nonce,
publicKey: result.latestKey.sender.publicKey,
privateKey: PRIVATE_KEY
});
const { ciphertext, nonce } = encryptAssymmetric({
plaintext: key,
publicKey,
privateKey: PRIVATE_KEY
});
const { ciphertext, nonce } = encryptAssymmetric({
plaintext: key,
publicKey,
privateKey: PRIVATE_KEY
});
uploadKeys(workspaceId, id, ciphertext, nonce);
router.reload();
await uploadWsKeyMutateAsync({
workspaceId,
userId: id,
encryptedKey: ciphertext,
nonce
});
router.reload();
}
};
const closeUpgradeModal = () => {
@@ -2,9 +2,9 @@ import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/router";
import { useAddUserToOrg } from "@app/hooks/api";
import { useFetchServerStatus } from "@app/hooks/api/serverDetails";
import { usePopUp } from "@app/hooks/usePopUp";
import addUserToOrg from "@app/pages/api/organization/addUserToOrg";
import { Button, EmailServiceSetupModal } from "../v2";
@@ -12,10 +12,12 @@ import { Button, EmailServiceSetupModal } from "../v2";
* This is the last step of the signup flow. People can optionally invite their teammates here.
*/
export default function TeamInviteStep(): JSX.Element {
const [emails, setEmails] = useState("");
const { t } = useTranslation();
const router = useRouter();
const [emails, setEmails] = useState("");
const { data: serverDetails } = useFetchServerStatus();
const { mutateAsync } = useAddUserToOrg();
const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["setUpEmail"] as const);
// Redirect user to the getting started page
@@ -27,7 +29,12 @@ export default function TeamInviteStep(): JSX.Element {
inviteEmails
.split(",")
.map((email) => email.trim())
.map(async (email) => addUserToOrg(email, String(localStorage.getItem("orgData.id"))));
.map(async (email) => {
mutateAsync({
inviteeEmail: email,
organizationId: String(localStorage.getItem("orgData.id"))
});
});
await redirectToHome();
};
@@ -9,8 +9,8 @@ import nacl from "tweetnacl";
import { encodeBase64 } from "tweetnacl-util";
import { useGetCommonPasswords } from "@app/hooks/api";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import completeAccountInformationSignup from "@app/pages/api/auth/CompleteAccountInformationSignup";
import getOrganizations from "@app/pages/api/organization/getOrgs";
import ProjectService from "@app/services/ProjectService";
import InputField from "../basic/InputField";
@@ -190,7 +190,8 @@ export default function UserInfoStep({
privateKey
});
const userOrgs = await getOrganizations();
const userOrgs = await fetchOrganizations();
const orgId = userOrgs[0]?._id;
const project = await ProjectService.initProject({
organizationId: orgId,
@@ -1,10 +1,10 @@
/* eslint-disable prefer-destructuring */
import jsrp from "jsrp";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import { fetchMyOrganizationProjects } from "@app/hooks/api/users/queries";
import login1 from "@app/pages/api/auth/Login1";
import login2 from "@app/pages/api/auth/Login2";
import getOrganizations from "@app/pages/api/organization/getOrgs";
import getOrganizationUserProjects from "@app/pages/api/organization/GetOrgUserProjects";
import KeyService from "@app/services/KeyService";
import Telemetry from "./telemetry/Telemetry";
@@ -125,13 +125,11 @@ const attemptLogin = async (
privateKey
});
const userOrgs = await getOrganizations();
const userOrgs = await fetchOrganizations();
const orgId = userOrgs[0]._id;
localStorage.setItem("orgData.id", orgId);
const orgUserProjects = await getOrganizationUserProjects({
orgId
});
const orgUserProjects = await fetchMyOrganizationProjects(orgId);
if (orgUserProjects.length > 0) {
localStorage.setItem("projectData.id", orgUserProjects[0]._id);
@@ -1,10 +1,10 @@
/* eslint-disable prefer-destructuring */
import jsrp from "jsrp";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import { fetchMyOrganizationProjects } from "@app/hooks/api/users/queries";
import login1 from "@app/pages/api/auth/Login1";
import verifyMfaToken from "@app/pages/api/auth/verifyMfaToken";
import getOrganizations from "@app/pages/api/organization/getOrgs";
import getOrganizationUserProjects from "@app/pages/api/organization/GetOrgUserProjects";
import KeyService from "@app/services/KeyService";
import { saveTokenToLocalStorage } from "./saveTokenToLocalStorage";
@@ -96,13 +96,11 @@ const attemptLoginMfa = async ({
// TODO: in the future - move this logic elsewhere
// because this function is about logging the user in
// and not initializing the login details
const userOrgs = await getOrganizations();
const userOrgs = await fetchOrganizations();
const orgId = userOrgs[0]._id;
localStorage.setItem("orgData.id", orgId);
const orgUserProjects = await getOrganizationUserProjects({
orgId
});
const orgUserProjects = await fetchMyOrganizationProjects(orgId);
localStorage.setItem("projectData.id", orgUserProjects[0]._id);
resolve({
@@ -1,10 +1,10 @@
/* eslint-disable prefer-destructuring */
import jsrp from "jsrp";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import { fetchMyOrganizationProjects } from "@app/hooks/api/users/queries";
import login1 from "@app/pages/api/auth/Login1";
import login2 from "@app/pages/api/auth/Login2";
import getOrganizations from "@app/pages/api/organization/getOrgs";
import getOrganizationUserProjects from "@app/pages/api/organization/GetOrgUserProjects";
import KeyService from "@app/services/KeyService";
import Telemetry from "./telemetry/Telemetry";
@@ -36,7 +36,6 @@ const attemptLogin = async (
providerAuthToken?: string;
}
): Promise<IsLoginSuccessful> => {
const telemetry = new Telemetry().getInstance();
return new Promise((resolve, reject) => {
client.init(
@@ -124,14 +123,12 @@ const attemptLogin = async (
// TODO: in the future - move this logic elsewhere
// because this function is about logging the user in
// and not initializing the login details
const userOrgs = await getOrganizations();
const userOrgs = await fetchOrganizations();
const orgId = userOrgs[0]._id;
localStorage.setItem("orgData.id", orgId);
const orgUserProjects = await getOrganizationUserProjects({
orgId
});
const orgUserProjects = await fetchMyOrganizationProjects(orgId);
if (orgUserProjects.length > 0) {
localStorage.setItem("projectData.id", orgUserProjects[0]._id);
@@ -1,10 +1,10 @@
/* eslint-disable prefer-destructuring */
import jsrp from "jsrp";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import { fetchMyOrganizationProjects } from "@app/hooks/api/users/queries";
import login1 from "@app/pages/api/auth/Login1";
import verifyMfaToken from "@app/pages/api/auth/verifyMfaToken";
import getOrganizations from "@app/pages/api/organization/getOrgs";
import getOrganizationUserProjects from "@app/pages/api/organization/GetOrgUserProjects";
import KeyService from "@app/services/KeyService";
import { saveTokenToLocalStorage } from "./saveTokenToLocalStorage";
@@ -87,13 +87,11 @@ const attemptLoginMfa = async ({
// TODO: in the future - move this logic elsewhere
// because this function is about logging the user in
// and not initializing the login details
const userOrgs = await getOrganizations();
const userOrgs = await fetchOrganizations();
const orgId = userOrgs[0]._id;
localStorage.setItem("orgData.id", orgId);
const orgUserProjects = await getOrganizationUserProjects({
orgId
});
const orgUserProjects = await fetchMyOrganizationProjects(orgId);
localStorage.setItem("projectData.id", orgUserProjects[0]._id);
resolve(true);
@@ -1,5 +1,4 @@
import { fetchUserAction } from "@app/hooks/api/users/queries";
import getOrganizationUsers from "@app/pages/api/organization/GetOrgUsers";
import { fetchOrgUsers,fetchUserAction } from "@app/hooks/api/users/queries";
interface OnboardingCheckProps {
setTotalOnboardingActionsDone?: (value: number) => void;
@@ -43,9 +42,8 @@ const onboardingCheck = async ({
if (setHasUserClickedIntro) setHasUserClickedIntro(!!userActionIntro);
const orgId = localStorage.getItem("orgData.id");
const orgUsers = await getOrganizationUsers({
orgId: orgId || ""
});
const orgUsers = await fetchOrgUsers(orgId || "");
if (orgUsers.length > 1) {
countActions += 1;
}
@@ -2,7 +2,7 @@ import crypto from "crypto";
import { SecretDataProps, Tag } from "public/data/frequentInterfaces";
import getLatestFileKey from "@app/pages/api/workspace/getLatestFileKey";
import { fetchUserWsKey } from "@app/hooks/api/keys/queries";
import { decryptAssymmetric, encryptSymmetric } from "../cryptography/crypto";
@@ -42,19 +42,21 @@ const encryptSecrets = async ({
}) => {
let secrets;
try {
const sharedKey = await getLatestFileKey({ workspaceId });
// const sharedKey = await getLatestFileKey({ workspaceId });
const wsKey = await fetchUserWsKey(workspaceId);
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string;
let randomBytes: string;
if (Object.keys(sharedKey).length > 0) {
if (wsKey) {
// case: a (shared) key exists for the workspace
randomBytes = decryptAssymmetric({
ciphertext: sharedKey.latestKey.encryptedKey,
nonce: sharedKey.latestKey.nonce,
publicKey: sharedKey.latestKey.sender.publicKey,
ciphertext: wsKey.encryptedKey,
nonce: wsKey.nonce,
publicKey: wsKey.sender.publicKey,
privateKey: PRIVATE_KEY
});
} else {
// case: a (shared) key does not exist for the workspace
randomBytes = crypto.randomBytes(16).toString("hex");
@@ -114,6 +116,7 @@ const encryptSecrets = async ({
return result;
});
} catch (error) {
console.log("Error while encrypting secrets");
}