You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail-and-password-auth.tsx 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import Link from 'next/link'
  2. import { useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useRouter, useSearchParams } from 'next/navigation'
  5. import { useContext } from 'use-context-selector'
  6. import Button from '@/app/components/base/button'
  7. import Toast from '@/app/components/base/toast'
  8. import { emailRegex } from '@/config'
  9. import { login } from '@/service/common'
  10. import Input from '@/app/components/base/input'
  11. import I18NContext from '@/context/i18n'
  12. import { noop } from 'lodash-es'
  13. import { resolvePostLoginRedirect } from '../utils/post-login-redirect'
  14. type MailAndPasswordAuthProps = {
  15. isInvite: boolean
  16. isEmailSetup: boolean
  17. allowRegistration: boolean
  18. }
  19. const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
  20. export default function MailAndPasswordAuth({ isInvite, isEmailSetup, allowRegistration }: MailAndPasswordAuthProps) {
  21. const { t } = useTranslation()
  22. const { locale } = useContext(I18NContext)
  23. const router = useRouter()
  24. const searchParams = useSearchParams()
  25. const [showPassword, setShowPassword] = useState(false)
  26. const emailFromLink = decodeURIComponent(searchParams.get('email') || '')
  27. const [email, setEmail] = useState(emailFromLink)
  28. const [password, setPassword] = useState('')
  29. const [isLoading, setIsLoading] = useState(false)
  30. const handleEmailPasswordLogin = async () => {
  31. if (!email) {
  32. Toast.notify({ type: 'error', message: t('login.error.emailEmpty') })
  33. return
  34. }
  35. if (!emailRegex.test(email)) {
  36. Toast.notify({
  37. type: 'error',
  38. message: t('login.error.emailInValid'),
  39. })
  40. return
  41. }
  42. if (!password?.trim()) {
  43. Toast.notify({ type: 'error', message: t('login.error.passwordEmpty') })
  44. return
  45. }
  46. if (!passwordRegex.test(password)) {
  47. Toast.notify({
  48. type: 'error',
  49. message: t('login.error.passwordInvalid'),
  50. })
  51. return
  52. }
  53. try {
  54. setIsLoading(true)
  55. const loginData: Record<string, any> = {
  56. email,
  57. password,
  58. language: locale,
  59. remember_me: true,
  60. }
  61. if (isInvite)
  62. loginData.invite_token = decodeURIComponent(searchParams.get('invite_token') as string)
  63. const res = await login({
  64. url: '/login',
  65. body: loginData,
  66. })
  67. if (res.result === 'success') {
  68. if (isInvite) {
  69. router.replace(`/signin/invite-settings?${searchParams.toString()}`)
  70. }
  71. else {
  72. localStorage.setItem('console_token', res.data.access_token)
  73. localStorage.setItem('refresh_token', res.data.refresh_token)
  74. const redirectUrl = resolvePostLoginRedirect(searchParams)
  75. router.replace(redirectUrl || '/apps')
  76. }
  77. }
  78. else if (res.code === 'account_not_found') {
  79. if (allowRegistration) {
  80. const params = new URLSearchParams()
  81. params.append('email', encodeURIComponent(email))
  82. params.append('token', encodeURIComponent(res.data))
  83. router.replace(`/reset-password/check-code?${params.toString()}`)
  84. }
  85. else {
  86. Toast.notify({
  87. type: 'error',
  88. message: t('login.error.registrationNotAllowed'),
  89. })
  90. }
  91. }
  92. else {
  93. Toast.notify({
  94. type: 'error',
  95. message: res.data,
  96. })
  97. }
  98. }
  99. finally {
  100. setIsLoading(false)
  101. }
  102. }
  103. return <form onSubmit={noop}>
  104. <div className='mb-3'>
  105. <label htmlFor="email" className="system-md-semibold my-2 text-text-secondary">
  106. {t('login.email')}
  107. </label>
  108. <div className="mt-1">
  109. <Input
  110. value={email}
  111. onChange={e => setEmail(e.target.value)}
  112. disabled={isInvite}
  113. id="email"
  114. type="email"
  115. autoComplete="email"
  116. placeholder={t('login.emailPlaceholder') || ''}
  117. tabIndex={1}
  118. />
  119. </div>
  120. </div>
  121. <div className='mb-3'>
  122. <label htmlFor="password" className="my-2 flex items-center justify-between">
  123. <span className='system-md-semibold text-text-secondary'>{t('login.password')}</span>
  124. <Link
  125. href={`/reset-password?${searchParams.toString()}`}
  126. className={`system-xs-regular ${isEmailSetup ? 'text-components-button-secondary-accent-text' : 'pointer-events-none text-components-button-secondary-accent-text-disabled'}`}
  127. tabIndex={isEmailSetup ? 0 : -1}
  128. aria-disabled={!isEmailSetup}
  129. >
  130. {t('login.forget')}
  131. </Link>
  132. </label>
  133. <div className="relative mt-1">
  134. <Input
  135. id="password"
  136. value={password}
  137. onChange={e => setPassword(e.target.value)}
  138. onKeyDown={(e) => {
  139. if (e.key === 'Enter')
  140. handleEmailPasswordLogin()
  141. }}
  142. type={showPassword ? 'text' : 'password'}
  143. autoComplete="current-password"
  144. placeholder={t('login.passwordPlaceholder') || ''}
  145. tabIndex={2}
  146. />
  147. <div className="absolute inset-y-0 right-0 flex items-center">
  148. <Button
  149. type="button"
  150. variant='ghost'
  151. onClick={() => setShowPassword(!showPassword)}
  152. >
  153. {showPassword ? '👀' : '😝'}
  154. </Button>
  155. </div>
  156. </div>
  157. </div>
  158. <div className='mb-2'>
  159. <Button
  160. tabIndex={2}
  161. variant='primary'
  162. onClick={handleEmailPasswordLogin}
  163. disabled={isLoading || !email || !password}
  164. className="w-full"
  165. >{t('login.signBtn')}</Button>
  166. </div>
  167. </form>
  168. }