This repository has no description
1import { ServerCookieAuthService } from '@/services/auth/CookieAuthService.server';
2import type { GetProfileResponse } from '@/api-client/ApiClient';
3
4const ENABLE_AUTH_LOGGING = true;
5
6type UserProfile = GetProfileResponse;
7
8export async function getServerAuthStatus(): Promise<{
9 isAuthenticated: boolean;
10 user: UserProfile | null;
11 error: string | null;
12}> {
13 try {
14 const { accessToken } = await ServerCookieAuthService.getTokens();
15
16 if (!accessToken || ServerCookieAuthService.isTokenExpired(accessToken)) {
17 if (ENABLE_AUTH_LOGGING) {
18 const reason = !accessToken
19 ? 'No access token'
20 : 'Access token expired';
21 console.log(`[serverAuth] Authentication failed: ${reason}`);
22 }
23 return {
24 isAuthenticated: false,
25 user: null,
26 error: 'No valid access token',
27 };
28 }
29
30 // Make direct API call with cookie header for server-side
31 const baseUrl =
32 process.env.NEXT_PUBLIC_API_BASE_URL || 'http://127.0.0.1:3000';
33 const response = await fetch(`${baseUrl}/api/users/me`, {
34 method: 'GET',
35 headers: {
36 'Content-Type': 'application/json',
37 Cookie: `accessToken=${accessToken}`,
38 },
39 cache: 'no-store',
40 });
41
42 if (!response.ok) {
43 if (ENABLE_AUTH_LOGGING) {
44 console.log(
45 `[serverAuth] Profile API request failed with status: ${response.status}`,
46 );
47 }
48 return {
49 isAuthenticated: false,
50 user: null,
51 error: `API request failed: ${response.status}`,
52 };
53 }
54
55 const user: UserProfile = await response.json();
56 if (ENABLE_AUTH_LOGGING) {
57 console.log(
58 `[serverAuth] Server-side authentication successful for user: ${user.handle} (${user.id})`,
59 );
60 }
61
62 return {
63 isAuthenticated: true,
64 user,
65 error: null,
66 };
67 } catch (error: any) {
68 if (ENABLE_AUTH_LOGGING) {
69 console.log(
70 `[serverAuth] Authentication error: ${error.message || 'Unknown error'}`,
71 );
72 }
73 return {
74 isAuthenticated: false,
75 user: null,
76 error: error.message || 'Authentication failed',
77 };
78 }
79}