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

92.42% Statements 61/66
82.14% Branches 46/56
100% Functions 13/13
98.27% Lines 57/58

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                            47x 46x 46x 45x       19x   18x 18x 18x 19x 19x 1x 1x       9x                 9x       36x 36x 36x   36x 36x   36x 36x 36x   36x 2x 2x 2x 2x 1x 1x   1x   2x       36x 2x 2x 2x 2x 1x 1x   1x   2x       36x 2x 2x 2x 2x 1x 1x   1x   2x       36x                     36x                                                                                 2x                   19x                                           2x                                               2x                   9x                                 2x                            
import { useState } from "react";
import { Link, useParams } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
 
import { Breadcrumb } from "../../components/ui/breadcrumb";
import { adminAuthApi } from "../../lib/api/admin-auth";
import { queryKeys } from "../../lib/query-keys";
import {
	useAdminUserSessions,
	useAdminUserAccounts,
} from "../../hooks/queries/useAdminQueries";
 
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 date.toLocaleString();
}
 
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 { 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;
		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;
		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;
		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-muted-foreground">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" },
				]}
			/>
 
			<div>
				<h1 className="text-xl font-semibold">User Security</h1>
				<p className="text-sm text-muted-foreground mt-1">
					Manage active sessions and linked accounts for this user.
				</p>
			</div>
 
			{/* ─── Active Sessions ──────────────────────────────────────────── */}
			<div className="rounded-lg border p-4 space-y-4">
				<div className="flex items-center justify-between">
					<div>
						<h2 className="text-base font-medium">Active Sessions</h2>
						<p className="text-sm text-muted-foreground">
							All currently active login sessions for this user.
						</p>
					</div>
					{sessions.length > 0 && (
						<button
							type="button"
							onClick={handleRevokeAll}
							disabled={revokingAll}
							className="text-sm text-destructive hover:underline disabled:opacity-50"
						>
							{revokingAll ? "Revoking..." : "Revoke All"}
						</button>
					)}
				</div>
 
				{sessionsLoading ? (
					<div className="space-y-3">
						{[1, 2].map((i) => (
							<div key={i} className="h-16 bg-muted rounded animate-pulse" />
						))}
					</div>
				) : sessions.length === 0 ? (
					<p className="text-sm text-muted-foreground py-4 text-center">
						No active sessions found.
					</p>
				) : (
					<ul className="space-y-3">
						{sessions.map((session) => (
							<li
								key={session.id}
								className="flex items-start justify-between gap-4 rounded-md border bg-muted/40 p-3"
							>
								<div className="flex-1 min-w-0 space-y-0.5">
									<p className="text-sm font-medium truncate">
										{parseUserAgent(session.userAgent)}
									</p>
									{session.ipAddress && (
										<p className="text-xs text-muted-foreground">
											IP: {session.ipAddress}
										</p>
									)}
									<p className="text-xs text-muted-foreground">
										Created: {formatDate(session.createdAt)}
									</p>
									<p className="text-xs text-muted-foreground">
										Expires: {formatDate(session.expiresAt)}
									</p>
								</div>
								<button
									type="button"
									onClick={() => handleRevokeSession(session.id)}
									disabled={revokingId === session.id}
									className="shrink-0 text-sm text-destructive hover:underline disabled:opacity-50"
								>
									{revokingId === session.id ? "Revoking..." : "Revoke"}
								</button>
							</li>
						))}
					</ul>
				)}
			</div>
 
			{/* ─── Linked Accounts ─────────────────────────────────────────── */}
			<div className="rounded-lg border p-4 space-y-4">
				<div>
					<h2 className="text-base font-medium">Linked Accounts</h2>
					<p className="text-sm text-muted-foreground">
						OAuth providers and authentication methods linked to this user.
					</p>
				</div>
 
				{accountsLoading ? (
					<div className="space-y-3">
						{[1, 2].map((i) => (
							<div key={i} className="h-14 bg-muted rounded animate-pulse" />
						))}
					</div>
				) : accounts.length === 0 ? (
					<p className="text-sm text-muted-foreground py-4 text-center">
						No linked accounts found.
					</p>
				) : (
					<ul className="space-y-3">
						{accounts.map((account) => (
							<li
								key={account.id}
								className="flex items-center justify-between gap-4 rounded-md border bg-muted/40 p-3"
							>
								<div className="space-y-0.5">
									<p className="text-sm font-medium">
										{formatProviderId(account.providerId)}
									</p>
									<p className="text-xs text-muted-foreground">
										Account ID: {account.accountId}
									</p>
									<p className="text-xs text-muted-foreground">
										Linked: {formatDate(account.createdAt)}
									</p>
								</div>
								<button
									type="button"
									onClick={() => handleUnlinkAccount(account.id)}
									disabled={unlinkingId === account.id}
									className="shrink-0 text-sm text-destructive hover:underline disabled:opacity-50"
								>
									{unlinkingId === account.id ? "Unlinking..." : "Unlink"}
								</button>
							</li>
						))}
					</ul>
				)}
			</div>
		</div>
	);
}