All files / src/pages/admin user-security.tsx

93.15% Statements 68/73
80.3% Branches 53/66
100% Functions 13/13
98.46% Lines 64/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318                                                72x 71x 71x 70x       29x   28x     28x 28x 29x 29x 1x 1x       14x                 14x       51x 51x 51x 51x   51x   51x     51x 51x 51x   51x 3x 3x                 1x   2x 2x 2x 1x 1x       1x       2x       51x 3x 3x                 1x   2x 2x 2x 1x 1x       1x       2x       51x 3x 3x                 1x   2x 2x 2x 1x 1x       1x       2x       51x                     51x                                                                               2x                       29x                                               3x                                                 2x                     14x                                     3x                                
import { useState } from "react";
import { Link, useParams } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
 
import { AdminBand, AdminPageHead } from "../../components/admin/AdminPageHead";
import { Breadcrumb } from "../../components/ui/breadcrumb";
import { Button } from "../../components/ui/button";
import { Card } from "../../components/ui/card";
import { formatDateTime } from "../../lib/utils";
import { adminAuthApi } from "../../lib/api/admin-auth";
import { queryKeys } from "../../lib/query-keys";
import { useConfirmDialog } from "../../hooks";
import {
	useAdminUserSessions,
	useAdminUserAccounts,
} from "../../hooks/queries/useAdminQueries";
 
/**
 * A session timestamp, with the two non-dates this page really does receive
 * spelled out. The formatting itself is `en-IN` from one place — the shared
 * `formatDateTime`, not a bare `toLocaleString()`.
 */
function formatDate(dateStr: string | null | undefined): string {
	if (!dateStr) return "\u2014";
	const date = new Date(dateStr);
	if (Number.isNaN(date.getTime())) return "Invalid date";
	return formatDateTime(date);
}
 
function parseUserAgent(ua: string | null): string {
	if (!ua) return "Unknown device";
	// Simple extraction: grab browser and OS hints
	const browserMatch = ua.match(
		/(Chrome|Firefox|Safari|Edge|Opera)[/\s][\d.]+/i,
	);
	const osMatch = ua.match(/\(([^)]+)\)/);
	const browser = browserMatch ? browserMatch[0] : null;
	const os = osMatch ? osMatch[1].split(";")[0].trim() : null;
	if (browser && os) return `${browser} on ${os}`;
	Iif (browser) return browser;
	return ua.substring(0, 80);
}
 
function formatProviderId(providerId: string): string {
	const map: Record<string, string> = {
		google: "Google",
		github: "GitHub",
		facebook: "Facebook",
		apple: "Apple",
		phone: "Phone (OTP)",
		email: "Email",
		credential: "Email / Password",
	};
	return map[providerId.toLowerCase()] ?? providerId;
}
 
