80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
// components/auth/login-form.tsx
|
|
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import Link from 'next/link'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/field'
|
|
|
|
export function LoginForm() {
|
|
const [email, setEmail] = useState('')
|
|
const [password, setPassword] = useState('')
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [loading, setLoading] = useState(false)
|
|
const router = useRouter()
|
|
|
|
async function handleSubmit(e: React.FormEvent) {
|
|
e.preventDefault()
|
|
setLoading(true)
|
|
setError(null)
|
|
|
|
const res = await fetch('/api/auth/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password }),
|
|
})
|
|
|
|
if (!res.ok) {
|
|
const data = await res.json()
|
|
setError(data.error ?? 'Login failed')
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
// Middleware will redirect to correct role home based on JWT
|
|
router.push('/')
|
|
router.refresh()
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit} className="flex flex-col gap-4 w-full max-w-sm">
|
|
<div className="pb-3 border-b-2 border-divider">
|
|
<h1 className="text-3xl font-extrabold">IMS</h1>
|
|
<p className="text-sm text-ink/60 mt-1">HSE Incident Management</p>
|
|
</div>
|
|
|
|
{error && (
|
|
<p className="bg-accent-100 border border-accent text-accent-800 text-sm px-3 py-2">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
<Input
|
|
type="email"
|
|
placeholder="Email"
|
|
value={email}
|
|
onChange={(e) => setEmail(e.target.value)}
|
|
required
|
|
autoComplete="email"
|
|
/>
|
|
<Input
|
|
type="password"
|
|
placeholder="Password"
|
|
value={password}
|
|
onChange={(e) => setPassword(e.target.value)}
|
|
required
|
|
autoComplete="current-password"
|
|
/>
|
|
<Button type="submit" variant="primary" block disabled={loading}>
|
|
{loading ? 'Signing in…' : 'Sign in'}
|
|
</Button>
|
|
<p className="text-sm text-ink/60">
|
|
<Link href="/forgot-password" className="text-accent-700 hover:underline">
|
|
Forgot password?
|
|
</Link>
|
|
</p>
|
|
</form>
|
|
)
|
|
}
|