회원가입

This commit is contained in:
2026-02-03 10:51:22 +09:00
parent 3058b93c66
commit 12182823b0
44 changed files with 9590 additions and 1 deletions

View File

@@ -0,0 +1,57 @@
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}`);
}

76
app/auth/confirm/route.ts Normal file
View File

@@ -0,0 +1,76 @@
import { createClient } from "@/utils/supabase/server";
import { AUTH_ERROR_MESSAGES } from "@/features/auth/constants";
import { type EmailOtpType } from "@supabase/supabase-js";
import { redirect } from "next/navigation";
import { type NextRequest } from "next/server";
// ========================================
// 상수 정의
// ========================================
/** 비밀번호 재설정 후 이동할 경로 */
const RESET_PASSWORD_PATH = "/reset-password";
/** 인증 실패 시 리다이렉트할 경로 */
const LOGIN_PATH = "/login";
// ========================================
// 라우트 핸들러
// ========================================
/**
* [이메일 인증 확인 라우트]
*
* Supabase 이메일 템플릿의 인증 링크를 처리합니다.
* - 회원가입 이메일 확인
* - 비밀번호 재설정
*
* @example Supabase 이메일 템플릿 형식
* {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=recovery
*/
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
// ========== 파라미터 추출 ==========
const tokenHash = searchParams.get("token_hash");
const type = searchParams.get("type") as EmailOtpType | null;
const rawNext = searchParams.get("next");
// 보안: 외부 URL 리다이렉트 방지 (상대 경로만 허용)
const nextPath = rawNext?.startsWith("/") ? rawNext : "/";
// ========== 토큰 검증 ==========
if (!tokenHash || !type) {
return redirectWithError(AUTH_ERROR_MESSAGES.INVALID_AUTH_LINK);
}
const supabase = await createClient();
const { error } = await supabase.auth.verifyOtp({
type,
token_hash: tokenHash,
});
if (error) {
console.error("[Auth Confirm] verifyOtp 실패:", error.message);
return redirectWithError(AUTH_ERROR_MESSAGES.INVALID_AUTH_LINK);
}
// ========== 검증 성공 - 적절한 페이지로 리다이렉트 ==========
if (type === "recovery") {
redirect(RESET_PASSWORD_PATH);
}
redirect(nextPath);
}
// ========================================
// 헬퍼 함수
// ========================================
/**
* 에러 메시지와 함께 로그인 페이지로 리다이렉트
*/
function redirectWithError(message: string): never {
const encodedMessage = encodeURIComponent(message);
redirect(`${LOGIN_PATH}?message=${encodedMessage}`);
}