Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions public/images/auth/icon-github.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions public/images/auth/icon-google.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/auth/login-symbol.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions src/app/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/shared/lib/server';

export async function GET(request: NextRequest) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get('code');
const rawNext = searchParams.get('next') ?? '/workspaces';
let next = '/workspaces';
try {
const parsed = new URL(rawNext, origin);
if (parsed.origin === origin) next = parsed.pathname + parsed.search;
} catch {
// invalid URL, keep default
}

if (code) {
const supabase = await createClient();
const { data, error } = await supabase.auth.exchangeCodeForSession(code);

if (!error && data.user) {
if (!data.user.email) {
return NextResponse.redirect(`${origin}/login?error=email_missing`);
}
const meta = data.user.user_metadata ?? {};
const realName =
[meta.full_name, meta.name, meta.user_name].find((n) => n && n !== '-') ??
data.user.email.split('@')[0];

const { error: upsertError } = await supabase.from('profiles').upsert(
{
id: data.user.id,
email: data.user.email,
real_name: realName,
avatar_url: meta.avatar_url ?? null,
},
{ onConflict: 'id', ignoreDuplicates: true },
);

if (upsertError) {
return NextResponse.redirect(`${origin}/login?error=auth_failed`);
}

return NextResponse.redirect(`${origin}${next}`);
}
}

return NextResponse.redirect(`${origin}/login?error=auth_failed`);
}
10 changes: 10 additions & 0 deletions src/app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Suspense } from 'react';
import { LoginView } from '@/views/login';

export default function LoginPage() {
return (
<Suspense>
<LoginView />
</Suspense>
);
}
5 changes: 5 additions & 0 deletions src/app/signup/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SignupView } from '@/views/signup';

export default function SignupPage() {
return <SignupView />;
}
10 changes: 10 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { updateSession } from '@/shared/lib/middleware';
import { type NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
return await updateSession(request);
}

export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
};
23 changes: 16 additions & 7 deletions src/shared/lib/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { createServerClient } from '@supabase/ssr';
import { NextResponse, type NextRequest } from 'next/server';

const PUBLIC_PATHS = ['/', '/login', '/signup', '/auth'];
const AUTH_PAGES = ['/login', '/signup'];

