| 1 |
import { useState } from 'react' |
| 2 |
import FormErrors from '../components/FormErrors' |
| 3 |
import { changePassword } from '../lib/allauth' |
| 4 |
import { Navigate } from 'react-router-dom' |
| 5 |
import { useUser } from '../auth' |
| 6 |
import Button from '../components/Button' |
| 7 |
|
| 8 |
export default function ChangePassword () { |
| 9 |
const hasCurrentPassword = useUser().has_usable_password |
| 10 |
const [currentPassword, setCurrentPassword] = useState('') |
| 11 |
const [newPassword, setNewPassword] = useState('') |
| 12 |
const [newPassword2, setNewPassword2] = useState('') |
| 13 |
const [newPassword2Errors, setNewPassword2Errors] = useState([]) |
| 14 |
|
| 15 |
const [response, setResponse] = useState({ fetching: false, content: null }) |
| 16 |
|
| 17 |
function submit () { |
| 18 |
if (newPassword !== newPassword2) { |
| 19 |
setNewPassword2Errors([{ param: 'new_password2', message: 'Password does not match.' }]) |
| 20 |
return |
| 21 |
} |
| 22 |
setNewPassword2Errors([]) |
| 23 |
setResponse({ ...response, fetching: true }) |
| 24 |
changePassword({ current_password: currentPassword, new_password: newPassword }).then((resp) => { |
| 25 |
setResponse((r) => { return { ...r, content: resp } }) |
| 26 |
}).catch((e) => { |
| 27 |
console.error(e) |
| 28 |
window.alert(e) |
| 29 |
}).then(() => { |
| 30 |
setResponse((r) => { return { ...r, fetching: false } }) |
| 31 |
}) |
| 32 |
} |
| 33 |
if (response.content?.status === 200) { |
| 34 |
return <Navigate to='/calculator' /> |
| 35 |
} |
| 36 |
return ( |
| 37 |
<div> |
| 38 |
<h1>{hasCurrentPassword ? 'Change Password' : 'Set Password'}</h1> |
| 39 |
|
| 40 |
<p>{hasCurrentPassword ? 'Enter your current password, followed by your new password.' : 'You currently have no password set. Enter your (new) password.'}</p> |
| 41 |
{hasCurrentPassword |
| 42 |
? <div><label>Current password: <input autoComplete='password' value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} type='password' required /></label> |
| 43 |
<FormErrors param='current_password' errors={response.content?.errors} /> |
| 44 |
</div> |
| 45 |
: null} |
| 46 |
<div><label>Password: <input autoComplete='new-password' value={newPassword} onChange={(e) => setNewPassword(e.target.value)} type='password' required /></label> |
| 47 |
<FormErrors param='new_password' errors={response.content?.errors} /> |
| 48 |
</div> |
| 49 |
<div><label>Password (again): <input value={newPassword2} onChange={(e) => setNewPassword2(e.target.value)} type='password' required /></label> |
| 50 |
<FormErrors param='new_password2' errors={newPassword2Errors} /> |
| 51 |
</div> |
| 52 |
|
| 53 |
<Button disabled={response.fetching} onClick={() => submit()}>{hasCurrentPassword ? 'Change' : 'Set'}</Button> |
| 54 |
</div> |
| 55 |
) |
| 56 |
} |