-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsignup.tsx
More file actions
176 lines (155 loc) · 7.17 KB
/
Copy pathsignup.tsx
File metadata and controls
176 lines (155 loc) · 7.17 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
174
175
176
'use client'
import { useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { SimpleForm } from '@repo/ui/simple-form'
import { Button } from '@repo/ui/button'
import { ArrowRightCircle, Github } from 'lucide-react'
import { registerUser, type RegisterUser } from '@/lib/user'
import { recordLastLoginMethod } from '@/lib/auth/utils/last-login-method'
import { UserAuthProvider } from '@repo/codegen/src/schema'
import { GoogleIcon } from '@repo/ui/icons/google'
import { signIn } from 'next-auth/react'
import { Separator } from '@repo/ui/separator'
import { Input } from '@repo/ui/input'
import { PasswordInput } from '@repo/ui/password-input'
import Link from 'next/link'
import { allowedLoginDomains, recaptchaSiteKey } from '@repo/dally/auth'
import { loginStyles } from '../login/login.styles'
import { OPENLANE_WEBSITE_URL } from '@/constants'
import { cn } from '@repo/ui/lib/utils'
export const SignupPage = () => {
const searchParams = useSearchParams()
const token = searchParams?.get('token')
const router = useRouter()
const [registrationErrorMessage, setRegistrationErrorMessage] = useState('')
const [isLoading, setIsLoading] = useState<boolean>(false)
const [isPasswordActive, setIsPasswordActive] = useState(false)
const { separator, buttons, form, input } = loginStyles()
const showError = !isLoading && !!registrationErrorMessage
const github = async () => {
recordLastLoginMethod(UserAuthProvider.GITHUB)
await signIn('github', { redirectTo: '/' })
}
const google = async () => {
recordLastLoginMethod(UserAuthProvider.GOOGLE)
await signIn('google', {
redirect: true,
redirectTo: '/signup',
})
}
async function validateEmail(payload: RegisterUser) {
return allowedLoginDomains.length === 0 || allowedLoginDomains.some((domain) => payload.email.endsWith(domain))
}
return (
<div className="flex flex-col self-center text-center">
<p className="text-3xl font-medium">Create your account</p>
{!isPasswordActive && (
<div className="mt-2 text-center">
<span className="text-muted-foreground text-sm">Already have an account? </span>
<Link href={`/login${token ? `?token=${token}` : ''}`} className="text-sm hover:text-blue-500 hover:opacity-80 transition-color duration-500">
Login
</Link>
</div>
)}
<div className={cn(buttons(), 'mt-[32px]')}>
<Button className="!px-3.5 w-full" variant="secondary" size="md" icon={<GoogleIcon />} iconPosition="left" onClick={google}>
<p className="text-sm font-normal">Google</p>
</Button>
<Button className="!px-3.5 w-full" variant="secondary" size="md" icon={<Github className="text-input-text" />} iconPosition="left" onClick={github}>
<p className="text-sm font-normal">GitHub</p>
</Button>
</div>
<Separator label="or" login className={cn(separator(), 'text-muted-foreground')} />
<SimpleForm
classNames={form()}
onChange={(e: { email: string }) => setIsPasswordActive(e.email.length > 0)}
onSubmit={async (payload: RegisterUser) => {
setIsLoading(true)
setRegistrationErrorMessage('')
try {
if (recaptchaSiteKey) {
const recaptchaToken = await grecaptcha.execute(recaptchaSiteKey, { action: 'signup' })
const validation = await fetch('/api/recaptchaVerify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: recaptchaToken }),
})
const validationResult = await validation.json()
if (!validationResult.success) {
setRegistrationErrorMessage('reCAPTCHA validation failed.')
setIsLoading(false)
return
}
}
const isEmailValid = await validateEmail(payload)
if (!isEmailValid) {
router.push('/waitlist')
return
}
if (payload.password === payload.confirmedPassword) {
delete payload.confirmedPassword
if (token) {
payload.token = token
}
const res = await registerUser(payload)
if (res?.ok) {
recordLastLoginMethod(UserAuthProvider.CREDENTIALS)
}
if (res?.ok && token) {
router.push(`/login`)
} else if (res?.ok) {
router.push('/verify')
} else if (token && res?.message && /already exists/i.test(res.message)) {
// invitee already has an account, route to login carrying the invite
router.push(`/login?token=${token}&email=${encodeURIComponent(payload.email)}`)
} else if (res?.message) {
setRegistrationErrorMessage(res.message)
} else {
setRegistrationErrorMessage('Unknown error. Please try again.')
}
} else {
setRegistrationErrorMessage('Passwords do not match')
}
} catch (err) {
console.error('Signup error:', err)
setRegistrationErrorMessage('Unknown error. Please try again.')
} finally {
setIsLoading(false)
}
}}
>
<div className={input()}>
<div className="flex items-center gap-1">
<p className="text-sm">Email</p>
</div>
<Input type="email" variant="light" name="email" placeholder="Enter your email" className={`bg-transparent !text-text ${showError ? 'border border-toast-error-icon' : ''}`} />
{showError && <span className="text-xs text-toast-error-icon text-left">{registrationErrorMessage}</span>}
</div>
{isPasswordActive && (
<>
<div className={input()}>
<PasswordInput variant="light" name="password" placeholder="password" autoComplete="new-password" className="bg-transparent !text-text" />
</div>
<div className={input()}>
<PasswordInput variant="light" name="confirmedPassword" placeholder="confirm password" autoComplete="new-password" className="bg-transparent !text-text" />
</div>
<Button variant="primary" className="p-4 items-center justify-center rounded-md text-sm h-[36px] font-bold flex mt-2" type="submit" disabled={isLoading}>
<span>{isLoading ? 'Creating account...' : 'Sign up'}</span>
<ArrowRightCircle size={16} />
</Button>
</>
)}
</SimpleForm>
<div className="text-xs opacity-90 flex gap-1 mt-4 text-muted-foreground">
By signing up, you agree to our
<Link href={`${OPENLANE_WEBSITE_URL}/legal/terms-of-service`} className="text-xs underline hover:text-blue-500 hover:opacity-80 transition-colors duration-500">
Terms of Service
</Link>{' '}
and
<Link href={`${OPENLANE_WEBSITE_URL}/legal/privacy`} className="text-xs underline hover:text-blue-500 hover:opacity-80 transition-colors duration-500">
Privacy Policy
</Link>
</div>
</div>
)
}