Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(Sidebar):session-termination-implemented

Aswin Asok175775dbd667
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 2ae9ac8127..2809f2631b 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -71,6 +71,7 @@ import {
import { DeleteAccount } from "ente-new/photos/components/DeleteAccount";
import { DropdownInput } from "ente-new/photos/components/DropdownInput";
import { MLSettings } from "ente-new/photos/components/sidebar/MLSettings";
+import { SessionsSettings } from "ente-new/photos/components/sidebar/SessionsSettings";
import { TwoFactorSettings } from "ente-new/photos/components/sidebar/TwoFactorSettings";
import { downloadAppDialogAttributes } from "ente-new/photos/components/utils/download";
import {
@@ -696,6 +697,8 @@ const Account: React.FC<AccountProps> = ({
useModalVisibility();
const { show: showTwoFactor, props: twoFactorVisibilityProps } =
useModalVisibility();
+ const { show: showSessions, props: sessionsVisibilityProps } =
+ useModalVisibility();
const { show: showDeleteAccount, props: deleteAccountVisibilityProps } =
useModalVisibility();
@@ -712,6 +715,11 @@ const Account: React.FC<AccountProps> = ({
await openAccountsManagePasskeysPage();
};
+ const handleActiveSessions = async () => {
+ await onAuthenticateUser();
+ showSessions();
+ };
+
return (
<TitledNestedSidebarDrawer
{...{ open, onClose }}
@@ -737,6 +745,11 @@ const Account: React.FC<AccountProps> = ({
/>
<RowButtonDivider />
<RowButton label={t("passkeys")} onClick={handlePasskeys} />
+ <RowButtonDivider />
+ <RowButton
+ label={t("active_sessions")}
+ onClick={handleActiveSessions}
+ />
</RowButtonGroup>
<RowButtonGroup>
<RowButton
@@ -765,6 +778,10 @@ const Account: React.FC<AccountProps> = ({
{...twoFactorVisibilityProps}
onRootClose={onRootClose}
/>
+ <SessionsSettings
+ {...sessionsVisibilityProps}
+ onRootClose={onRootClose}
+ />
<DeleteAccount
{...deleteAccountVisibilityProps}
{...{ onAuthenticateUser }}
diff --git a/web/packages/accounts/services/sessions.ts b/web/packages/accounts/services/sessions.ts
new file mode 100644
index 0000000000..5b252083f7
--- /dev/null
+++ b/web/packages/accounts/services/sessions.ts
@@ -0,0 +1,73 @@
+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
+import { apiURL } from "ente-base/origins";
+import { z } from "zod";
+
+/**
+ * Zod schema for an individual session returned by the API.
+ */
+const Session = z.object({
+ /**
+ * The session token.
+ */
+ token: z.string(),
+ /**
+ * The time (epoch microseconds) when the session was created.
+ */
+ creationTime: z.number(),
+ /**
+ * The IP address from which the session was created.
+ */
+ ip: z.string(),
+ /**
+ * The raw user agent string.
+ */
+ ua: z.string(),
+ /**
+ * A human-readable version of the user agent.
+ */
+ prettyUA: z.string(),
+ /**
+ * The time (epoch microseconds) when the session was last used.
+ */
+ lastUsedTime: z.number(),
+});
+
+/**
+ * TypeScript type for a session, derived from the Zod schema.
+ */
+export type Session = z.infer<typeof Session>;
+
+/**
+ * Zod schema for the sessions API response.
+ */
+const SessionsResponse = z.object({ sessions: z.array(Session) });
+
+/**
+ * Fetch all active sessions for the current user.
+ *
+ * @returns A promise that resolves to an array of {@link Session} objects,
+ * sorted by last used time (most recent first).
+ */
+export const getActiveSessions = async (): Promise<Session[]> => {
+ const res = await fetch(await apiURL("/users/sessions"), {
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+ const { sessions } = SessionsResponse.parse(await res.json());
+ // Sort by last used time, most recent first.
+ return sessions.sort((a, b) => b.lastUsedTime - a.lastUsedTime);
+};
+
+/**
+ * Terminate a specific session.
+ *
+ * @param token The token of the session to terminate.
+ */
+export const terminateSession = async (token: string): Promise<void> => {
+ const url = await apiURL("/users/session");
+ const res = await fetch(`${url}?token=${encodeURIComponent(token)}`, {
+ method: "DELETE",
+ headers: await authenticatedRequestHeaders(),
+ });
+ ensureOk(res);
+};
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index 60ce9e6000..1d1f0b39d1 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -161,6 +161,14 @@
"delete_account_multi_app_warning": "This will delete your Ente Auth, Ente Photos and Ente Locker account.",
"delete_account_manually_message": "<p>Please send an email to <a>{{emailID}}</a> from your registered email address.</p><p>Your request will be processed within 72 hours.</p>",
"change_email": "Change email",
+ "active_sessions": "Active sessions",
+ "active_sessions_hint": "These are the devices where you are currently logged in",
+ "this_device": "This device",
+ "terminate_session": "Terminate session",
+ "terminate_session_confirm_message": "This will log you out of the following device",
+ "terminate_session_confirm_message_self": "This will log you out of this device",
+ "terminate": "Terminate",
+ "terminate_session_failed": "Failed to terminate session",
"ok": "OK",
"success": "Success",
"error": "Error",
diff --git a/web/packages/new/photos/components/sidebar/SessionsSettings.tsx b/web/packages/new/photos/components/sidebar/SessionsSettings.tsx
new file mode 100644
index 0000000000..84cad77031
--- /dev/null
+++ b/web/packages/new/photos/components/sidebar/SessionsSettings.tsx
@@ -0,0 +1,223 @@
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import DevicesIcon from "@mui/icons-material/Devices";
+import { CircularProgress, Divider, Stack, Typography } from "@mui/material";
+import {
+ getActiveSessions,
+ terminateSession,
+ type Session,
+} from "ente-accounts/services/sessions";
+import { RowButton, RowButtonGroup } from "ente-base/components/RowButton";
+import {
+ TitledNestedSidebarDrawer,
+ type NestedSidebarDrawerVisibilityProps,
+} from "ente-base/components/mui/SidebarDrawer";
+import { useBaseContext } from "ente-base/context";
+import { formattedDateTime } from "ente-base/i18n-date";
+import log from "ente-base/log";
+import { savedAuthToken } from "ente-base/token";
+import { t } from "i18next";
+import { useCallback, useEffect, useState } from "react";
+
+export const SessionsSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
+ open,
+ onClose,
+ onRootClose,
+}) => {
+ const handleRootClose = () => {
+ onClose();
+ onRootClose();
+ };
+
+ return (
+ <TitledNestedSidebarDrawer
+ {...{ open, onClose }}
+ onRootClose={handleRootClose}
+ title={t("active_sessions")}
+ >
+ <SessionsSettingsContents />
+ </TitledNestedSidebarDrawer>
+ );
+};
+
+const SessionsSettingsContents: React.FC = () => {
+ const { logout, showMiniDialog } = useBaseContext();
+
+ const [sessions, setSessions] = useState<Session[] | undefined>(); // storing and displaying the current active sessions
+ const [currentToken, setCurrentToken] = useState<string | undefined>(); // to check whether isCurrentDevice
+ const [isLoading, setIsLoading] = useState(true); // to show loader on each session termination and inital load
+ const [error, setError] = useState<string | undefined>();
+
+ const fetchSessions = useCallback(async () => {
+ setIsLoading(true);
+ setError(undefined);
+ try {
+ const [activeSessions, token] = await Promise.all([
+ getActiveSessions(),
+ savedAuthToken(),
+ ]);
+ setSessions(activeSessions);
+ setCurrentToken(token ?? undefined);
+ } catch (e) {
+ log.error("Failed to fetch active sessions", e);
+ setError(t("generic_error"));
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void fetchSessions();
+ }, [fetchSessions]);
+
+ const handleTerminateSession = useCallback(
+ (session: Session) => {
+ const isCurrentDevice = session.token === currentToken;
+
+ showMiniDialog({
+ title: t("terminate_session"),
+ message: isCurrentDevice
+ ? t("terminate_session_confirm_message_self")
+ : t("terminate_session_confirm_message"),
+ continue: {
+ text: t("terminate"),
+ color: "critical",
+ action: async () => {
+ if (isCurrentDevice) {
+ logout();
+ } else {
+ try {
+ await terminateSession(session.token);
+ await fetchSessions();
+ } catch (e) {
+ log.error("Failed to terminate session", e);
+ showMiniDialog({
+ title: t("error"),
+ message: t("terminate_session_failed"),
+ });
+ }
+ }
+ },
+ },
+ });
+ },
+ [currentToken, fetchSessions, logout, showMiniDialog],
+ );
+
+ if (isLoading) {
+ return (
+ <Stack
+ sx={{
+ flex: 1,
+ alignItems: "center",
+ justifyContent: "center",
+ py: 4,
+ }}
+ >
+ <CircularProgress color="accent" />
+ </Stack>
+ );
+ }
+
+ if (error) {
+ return (
+ <Stack sx={{ px: 2, py: 2 }}>
+ <Typography
+ variant="small"
+ sx={{ color: "critical.main", textAlign: "center" }}
+ >
+ {error}
+ </Typography>
+ </Stack>
+ );
+ }
+
+ if (!sessions || sessions.length === 0) {
+ return (
+ <Stack sx={{ px: 2, py: 2 }}>
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted", textAlign: "center" }}
+ >
+ {t("nothing_here")}
+ </Typography>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack sx={{ px: 2, pb: "12px", gap: 2 }}>
+ <Typography variant="small" sx={{ px: 0, color: "text.faint" }}>
+ {t("active_sessions_hint")}
+ </Typography>
+ <RowButtonGroup>
+ {sessions.map((session, index) => (
+ <SessionRow
+ key={session.token}
+ session={session}
+ isCurrentDevice={session.token === currentToken}
+ onTerminate={() => handleTerminateSession(session)}
+ showDivider={index < sessions.length - 1}
+ />
+ ))}
+ </RowButtonGroup>
+ </Stack>
+ );
+};
+
+interface SessionRowProps {
+ session: Session;
+ isCurrentDevice: boolean;
+ onTerminate: () => void;
+ showDivider: boolean;
+}
+
+const SessionRow: React.FC<SessionRowProps> = ({
+ session,
+ isCurrentDevice,
+ onTerminate,
+ showDivider,
+}) => {
+ const lastUsedFormatted = formattedDateTime(session.lastUsedTime);
+
+ return (
+ <>
+ <RowButton
+ startIcon={<DevicesIcon />}
+ label={
+ <Stack sx={{ gap: 0.5, alignItems: "flex-start" }}>
+ <Typography
+ sx={{
+ fontWeight: isCurrentDevice ? "bold" : "medium",
+ color: isCurrentDevice
+ ? "accent.main"
+ : "text.base",
+ textAlign: "left",
+ }}
+ >
+ {isCurrentDevice
+ ? t("this_device")
+ : session.prettyUA}
+ </Typography>
+ {!isCurrentDevice && (
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted" }}
+ >
+ {session.ip}
+ </Typography>
+ )}
+ <Typography
+ variant="small"
+ sx={{ color: "text.faint" }}
+ >
+ {lastUsedFormatted}
+ </Typography>
+ </Stack>
+ }
+ endIcon={<ChevronRightIcon />}
+ onClick={onTerminate}
+ />
+ {showDivider && <Divider sx={{ opacity: 0.4 }} />}
+ </>
+ );
+};