58 lines
2.2 KiB
TypeScript
58 lines
2.2 KiB
TypeScript
|
|
import { createClient } from "@/utils/supabase/server";
|
||
|
|
import { NextResponse } from "next/server";
|
||
|
|
|
||
|
|
/**
|
||
|
|
* [인증 콜백 라우트 핸들러]
|
||
|
|
*
|
||
|
|
* Supabase 인증 이메일(회원가입 확인, 비밀번호 재설정 등)에서
|
||
|
|
* 리다이렉트될 때 호출되는 API 라우트입니다.
|
||
|
|
*
|
||
|
|
* PKCE(Proof Key for Code Exchange) 흐름:
|
||
|
|
* 1. 사용자가 이메일 링크 클릭
|
||
|
|
* 2. Supabase 서버가 토큰 검증 후 이 라우트로 `code` 파라미터와 함께 리다이렉트
|
||
|
|
* 3. 이 라우트에서 `code`를 세션으로 교환
|
||
|
|
* 4. 원래 목적지(next 파라미터)로 리다이렉트
|
||
|
|
*
|
||
|
|
* @param request - Next.js Request 객체
|
||
|
|
*/
|
||
|
|
export async function GET(request: Request) {
|
||
|
|
const { searchParams, origin } = new URL(request.url);
|
||
|
|
|
||
|
|
// 1. URL에서 code와 next(리다이렉트 목적지) 추출
|
||
|
|
const code = searchParams.get("code");
|
||
|
|
const next = searchParams.get("next") ?? "/";
|
||
|
|
|
||
|
|
// 2. code가 있으면 세션으로 교환
|
||
|
|
if (code) {
|
||
|
|
const supabase = await createClient();
|
||
|
|
const { error } = await supabase.auth.exchangeCodeForSession(code);
|
||
|
|
|
||
|
|
if (!error) {
|
||
|
|
// 3. 세션 교환 성공 - 원래 목적지로 리다이렉트
|
||
|
|
// next가 절대 URL(http://...)이면 그대로 사용, 아니면 origin + next
|
||
|
|
const forwardedHost = request.headers.get("x-forwarded-host"); // 프록시 환경 대응
|
||
|
|
const isLocalEnv = process.env.NODE_ENV === "development";
|
||
|
|
|
||
|
|
if (isLocalEnv) {
|
||
|
|
// 개발 환경: localhost 사용
|
||
|
|
return NextResponse.redirect(`${origin}${next}`);
|
||
|
|
} else if (forwardedHost) {
|
||
|
|
// 프로덕션 + 프록시: x-forwarded-host 사용
|
||
|
|
return NextResponse.redirect(`https://${forwardedHost}${next}`);
|
||
|
|
} else {
|
||
|
|
// 프로덕션: origin 사용
|
||
|
|
return NextResponse.redirect(`${origin}${next}`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 에러 발생 시 로그 출력
|
||
|
|
console.error("Auth callback error:", error.message);
|
||
|
|
}
|
||
|
|
|
||
|
|
// 4. code가 없거나 교환 실패 시 에러 페이지로 리다이렉트
|
||
|
|
const errorMessage = encodeURIComponent(
|
||
|
|
"인증 링크가 만료되었거나 유효하지 않습니다.",
|
||
|
|
);
|
||
|
|
return NextResponse.redirect(`${origin}/login?message=${errorMessage}`);
|
||
|
|
}
|