mail-and-password-auth.tsx 5.3 KB

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