password-section.tsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import { useEffect, useState } from 'react'
  2. import {
  3. Alert,
  4. Button,
  5. ControlLabel,
  6. FormControl,
  7. FormGroup,
  8. } from 'react-bootstrap'
  9. import { Trans, useTranslation } from 'react-i18next'
  10. import {
  11. getUserFacingMessage,
  12. getErrorMessageKey,
  13. postJSON,
  14. } from '../../../infrastructure/fetch-json'
  15. import getMeta from '../../../utils/meta'
  16. import { ExposedSettings } from '../../../../../types/exposed-settings'
  17. import { PasswordStrengthOptions } from '../../../../../types/password-strength-options'
  18. import useAsync from '../../../shared/hooks/use-async'
  19. type PasswordUpdateResult = {
  20. message?: {
  21. text: string
  22. }
  23. }
  24. function PasswordSection() {
  25. const { t } = useTranslation()
  26. return (
  27. <>
  28. <h3>{t('change_password')}</h3>
  29. <PasswordInnerSection />
  30. </>
  31. )
  32. }
  33. function PasswordInnerSection() {
  34. const { t } = useTranslation()
  35. const { isOverleaf } = getMeta('ol-ExposedSettings') as ExposedSettings
  36. const isExternalAuthenticationSystemUsed = getMeta(
  37. 'ol-isExternalAuthenticationSystemUsed'
  38. ) as boolean
  39. const hasPassword = getMeta('ol-hasPassword') as boolean
  40. if (isExternalAuthenticationSystemUsed && !isOverleaf) {
  41. return <p>{t('password_managed_externally')}</p>
  42. }
  43. if (!hasPassword) {
  44. return (
  45. <p>
  46. <a href="/user/password/reset" target="_blank">
  47. {t('no_existing_password')}
  48. </a>
  49. </p>
  50. )
  51. }
  52. return <PasswordForm />
  53. }
  54. function PasswordForm() {
  55. const { t } = useTranslation()
  56. const passwordStrengthOptions = getMeta(
  57. 'ol-passwordStrengthOptions'
  58. ) as PasswordStrengthOptions
  59. const [currentPassword, setCurrentPassword] = useState('')
  60. const [newPassword1, setNewPassword1] = useState('')
  61. const [newPassword2, setNewPassword2] = useState('')
  62. const { isLoading, isSuccess, isError, data, error, runAsync } =
  63. useAsync<PasswordUpdateResult>()
  64. const [isNewPasswordValid, setIsNewPasswordValid] = useState(false)
  65. const [isFormValid, setIsFormValid] = useState(false)
  66. const handleCurrentPasswordChange = (
  67. event: React.ChangeEvent<HTMLInputElement>
  68. ) => {
  69. setCurrentPassword(event.target.value)
  70. }
  71. const handleNewPassword1Change = (
  72. event: React.ChangeEvent<HTMLInputElement>
  73. ) => {
  74. setNewPassword1(event.target.value)
  75. setIsNewPasswordValid(event.target.validity.valid)
  76. }
  77. const handleNewPassword2Change = (
  78. event: React.ChangeEvent<HTMLInputElement>
  79. ) => {
  80. setNewPassword2(event.target.value)
  81. }
  82. useEffect(() => {
  83. setIsFormValid(
  84. !!currentPassword && isNewPasswordValid && newPassword1 === newPassword2
  85. )
  86. }, [currentPassword, newPassword1, newPassword2, isNewPasswordValid])
  87. const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  88. event.preventDefault()
  89. if (!isFormValid) {
  90. return
  91. }
  92. runAsync(
  93. postJSON('/user/password/update', {
  94. body: {
  95. currentPassword,
  96. newPassword1,
  97. newPassword2,
  98. },
  99. })
  100. ).catch(() => {})
  101. }
  102. return (
  103. <form id="password-change-form" onSubmit={handleSubmit}>
  104. <PasswordFormGroup
  105. id="current-password-input"
  106. label={t('current_password')}
  107. value={currentPassword}
  108. handleChange={handleCurrentPasswordChange}
  109. autoComplete="current-password"
  110. />
  111. <PasswordFormGroup
  112. id="new-password-1-input"
  113. label={t('new_password')}
  114. value={newPassword1}
  115. handleChange={handleNewPassword1Change}
  116. minLength={passwordStrengthOptions?.length?.min || 8}
  117. autoComplete="new-password"
  118. />
  119. <PasswordFormGroup
  120. id="new-password-2-input"
  121. label={t('confirm_new_password')}
  122. value={newPassword2}
  123. handleChange={handleNewPassword2Change}
  124. validationMessage={
  125. newPassword1 !== newPassword2 ? t('doesnt_match') : ''
  126. }
  127. autoComplete="new-password"
  128. />
  129. {isSuccess && data?.message?.text ? (
  130. <FormGroup>
  131. <Alert bsStyle="success">{data.message.text}</Alert>
  132. </FormGroup>
  133. ) : null}
  134. {isError ? (
  135. <FormGroup>
  136. <Alert bsStyle="danger">
  137. {getErrorMessageKey(error) === 'password-must-be-strong' ? (
  138. <>
  139. <Trans
  140. i18nKey="password_was_detected_on_a_public_list_of_known_compromised_passwords"
  141. components={[
  142. /* eslint-disable-next-line jsx-a11y/anchor-has-content, react/jsx-key */
  143. <a
  144. href="https://haveibeenpwned.com"
  145. target="_blank"
  146. rel="noreferrer noopener"
  147. />,
  148. ]}
  149. />
  150. . {t('use_a_different_password')}.
  151. </>
  152. ) : getErrorMessageKey(error) === 'password-contains-email' ? (
  153. <>
  154. {t('invalid_password_contains_email')}.{' '}
  155. {t('use_a_different_password')}.
  156. </>
  157. ) : getErrorMessageKey(error) === 'password-too-similar' ? (
  158. <>
  159. {t('invalid_password_too_similar')}.{' '}
  160. {t('use_a_different_password')}.
  161. </>
  162. ) : (
  163. getUserFacingMessage(error)
  164. )}
  165. </Alert>
  166. </FormGroup>
  167. ) : null}
  168. <Button
  169. form="password-change-form"
  170. type="submit"
  171. bsStyle="primary"
  172. disabled={isLoading || !isFormValid}
  173. >
  174. {isLoading ? <>{t('saving')}…</> : t('change')}
  175. </Button>
  176. </form>
  177. )
  178. }
  179. type PasswordFormGroupProps = {
  180. id: string
  181. label: string
  182. value: string
  183. handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void
  184. minLength?: number
  185. validationMessage?: string
  186. autoComplete?: string
  187. }
  188. function PasswordFormGroup({
  189. id,
  190. label,
  191. value,
  192. handleChange,
  193. minLength,
  194. validationMessage: parentValidationMessage,
  195. autoComplete,
  196. }: PasswordFormGroupProps) {
  197. const [validationMessage, setValidationMessage] = useState('')
  198. const [hadInteraction, setHadInteraction] = useState(false)
  199. const handleInvalid = (
  200. event: React.InvalidEvent<HTMLInputElement & FormControl>
  201. ) => {
  202. event.preventDefault()
  203. }
  204. const handleChangeAndValidity = (
  205. event: React.ChangeEvent<HTMLInputElement & FormControl>
  206. ) => {
  207. handleChange(event)
  208. setHadInteraction(true)
  209. setValidationMessage(event.target.validationMessage)
  210. }
  211. return (
  212. <FormGroup>
  213. <ControlLabel htmlFor={id}>{label}</ControlLabel>
  214. <FormControl
  215. id={id}
  216. type="password"
  217. placeholder="*********"
  218. autoComplete={autoComplete}
  219. value={value}
  220. data-ol-dirty={!!validationMessage}
  221. onChange={handleChangeAndValidity}
  222. onInvalid={handleInvalid}
  223. required={hadInteraction}
  224. minLength={minLength}
  225. />
  226. {hadInteraction && (parentValidationMessage || validationMessage) ? (
  227. <span className="small text-danger">
  228. {parentValidationMessage || validationMessage}
  229. </span>
  230. ) : null}
  231. </FormGroup>
  232. )
  233. }
  234. export default PasswordSection