File size: 2,518 Bytes
1a12d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Authentication hook β€” simple server-side OAuth.
 *
 * - Hors iframe: /auth/login redirect (cookies work fine)
 * - Dans iframe: show "Open in full page" link
 *
 * Token is stored via HttpOnly cookie by the backend.
 * In dev mode (no OAUTH_CLIENT_ID), auth is bypassed.
 * 
 * NOTE: This version supports separate frontend/backend hosting.
 */

import { useEffect } from 'react';
import { API_CONFIG } from '@/config/api';
import { useAgentStore } from '@/store/agentStore';
import { logger } from '@/utils/logger';

/** Check if we're running inside an iframe. */
export function isInIframe(): boolean {
  try {
    return window.top !== window.self;
  } catch {
    return true; // SecurityError = cross-origin iframe
  }
}

/** Redirect to the server-side OAuth login. */
export function triggerLogin(): void {
  window.location.href = API_CONFIG.getApiUrl('/auth/login');
}

/**
 * Hook: on mount, check if user is authenticated.
 * Sets user in the agent store.
 */
export function useAuth() {
  const setUser = useAgentStore((s) => s.setUser);

  useEffect(() => {
    let cancelled = false;

    async function checkAuth() {
      try {
        // Check if user is already authenticated (cookie-based)
        const response = await fetch(API_CONFIG.getApiUrl('/auth/me'), { 
          credentials: 'include' 
        });
        if (response.ok) {
          const data = await response.json();
          if (!cancelled && data.authenticated) {
            setUser({
              authenticated: true,
              username: data.username,
              name: data.name,
              picture: data.picture,
            });
            logger.log('Authenticated as', data.username);
            return;
          }
        }

        // Not authenticated β€” check if auth is enabled
        const statusRes = await fetch(API_CONFIG.getApiUrl('/auth/status'), { 
          credentials: 'include' 
        });
        const statusData = await statusRes.json();
        if (!statusData.auth_enabled) {
          // Dev mode β€” no OAuth configured
          if (!cancelled) setUser({ authenticated: true, username: 'dev' });
          return;
        }

        // Auth enabled but not logged in β€” welcome screen will handle it
        if (!cancelled) setUser(null);
      } catch {
        // Backend unreachable β€” assume dev mode
        if (!cancelled) setUser({ authenticated: true, username: 'dev' });
      }
    }

    checkAuth();
    return () => { cancelled = true; };
  }, [setUser]);
}