summaryrefslogtreecommitdiff
path: root/frontend/lib/auth.ts
blob: 55255fc94ece021675413fb11a4bc344e5504e09 (plain)
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
import { cookies } from 'next/headers';
import { Env_is_development } from './env';
import type { UserSessionCookie, UserAuth } from './auth_types';


export async function Auth_extract_session_cookie(): Promise<UserSessionCookie | null> {
  const cookieStore = await cookies();
  for (const cookie of cookieStore.getAll()) {
    if (!cookie.name.includes("tinyauth-session"))
      continue;
    return {
      name: cookie.name,
      value: cookie.value,
    } as UserSessionCookie;
  }
  return null;
}

export async function Auth_get_user(): Promise<UserAuth> {
  // Development mode bypass for testing with AUTH header
  if (Env_is_development()) {
    const { headers } = await import('next/headers');
    const headersList = await headers();
    if (headersList.get('AUTH') === '1') {
      return {
        isLoggedIn: true,
        username: 'testuser',
        name: 'Test User',
        email: '[email protected]',
        provider: 'dev',
        oauth: false
      };
    }
  }

  const cookie = await Auth_extract_session_cookie();
  const { Auth_tinyauth_endpoint } = await import('./auth_shared');
  const endpoint = Auth_tinyauth_endpoint();

  try {
    const headers: Record<string, string> = {};
    if (cookie) {
      headers['Cookie'] = `${cookie.name}=${cookie.value}`;
    }

    const response = await fetch(`${endpoint}/api/user`, {
      method: 'GET',
      headers
    });

    if (!response.ok) {
      return {
        isLoggedIn: false,
        username: '',
        name: '',
        email: '',
        provider: '',
        oauth: false
      };
    }

    const data = await response.json();

    return {
      isLoggedIn: data.isLoggedIn || false,
      username: data.username || '',
      name: data.name || '',
      email: data.email || '',
      provider: data.provider || '',
      oauth: data.oauth || false
    };
  } catch (error) {
    console.error('Failed to fetch user:', error);
    return {
      isLoggedIn: false,
      username: '',
      name: '',
      email: '',
      provider: '',
      oauth: false
    };
  }
}