password-section.tsx 7.9 KB

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