Files
Todo/components/PasswordChangeForm.tsx
Paul Bailey 85c8a1650b Implement profile management (task 14)
- Add updateProfile and updatePassword server actions
- Add getUserProfile function with sensitive data protection
- Create ProfileForm component for name and email updates
- Create PasswordChangeForm component with current password verification
- Create profile page at /profile with all profile management features
- Add profile and invitations navigation links to main page
- Implement email uniqueness validation
- Implement password hashing on password change

Requirements: 7.1, 7.2, 7.3, 7.4, 7.5
2025-12-02 01:06:21 +00:00

246 lines
8.6 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import { validatePassword } from '@/lib/validation'
import { updatePassword } from '@/lib/auth-actions'
import { useToast } from './ToastContainer'
interface PasswordChangeFormProps {
userId: string
}
export default function PasswordChangeForm({ userId }: PasswordChangeFormProps) {
const { showToast } = useToast()
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [errors, setErrors] = useState<{
currentPassword?: string
newPassword?: string
confirmPassword?: string
}>({})
const [touched, setTouched] = useState<{
currentPassword: boolean
newPassword: boolean
confirmPassword: boolean
}>({
currentPassword: false,
newPassword: false,
confirmPassword: false,
})
// Inline validation when fields change
useEffect(() => {
if (touched.currentPassword) {
if (!currentPassword) {
setErrors((prev) => ({ ...prev, currentPassword: 'Current password is required' }))
} else {
setErrors((prev) => ({ ...prev, currentPassword: undefined }))
}
}
}, [currentPassword, touched.currentPassword])
useEffect(() => {
if (touched.newPassword) {
const result = validatePassword(newPassword)
setErrors((prev) => ({
...prev,
newPassword: result.isValid ? undefined : result.error,
}))
}
}, [newPassword, touched.newPassword])
useEffect(() => {
if (touched.confirmPassword) {
if (!confirmPassword) {
setErrors((prev) => ({ ...prev, confirmPassword: 'Please confirm your new password' }))
} else if (newPassword !== confirmPassword) {
setErrors((prev) => ({ ...prev, confirmPassword: 'Passwords do not match' }))
} else {
setErrors((prev) => ({ ...prev, confirmPassword: undefined }))
}
}
}, [confirmPassword, newPassword, touched.confirmPassword])
const handleCurrentPasswordBlur = () => {
setTouched((prev) => ({ ...prev, currentPassword: true }))
}
const handleNewPasswordBlur = () => {
setTouched((prev) => ({ ...prev, newPassword: true }))
}
const handleConfirmPasswordBlur = () => {
setTouched((prev) => ({ ...prev, confirmPassword: true }))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Validate all fields before submission
const newPasswordResult = validatePassword(newPassword)
const newErrors: {
currentPassword?: string
newPassword?: string
confirmPassword?: string
} = {}
if (!currentPassword) {
newErrors.currentPassword = 'Current password is required'
}
if (!newPasswordResult.isValid) {
newErrors.newPassword = newPasswordResult.error
}
if (!confirmPassword) {
newErrors.confirmPassword = 'Please confirm your new password'
} else if (newPassword !== confirmPassword) {
newErrors.confirmPassword = 'Passwords do not match'
}
if (currentPassword === newPassword) {
newErrors.newPassword = 'New password must be different from current password'
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors)
setTouched({ currentPassword: true, newPassword: true, confirmPassword: true })
return
}
setIsSubmitting(true)
setErrors({})
try {
const result = await updatePassword(userId, currentPassword, newPassword)
if (!result.success) {
if (result.error === 'Current password is incorrect') {
setErrors({ currentPassword: 'Current password is incorrect' })
showToast('Current password is incorrect', 'error')
} else {
showToast(result.error || 'Password update failed', 'error')
}
} else {
showToast('Password updated successfully', 'success')
// Reset form
setCurrentPassword('')
setNewPassword('')
setConfirmPassword('')
setTouched({ currentPassword: false, newPassword: false, confirmPassword: false })
}
} catch (err) {
console.error('Password update 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="currentPassword" className="block text-sm font-medium text-gray-700 mb-2">
Current Password *
</label>
<input
type="password"
id="currentPassword"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
onBlur={handleCurrentPasswordBlur}
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.currentPassword && touched.currentPassword
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter your current password"
disabled={isSubmitting}
autoComplete="current-password"
aria-invalid={errors.currentPassword && touched.currentPassword ? 'true' : 'false'}
aria-describedby={errors.currentPassword && touched.currentPassword ? 'current-password-error' : undefined}
/>
{errors.currentPassword && touched.currentPassword && (
<p id="current-password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.currentPassword}
</p>
)}
</div>
<div>
<label htmlFor="newPassword" className="block text-sm font-medium text-gray-700 mb-2">
New Password *
</label>
<input
type="password"
id="newPassword"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
onBlur={handleNewPasswordBlur}
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.newPassword && touched.newPassword
? '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.newPassword && touched.newPassword ? 'true' : 'false'}
aria-describedby={errors.newPassword && touched.newPassword ? 'new-password-error' : undefined}
/>
{errors.newPassword && touched.newPassword && (
<p id="new-password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{errors.newPassword}
</p>
)}
{!errors.newPassword && touched.newPassword && (
<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 New 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 new 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 disabled:cursor-not-allowed tap-target font-medium text-sm sm:text-base"
>
{isSubmitting ? 'Updating...' : 'Update Password'}
</button>
</form>
)
}