Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Simplify staff source code

Manav Rathi0b747ae15997
diff --git a/infra/staff/src/App.tsx b/infra/staff/src/App.tsx
index 5cac5b00ee..ec6bbac44c 100644
--- a/infra/staff/src/App.tsx
+++ b/infra/staff/src/App.tsx
@@ -26,6 +26,16 @@ const buildUserSearchUrl = (input: string): string => {
return `${apiOrigin}/admin/user?email=${encodeURIComponent(trimmedInput)}`;
};
+const formatStorage = (bytes: number | undefined, noneWhenZero = false) => {
+ if (bytes === undefined || (noneWhenZero && bytes === 0)) {
+ return "None";
+ }
+ if (bytes >= 1024 ** 3) {
+ return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
+ }
+ return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
+};
+
const App: React.FC = () => {
const [localEmail, setLocalEmail] = useState<string>("");
const [localToken, setLocalToken] = useState<string>("");
@@ -81,7 +91,6 @@ const App: React.FC = () => {
}
const userDataResponse: UserResponse =
(await response.json()) as UserResponse;
- console.log("API Response:", userDataResponse);
setEmail(userDataResponse.user.email || userSearchInput);
const extractedUserData: UserData = {
@@ -94,24 +103,16 @@ const App: React.FC = () => {
).toLocaleString() || "None",
},
storage: {
- Total: userDataResponse.subscription.storage
- ? userDataResponse.subscription.storage >= 1024 ** 3
- ? `${(userDataResponse.subscription.storage / 1024 ** 3).toFixed(2)} GB`
- : `${(userDataResponse.subscription.storage / 1024 ** 2).toFixed(2)} MB`
- : "None",
- Consumed:
- userDataResponse.details?.usage !== undefined
- ? userDataResponse.details.usage >= 1024 ** 3
- ? `${(userDataResponse.details.usage / 1024 ** 3).toFixed(2)} GB`
- : `${(userDataResponse.details.usage / 1024 ** 2).toFixed(2)} MB`
- : "None",
- Bonus:
- userDataResponse.details?.storageBonus !== undefined
- ? userDataResponse.details.storageBonus >=
- 1024 ** 3
- ? `${(userDataResponse.details.storageBonus / 1024 ** 3).toFixed(2)} GB`
- : `${(userDataResponse.details.storageBonus / 1024 ** 2).toFixed(2)} MB`
- : "None",
+ Total: formatStorage(
+ userDataResponse.subscription.storage,
+ true,
+ ),
+ Consumed: formatStorage(
+ userDataResponse.details?.usage,
+ ),
+ Bonus: formatStorage(
+ userDataResponse.details?.storageBonus,
+ ),
},
subscription: {
"Product ID":
@@ -171,11 +172,15 @@ const App: React.FC = () => {
const urlEmail = urlParams.get("email");
const urlToken = urlParams.get("token");
- if (urlEmail && urlToken) {
+ if (urlEmail) {
setLocalEmail(urlEmail);
- setLocalToken(urlToken);
setEmail(urlEmail);
+ }
+ if (urlToken) {
+ setLocalToken(urlToken);
setToken(urlToken);
+ }
+ if (urlEmail && urlToken) {
fetchData(urlEmail, urlToken).catch((error: unknown) =>
console.error("Fetch data error:", error),
);
@@ -198,16 +203,6 @@ const App: React.FC = () => {
) => {
setTabValue(newValue);
};
- useEffect(() => {
- const searchParam = new URLSearchParams(window.location.search);
- const userToken = searchParam.get("token");
-
- if (userToken) {
- setLocalToken(userToken);
- setToken(userToken);
- }
- }, []);
-
return (
<div className="container">
<div>
diff --git a/infra/staff/src/components/AddOtt.tsx b/infra/staff/src/components/AddOtt.tsx
index c5ec9b50ed..ca8b1ede40 100644
--- a/infra/staff/src/components/AddOtt.tsx
+++ b/infra/staff/src/components/AddOtt.tsx
@@ -15,8 +15,7 @@ import {
} from "@mui/material";
import type { SelectChangeEvent } from "@mui/material/Select";
import { useEffect, useState } from "react";
-import { getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import { apiOrigin, requireToken } from "../services/support";
const APP_OPTIONS = [
{ label: "Photos", value: "photos" },
@@ -74,10 +73,7 @@ const AddOtt = ({ open, onClose, userEmail }: AddOttProps) => {
throw new Error("User email is unavailable");
}
- const token = getToken();
- if (!token) {
- throw new Error("Auth token is unavailable");
- }
+ const token = requireToken();
const otp = generateOtp();
const expiryTime = computeExpiryTimeMicros();
@@ -93,7 +89,7 @@ const AddOtt = ({ open, onClose, userEmail }: AddOttProps) => {
email: userEmail,
code: otp,
app: selectedApp,
- expiryTime: expiryTime,
+ expiryTime,
}),
});
diff --git a/infra/staff/src/components/ChangeEmail.tsx b/infra/staff/src/components/ChangeEmail.tsx
index 0a732d7ee0..16cff99a6d 100644
--- a/infra/staff/src/components/ChangeEmail.tsx
+++ b/infra/staff/src/components/ChangeEmail.tsx
@@ -8,21 +8,19 @@ import {
TextField,
} from "@mui/material";
import React, { useEffect, useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import { getEmail } from "../services/session";
+import {
+ apiOrigin,
+ getCurrentAdminUserId,
+ requireToken,
+} from "../services/support";
import type { ErrorResponse } from "../types";
-// The below interfaces will only be used in this file
-// hence not including them into a sub-merged types file
interface ChangeEmailProps {
open: boolean;
onClose: () => void;
}
-interface UserDataResponse {
- subscription: { userID: string } | null;
-}
-
const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {
const [newEmail, setNewEmail] = useState<string>("");
const [userID, setUserID] = useState<string>("");
@@ -30,30 +28,10 @@ const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {
useEffect(() => {
const fetchUserID = async () => {
const email = getEmail();
- setNewEmail(email); // Set initial email state
+ setNewEmail(email);
- const encodedEmail = encodeURIComponent(email);
-
- const url = `${apiOrigin}/admin/user?email=${encodedEmail}`;
try {
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-AUTH-TOKEN": getToken(),
- },
- });
-
- if (!response.ok) {
- throw new Error("Network response was not ok");
- }
-
- const data = (await response.json()) as UserDataResponse;
- if (data.subscription) {
- setUserID(data.subscription.userID); // Update userID state
- } else {
- throw new Error("Subscription data not found");
- }
+ setUserID(await getCurrentAdminUserId());
} catch (error) {
console.error("Error fetching user ID:", error);
}
@@ -67,7 +45,7 @@ const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {
}, [open]);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- setNewEmail(event.target.value); // Update newEmail state on input change
+ setNewEmail(event.target.value);
};
const handleSubmit = async (
@@ -75,7 +53,7 @@ const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {
) => {
event.preventDefault();
- const token = getToken();
+ const token = requireToken();
const url = `${apiOrigin}/admin/user/change-email`;
const body = { userID, email: newEmail };
@@ -102,7 +80,6 @@ const ChangeEmail: React.FC<ChangeEmailProps> = ({ open, onClose }) => {
);
}
- console.log("Email updated successfully");
onClose();
} catch (error) {
console.error("Error updating email:", error);
diff --git a/infra/staff/src/components/CloseFamily.tsx b/infra/staff/src/components/CloseFamily.tsx
index 16f4a9d664..dd12fd4d07 100644
--- a/infra/staff/src/components/CloseFamily.tsx
+++ b/infra/staff/src/components/CloseFamily.tsx
@@ -8,9 +8,11 @@ import {
Paper,
} from "@mui/material";
import React, { useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
-import type { UserData } from "../types";
+import {
+ apiOrigin,
+ getCurrentAdminUserId,
+ requireToken,
+} from "../services/support";
interface CloseFamilyProps {
open: boolean;
@@ -28,48 +30,17 @@ const CloseFamily: React.FC<CloseFamilyProps> = ({
const handleClosure = async () => {
try {
setLoading(true);
- const email = getEmail();
- const token = getToken();
-
- if (!email) {
- throw new Error("Email not found");
- }
-
- if (!token) {
- throw new Error("Token not found");
- }
+ const token = requireToken();
+ const userId = await getCurrentAdminUserId();
- const encodedEmail = encodeURIComponent(email);
-
- // Fetch user data
- const userUrl = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const userResponse = await fetch(userUrl, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!userResponse.ok) {
- throw new Error("Failed to fetch user data");
- }
- const userData = (await userResponse.json()) as UserData;
- const userId = userData.subscription?.userID;
-
- if (!userId) {
- throw new Error("User ID not found");
- }
-
- // Close family action
const closeFamilyUrl = `${apiOrigin}/admin/user/close-family`;
- const body = JSON.stringify({ userId });
const closeFamilyResponse = await fetch(closeFamilyUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Auth-Token": token,
},
- body: body,
+ body: JSON.stringify({ userId }),
});
if (!closeFamilyResponse.ok) {
@@ -77,8 +48,8 @@ const CloseFamily: React.FC<CloseFamilyProps> = ({
throw new Error(`Failed to close family: ${errorResponse}`);
}
- handleCloseFamily(); // Notify parent component of successful action
- handleClose(); // Close dialog on successful action
+ handleCloseFamily();
+ handleClose();
} catch (error) {
if (error instanceof Error) {
alert(error.message);
@@ -90,10 +61,6 @@ const CloseFamily: React.FC<CloseFamilyProps> = ({
}
};
- const handleCancel = () => {
- handleClose(); // Close dialog
- };
-
return (
<div>
<Dialog
@@ -130,7 +97,7 @@ const CloseFamily: React.FC<CloseFamilyProps> = ({
</DialogContent>
<DialogActions sx={{ justifyContent: "center" }}>
<Button
- onClick={handleCancel}
+ onClick={handleClose}
sx={{
bgcolor: "white",
color: "black",
diff --git a/infra/staff/src/components/DeleteAccont.tsx b/infra/staff/src/components/DeleteAccont.tsx
index 6d77e52bbc..457953f186 100644
--- a/infra/staff/src/components/DeleteAccont.tsx
+++ b/infra/staff/src/components/DeleteAccont.tsx
@@ -8,8 +8,8 @@ import {
Paper,
} from "@mui/material";
import React from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import { getEmail } from "../services/session";
+import { apiOrigin, requireToken } from "../services/support";
interface DeleteAccountProps {
open: boolean;
@@ -19,11 +19,11 @@ interface DeleteAccountProps {
const DeleteAccount: React.FC<DeleteAccountProps> = ({ open, handleClose }) => {
const handleDelete = async () => {
try {
- const encodedEmail = encodeURIComponent(getEmail());
- console.log(encodedEmail);
- const token = getToken();
+ const email = getEmail();
+ if (!email) throw new Error("Email not found");
+ const token = requireToken();
- const deleteUrl = `${apiOrigin}/admin/user/delete?email=${encodedEmail}`;
+ const deleteUrl = `${apiOrigin}/admin/user/delete?email=${encodeURIComponent(email)}`;
const response = await fetch(deleteUrl, {
method: "DELETE",
headers: { "X-Auth-Token": token },
@@ -31,8 +31,7 @@ const DeleteAccount: React.FC<DeleteAccountProps> = ({ open, handleClose }) => {
if (!response.ok) {
throw new Error("Failed to delete user account");
}
- handleClose(); // Close dialog on successful delete
- console.log("Account deleted successfully");
+ handleClose();
} catch (error) {
if (error instanceof Error) {
alert("Failed to delete the account: " + error.message);
@@ -98,7 +97,7 @@ const DeleteAccount: React.FC<DeleteAccountProps> = ({ open, handleClose }) => {
"&:hover": { bgcolor: "#E53935" },
}}
>
- Delete{" "}
+ Delete
</Button>
</DialogActions>
</Dialog>
diff --git a/infra/staff/src/components/Disable2FA.tsx b/infra/staff/src/components/Disable2FA.tsx
index 6ad7c82587..ecc37d5fcf 100644
--- a/infra/staff/src/components/Disable2FA.tsx
+++ b/infra/staff/src/components/Disable2FA.tsx
@@ -8,9 +8,11 @@ import {
Paper,
} from "@mui/material";
import React, { useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
-import type { UserData } from "../types";
+import {
+ apiOrigin,
+ getCurrentAdminUserId,
+ requireToken,
+} from "../services/support";
interface Disable2FAProps {
open: boolean;
@@ -28,57 +30,25 @@ const Disable2FA: React.FC<Disable2FAProps> = ({
const handleDisable = async () => {
try {
setLoading(true);
- const email = getEmail();
- const token = getToken();
-
- if (!email) {
- throw new Error("Email not found");
- }
-
- if (!token) {
- throw new Error("Token not found");
- }
+ const token = requireToken();
+ const userID = await getCurrentAdminUserId();
- const encodedEmail = encodeURIComponent(email);
-
- // Fetch user data
- const userUrl = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const userResponse = await fetch(userUrl, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!userResponse.ok) {
- throw new Error("Failed to fetch user data");
- }
- const userData = (await userResponse.json()) as UserData;
- const userID = userData.subscription?.userID;
-
- if (!userID) {
- throw new Error("User ID not found");
- }
-
- // Disable 2FA
const disableUrl = `${apiOrigin}/admin/user/disable-2fa`;
- const body = JSON.stringify({ userID });
const disableResponse = await fetch(disableUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Auth-Token": token,
},
- body: body,
+ body: JSON.stringify({ userID }),
});
if (!disableResponse.ok) {
const errorResponse = await disableResponse.text();
throw new Error(`Failed to disable 2FA: ${errorResponse}`);
}
- handleDisable2FA(); // Notify parent component of successful disable
- handleClose(); // Close dialog on successful disable
- console.log("2FA disabled successfully");
+ handleDisable2FA();
+ handleClose();
} catch (error) {
if (error instanceof Error) {
alert(error.message);
@@ -90,10 +60,6 @@ const Disable2FA: React.FC<Disable2FAProps> = ({
}
};
- const handleCancel = () => {
- handleClose(); // Close dialog
- };
-
return (
<div>
<Dialog
@@ -129,7 +95,7 @@ const Disable2FA: React.FC<Disable2FAProps> = ({
</DialogContent>
<DialogActions sx={{ justifyContent: "center" }}>
<Button
- onClick={handleCancel}
+ onClick={handleClose}
sx={{
bgcolor: "white",
color: "black",
diff --git a/infra/staff/src/components/DisablePasskeys.tsx b/infra/staff/src/components/DisablePasskeys.tsx
index 53eef0fb87..4d5232b792 100644
--- a/infra/staff/src/components/DisablePasskeys.tsx
+++ b/infra/staff/src/components/DisablePasskeys.tsx
@@ -8,9 +8,12 @@ import {
Paper,
} from "@mui/material";
import React, { useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
-import type { DisablePasskeysProps, UserData } from "../types";
+import {
+ apiOrigin,
+ getCurrentAdminUserId,
+ requireToken,
+} from "../services/support";
+import type { DisablePasskeysProps } from "../types";
const DisablePasskeys: React.FC<DisablePasskeysProps> = ({
open,
@@ -22,48 +25,17 @@ const DisablePasskeys: React.FC<DisablePasskeysProps> = ({
const handleDisabling = async () => {
try {
setLoading(true);
- const email = getEmail();
- const token = getToken();
-
- if (!email) {
- throw new Error("Email not found");
- }
-
- if (!token) {
- throw new Error("Token not found");
- }
+ const token = requireToken();
+ const userId = await getCurrentAdminUserId();
- const encodedEmail = encodeURIComponent(email);
-
- // Fetch user data
- const userUrl = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const userResponse = await fetch(userUrl, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!userResponse.ok) {
- throw new Error("Failed to fetch user data");
- }
- const userData = (await userResponse.json()) as UserData;
- const userId = userData.subscription?.userID;
-
- if (!userId) {
- throw new Error("User ID not found");
- }
-
- // Disable passkeys action
const disablePasskeysUrl = `${apiOrigin}/admin/user/disable-passkeys`;
- const body = JSON.stringify({ userId });
const disablePasskeysResponse = await fetch(disablePasskeysUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Auth-Token": token,
},
- body: body,
+ body: JSON.stringify({ userId }),
});
if (!disablePasskeysResponse.ok) {
@@ -71,9 +43,8 @@ const DisablePasskeys: React.FC<DisablePasskeysProps> = ({
throw new Error(`Failed to disable passkeys: ${errorResponse}`);
}
- handleDisablePasskeys(); // Notify parent component of successful action
- handleClose(); // Close dialog on successful action
- console.log("Passkeys disabled successfully");
+ handleDisablePasskeys();
+ handleClose();
} catch (error) {
if (error instanceof Error) {
alert(error.message);
@@ -85,10 +56,6 @@ const DisablePasskeys: React.FC<DisablePasskeysProps> = ({
}
};
- const handleCancel = () => {
- handleClose(); // Close dialog
- };
-
return (
<div>
<Dialog
@@ -125,7 +92,7 @@ const DisablePasskeys: React.FC<DisablePasskeysProps> = ({
</DialogContent>
<DialogActions sx={{ justifyContent: "center" }}>
<Button
- onClick={handleCancel}
+ onClick={handleClose}
sx={{
bgcolor: "white",
color: "black",
diff --git a/infra/staff/src/components/FamilyComponentTable.tsx b/infra/staff/src/components/FamilyComponentTable.tsx
index 836ec74e37..9c3082561f 100644
--- a/infra/staff/src/components/FamilyComponentTable.tsx
+++ b/infra/staff/src/components/FamilyComponentTable.tsx
@@ -11,9 +11,8 @@ import {
} from "@mui/material";
import * as React from "react";
import { useEffect, useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
-import type { FamilyMember, UserData } from "../types";
+import { getCurrentAdminUser } from "../services/support";
+import type { FamilyMember } from "../types";
import { formatUsageToGB } from "../utils/";
import CloseFamily from "./CloseFamily";
@@ -26,22 +25,11 @@ const FamilyTableComponent: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
- const encodedEmail = encodeURIComponent(getEmail());
- const token = getToken();
- const url = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!response.ok) {
- throw new Error("Network response was not ok");
- }
- const userData = (await response.json()) as UserData; // Typecast to UserData interface
+ const userData = await getCurrentAdminUser<{
+ details?: { familyData?: { members?: FamilyMember[] } };
+ }>();
const members: FamilyMember[] =
- userData.details?.familyData.members ?? [];
+ userData.details?.familyData?.members ?? [];
setFamilyMembers(members);
} catch (error) {
console.error("Error fetching family data:", error);
@@ -64,11 +52,6 @@ const FamilyTableComponent: React.FC = () => {
setCloseFamilyOpen(false);
};
- const handleCloseFamily = () => {
- console.log("Close family action");
- handleOpenCloseFamily();
- };
-
if (loading) {
return <CircularProgress />;
}
@@ -153,7 +136,7 @@ const FamilyTableComponent: React.FC = () => {
<Button
variant="contained"
color="error"
- onClick={handleCloseFamily}
+ onClick={handleOpenCloseFamily}
>
Close Family
</Button>
diff --git a/infra/staff/src/components/StorageBonusTableComponent.tsx b/infra/staff/src/components/StorageBonusTableComponent.tsx
index f387c6a264..893f81e034 100644
--- a/infra/staff/src/components/StorageBonusTableComponent.tsx
+++ b/infra/staff/src/components/StorageBonusTableComponent.tsx
@@ -9,8 +9,7 @@ import {
} from "@mui/material";
import * as React from "react";
import { useEffect, useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import { getCurrentAdminUser } from "../services/support";
interface BonusData {
storage: number;
@@ -20,10 +19,6 @@ interface BonusData {
isRevoked: boolean;
}
-interface UserData {
- details: { bonusData: { storageBonuses: BonusData[] } };
-}
-
const StorageBonusTableComponent: React.FC = () => {
const [storageBonuses, setStorageBonuses] = useState<BonusData[]>([]);
const [loading, setLoading] = useState(true);
@@ -32,22 +27,11 @@ const StorageBonusTableComponent: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
- const encodedEmail = encodeURIComponent(getEmail());
- const token = getToken();
- const url = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!response.ok) {
- throw new Error("Failed to fetch bonus data");
- }
- const userData = (await response.json()) as UserData; // Typecast to UserData interface
+ const userData = await getCurrentAdminUser<{
+ details?: { bonusData?: { storageBonuses?: BonusData[] } };
+ }>();
const bonuses: BonusData[] =
- userData.details.bonusData.storageBonuses;
+ userData.details?.bonusData?.storageBonuses ?? [];
setStorageBonuses(bonuses);
} catch (error) {
console.error("Error fetching bonus data:", error);
diff --git a/infra/staff/src/components/ToggleEmailMFA.tsx b/infra/staff/src/components/ToggleEmailMFA.tsx
index aaa8c093a6..36457d9a97 100644
--- a/infra/staff/src/components/ToggleEmailMFA.tsx
+++ b/infra/staff/src/components/ToggleEmailMFA.tsx
@@ -8,9 +8,11 @@ import {
Paper,
} from "@mui/material";
import React, { useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
-import type { UserData } from "../types";
+import {
+ apiOrigin,
+ getCurrentAdminUserId,
+ requireToken,
+} from "../services/support";
interface ToggleEmailMFAProps {
open: boolean;
@@ -28,48 +30,17 @@ const ToggleEmailMFA: React.FC<ToggleEmailMFAProps> = ({
const handleToggle = async (enable: boolean) => {
try {
setLoading(true);
- const email = getEmail();
- const token = getToken();
-
- if (!email) {
- throw new Error("Email not found");
- }
-
- if (!token) {
- throw new Error("Token not found");
- }
+ const token = requireToken();
+ const userId = await getCurrentAdminUserId();
- const encodedEmail = encodeURIComponent(email);
-
- // Fetch user data
- const userUrl = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const userResponse = await fetch(userUrl, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!userResponse.ok) {
- throw new Error("Failed to fetch user data");
- }
- const userData = (await userResponse.json()) as UserData;
- const userId = userData.subscription?.userID;
-
- if (!userId) {
- throw new Error("User ID not found");
- }
-
- // Toggle Email MFA action
const toggleEmailMFAUrl = `${apiOrigin}/admin/user/update-email-mfa`;
- const body = JSON.stringify({ userID: userId, emailMFA: enable });
const toggleEmailMFAResponse = await fetch(toggleEmailMFAUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Auth-Token": token,
},
- body: body,
+ body: JSON.stringify({ userID: userId, emailMFA: enable }),
});
if (!toggleEmailMFAResponse.ok) {
@@ -77,11 +48,8 @@ const ToggleEmailMFA: React.FC<ToggleEmailMFAProps> = ({
throw new Error(`Failed to update Email MFA: ${errorResponse}`);
}
- handleToggleEmailMFA(enable); // Notify parent component of successful action with status
- handleClose(); // Close dialog on successful action
- console.log(
- `Email MFA ${enable ? "enabled" : "disabled"} successfully`,
- );
+ handleToggleEmailMFA(enable);
+ handleClose();
} catch (error) {
if (error instanceof Error) {
alert(error.message);
@@ -93,10 +61,6 @@ const ToggleEmailMFA: React.FC<ToggleEmailMFAProps> = ({
}
};
- const handleCancel = () => {
- handleClose(); // Close dialog
- };
-
return (
<div>
<Dialog
@@ -133,7 +97,7 @@ const ToggleEmailMFA: React.FC<ToggleEmailMFAProps> = ({
</DialogContent>
<DialogActions sx={{ justifyContent: "center" }}>
<Button
- onClick={handleCancel}
+ onClick={handleClose}
sx={{
bgcolor: "white",
color: "black",
diff --git a/infra/staff/src/components/TokenTableComponent.tsx b/infra/staff/src/components/TokenTableComponent.tsx
index bd1242270b..04a3a16b54 100644
--- a/infra/staff/src/components/TokenTableComponent.tsx
+++ b/infra/staff/src/components/TokenTableComponent.tsx
@@ -9,9 +9,8 @@ import {
TableSortLabel,
} from "@mui/material";
import * as React from "react";
-import { useEffect, useState } from "react";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import { useEffect, useMemo, useState } from "react";
+import { getCurrentAdminUser } from "../services/support";
interface TokenData {
creationTime: number;
@@ -21,10 +20,6 @@ interface TokenData {
app: string;
}
-interface UserData {
- tokens: TokenData[];
-}
-
const TokensTableComponent: React.FC = () => {
const [tokens, setTokens] = useState<TokenData[]>([]);
const [loading, setLoading] = useState(true);
@@ -35,21 +30,10 @@ const TokensTableComponent: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
- const encodedEmail = encodeURIComponent(getEmail());
- const token = getToken();
- const url = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- "X-Auth-Token": token,
- },
- });
- if (!response.ok) {
- throw new Error("Failed to fetch token data");
- }
- const userData = (await response.json()) as UserData;
- setTokens(userData.tokens);
+ const userData = await getCurrentAdminUser<{
+ tokens?: TokenData[];
+ }>();
+ setTokens(userData.tokens ?? []);
} catch (error) {
console.error("Error fetching token data:", error);
setError("No token data");
@@ -69,14 +53,18 @@ const TokensTableComponent: React.FC = () => {
setOrderBy(property);
};
- const sortedTokens = tokens.sort((a, b) => {
- if (orderBy === "lastUsedTime" || orderBy === "creationTime") {
- return order === "asc"
- ? a[orderBy] - b[orderBy]
- : b[orderBy] - a[orderBy];
- }
- return 0;
- });
+ const sortedTokens = useMemo(() => {
+ const sortableTokens = [...tokens];
+ sortableTokens.sort((a, b) => {
+ if (orderBy === "lastUsedTime" || orderBy === "creationTime") {
+ return order === "asc"
+ ? a[orderBy] - b[orderBy]
+ : b[orderBy] - a[orderBy];
+ }
+ return 0;
+ });
+ return sortableTokens;
+ }, [order, orderBy, tokens]);
const formatDate = (timestamp: number): string => {
const date = new Date(timestamp / 1000);
diff --git a/infra/staff/src/components/UpdateSubscription.tsx b/infra/staff/src/components/UpdateSubscription.tsx
index ebbdfba7b4..798c015ae7 100644
--- a/infra/staff/src/components/UpdateSubscription.tsx
+++ b/infra/staff/src/components/UpdateSubscription.tsx
@@ -13,8 +13,11 @@ import TextField from "@mui/material/TextField";
import React, { useEffect, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
-import { getEmail, getToken } from "../services/session";
-import { apiOrigin } from "../services/support";
+import {
+ apiOrigin,
+ getCurrentAdminUser,
+ requireToken,
+} from "../services/support";
interface Subscription {
productID: string;
paymentProvider: string;
@@ -63,18 +66,8 @@ const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({
useEffect(() => {
const fetchData = async () => {
try {
- const email = getEmail();
- const token = getToken();
- const encodedEmail = encodeURIComponent(email);
- const url = `${apiOrigin}/admin/user?email=${encodedEmail}`;
- const response = await fetch(url, {
- headers: { "X-AUTH-TOKEN": token },
- });
- if (!response.ok) {
- throw new Error("Network response was not ok");
- }
const userDataResponse =
- (await response.json()) as UserDataResponse;
+ await getCurrentAdminUser<UserDataResponse>();
if (!userDataResponse.subscription) {
throw new Error("Subscription data not found");
@@ -143,7 +136,7 @@ const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({
const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
event.preventDefault();
(async () => {
- const token = getToken();
+ const token = requireToken();
const url = `${apiOrigin}/admin/user/subscription`;
let expiryTime = null;
@@ -179,7 +172,6 @@ const UpdateSubscription: React.FC<UpdateSubscriptionProps> = ({
if (!response.ok) {
throw new Error("Network response was not ok");
}
- console.log("Subscription updated successfully");
onClose();
} catch (error) {
if (error instanceof Error) {
diff --git a/infra/staff/src/components/UserComponent.tsx b/infra/staff/src/components/UserComponent.tsx
index 82c21833ba..bf9b66b647 100644
--- a/infra/staff/src/components/UserComponent.tsx
+++ b/infra/staff/src/components/UserComponent.tsx
@@ -12,7 +12,7 @@ import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableRow from "@mui/material/TableRow";
import Typography from "@mui/material/Typography";
-import * as React from "react";
+import { useEffect, useState } from "react";
import type { UserComponentProps } from "../types";
import AddOtt from "./AddOtt";
import ChangeEmail from "./ChangeEmail";
@@ -22,20 +22,19 @@ import DisablePasskeys from "./DisablePasskeys";
import ToggleEmailMFA from "./ToggleEmailMFA";
import UpdateSubscription from "./UpdateSubscription";
-const UserComponent: React.FC<UserComponentProps> = ({ userData }) => {
- const [deleteAccountOpen, setDeleteAccountOpen] = React.useState(false);
- const [email2FAEnabled, setEmail2FAEnabled] = React.useState(false);
- const [email2FAOpen, setEmail2FAToggleOpen] = React.useState(false);
- const [disable2FAOpen, setDisable2FAOpen] = React.useState(false);
- const [twoFactorEnabled, setTwoFactorEnabled] = React.useState(false);
- const [canDisableEmailMFA, setCanDisableEmailMFA] = React.useState(false);
- const [updateSubscriptionOpen, setUpdateSubscriptionOpen] =
- React.useState(false);
- const [changeEmailOpen, setChangeEmailOpen] = React.useState(false);
- const [disablePasskeysOpen, setDisablePasskeysOpen] = React.useState(false);
- const [addOttOpen, setAddOttOpen] = React.useState(false);
+const UserComponent = ({ userData }: UserComponentProps) => {
+ const [deleteAccountOpen, setDeleteAccountOpen] = useState(false);
+ const [email2FAEnabled, setEmail2FAEnabled] = useState(false);
+ const [email2FAOpen, setEmail2FAToggleOpen] = useState(false);
+ const [disable2FAOpen, setDisable2FAOpen] = useState(false);
+ const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);
+ const [canDisableEmailMFA, setCanDisableEmailMFA] = useState(false);
+ const [updateSubscriptionOpen, setUpdateSubscriptionOpen] = useState(false);
+ const [changeEmailOpen, setChangeEmailOpen] = useState(false);
+ const [disablePasskeysOpen, setDisablePasskeysOpen] = useState(false);
+ const [addOttOpen, setAddOttOpen] = useState(false);
- React.useEffect(() => {
+ useEffect(() => {
setTwoFactorEnabled(userData?.security["Two factor 2FA"] === "Enabled");
setEmail2FAEnabled(userData?.security["Email MFA"] === "Enabled");
setCanDisableEmailMFA(
@@ -50,13 +49,19 @@ const UserComponent: React.FC<UserComponentProps> = ({ userData }) => {
if (!userData) return null;
+ const sections = [
+ { title: "user", data: userData.user },
+ { title: "storage", data: userData.storage },
+ { title: "subscription", data: userData.subscription },
+ { title: "security", data: userData.security },
+ ];
+
return (
<Grid container spacing={6} sx={{ justifyContent: "center" }}>
- {Object.entries(userData).map(([title, data]) => (
+ {sections.map(({ title, data }) => (
<Grid size={{ xs: 12, sm: 10, md: 6 }} key={title}>
<DataTable
title={title}
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data={data}
onEditEmail={handleEditEmail}
onDeleteAccount={handleDeleteAccountClick}
@@ -125,7 +130,7 @@ interface DataTableProps {
setEmail2FAToggleOpen: (open: boolean) => void;
}
-const DataTable: React.FC<DataTableProps> = ({
+const DataTable = ({
title,
data,
onEditEmail,
@@ -139,7 +144,7 @@ const DataTable: React.FC<DataTableProps> = ({
setDisable2FAOpen,
email2FAEnabled,
setEmail2FAToggleOpen,
-}) => (
+}: DataTableProps) => (
<TableContainer
component={Paper}
variant="outlined"
@@ -382,8 +387,7 @@ const renderTableCellContent = (
{canToggleEmailMFA && (
<Switch
checked={email2FAEnabled}
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- onChange={(_) => {
+ onChange={() => {
setEmail2FAToggleOpen(true);
}}
sx={{
diff --git a/infra/staff/src/services/support.ts b/infra/staff/src/services/support.ts
index e0b988739c..d53b2b5519 100644
--- a/infra/staff/src/services/support.ts
+++ b/infra/staff/src/services/support.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { getEmail, getToken } from "./session";
export const apiOrigin =
import.meta.env.VITE_ENTE_API_ORIGIN ?? "https://api.ente.io";
@@ -16,3 +17,35 @@ export const getUserDetails = async (
if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
return UserDetails.parse(await res.json());
};
+
+const requireEmail = () => {
+ const email = getEmail();
+ if (!email) throw new Error("Email not found");
+ return email;
+};
+
+export const requireToken = () => {
+ const token = getToken();
+ if (!token) throw new Error("Token not found");
+ return token;
+};
+
+export const getCurrentAdminUser = async <T>(): Promise<T> => {
+ const email = requireEmail();
+ const token = requireToken();
+ const url = `${apiOrigin}/admin/user?email=${encodeURIComponent(email)}`;
+ const response = await fetch(url, {
+ headers: { "Content-Type": "application/json", "X-Auth-Token": token },
+ });
+ if (!response.ok) throw new Error("Failed to fetch user data");
+ return (await response.json()) as T;
+};
+
+export const getCurrentAdminUserId = async () => {
+ const userData = await getCurrentAdminUser<{
+ subscription?: { userID?: string } | null;
+ }>();
+ const userId = userData.subscription?.userID;
+ if (!userId) throw new Error("User ID not found");
+ return userId;
+};
diff --git a/infra/staff/src/types/index.ts b/infra/staff/src/types/index.ts
index ae86fb73ea..4e66272f0e 100644
--- a/infra/staff/src/types/index.ts
+++ b/infra/staff/src/types/index.ts
@@ -1,5 +1,3 @@
-// Type related Users
-
export interface User {
ID: string;
email: string;
@@ -16,21 +14,18 @@ export interface UserResponse {
export interface UserData {
user: Record<string, string>;
storage: Record<string, string>;
- subscription?: Record<string, string>;
+ subscription: Record<string, string>;
security: Record<string, string>;
- details?: { familyData: { members: FamilyMember[] } };
}
export interface UserComponentProps {
userData: UserData | null;
}
-// Error Response Interface
export interface ErrorResponse {
message: string;
}
-// Types related to Subscriptions
export interface Subscription {
productID: string;
paymentProvider: string;
@@ -46,7 +41,6 @@ export interface Security {
canDisableEmailMFA: boolean;
}
-// Types related Family
export interface FamilyMember {
id: string;
email: string;
@@ -55,9 +49,8 @@ export interface FamilyMember {
storageLimit: number;
}
-// Types related to passkeys
export interface DisablePasskeysProps {
open: boolean;
handleClose: () => void;
- handleDisablePasskeys: () => void; // Callback to handle disabling passkeys
+ handleDisablePasskeys: () => void;
}