File size: 2,458 Bytes
ec1372e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
071f340
ad5892d
ec1372e
ad5892d
 
ec1372e
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
/**
 * Session management utilities
 * Centralizes authentication session handling for both client and server
 */

/**
 * Get credentials from browser localStorage (client-side only)
 * @returns {username, password} or null if not found
 */
export function getStoredCredentials(): { username: string; password: string } | null {
  if (typeof window === 'undefined') {
    return null; // Server-side rendering
  }

  const stored = localStorage.getItem('auth_credentials');
  if (!stored) {
    return null;
  }

  try {
    return JSON.parse(stored);
  } catch (error) {
    console.error('[Session] Failed to parse stored credentials:', error);
    localStorage.removeItem('auth_credentials');
    return null;
  }
}

/**
 * Store credentials in browser localStorage (client-side only)
 */
export function storeCredentials(username: string, password: string): void {
  if (typeof window === 'undefined') {
    return; // Server-side rendering
  }

  localStorage.setItem('auth_credentials', JSON.stringify({ username, password }));
}

/**
 * Clear stored credentials from browser localStorage (client-side only)
 */
export function clearStoredCredentials(): void {
  if (typeof window === 'undefined') {
    return; // Server-side rendering
  }

  localStorage.removeItem('auth_credentials');
}

/**
 * Generate Basic Auth header from credentials
 */
export function createBasicAuthHeader(username: string, password: string): string {
  return 'Basic ' + btoa(`${username}:${password}`);
}

/**
 * Parse Basic Auth header to extract credentials
 * @returns {username, password} or null if invalid
 */
export function parseBasicAuthHeader(authHeader: string): { username: string; password: string } | null {
  if (!authHeader || !authHeader.startsWith('Basic ')) {
    return null;
  }

  try {
    const base64Credentials = authHeader.slice(6); // Remove "Basic " prefix
    const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
    const [username, password] = credentials.split(':');

    if (!username || !password) {
      return null;
    }

    return { username, password };
  } catch (error) {
    console.error('[Session] Failed to parse auth header:', error);
    return null;
  }
}

/**
 * Get the user password from environment
 * Falls back to 'cz-2025' if not set
 */
export function getDefaultPassword(): string {
  return process.env.BASIC_AUTH_PASSWORD || process.env.NEXT_PUBLIC_DEFAULT_PASSWORD || 'cz-2025';
}