All files / src/components/features/account/SessionManager index.tsx

0% Statements 0/273
100% Branches 0/0
0% Functions 0/1
0% Lines 0/273

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
"use client";

import { useState, useEffect, useCallback } from "react";
import { Icon, IconName } from "@/components/ui/icons/Icon";

interface Session {
  id: string;
  browser: string;
  os: string;
  device: string;
  ipAddress: string | null;
  lastActive: Date | null;
  expires: Date;
  isCurrent: boolean;
}

export function SessionManager() {
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [revoking, setRevoking] = useState<string | null>(null);
  const [revokingAll, setRevokingAll] = useState(false);

  const fetchSessions = useCallback(async () => {
    try {
      const response = await fetch("/api/user/sessions");
      if (!response.ok) throw new Error("Failed to fetch sessions");
      const result = await response.json();
      setSessions(result.data.sessions);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSessions();
  }, [fetchSessions]);

  async function handleRevokeSession(sessionToken: string) {
    if (!confirm("Are you sure you want to revoke this session?")) return;

    setRevoking(sessionToken);
    try {
      const response = await fetch("/api/user/sessions", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sessionToken }),
      });
      if (!response.ok) throw new Error("Failed to revoke session");
      fetchSessions();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to revoke session");
    } finally {
      setRevoking(null);
    }
  }

  async function handleRevokeAll() {
    if (
      !confirm(
        "Are you sure you want to sign out of all other devices? You will remain signed in on this device."
      )
    )
      return;

    setRevokingAll(true);
    try {
      const response = await fetch("/api/user/sessions", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ revokeAll: true }),
      });
      if (!response.ok) throw new Error("Failed to revoke sessions");
      fetchSessions();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to revoke sessions"
      );
    } finally {
      setRevokingAll(false);
    }
  }

  const getDeviceIcon = (device: string): IconName => {
    switch (device.toLowerCase()) {
      case "mobile":
        return "phone";
      case "tablet":
        return "dashboard";
      default:
        return "dashboard";
    }
  };

  const formatLastActive = (date: Date | null) => {
    if (!date) return "Unknown";
    const d = new Date(date);
    const now = new Date();
    const diff = now.getTime() - d.getTime();

    if (diff < 60000) return "Just now";
    if (diff < 3600000) return `${Math.floor(diff / 60000)} minutes ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)} hours ago`;
    return d.toLocaleDateString();
  };

  if (loading) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/3" />
          <div className="space-y-3">
            {[...Array(3)].map((_, i) => (
              <div
                key={i}
                className="h-16 bg-gray-200 dark:bg-gray-700 rounded"
              />
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-700 dark:text-red-400">{error}</p>
          <button
            onClick={() => {
              setError(null);
              fetchSessions();
            }}
            className="mt-2 text-sm text-red-600 dark:text-red-400 hover:underline"
          >
            Try again
          </button>
        </div>
      </div>
    );
  }

  const otherSessions = sessions.filter((s) => !s.isCurrent);

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            Active Sessions
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Manage your active sessions across devices
          </p>
        </div>
        {otherSessions.length > 0 && (
          <button
            onClick={handleRevokeAll}
            disabled={revokingAll}
            className="flex items-center gap-2 px-4 py-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
          >
            {revokingAll ? (
              <>
                <div className="animate-spin h-4 w-4 border-2 border-red-600 dark:border-red-400 border-t-transparent rounded-full" />
                Signing out...
              </>
            ) : (
              <>
                <Icon name="logout" size={18} />
                Sign out all other devices
              </>
            )}
          </button>
        )}
      </div>

      <div className="space-y-3">
        {sessions.map((session) => (
          <div
            key={session.id}
            className={`p-4 rounded-lg border ${
              session.isCurrent
                ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"
                : "bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-700"
            }`}
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div
                  className={`p-2 rounded-lg ${
                    session.isCurrent
                      ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"
                      : "bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-400"
                  }`}
                >
                  <Icon name={getDeviceIcon(session.device)} size={24} />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <p className="font-medium text-gray-900 dark:text-gray-100">
                      {session.browser} on {session.os}
                    </p>
                    {session.isCurrent && (
                      <span className="px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded-full">
                        Current
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-3 mt-1 text-sm text-gray-500 dark:text-gray-400">
                    {session.ipAddress && (
                      <span className="flex items-center gap-1">
                        <Icon name="map-pin" size={14} />
                        {session.ipAddress}
                      </span>
                    )}
                    <span className="flex items-center gap-1">
                      <Icon name="clock" size={14} />
                      {formatLastActive(session.lastActive)}
                    </span>
                  </div>
                </div>
              </div>
              {!session.isCurrent && (
                <button
                  onClick={() =>
                    handleRevokeSession(
                      sessions.find((s) => s.id === session.id)?.id || ""
                    )
                  }
                  disabled={revoking === session.id}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
                >
                  {revoking === session.id ? (
                    <div className="animate-spin h-4 w-4 border-2 border-red-600 dark:border-red-400 border-t-transparent rounded-full" />
                  ) : (
                    <Icon name="logout" size={16} />
                  )}
                  Sign out
                </button>
              )}
            </div>
          </div>
        ))}

        {sessions.length === 0 && (
          <div className="text-center py-8">
            <Icon
              name="shield-check"
              size={48}
              className="mx-auto text-gray-400 dark:text-gray-500"
            />
            <p className="mt-2 text-gray-500 dark:text-gray-400">
              No active sessions found
            </p>
          </div>
        )}
      </div>

      <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
        <p className="text-xs text-gray-500 dark:text-gray-400">
          Sessions automatically expire after 24 hours of inactivity. If you
          notice any suspicious activity, sign out of all devices and change
          your password immediately.
        </p>
      </div>
    </div>
  );
}

export default SessionManager;