summaryrefslogtreecommitdiff
path: root/lib/auth/custom-signout.ts
blob: d59bd81ce6421eabc40cd0835565d6ce0445badc (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
/**
 * 커스텀 로그아웃 함수
 * NextAuth의 signOut이 NEXTAUTH_URL로 강제 리다이렉트하는 문제를 해결하기 위해 직접 구현
 */

interface CustomSignOutOptions {
  callbackUrl?: string;
  redirect?: boolean;
}

/**
 * 커스텀 로그아웃 함수
 * 
 * @param options - callbackUrl: 로그아웃 후 이동할 URL (기본: 현재 origin + "/")
 * @param options - redirect: 자동 리다이렉트 여부 (기본: true)
 */
export async function customSignOut(options?: CustomSignOutOptions): Promise<void> {
  const { callbackUrl, redirect = true } = options || {};
  
  try {
    // 1. CSRF 토큰 가져오기
    const csrfResponse = await fetch('/api/auth/csrf');
    const { csrfToken } = await csrfResponse.json();
    
    // 2. 서버에 로그아웃 요청
    await fetch('/api/auth/signout', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        csrfToken,
        json: 'true',
      }),
    });
    
    // 3. 리다이렉트
    if (redirect) {
      const finalUrl = callbackUrl || window.location.origin;
      window.location.href = finalUrl;
    }
  } catch (error) {
    console.error('Custom sign out error:', error);
    // 에러 발생 시에도 리다이렉트 (세션이 이미 만료되었을 수 있음)
    if (redirect) {
      const finalUrl = callbackUrl || window.location.origin;
      window.location.href = finalUrl;
    }
  }
}