feat: self-service change password for all roles

- middleware.ts: add /account to isSharedRoute so all roles can reach it
- components/account/change-password-form.tsx: re-auth with current password
  then updateUser({password}) with client-side validation (length, match, diff)
- app/(protected)/account/page.tsx: dedicated account page, no role gate
- sidebar.tsx: Account link (all roles) above Logout in desktop footer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
This commit is contained in:
2026-07-12 22:17:51 +08:00
co-authored by Claude Sonnet 4.6
parent b2891a433d
commit 8061f804f7
4 changed files with 165 additions and 3 deletions
+13
View File
@@ -0,0 +1,13 @@
import ChangePasswordForm from '@/components/account/change-password-form'
export const metadata = { title: 'Account' }
export default function AccountPage() {
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<h1 className="text-2xl font-bold text-gray-900 mb-2">Account</h1>
<p className="text-sm text-gray-500 mb-6">Manage your password.</p>
<ChangePasswordForm />
</main>
)
}
+131
View File
@@ -0,0 +1,131 @@
'use client'
import { useState } from 'react'
import { createClient } from '@/lib/supabase/client'
export default function ChangePasswordForm() {
const [current, setCurrent] = useState('')
const [newPass, setNewPass] = useState('')
const [confirm, setConfirm] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError(null)
setSuccess(false)
// Client-side validation
if (!current || !newPass || !confirm) {
setError('All fields are required.')
return
}
if (newPass.length < 8) {
setError('Password must be at least 8 characters.')
return
}
if (newPass !== confirm) {
setError('Passwords do not match.')
return
}
if (newPass === current) {
setError('New password must differ from current password.')
return
}
setLoading(true)
const supabase = createClient()
// Get current user email for re-auth
const { data: { user } } = await supabase.auth.getUser()
if (!user?.email) {
setError('Session expired, please log in again.')
setLoading(false)
return
}
// Re-authenticate with current password
const { error: reauthError } = await supabase.auth.signInWithPassword({
email: user.email,
password: current,
})
if (reauthError) {
setError('Current password is incorrect.')
setLoading(false)
return
}
// Update to new password
const { error: updateError } = await supabase.auth.updateUser({ password: newPass })
if (updateError) {
setError(updateError.message)
setLoading(false)
return
}
setCurrent('')
setNewPass('')
setConfirm('')
setSuccess(true)
setLoading(false)
}
return (
<div className="bg-white rounded-xl shadow-sm p-5">
<h2 className="text-base font-semibold text-gray-900 mb-4">Change Password</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-semibold text-gray-800 mb-1">
Current Password
</label>
<input
type="password"
value={current}
onChange={e => setCurrent(e.target.value)}
disabled={loading}
autoComplete="current-password"
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
/>
</div>
<div>
<label className="block text-sm font-semibold text-gray-800 mb-1">
New Password
</label>
<input
type="password"
value={newPass}
onChange={e => setNewPass(e.target.value)}
disabled={loading}
autoComplete="new-password"
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
/>
</div>
<div>
<label className="block text-sm font-semibold text-gray-800 mb-1">
Confirm New Password
</label>
<input
type="password"
value={confirm}
onChange={e => setConfirm(e.target.value)}
disabled={loading}
autoComplete="new-password"
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
/>
</div>
{error && <p className="text-xs text-red-600 mt-1">{error}</p>}
{success && <p className="text-xs text-green-600 mt-1">Password changed successfully.</p>}
<button
type="submit"
disabled={loading}
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-semibold disabled:opacity-50 hover:bg-blue-700"
>
{loading ? 'Saving…' : 'Update Password'}
</button>
</form>
</div>
)
}
+20 -2
View File
@@ -58,6 +58,11 @@ const IconLogout = () => (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg> </svg>
) )
const IconUser = () => (
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
)
const NAV_ITEMS: Record<string, NavItem[]> = { const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [ reporter: [
@@ -104,7 +109,7 @@ function useNavItems(role: string): NavItem[] {
function NavLink({ item, pathname }: { item: NavItem; pathname: string }) { function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
// Exact match for root-level single-page roles, prefix match otherwise // Exact match for root-level single-page roles, prefix match otherwise
const exactRoots = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report'] const exactRoots = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
const isActive = exactRoots.includes(item.href) const isActive = exactRoots.includes(item.href)
? pathname === item.href ? pathname === item.href
: pathname.startsWith(item.href) : pathname.startsWith(item.href)
@@ -170,6 +175,19 @@ export function Sidebar({ role, userName, userEmail }: SidebarProps) {
<p className="text-xs text-gray-500 truncate">{roleLabel}</p> <p className="text-xs text-gray-500 truncate">{roleLabel}</p>
</div> </div>
</div> </div>
<Link
href="/account"
className={`flex items-center gap-2 w-full px-3 py-2 text-sm rounded-lg transition-colors ${
pathname === '/account'
? 'bg-blue-50 text-blue-700'
: 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
}`}
>
<span className={pathname === '/account' ? 'text-blue-600' : 'text-gray-400'}>
<IconUser />
</span>
Account
</Link>
<button <button
onClick={logout} onClick={logout}
className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 rounded-lg transition-colors" className="flex items-center gap-2 w-full px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 rounded-lg transition-colors"
@@ -183,7 +201,7 @@ export function Sidebar({ role, userName, userEmail }: SidebarProps) {
{/* Mobile bottom tab bar */} {/* Mobile bottom tab bar */}
<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex z-40 safe-area-pb"> <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex z-40 safe-area-pb">
{mobileItems.map(item => { {mobileItems.map(item => {
const exactRoots = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report'] const exactRoots = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
const isActive = exactRoots.includes(item.href) const isActive = exactRoots.includes(item.href)
? pathname === item.href ? pathname === item.href
: pathname.startsWith(item.href) : pathname.startsWith(item.href)
+1 -1
View File
@@ -25,7 +25,7 @@ export async function middleware(request: NextRequest) {
const { data: { user } } = await supabase.auth.getUser() const { data: { user } } = await supabase.auth.getUser()
const { pathname } = request.nextUrl const { pathname } = request.nextUrl
const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth') || pathname.startsWith('/api/cron') const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth') || pathname.startsWith('/api/cron')
const isSharedRoute = pathname.startsWith('/report') const isSharedRoute = pathname.startsWith('/report') || pathname.startsWith('/account')
if (!user && !isPublicRoute) { if (!user && !isPublicRoute) {
const redirectUrl = request.nextUrl.clone() const redirectUrl = request.nextUrl.clone()