export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
Expand Down Expand Up @@ -38,14 +41,20 @@ export async function updateSession(request: NextRequest) {
const { data } = await supabase.auth.getClaims();
const user = data?.claims;

if (
!user &&
!request.nextUrl.pathname.startsWith('/login') &&
!request.nextUrl.pathname.startsWith('/auth')
) {
// no user, potentially respond by redirecting the user to the login page
const isPublic = PUBLIC_PATHS.some(
(p) => request.nextUrl.pathname === p || request.nextUrl.pathname.startsWith(p + '/'),
);

if (!user && !isPublic) {
const url = request.nextUrl.clone();
url.pathname = '/login';
url.search = new URLSearchParams({ redirect: request.nextUrl.pathname }).toString();
return NextResponse.redirect(url);
}
Comment on lines +48 to +53

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

비로그인 리다이렉트 시 원래 목적지 보존 안 됨.

보호된 경로 접근 시 /login으로만 리다이렉트되고 원래 경로가 보존되지 않습니다. LoginView(다른 파일)가 로그인 성공 후 항상 /workspaces로 고정 이동한다면, 사용자는 원래 방문하려던 페이지로 돌아가지 못합니다. ?redirect= 쿼리 파라미터를 추가해 로그인 후 원래 경로로 복귀시키는 것을 고려해보세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/shared/lib/middleware.ts` around lines 46 - 50, Update the
unauthenticated redirect in the middleware condition `if (!user && !isPublic)`
to append the originally requested destination as a `redirect` query parameter
before returning `NextResponse.redirect`. Build it from the current request URL
so the login flow can restore the protected path, query string, and other
relevant destination details.


if (user && AUTH_PAGES.includes(request.nextUrl.pathname)) {
const url = request.nextUrl.clone();
url.pathname = '/auth/login';
url.pathname = '/workspaces';
return NextResponse.redirect(url);
}

Expand Down
37 changes: 37 additions & 0 deletions src/shared/lib/use-oauth-sign-in.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useState } from 'react';

import { createClient } from '@/shared/lib/client';

const OAUTH_ERROR_MAP: Record<string, string> = {
'Email rate limit exceeded': '잠시 후 다시 시도해주세요',
'too many requests': '잠시 후 다시 시도해주세요',
over_email_send_rate_limit: '잠시 후 다시 시도해주세요',
};

function toKoreanOAuthError(message: string): string {
const matched = Object.entries(OAUTH_ERROR_MAP).find(([key]) =>
message.toLowerCase().includes(key.toLowerCase()),
);
return matched ? matched[1] : '소셜 로그인 중 오류가 발생했어요. 다시 시도해주세요';
}

export function useOAuthSignIn() {
const supabase = createClient();
const [oauthError, setOauthError] = useState<string | null>(null);
const [oauthLoading, setOauthLoading] = useState(false);

const signInWithOAuth = async (provider: 'google' | 'github') => {
setOauthError(null);
setOauthLoading(true);
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: { redirectTo: `${window.location.origin}/auth/callback` },
});
if (error) {
setOauthError(toKoreanOAuthError(error.message));
setOauthLoading(false);
}
};

return { signInWithOAuth, oauthError, oauthLoading };
}
1 change: 1 addition & 0 deletions src/views/login/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as LoginView } from './ui/LoginView';
219 changes: 219 additions & 0 deletions src/views/login/ui/LoginView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { Eye, EyeOff, Loader2 } from 'lucide-react';

import { createClient } from '@/shared/lib/client';
import { useOAuthSignIn } from '@/shared/lib/use-oauth-sign-in';
import { Input } from '@/shared/ui/input';

const AUTH_ERROR_MAP: Record<string, string> = {
'Invalid login credentials': '이메일 또는 비밀번호가 올바르지 않아요',
'Email not confirmed': '이메일 인증이 필요해요. 메일함을 확인해주세요',
'User already registered': '이미 가입된 이메일이에요',
'Password should be at least 6 characters': '비밀번호는 6자 이상으로 입력해주세요',
'Unable to validate email address: invalid format': '올바른 이메일 형식이 아니에요',
'signup requires a valid password': '비밀번호를 입력해주세요',
'Email rate limit exceeded': '잠시 후 다시 시도해주세요',
over_email_send_rate_limit: '잠시 후 다시 시도해주세요',
'too many requests': '잠시 후 다시 시도해주세요',
};

function toKoreanError(message: string): string {
const matched = Object.entries(AUTH_ERROR_MAP).find(([key]) =>
message.toLowerCase().includes(key.toLowerCase()),
);
return matched ? matched[1] : '로그인 중 오류가 발생했어요. 다시 시도해주세요';
}

const CALLBACK_ERROR_MAP: Record<string, string> = {
auth_failed: '소셜 로그인에 실패했어요. 다시 시도해주세요',
session_exchange_failed: '인증 처리 중 오류가 발생했어요. 다시 시도해주세요',
email_missing: 'OAuth 계정에서 이메일 정보를 확인할 수 없어요. 다른 방법으로 로그인해 주세요',
};

const SAVED_EMAIL_KEY = 'syncly_saved_email';

export default function LoginView() {
const supabase = createClient();
const router = useRouter();
const searchParams = useSearchParams();
const callbackError = searchParams.get('error');
const [email, setEmail] = useState(() =>
typeof window !== 'undefined' ? (localStorage.getItem(SAVED_EMAIL_KEY) ?? '') : '',
);
const [password, setPassword] = useState('');
const [rememberEmail, setRememberEmail] = useState(() =>
typeof window !== 'undefined' ? !!localStorage.getItem(SAVED_EMAIL_KEY) : false,
);
Comment on lines +45 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

localStorage 기반 lazy 초기값이 하이드레이션 불일치를 유발할 수 있음.

LoginPageSuspense로 서버에서 프리렌더링되는 클라이언트 컴포넌트이므로, 최초 렌더(SSR)에서는 typeof window === 'undefined'가 되어 email='', rememberEmail=false로 렌더링됩니다. 클라이언트 하이드레이션 시점에는 window가 존재하므로 초기화 함수가 즉시 저장된 값을 반환해, 서버가 렌더링한 HTML과 클라이언트 첫 렌더 결과(controlled input의 value)가 달라져 React 하이드레이션 경고/불일치가 발생할 수 있습니다.

useEffect로 마운트 후 값을 채우는 방식으로 바꾸면 이 문제를 피할 수 있습니다.

🔧 하이드레이션 불일치 방지 수정안
-  const [email, setEmail] = useState(() =>
-    typeof window !== 'undefined' ? (localStorage.getItem(SAVED_EMAIL_KEY) ?? '') : '',
-  );
+  const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');
-  const [rememberEmail, setRememberEmail] = useState(() =>
-    typeof window !== 'undefined' ? !!localStorage.getItem(SAVED_EMAIL_KEY) : false,
-  );
+  const [rememberEmail, setRememberEmail] = useState(false);
+
+  useEffect(() => {
+    const saved = localStorage.getItem(SAVED_EMAIL_KEY);
+    if (saved) {
+      setEmail(saved);
+      setRememberEmail(true);
+    }
+  }, []);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [email, setEmail] = useState(() =>
typeof window !== 'undefined' ? (localStorage.getItem(SAVED_EMAIL_KEY) ?? '') : '',
);
const [password, setPassword] = useState('');
const [rememberEmail, setRememberEmail] = useState(() =>
typeof window !== 'undefined' ? !!localStorage.getItem(SAVED_EMAIL_KEY) : false,
);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [rememberEmail, setRememberEmail] = useState(false);
useEffect(() => {
const saved = localStorage.getItem(SAVED_EMAIL_KEY);
if (saved) {
setEmail(saved);
setRememberEmail(true);
}
}, []);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/views/login/ui/LoginView.tsx` around lines 43 - 49, Update the email and
rememberEmail state initialization in LoginPage to use SSR-safe empty defaults,
then read SAVED_EMAIL_KEY in a mount-time useEffect and populate both states
after hydration. Preserve the current password initialization and controlled
input behavior.

const [emailError, setEmailError] = useState<string | null>(null);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [error, setError] = useState<string | null>(
callbackError ? (CALLBACK_ERROR_MAP[callbackError] ?? '로그인 중 오류가 발생했어요') : null,
);
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);

const { signInWithOAuth, oauthError, oauthLoading } = useOAuthSignIn();

const signInWithEmail = async () => {
setEmailError(null);
setPasswordError(null);
setError(null);

if (!email) {
setEmailError('이메일을 입력해주세요');
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
setEmailError('올바른 이메일 형식이 아니에요');
return;
}
if (!password) {
setPasswordError('비밀번호를 입력해주세요');
return;
}

if (rememberEmail) {
localStorage.setItem(SAVED_EMAIL_KEY, email);
} else {
localStorage.removeItem(SAVED_EMAIL_KEY);
}

setLoading(true);
const { error } = await supabase.auth.signInWithPassword({ email, password });
if (error) {
setError(toKoreanError(error.message));
} else {
const redirect = searchParams.get('redirect');
router.push(redirect ?? '/workspaces');
}
setLoading(false);
};

return (
<div className="bg-brand-surface flex min-h-screen items-center justify-center px-4">
<div className="flex w-full max-w-[384px] flex-col items-stretch gap-5">
<div className="flex flex-col items-center gap-4">
<Image src="/images/auth/login-symbol.png" alt="Syncly" width={33} height={47} priority />
<div className="flex flex-col items-center gap-2">
<h1 className="text-brand-ink text-2xl font-bold">Syncly에 오신 걸 환영해요</h1>
<p className="text-brand-muted text-sm">소규모 팀을 위한 가벼운 협업 공간</p>
</div>
</div>

<div className="border-brand/10 flex flex-col gap-3 rounded-[16px] border bg-white p-6 shadow-sm">
<button
onClick={() => signInWithOAuth('google')}
disabled={loading || oauthLoading}
className="border-brand/10 text-brand-ink hover:bg-brand-surface flex h-11 w-full items-center gap-3 rounded-[18px] border px-5 text-sm font-semibold transition-colors disabled:pointer-events-none disabled:opacity-60"
>
<Image src="/images/auth/icon-google.svg" alt="" width={21} height={20} />
<span className="flex-1 text-center">Google로 계속하기</span>
</button>

<button
onClick={() => signInWithOAuth('github')}
disabled={loading || oauthLoading}
className="border-brand/10 text-brand-ink hover:bg-brand-surface flex h-11 w-full items-center gap-3 rounded-[18px] border px-5 text-sm font-semibold transition-colors disabled:pointer-events-none disabled:opacity-60"
>
<Image src="/images/auth/icon-github.svg" alt="" width={21} height={20} />
<span className="flex-1 text-center">GitHub로 계속하기</span>
</button>

{oauthError && <p className="px-1 text-sm text-red-500">{oauthError}</p>}

<div className="flex items-center gap-3 py-1">
<div className="bg-brand/10 h-px flex-1" />
<span className="text-brand-muted text-xs">또는</span>
<div className="bg-brand/10 h-px flex-1" />
</div>

<form
onSubmit={(e) => {
e.preventDefault();
signInWithEmail();
}}
noValidate
className="flex flex-col gap-3"
>
<div className="flex flex-col gap-1">
<Input
suppressHydrationWarning
type="email"
placeholder="이메일 주소"
value={email}
onChange={(e) => {
setEmail(e.target.value);
setEmailError(null);
}}
className={`bg-brand-secondary text-brand-ink placeholder:text-brand-ink/50 h-11 rounded-[18px] border-2 px-4 text-sm transition-colors focus-visible:ring-0 ${emailError ? 'border-red-400 focus-visible:border-red-400' : 'focus-visible:border-brand border-transparent'}`}
/>
{emailError && <p className="px-1 text-sm text-red-500">{emailError}</p>}
</div>
<div className="flex flex-col gap-1">
<div className="relative">
<Input
type={showPassword ? 'text' : 'password'}
placeholder="비밀번호"
value={password}
onChange={(e) => {
setPassword(e.target.value);
setPasswordError(null);
}}
className={`bg-brand-secondary text-brand-ink placeholder:text-brand-ink/50 h-11 w-full rounded-[18px] border-2 px-4 pr-11 text-sm transition-colors focus-visible:ring-0 ${passwordError ? 'border-red-400 focus-visible:border-red-400' : 'focus-visible:border-brand border-transparent'}`}
/>
<button
type="button"
onClick={() => setShowPassword((v) => !v)}
aria-label={showPassword ? '비밀번호 숨기기' : '비밀번호 보이기'}
className="text-brand-muted hover:text-brand-ink absolute top-1/2 right-3 -translate-y-1/2"
>
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
</button>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
</div>
{passwordError && <p className="px-1 text-sm text-red-500">{passwordError}</p>}
</div>

<label className="flex cursor-pointer items-center gap-2">
<input
type="checkbox"
checked={rememberEmail}
onChange={(e) => setRememberEmail(e.target.checked)}
className="accent-brand h-4 w-4"
/>
<span className="text-brand-muted text-sm">아이디 저장</span>
</label>

{error && <p className="px-1 text-sm text-red-500">{error}</p>}
<button
type="submit"
disabled={loading}
className="bg-brand hover:bg-brand/90 flex h-12 w-full items-center justify-center rounded-[18px] text-base font-semibold text-white transition-colors disabled:pointer-events-none disabled:opacity-60"
>
{loading ? <Loader2 size={18} className="animate-spin" /> : '로그인'}
</button>
</form>
</div>

<div className="flex items-center justify-between">
<Link
href="/"
className="text-brand-muted hover:text-brand-ink text-sm transition-colors"
>
← 홈으로
</Link>
<p className="text-brand-muted text-sm">
아직 회원이 아니신가요?{' '}
<Link href="/signup" className="text-brand font-semibold underline">
가입하기
</Link>
</p>
</div>
</div>
</div>
);
}
1 change: 1 addition & 0 deletions src/views/signup/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as SignupView } from './ui/SignupView';
Loading