add-email.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import { useState, useEffect } from 'react'
  2. import { useTranslation, Trans } from 'react-i18next'
  3. import Cell from './cell'
  4. import Layout from './add-email/layout'
  5. import Input, { DomainInfo } from './add-email/input'
  6. import AddAnotherEmailBtn from './add-email/add-another-email-btn'
  7. import InstitutionFields from './add-email/institution-fields'
  8. import SsoLinkingInfo from './add-email/sso-linking-info'
  9. import AddNewEmailBtn from './add-email/add-new-email-btn'
  10. import useAsync from '../../../../shared/hooks/use-async'
  11. import { useUserEmailsContext } from '../../context/user-email-context'
  12. import { ssoAvailableForDomain } from '../../utils/sso'
  13. import { postJSON } from '../../../../infrastructure/fetch-json'
  14. import { University } from '../../../../../../types/university'
  15. import { CountryCode } from '../../data/countries-list'
  16. import { isValidEmail } from '../../../../shared/utils/email'
  17. import getMeta from '../../../../utils/meta'
  18. import { ReCaptcha2 } from '../../../../shared/components/recaptcha-2'
  19. import { useRecaptcha } from '../../../../shared/hooks/use-recaptcha'
  20. import OLCol from '@/shared/components/ol/ol-col'
  21. import { ConfirmEmailForm } from '@/features/settings/components/emails/confirm-email-form'
  22. import RecaptchaConditions from '@/shared/components/recaptcha-conditions'
  23. import SsoLinkingInfoGroup from './add-email/sso-linking-info-group'
  24. import Notification from '@/shared/components/notification'
  25. function AddEmail() {
  26. const { t } = useTranslation()
  27. const [isFormVisible, setIsFormVisible] = useState(
  28. () => window.location.hash === '#add-email'
  29. )
  30. const [newEmail, setNewEmail] = useState('')
  31. const [confirmationStep, setConfirmationStep] = useState(false)
  32. const [newEmailMatchedDomain, setNewEmailMatchedDomain] =
  33. useState<DomainInfo | null>(null)
  34. const [countryCode, setCountryCode] = useState<CountryCode | null>(null)
  35. const [universities, setUniversities] = useState<
  36. Partial<Record<CountryCode, University[]>>
  37. >({})
  38. const [universityName, setUniversityName] = useState('')
  39. const [role, setRole] = useState('')
  40. const [department, setDepartment] = useState('')
  41. const { isLoading, isError, error, runAsync } = useAsync()
  42. const {
  43. state,
  44. setLoading: setUserEmailsContextLoading,
  45. getEmails,
  46. } = useUserEmailsContext()
  47. const emailAddressLimit = getMeta('ol-emailAddressLimit') || 10
  48. const { ref: recaptchaRef, getReCaptchaToken } = useRecaptcha()
  49. useEffect(() => {
  50. setUserEmailsContextLoading(isLoading)
  51. }, [setUserEmailsContextLoading, isLoading])
  52. const handleShowAddEmailForm = () => {
  53. setIsFormVisible(true)
  54. }
  55. const handleEmailChange = (value: string, domain?: DomainInfo) => {
  56. setNewEmail(value)
  57. setNewEmailMatchedDomain(domain || null)
  58. }
  59. const getSelectedKnownUniversityId = (): number | undefined => {
  60. if (countryCode) {
  61. return universities[countryCode]?.find(
  62. ({ name }) => name === universityName
  63. )?.id
  64. }
  65. return newEmailMatchedDomain?.university.id
  66. }
  67. const handleAddNewEmail = () => {
  68. const selectedKnownUniversityId = getSelectedKnownUniversityId()
  69. const knownUniversityData = selectedKnownUniversityId && {
  70. university: {
  71. id: selectedKnownUniversityId,
  72. },
  73. role,
  74. department,
  75. }
  76. const unknownUniversityData = universityName &&
  77. !selectedKnownUniversityId && {
  78. university: {
  79. name: universityName,
  80. country_code: countryCode,
  81. },
  82. role,
  83. department,
  84. }
  85. runAsync(
  86. (async () => {
  87. const token = await getReCaptchaToken()
  88. await postJSON('/user/emails/secondary', {
  89. body: {
  90. email: newEmail,
  91. ...knownUniversityData,
  92. ...unknownUniversityData,
  93. 'g-recaptcha-response': token,
  94. },
  95. })
  96. })()
  97. )
  98. .then(() => {
  99. setConfirmationStep(true)
  100. })
  101. .catch(() => {})
  102. }
  103. if (confirmationStep) {
  104. return (
  105. <ConfirmEmailForm
  106. confirmationEndpoint="/user/emails/confirm-secondary"
  107. resendEndpoint="/user/emails/resend-secondary-confirmation"
  108. flow="secondary"
  109. email={newEmail}
  110. onSuccessfulConfirmation={getEmails}
  111. interstitial={false}
  112. onCancel={() => {
  113. setConfirmationStep(false)
  114. setIsFormVisible(false)
  115. }}
  116. />
  117. )
  118. }
  119. if (!isFormVisible) {
  120. return (
  121. <Layout isError={isError} error={error}>
  122. <OLCol lg={12}>
  123. <Cell>
  124. {state.data.emailCount >= emailAddressLimit ? (
  125. <span className="small">
  126. <Trans
  127. i18nKey="email_limit_reached"
  128. values={{
  129. emailAddressLimit,
  130. }}
  131. shouldUnescape
  132. tOptions={{ interpolation: { escapeValue: true } }}
  133. components={[<strong />]} // eslint-disable-line react/jsx-key
  134. />
  135. </span>
  136. ) : (
  137. <AddAnotherEmailBtn onClick={handleShowAddEmailForm} />
  138. )}
  139. </Cell>
  140. </OLCol>
  141. </Layout>
  142. )
  143. }
  144. const InputComponent = (
  145. <>
  146. <label htmlFor="affiliations-email">{t('email')}</label>
  147. <Input
  148. onChange={handleEmailChange}
  149. handleAddNewEmail={handleAddNewEmail}
  150. />
  151. </>
  152. )
  153. const recaptchaConditions = (
  154. <OLCol>
  155. <Cell>
  156. <div className="affiliations-table-cell-tabbed">
  157. <RecaptchaConditions />
  158. </div>
  159. </Cell>
  160. </OLCol>
  161. )
  162. if (!isValidEmail(newEmail)) {
  163. return (
  164. <form>
  165. <Layout isError={isError} error={error}>
  166. <ReCaptcha2 page="addEmail" recaptchaRef={recaptchaRef} />
  167. <OLCol lg={8}>
  168. <Cell>
  169. {InputComponent}
  170. <div className="affiliations-table-cell-tabbed">
  171. <div>{t('start_by_adding_your_email')}</div>
  172. </div>
  173. </Cell>
  174. </OLCol>
  175. <OLCol lg={4}>
  176. <Cell className="text-lg-end">
  177. <AddNewEmailBtn email={newEmail} disabled />
  178. </Cell>
  179. </OLCol>
  180. {recaptchaConditions}
  181. </Layout>
  182. </form>
  183. )
  184. }
  185. const isSsoAvailableForDomain =
  186. newEmailMatchedDomain && ssoAvailableForDomain(newEmailMatchedDomain)
  187. return (
  188. <form>
  189. <Layout isError={isError} error={error}>
  190. <ReCaptcha2 page="addEmail" recaptchaRef={recaptchaRef} />
  191. <OLCol lg={8}>
  192. <Cell>
  193. {InputComponent}
  194. {!isSsoAvailableForDomain ? (
  195. <div className="affiliations-table-cell-tabbed">
  196. <InstitutionFields
  197. countryCode={countryCode}
  198. setCountryCode={setCountryCode}
  199. universities={universities}
  200. setUniversities={setUniversities}
  201. universityName={universityName}
  202. setUniversityName={setUniversityName}
  203. role={role}
  204. setRole={setRole}
  205. department={department}
  206. setDepartment={setDepartment}
  207. newEmailMatchedDomain={newEmailMatchedDomain}
  208. />
  209. </div>
  210. ) : null}
  211. </Cell>
  212. </OLCol>
  213. {!isSsoAvailableForDomain ? (
  214. <OLCol lg={4}>
  215. <Cell className="text-lg-end">
  216. <AddNewEmailBtn
  217. email={newEmail}
  218. disabled={state.isLoading}
  219. isLoading={isLoading}
  220. onClick={handleAddNewEmail}
  221. />
  222. </Cell>
  223. </OLCol>
  224. ) : (
  225. <OLCol lg={12}>
  226. <Cell>
  227. <div className="affiliations-table-cell-tabbed">
  228. <AddEmailViaSSO
  229. email={newEmail}
  230. domainInfo={newEmailMatchedDomain}
  231. userInstitutions={state.data.linkedInstitutionIds}
  232. />
  233. </div>
  234. </Cell>
  235. </OLCol>
  236. )}
  237. {recaptchaConditions}
  238. </Layout>
  239. </form>
  240. )
  241. }
  242. function AddEmailViaSSO({
  243. email,
  244. domainInfo,
  245. userInstitutions,
  246. }: {
  247. email: string
  248. domainInfo: DomainInfo
  249. userInstitutions: string[]
  250. }) {
  251. if (domainInfo.university.ssoEnabled) {
  252. // Check if the user has already linked this institution
  253. if (userInstitutions.includes(domainInfo.university.id.toString())) {
  254. return (
  255. <Notification
  256. type="error"
  257. ariaLive="polite"
  258. content={
  259. <>
  260. This institution is already linked with your account via another
  261. email address.
  262. </>
  263. }
  264. />
  265. )
  266. }
  267. return <SsoLinkingInfo email={email} domainInfo={domainInfo} />
  268. } else if (
  269. domainInfo.group?.domainCaptureEnabled &&
  270. domainInfo.group?.managedUsersEnabled
  271. ) {
  272. return (
  273. <Notification
  274. type="error"
  275. ariaLive="polite"
  276. content={
  277. <>
  278. Your company email address has been registered under a verified
  279. domain, and cannot be added as a secondary email. Please create a
  280. new <strong>Overleaf</strong> account linked to this email address.
  281. </>
  282. }
  283. />
  284. )
  285. } else if (
  286. domainInfo.group?.domainCaptureEnabled &&
  287. domainInfo.group?.ssoConfig?.enabled
  288. ) {
  289. return <SsoLinkingInfoGroup domainInfo={domainInfo} />
  290. }
  291. }
  292. export default AddEmail