'use client' import React, { useEffect, useReducer, useState } from 'react' import { useTranslation } from 'react-i18next' import { useRouter } from 'next/navigation' import classNames from 'classnames' import useSWR from 'swr' import Link from 'next/link' import { useContext } from 'use-context-selector' import Toast from '../components/base/toast' import style from './page.module.css' import { IS_CE_EDITION, apiPrefix } from '@/config' import Button from '@/app/components/base/button' import { login, oauth } from '@/service/common' import I18n from '@/context/i18n' import { LanguagesSupportedUnderscore, getModelRuntimeSupported } from '@/utils/language' import { getPurifyHref } from '@/utils' const validEmailReg = /^[\w\.-]+@([\w-]+\.)+[\w-]{2,}$/ type IState = { formValid: boolean github: boolean google: boolean } type IAction = { type: 'login' | 'login_failed' | 'github_login' | 'github_login_failed' | 'google_login' | 'google_login_failed' } function reducer(state: IState, action: IAction) { switch (action.type) { case 'login': return { ...state, formValid: true, } case 'login_failed': return { ...state, formValid: true, } case 'github_login': return { ...state, github: true, } case 'github_login_failed': return { ...state, github: false, } case 'google_login': return { ...state, google: true, } case 'google_login_failed': return { ...state, google: false, } default: throw new Error('Unknown action.') } } const NormalForm = () => { const { t } = useTranslation() const router = useRouter() const { locale } = useContext(I18n) const language = getModelRuntimeSupported(locale) const [state, dispatch] = useReducer(reducer, { formValid: false, github: false, google: false, }) const [showPassword, setShowPassword] = useState(false) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [isLoading, setIsLoading] = useState(false) const handleEmailPasswordLogin = async () => { if (!validEmailReg.test(email)) { Toast.notify({ type: 'error', message: t('login.error.emailInValid'), }) return } try { setIsLoading(true) const res = await login({ url: '/login', body: { email, password, remember_me: true, }, }) localStorage.setItem('console_token', res.data) router.replace('/apps') } finally { setIsLoading(false) } } const { data: github, error: github_error } = useSWR(state.github ? ({ url: '/oauth/login/github', // params: { // provider: 'github', // }, }) : null, oauth) const { data: google, error: google_error } = useSWR(state.google ? ({ url: '/oauth/login/google', // params: { // provider: 'google', // }, }) : null, oauth) useEffect(() => { if (github_error !== undefined) dispatch({ type: 'github_login_failed' }) if (github) window.location.href = github.redirect_url }, [github, github_error]) useEffect(() => { if (google_error !== undefined) dispatch({ type: 'google_login_failed' }) if (google) window.location.href = google.redirect_url }, [google, google]) return ( <>
{t('login.welcome')}