-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLoginForm.tsx
More file actions
173 lines (150 loc) · 4.8 KB
/
LoginForm.tsx
File metadata and controls
173 lines (150 loc) · 4.8 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
'use client';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { AuthErrorBanner } from '@/components/auth/AuthErrorBanner';
import { AuthProvidersBlock } from '@/components/auth/AuthProvidersBlock';
import { AuthShell } from '@/components/auth/AuthShell';
import { AuthSuccessBanner } from '@/components/auth/AuthSuccessBanner';
import { EmailField } from '@/components/auth/fields/EmailField';
import { PasswordField } from '@/components/auth/fields/PasswordField';
import { Button } from '@/components/ui/button';
import { Link } from '@/i18n/routing';
import { broadcastAuthUpdated } from '@/lib/auth-sync';
type LoginFormProps = {
locale: string;
returnTo: string;
};
export function LoginForm({ locale, returnTo }: LoginFormProps) {
const t = useTranslations('auth.login');
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [errorCode, setErrorCode] = useState<string | null>(null);
const [email, setEmail] = useState('');
const [verificationSent, setVerificationSent] = useState(false);
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
setErrorMessage(null);
setErrorCode(null);
setVerificationSent(false);
const formData = new FormData(e.currentTarget);
const emailValue = String(formData.get('email') || '');
setEmail(emailValue);
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: emailValue,
password: formData.get('password'),
}),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
setErrorCode(data?.code ?? null);
if (data?.code === 'EMAIL_NOT_VERIFIED') {
setErrorMessage(t('errors.emailNotVerified'));
} else {
setErrorMessage(t('errors.invalidCredentials'));
}
return;
}
broadcastAuthUpdated();
window.location.href = returnTo || `/${locale}/dashboard`;
} catch (err) {
console.error('Login request failed:', err);
setErrorMessage(t('errors.networkError'));
setErrorCode(null);
} finally {
setLoading(false);
}
}
async function resendVerification() {
if (!email) return;
try {
const res = await fetch('/api/auth/resend-verification', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
setErrorCode(data?.code ?? 'RESEND_FAILED');
setErrorMessage(data?.error ?? t('errors.resendFailed'));
return;
}
setVerificationSent(true);
setErrorCode(null);
setErrorMessage(null);
} catch (err) {
console.error('Resend verification failed:', err);
setErrorCode('NETWORK_ERROR');
setErrorMessage(t('errors.networkError'));
}
}
return (
<AuthShell
title={t('title')}
footer={
<p className="text-sm text-gray-600">
{t('noAccount')}{' '}
<Link
href={
returnTo
? `/signup?returnTo=${encodeURIComponent(returnTo)}`
: '/signup'
}
className="underline"
>
{t('signupLink')}
</Link>
</p>
}
>
<AuthProvidersBlock />
<form onSubmit={onSubmit} className="space-y-4">
<EmailField onChange={setEmail} />
<PasswordField />
<div className="text-right">
<Link
href={
returnTo
? `/forgot-password?returnTo=${encodeURIComponent(returnTo)}`
: '/forgot-password'
}
className="text-sm text-gray-600 underline"
>
{t('forgotPassword')}
</Link>
</div>
{errorMessage && !verificationSent && (
<AuthErrorBanner
message={errorMessage}
actionLabel={
errorCode === 'EMAIL_NOT_VERIFIED'
? t('resendVerification')
: undefined
}
onAction={
errorCode === 'EMAIL_NOT_VERIFIED'
? resendVerification
: undefined
}
/>
)}
{verificationSent && (
<AuthSuccessBanner
message={
<>
{t('verificationSent')} <strong>{email}</strong>
</>
}
/>
)}
<Button type="submit" disabled={loading} className="w-full">
{loading ? t('submitting') : t('submit')}
</Button>
</form>
</AuthShell>
);
}