export function AdminUserSecurityPage() {
	const params = useParams({ strict: false });
	const userId = (params as Record<string, string>).userId;
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
 
	const { data: sessions = [], isLoading: sessionsLoading } =
		useAdminUserSessions(userId ?? null);
	const { data: accounts = [], isLoading: accountsLoading } =
		useAdminUserAccounts(userId ?? null);
 
	const [revokingId, setRevokingId] = useState<string | null>(null);
	const [revokingAll, setRevokingAll] = useState(false);
	const [unlinkingId, setUnlinkingId] = useState<string | null>(null);
 
	const handleRevokeSession = async (sessionId: string) => {
		Iif (!userId) return;
		if (
			!(await confirm({
				title: "Revoke session",
				description:
					"Revoke this session? The user is signed out on that device immediately.",
				confirmLabel: "Revoke session",
				variant: "destructive",
			}))
		) {
			return;
		}
		setRevokingId(sessionId);
		try {
			await adminAuthApi.revokeSession(userId, sessionId);
			toast.success("Session revoked");
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.users.sessions(userId),
			});
		} catch (err) {
			toast.error(
				err instanceof Error ? err.message : "Failed to revoke session",
			);
		} finally {
			setRevokingId(null);
		}
	};
 
	const handleRevokeAll = async () => {
		Iif (!userId) return;
		if (
			!(await confirm({
				title: "Revoke all sessions",
				description:
					"Revoke every active session for this user? They are signed out on all devices immediately.",
				confirmLabel: "Revoke all sessions",
				variant: "destructive",
			}))
		) {
			return;
		}
		setRevokingAll(true);
		try {
			await adminAuthApi.revokeAllSessions(userId);
			toast.success("All sessions revoked");
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.users.sessions(userId),
			});
		} catch (err) {
			toast.error(
				err instanceof Error ? err.message : "Failed to revoke all sessions",
			);
		} finally {
			setRevokingAll(false);
		}
	};
 
	const handleUnlinkAccount = async (accountId: string) => {
		Iif (!userId) return;
		if (
			!(await confirm({
				title: "Unlink account",
				description:
					"Unlink this sign-in method? The user can no longer sign in with it, and this cannot be undone.",
				confirmLabel: "Unlink account",
				variant: "destructive",
			}))
		) {
			return;
		}
		setUnlinkingId(accountId);
		try {
			await adminAuthApi.unlinkAccount(userId, accountId);
			toast.success("Account unlinked");
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.users.accounts(userId),
			});
		} catch (err) {
			toast.error(
				err instanceof Error ? err.message : "Failed to unlink account",
			);
		} finally {
			setUnlinkingId(null);
		}
	};
 
	Iif (!userId) {
		return (
			<div className="text-center py-12">
				<p className="text-foreground-muted">User ID not found</p>
				<Link to="/admin/users" className="text-primary-600 hover:underline">
					Back to users
				</Link>
			</div>
		);
	}
 
	return (
		<div className="space-y-6">
			<Breadcrumb
				items={[
					{ label: "Users", href: "/admin/users" },
					{ label: userId, href: `/admin/users/${userId}` },
					{ label: "Security" },
				]}
			/>
 
			<AdminPageHead
				title="User Security"
				description="Manage active sessions and linked accounts for this user."
			/>
 
			{/* ─── Active Sessions ──────────────────────────────────────────── */}
			<section className="space-y-2">
				<AdminBand
					title="Active Sessions"
					count={sessionsLoading ? undefined : sessions.length}
					actions={
						sessions.length > 0 ? (
							<Button
								variant="outline"
								size="sm"
								onClick={handleRevokeAll}
								disabled={revokingAll}
							>
								{revokingAll ? "Revoking..." : "Revoke All"}
							</Button>
						) : undefined
					}
				/>
				<p className="text-sm text-foreground-muted">
					All currently active login sessions for this user.
				</p>
 
				{sessionsLoading ? (
					<div className="space-y-px">
						{[1, 2].map((i) => (
							<div key={i} className="h-14 animate-pulse bg-background-muted" />
						))}
					</div>
				) : sessions.length === 0 ? (
					<p className="py-4 text-center text-sm text-foreground-muted">
						No active sessions found.
					</p>
				) : (
					<Card className="overflow-hidden">
						<ul>
							{sessions.map((session) => (
								// Ruled rows that tint on hover — no boxed card per row.
								<li
									key={session.id}
									className="flex items-start justify-between gap-4 px-3.5 py-2.5 transition-colors hover:bg-foreground-default/7 [&+li]:border-t [&+li]:border-border-default"
								>
									<div className="min-w-0 flex-1 space-y-0.5">
										<p className="truncate text-sm font-medium text-foreground-default">
											{parseUserAgent(session.userAgent)}
										</p>
										{session.ipAddress && (
											<p className="text-xs tabular-nums text-foreground-muted">
												IP: {session.ipAddress}
											</p>
										)}
										<p className="text-xs tabular-nums text-foreground-muted">
											Created: {formatDate(session.createdAt)}
										</p>
										<p className="text-xs tabular-nums text-foreground-muted">
											Expires: {formatDate(session.expiresAt)}
										</p>
									</div>
									<Button
										variant="ghost"
										size="sm"
										className="shrink-0 text-error"
										onClick={() => handleRevokeSession(session.id)}
										disabled={revokingId === session.id}
									>
										{revokingId === session.id ? "Revoking..." : "Revoke"}
									</Button>
								</li>
							))}
						</ul>
					</Card>
				)}
			</section>
 
			{/* ─── Linked Accounts ─────────────────────────────────────────── */}
			<section className="space-y-2">
				<AdminBand
					title="Linked Accounts"
					count={accountsLoading ? undefined : accounts.length}
				/>
				<p className="text-sm text-foreground-muted">
					OAuth providers and authentication methods linked to this user.
				</p>
 
				{accountsLoading ? (
					<div className="space-y-px">
						{[1, 2].map((i) => (
							<div key={i} className="h-12 animate-pulse bg-background-muted" />
						))}
					</div>
				) : accounts.length === 0 ? (
					<p className="py-4 text-center text-sm text-foreground-muted">
						No linked accounts found.
					</p>
				) : (
					<Card className="overflow-hidden">
						<ul>
							{accounts.map((account) => (
								<li
									key={account.id}
									className="flex items-center justify-between gap-4 px-3.5 py-2.5 transition-colors hover:bg-foreground-default/7 [&+li]:border-t [&+li]:border-border-default"
								>
									<div className="min-w-0 space-y-0.5">
										<p className="text-sm font-medium text-foreground-default">
											{formatProviderId(account.providerId)}
										</p>
										<p className="text-xs font-mono text-foreground-muted">
											Account ID: {account.accountId}
										</p>
										<p className="text-xs tabular-nums text-foreground-muted">
											Linked: {formatDate(account.createdAt)}
										</p>
									</div>
									<Button
										variant="ghost"
										size="sm"
										className="shrink-0 text-error"
										onClick={() => handleUnlinkAccount(account.id)}
										disabled={unlinkingId === account.id}
									>
										{unlinkingId === account.id ? "Unlinking..." : "Unlink"}
									</Button>
								</li>
							))}
						</ul>
					</Card>
				)}
			</section>
 
			{confirmDialog}
		</div>
	);
}