normalForm.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. 'use client'
  2. import React, { useEffect, useReducer, useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useRouter } from 'next/navigation'
  5. import useSWR from 'swr'
  6. import Link from 'next/link'
  7. import Toast from '../components/base/toast'
  8. import style from './page.module.css'
  9. import classNames from '@/utils/classnames'
  10. import { IS_CE_EDITION, SUPPORT_MAIL_LOGIN, apiPrefix, emailRegex } from '@/config'
  11. import Button from '@/app/components/base/button'
  12. import { login, oauth } from '@/service/common'
  13. import { getPurifyHref } from '@/utils'
  14. import useRefreshToken from '@/hooks/use-refresh-token'
  15. type IState = {
  16. formValid: boolean
  17. github: boolean
  18. google: boolean
  19. }
  20. type IAction = {
  21. type: 'login' | 'login_failed' | 'github_login' | 'github_login_failed' | 'google_login' | 'google_login_failed'
  22. }
  23. function reducer(state: IState, action: IAction) {
  24. switch (action.type) {
  25. case 'login':
  26. return {
  27. ...state,
  28. formValid: true,
  29. }
  30. case 'login_failed':
  31. return {
  32. ...state,
  33. formValid: true,
  34. }
  35. case 'github_login':
  36. return {
  37. ...state,
  38. github: true,
  39. }
  40. case 'github_login_failed':
  41. return {
  42. ...state,
  43. github: false,
  44. }
  45. case 'google_login':
  46. return {
  47. ...state,
  48. google: true,
  49. }
  50. case 'google_login_failed':
  51. return {
  52. ...state,
  53. google: false,
  54. }
  55. default:
  56. throw new Error('Unknown action.')
  57. }
  58. }
  59. const NormalForm = () => {
  60. const { t } = useTranslation()
  61. const { getNewAccessToken } = useRefreshToken()
  62. const useEmailLogin = IS_CE_EDITION || SUPPORT_MAIL_LOGIN
  63. const router = useRouter()
  64. const [state, dispatch] = useReducer(reducer, {
  65. formValid: false,
  66. github: false,
  67. google: false,
  68. })
  69. const [showPassword, setShowPassword] = useState(false)
  70. const [email, setEmail] = useState('')
  71. const [password, setPassword] = useState('')
  72. const [isLoading, setIsLoading] = useState(false)
  73. const handleEmailPasswordLogin = async () => {
  74. if (!emailRegex.test(email)) {
  75. Toast.notify({
  76. type: 'error',
  77. message: t('login.error.emailInValid'),
  78. })
  79. return
  80. }
  81. try {
  82. setIsLoading(true)
  83. const res = await login({
  84. url: '/login',
  85. body: {
  86. email,
  87. password,
  88. remember_me: true,
  89. },
  90. })
  91. if (res.result === 'success') {
  92. localStorage.setItem('console_token', res.data.access_token)
  93. localStorage.setItem('refresh_token', res.data.refresh_token)
  94. getNewAccessToken(res.data.access_token, res.data.refresh_token)
  95. router.replace('/apps')
  96. }
  97. else {
  98. Toast.notify({
  99. type: 'error',
  100. message: res.data,
  101. })
  102. }
  103. }
  104. finally {
  105. setIsLoading(false)
  106. }
  107. }
  108. const { data: github, error: github_error } = useSWR(state.github
  109. ? ({
  110. url: '/oauth/login/github',
  111. // params: {
  112. // provider: 'github',
  113. // },
  114. })
  115. : null, oauth)
  116. const { data: google, error: google_error } = useSWR(state.google
  117. ? ({
  118. url: '/oauth/login/google',
  119. // params: {
  120. // provider: 'google',
  121. // },
  122. })
  123. : null, oauth)
  124. useEffect(() => {
  125. if (github_error !== undefined)
  126. dispatch({ type: 'github_login_failed' })
  127. if (github)
  128. window.location.href = github.redirect_url
  129. }, [github, github_error])
  130. useEffect(() => {
  131. if (google_error !== undefined)
  132. dispatch({ type: 'google_login_failed' })
  133. if (google)
  134. window.location.href = google.redirect_url
  135. }, [google, google_error])
  136. return (
  137. <>
  138. <div className="w-full mx-auto">
  139. <h2 className="text-[32px] font-bold text-gray-900">{t('login.pageTitle')}</h2>
  140. <p className='mt-1 text-sm text-gray-600'>{t('login.welcome')}</p>
  141. </div>
  142. <div className="w-full mx-auto mt-8">
  143. <div className="bg-white ">
  144. {!useEmailLogin && (
  145. <div className="flex flex-col gap-3 mt-6">
  146. <div className='w-full'>
  147. <a href={getPurifyHref(`${apiPrefix}/oauth/login/github`)}>
  148. <Button
  149. disabled={isLoading}
  150. className='w-full hover:!bg-gray-50'
  151. >
  152. <>
  153. <span className={
  154. classNames(
  155. style.githubIcon,
  156. 'w-5 h-5 mr-2',
  157. )
  158. } />
  159. <span className="truncate text-gray-800">{t('login.withGitHub')}</span>
  160. </>
  161. </Button>
  162. </a>
  163. </div>
  164. <div className='w-full'>
  165. <a href={getPurifyHref(`${apiPrefix}/oauth/login/google`)}>
  166. <Button
  167. disabled={isLoading}
  168. className='w-full hover:!bg-gray-50'
  169. >
  170. <>
  171. <span className={
  172. classNames(
  173. style.googleIcon,
  174. 'w-5 h-5 mr-2',
  175. )
  176. } />
  177. <span className="truncate text-gray-800">{t('login.withGoogle')}</span>
  178. </>
  179. </Button>
  180. </a>
  181. </div>
  182. </div>
  183. )}
  184. {
  185. useEmailLogin && <>
  186. {/* <div className="relative mt-6">
  187. <div className="absolute inset-0 flex items-center" aria-hidden="true">
  188. <div className="w-full border-t border-gray-300" />
  189. </div>
  190. <div className="relative flex justify-center text-sm">
  191. <span className="px-2 text-gray-300 bg-white">OR</span>
  192. </div>
  193. </div> */}
  194. <form onSubmit={() => { }}>
  195. <div className='mb-5'>
  196. <label htmlFor="email" className="my-2 block text-sm font-medium text-gray-900">
  197. {t('login.email')}
  198. </label>
  199. <div className="mt-1">
  200. <input
  201. value={email}
  202. onChange={e => setEmail(e.target.value)}
  203. id="email"
  204. type="email"
  205. autoComplete="email"
  206. placeholder={t('login.emailPlaceholder') || ''}
  207. className={'appearance-none block w-full rounded-lg pl-[14px] px-3 py-2 border border-gray-200 hover:border-gray-300 hover:shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 placeholder-gray-400 caret-primary-600 sm:text-sm'}
  208. tabIndex={1}
  209. />
  210. </div>
  211. </div>
  212. <div className='mb-4'>
  213. <label htmlFor="password" className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
  214. <span>{t('login.password')}</span>
  215. <Link href='/forgot-password' className='text-primary-600'>
  216. {t('login.forget')}
  217. </Link>
  218. </label>
  219. <div className="relative mt-1">
  220. <input
  221. id="password"
  222. value={password}
  223. onChange={e => setPassword(e.target.value)}
  224. onKeyDown={(e) => {
  225. if (e.key === 'Enter')
  226. handleEmailPasswordLogin()
  227. }}
  228. type={showPassword ? 'text' : 'password'}
  229. autoComplete="current-password"
  230. placeholder={t('login.passwordPlaceholder') || ''}
  231. className={'appearance-none block w-full rounded-lg pl-[14px] px-3 py-2 border border-gray-200 hover:border-gray-300 hover:shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 placeholder-gray-400 caret-primary-600 sm:text-sm pr-10'}
  232. tabIndex={2}
  233. />
  234. <div className="absolute inset-y-0 right-0 flex items-center pr-3">
  235. <button
  236. type="button"
  237. onClick={() => setShowPassword(!showPassword)}
  238. className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500"
  239. >
  240. {showPassword ? '👀' : '😝'}
  241. </button>
  242. </div>
  243. </div>
  244. </div>
  245. <div className='mb-2'>
  246. <Button
  247. tabIndex={0}
  248. variant='primary'
  249. onClick={handleEmailPasswordLogin}
  250. disabled={isLoading}
  251. className="w-full"
  252. >{t('login.signBtn')}</Button>
  253. </div>
  254. </form>
  255. </>
  256. }
  257. {/* agree to our Terms and Privacy Policy. */}
  258. <div className="w-hull text-center block mt-2 text-xs text-gray-600">
  259. {t('login.tosDesc')}
  260. &nbsp;
  261. <Link
  262. className='text-primary-600'
  263. target='_blank' rel='noopener noreferrer'
  264. href='https://dify.ai/terms'
  265. >{t('login.tos')}</Link>
  266. &nbsp;&&nbsp;
  267. <Link
  268. className='text-primary-600'
  269. target='_blank' rel='noopener noreferrer'
  270. href='https://dify.ai/privacy'
  271. >{t('login.pp')}</Link>
  272. </div>
  273. {IS_CE_EDITION && <div className="w-hull text-center block mt-2 text-xs text-gray-600">
  274. {t('login.goToInit')}
  275. &nbsp;
  276. <Link
  277. className='text-primary-600'
  278. href='/install'
  279. >{t('login.setAdminAccount')}</Link>
  280. </div>}
  281. </div>
  282. </div>
  283. </>
  284. )
  285. }
  286. export default NormalForm