import React, { useState, useEffect } from 'react'; import { Drawer, Box, Typography, TextField, Button, Alert, IconButton, LinearProgress } from '@mui/material'; import CloseIcon from '@mui/icons-material/Close'; import { encrypt } from '@/app/utils/encryption'; import { getPasswordStrength } from '@/app/utils/passwordStrength'; import { useAuth } from '@/context/AuthContext'; import Cookies from 'js-cookie'; const ChangePasswordDrawer = ({ open, onClose }: { open: boolean; onClose: () => void; }) => { const { username, authToken } = useAuth(); //console.log('🧪 username:', username); //console.log('🧪 authToken:', authToken); const [currentPassword, setCurrentPassword] = useState(''); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [message, setMessage] = useState(''); const [error, setError] = useState(''); const strength = getPasswordStrength(newPassword); const strengthValue = strength === 'Weak' ? 30 : strength === 'Medium' ? 60 : 100; useEffect(() => { if (!open) resetForm(); }, [open]); const resetForm = () => { setCurrentPassword(''); setNewPassword(''); setConfirmPassword(''); setMessage(''); setError(''); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setMessage(''); setError(''); if (!username) { setError('User not authenticated.'); return; } if (newPassword !== confirmPassword) { setError('New passwords do not match.'); return; } try { const res = await fetch('/api/auth/change-password', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ currentPassword: encrypt(currentPassword), newPassword: encrypt(newPassword), }), }); const text = await res.text(); if (res.ok) { setMessage(text); } else { setError(text); } } catch (err) { setError('An unexpected error occurred.'); } }; return ( Change Password
setCurrentPassword(e.target.value)} required /> setNewPassword(e.target.value)} required /> {/* Password Strength Bar */} Strength: {strength} setConfirmPassword(e.target.value)} required /> {username === 'testuser' && ( Password changes are disabled for this user. )} {message && {message}} {error && {error}}
); }; export default ChangePasswordDrawer;