feat: implement authentication UI components

- Add LoginForm component with email/password validation
- Add RegisterForm component with password confirmation
- Create login page at /auth/login
- Create register page at /auth/register
- Create authentication error page at /auth/error
- Add loading states and error handling
- Implement inline validation with user feedback
- Follow existing component patterns from ListForm

Implements task 6 from user-auth-and-sharing spec
Requirements: 1.1, 2.1
This commit is contained in:
2025-12-02 00:42:04 +00:00
parent 895ceba55f
commit d4a5232e71
5 changed files with 694 additions and 0 deletions

109
app/auth/error/page.tsx Normal file
View File

@@ -0,0 +1,109 @@
'use client'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { Suspense } from 'react'
function ErrorContent() {
const searchParams = useSearchParams()
const error = searchParams.get('error')
const getErrorMessage = (errorCode: string | null) => {
switch (errorCode) {
case 'Configuration':
return 'There is a problem with the server configuration.'
case 'AccessDenied':
return 'You do not have permission to sign in.'
case 'Verification':
return 'The verification token has expired or has already been used.'
case 'OAuthSignin':
return 'Error in constructing an authorization URL.'
case 'OAuthCallback':
return 'Error in handling the response from an OAuth provider.'
case 'OAuthCreateAccount':
return 'Could not create OAuth provider user in the database.'
case 'EmailCreateAccount':
return 'Could not create email provider user in the database.'
case 'Callback':
return 'Error in the OAuth callback handler route.'
case 'OAuthAccountNotLinked':
return 'Email on the account is already linked, but not with this OAuth account.'
case 'EmailSignin':
return 'Sending the email with the verification token failed.'
case 'CredentialsSignin':
return 'Invalid email or password. Please check your credentials and try again.'
case 'SessionRequired':
return 'Please sign in to access this page.'
default:
return 'An authentication error occurred. Please try again.'
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
<div className="max-w-md w-full space-y-8">
<div className="text-center">
<div className="mx-auto h-16 w-16 flex items-center justify-center rounded-full bg-red-100 mb-4">
<svg
className="h-8 w-8 text-red-600"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
/>
</svg>
</div>
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
Authentication Error
</h1>
<p className="text-sm sm:text-base text-gray-600 mb-8">
{getErrorMessage(error)}
</p>
</div>
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
<div className="space-y-4">
<Link
href="/auth/login"
className="block w-full px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors text-center font-medium text-sm sm:text-base"
>
Try Logging In Again
</Link>
<Link
href="/auth/register"
className="block w-full px-4 py-3 bg-gray-100 hover:bg-gray-200 active:bg-gray-300 text-gray-700 rounded-lg transition-colors text-center font-medium text-sm sm:text-base"
>
Create New Account
</Link>
</div>
{error && (
<div className="mt-6 p-4 bg-gray-50 rounded-lg">
<p className="text-xs text-gray-500">
Error code: <code className="font-mono">{error}</code>
</p>
</div>
)}
</div>
</div>
</div>
)
}
export default function AuthErrorPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-gray-600">Loading...</div>
</div>
}>
<ErrorContent />
</Suspense>
)
}

53
app/auth/login/page.tsx Normal file
View File

@@ -0,0 +1,53 @@
import Link from 'next/link'
import LoginForm from '@/components/LoginForm'
import { Suspense } from 'react'
export const metadata = {
title: 'Login - Ultimate Lists',
description: 'Log in to your Ultimate Lists account',
}
function LoginContent() {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
<div className="max-w-md w-full space-y-8">
<div className="text-center">
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
Welcome Back
</h1>
<p className="text-sm sm:text-base text-gray-600">
Log in to access your lists
</p>
</div>
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
<LoginForm />
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
Don't have an account?{' '}
<Link
href="/auth/register"
className="font-medium text-blue-600 hover:text-blue-500 transition-colors"
>
Sign up
</Link>
</p>
</div>
</div>
</div>
</div>
)
}
export default function LoginPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-gray-600">Loading...</div>
</div>
}>
<LoginContent />
</Suspense>
)
}

View File

@@ -0,0 +1,53 @@
import Link from 'next/link'
import RegisterForm from '@/components/RegisterForm'
import { Suspense } from 'react'
export const metadata = {
title: 'Register - Ultimate Lists',
description: 'Create your Ultimate Lists account',
}
function RegisterContent() {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
<div className="max-w-md w-full space-y-8">
<div className="text-center">
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
Create Account
</h1>
<p className="text-sm sm:text-base text-gray-600">
Sign up to start organizing your tasks
</p>
</div>
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
<RegisterForm />
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
Already have an account?{' '}
<Link
href="/auth/login"
className="font-medium text-blue-600 hover:text-blue-500 transition-colors"
>
Log in
</Link>
</p>
</div>
</div>
</div>
</div>
)
}
export default function RegisterPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-gray-600">Loading...</div>
</div>
}>
<RegisterContent />
</Suspense>
)
}

