password-section.tsx 8.3 KB

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