179
components/LoginForm.tsx Normal file
View File

@@ -0,0 +1,179 @@
'use client'
import { useState, useEffect } from 'react'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { validateEmail, validatePassword } from '@/lib/validation'
import { useToast } from './ToastContainer'
interface LoginFormProps {
callbackUrl?: string
}
export default function LoginForm({ callbackUrl = '/' }: LoginFormProps) {
const router = useRouter()
const { showToast } = useToast()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [errors, setErrors] = useState<{ email?: string; password?: string }>({})
const [touched, setTouched] = useState<{ email: boolean; password: boolean }>({
email: false,
password: false,
})
// Inline validation when fields change
useEffect(() => {
if (touched.email) {
const result = validateEmail(email)
setErrors((prev) => ({
...prev,
email: result.isValid ? undefined : result.error,
}))
}
}, [email, touched.email])
useEffect(() => {
if (touched.password) {
const result = validatePassword(password)
setErrors((prev) => ({
...prev,
password: result.isValid ? undefined : result.error,
}))
}
}, [password, touched.password])
const handleEmailBlur = () => {
setTouched((prev) => ({ ...prev, email: true }))
const result = validateEmail(email)
setErrors((prev) => ({
...prev,
email: result.isValid ? undefined : result.error,
}))
}
const handlePasswordBlur = () => {
setTouched((prev) => ({ ...prev, password: true }))
const result = validatePassword(password)
setErrors((prev) => ({
...prev,
password: result.isValid ? undefined : result.error,
}))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Validate all fields before submission
const emailResult = validateEmail(email)
const passwordResult = validatePassword(password)
const newErrors: { email?: string; password?: string } = {}
if (!emailResult.isValid) {
newErrors.email = emailResult.error
}
if (!passwordResult.isValid) {
newErrors.password = passwordResult.error
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors)
setTouched({ email: true, password: true })
return
}
setIsSubmitting(true)
setErrors({})
try {
const result = await signIn('credentials', {
email: email.trim(),
password,
redirect: false,
})
if (result?.error) {
showToast('Invalid email or password', 'error')
setErrors({ email: 'Invalid credentials', password: 'Invalid credentials' })
} else if (result?.ok) {
showToast('Login successful', 'success')
router.push(callbackUrl)
router.refresh()
}
} catch (err) {
console.error('Login error:', err)
showToast('An error occurred. Please try again.', 'error')
} finally {
setIsSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
Email *
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={handleEmailBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.email && touched.email
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter your email"
disabled={isSubmitting}
autoComplete="email"
autoFocus
aria-invalid={errors.email && touched.email ? 'true' : 'false'}
aria-describedby={errors.email && touched.email ? 'email-error' : undefined}
/>
{errors.email && touched.email && (
<p id="email-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.email}
</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
Password *
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onBlur={handlePasswordBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.password && touched.password
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter your password"
disabled={isSubmitting}
autoComplete="current-password"
aria-invalid={errors.password && touched.password ? 'true' : 'false'}
aria-describedby={errors.password && touched.password ? 'password-error' : undefined}
/>
{errors.password && touched.password && (
<p id="password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.password}
</p>
)}
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full px-4 sm:px-5 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
>
{isSubmitting ? 'Logging in...' : 'Log In'}
</button>
</form>
)
}

300
components/RegisterForm.tsx Normal file
View File

@@ -0,0 +1,300 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { validateEmail, validatePassword, sanitizeString } from '@/lib/validation'
import { registerUser } from '@/lib/auth-actions'
import { useToast } from './ToastContainer'
interface RegisterFormProps {
callbackUrl?: string
}
export default function RegisterForm({ callbackUrl = '/' }: RegisterFormProps) {
const router = useRouter()
const { showToast } = useToast()
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [errors, setErrors] = useState<{
name?: string
email?: string
password?: string
confirmPassword?: string
}>({})
const [touched, setTouched] = useState<{
name: boolean
email: boolean
password: boolean
confirmPassword: boolean
}>({
name: false,
email: false,
password: false,
confirmPassword: false,
})
// Inline validation when fields change
useEffect(() => {
if (touched.name) {
const sanitized = sanitizeString(name)
if (!sanitized) {
setErrors((prev) => ({ ...prev, name: 'Name is required' }))
} else if (sanitized.length > 100) {
setErrors((prev) => ({ ...prev, name: 'Name must be less than 100 characters' }))
} else {
setErrors((prev) => ({ ...prev, name: undefined }))
}
}
}, [name, touched.name])
useEffect(() => {
if (touched.email) {
const result = validateEmail(email)
setErrors((prev) => ({
...prev,
email: result.isValid ? undefined : result.error,
}))
}
}, [email, touched.email])
useEffect(() => {
if (touched.password) {
const result = validatePassword(password)
setErrors((prev) => ({
...prev,
password: result.isValid ? undefined : result.error,
}))
}
}, [password, touched.password])
useEffect(() => {
if (touched.confirmPassword) {
if (!confirmPassword) {
setErrors((prev) => ({ ...prev, confirmPassword: 'Please confirm your password' }))
} else if (password !== confirmPassword) {
setErrors((prev) => ({ ...prev, confirmPassword: 'Passwords do not match' }))
} else {
setErrors((prev) => ({ ...prev, confirmPassword: undefined }))
}
}
}, [confirmPassword, password, touched.confirmPassword])
const handleNameBlur = () => {
setTouched((prev) => ({ ...prev, name: true }))
}
const handleEmailBlur = () => {
setTouched((prev) => ({ ...prev, email: true }))
}
const handlePasswordBlur = () => {
setTouched((prev) => ({ ...prev, password: true }))
}
const handleConfirmPasswordBlur = () => {
setTouched((prev) => ({ ...prev, confirmPassword: true }))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Validate all fields before submission
const sanitizedName = sanitizeString(name)
const emailResult = validateEmail(email)
const passwordResult = validatePassword(password)
const newErrors: {
name?: string
email?: string
password?: string
confirmPassword?: string
} = {}
if (!sanitizedName) {
newErrors.name = 'Name is required'
} else if (sanitizedName.length > 100) {
newErrors.name = 'Name must be less than 100 characters'
}
if (!emailResult.isValid) {
newErrors.email = emailResult.error
}
if (!passwordResult.isValid) {
newErrors.password = passwordResult.error
}
if (!confirmPassword) {
newErrors.confirmPassword = 'Please confirm your password'
} else if (password !== confirmPassword) {
newErrors.confirmPassword = 'Passwords do not match'
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors)
setTouched({ name: true, email: true, password: true, confirmPassword: true })
return
}
setIsSubmitting(true)
setErrors({})
try {
const result = await registerUser(email.trim(), password, sanitizedName)
if (!result.success) {
if (result.error === 'Email already exists') {
setErrors({ email: 'This email is already registered' })
showToast('Email already exists', 'error')
} else {
showToast(result.error || 'Registration failed', 'error')
}
} else {
showToast('Registration successful! Logging you in...', 'success')
router.push(callbackUrl)
router.refresh()
}
} catch (err) {
console.error('Registration error:', err)
showToast('An error occurred. Please try again.', 'error')
} finally {
setIsSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
Name *
</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={handleNameBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.name && touched.name
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter your name"
disabled={isSubmitting}
autoComplete="name"
autoFocus
maxLength={100}
aria-invalid={errors.name && touched.name ? 'true' : 'false'}
aria-describedby={errors.name && touched.name ? 'name-error' : undefined}
/>
{errors.name && touched.name && (
<p id="name-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.name}
</p>
)}
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
Email *
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={handleEmailBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.email && touched.email
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter your email"
disabled={isSubmitting}
autoComplete="email"
aria-invalid={errors.email && touched.email ? 'true' : 'false'}
aria-describedby={errors.email && touched.email ? 'email-error' : undefined}
/>
{errors.email && touched.email && (
<p id="email-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.email}
</p>
)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
Password *
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onBlur={handlePasswordBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.password && touched.password
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="At least 8 characters"
disabled={isSubmitting}
autoComplete="new-password"
aria-invalid={errors.password && touched.password ? 'true' : 'false'}
aria-describedby={errors.password && touched.password ? 'password-error' : undefined}
/>
{errors.password && touched.password && (
<p id="password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.password}
</p>
)}
{!errors.password && touched.password && (
<p className="mt-1.5 text-xs sm:text-sm text-gray-500">
Password must be at least 8 characters
</p>
)}
</div>
<div>
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-2">
Confirm Password *
</label>
<input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
onBlur={handleConfirmPasswordBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
errors.confirmPassword && touched.confirmPassword
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Re-enter your password"
disabled={isSubmitting}
autoComplete="new-password"
aria-invalid={errors.confirmPassword && touched.confirmPassword ? 'true' : 'false'}
aria-describedby={
errors.confirmPassword && touched.confirmPassword ? 'confirm-password-error' : undefined
}
/>
{errors.confirmPassword && touched.confirmPassword && (
<p id="confirm-password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.confirmPassword}
</p>
)}
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full px-4 sm:px-5 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
>
{isSubmitting ? 'Creating account...' : 'Create Account'}
</button>
</form>
)
}