wip: auth methods

This commit is contained in:
douxc 2024-08-23 13:48:23 +08:00 committed by NFish
parent 38bfc3dfc8
commit a8a47e7251
12 changed files with 332 additions and 386 deletions

View File

@ -0,0 +1,3 @@
export default function CheckCode() {
return <div>CheckCode</div>
}

View File

@ -1,30 +0,0 @@
import { useTranslation } from 'react-i18next'
import style from '../page.module.css'
import Button from '@/app/components/base/button'
import { apiPrefix } from '@/config'
import { getPurifyHref } from '@/utils'
import classNames from '@/utils/classnames'
type GithubAuthButtonProps = {
disabled: boolean
}
export default function GithubAuthButton(props: GithubAuthButtonProps) {
const { t } = useTranslation()
return <a href={getPurifyHref(`${apiPrefix}/oauth/login/github`)}>
<Button
disabled={props.disabled}
className='w-full hover:!bg-gray-50'
>
<>
<span className={
classNames(
style.githubIcon,
'w-5 h-5 mr-2',
)
} />
<span className="truncate text-gray-800">{t('login.withGitHub')}</span>
</>
</Button>
</a>
}

View File

@ -1,30 +0,0 @@
import { useTranslation } from 'react-i18next'
import style from '../page.module.css'
import Button from '@/app/components/base/button'
import { apiPrefix } from '@/config'
import { getPurifyHref } from '@/utils'
import classNames from '@/utils/classnames'
type GoogleAuthButtonProps = {
disabled: boolean
}
export default function GoogleAuthButton(props: GoogleAuthButtonProps) {
const { t } = useTranslation()
return <a href={getPurifyHref(`${apiPrefix}/oauth/login/google`)}>
<Button
disabled={props.disabled}
className='w-full hover:!bg-gray-50'
>
<>
<span className={
classNames(
style.googleIcon,
'w-5 h-5 mr-2',
)
} />
<span className="truncate text-gray-800">{t('login.withGoogle')}</span>
</>
</Button>
</a>
}

View File

@ -0,0 +1,34 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
import Button from '@/app/components/base/button'
import { emailRegex } from '@/config'
import Toast from '@/app/components/base/toast'
export default function MailAndCodeAuth() {
const { t } = useTranslation()
const [email, setEmail] = useState('')
const handleGetEMailVerificationCode = async () => {
if (!emailRegex.test(email)) {
Toast.notify({
type: 'error',
message: t('login.error.emailInValid'),
})
}
window.location.href = '/signin/check-code'
}
return (<form onSubmit={() => { }}>
<div className='mb-2'>
<label htmlFor="email" className='my-2 block text-sm font-medium text-text-secondary'>{t('login.email')}</label>
<div className='mt-1'>
<Input type="email" value={email} placeholder={t('login.emailPlaceholder') as string} onChange={setEmail} className="px-3 h-9" />
</div>
<div className='mt-3'>
<Button variant='primary' className='w-full' onClick={handleGetEMailVerificationCode}>{t('login.continueWithCode')}</Button>
</div>
</div>
</form>
)
}

View File

@ -0,0 +1,112 @@
import Link from 'next/link'
import router from 'next/router'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '@/app/components/base/button'
import Toast from '@/app/components/base/toast'
import { emailRegex } from '@/config'
import { login } from '@/service/common'
export default function MailAndPasswordAuth() {
const { t } = useTranslation()
const [showPassword, setShowPassword] = useState(false)
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const handleEmailPasswordLogin = async () => {
if (!emailRegex.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,
},
})
if (res.result === 'success') {
localStorage.setItem('console_token', res.data)
router.replace('/apps')
}
else {
Toast.notify({
type: 'error',
message: res.data,
})
}
}
finally {
setIsLoading(false)
}
}
return <form onSubmit={() => { }}>
<div className='mb-3'>
<label htmlFor="email" className="my-2 block text-sm font-medium text-gray-900">
{t('login.email')}
</label>
<div className="mt-1">
<input
value={email}
onChange={e => setEmail(e.target.value)}
id="email"
type="email"
autoComplete="email"
placeholder={t('login.emailPlaceholder') || ''}
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'}
/>
</div>
</div>
<div className='mb-3'>
<label htmlFor="password" className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
<span>{t('login.password')}</span>
<Link href='/forgot-password' className='text-primary-600'>
{t('login.forget')}
</Link>
</label>
<div className="relative mt-1">
<input
id="password"
value={password}
onChange={e => setPassword(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter')
handleEmailPasswordLogin()
}}
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
placeholder={t('login.passwordPlaceholder') || ''}
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'}
/>
<div className="absolute inset-y-0 right-0 flex items-center pr-3">
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500"
>
{showPassword ? '👀' : '😝'}
</button>
</div>
</div>
</div>
<div className='mb-2'>
<Button
tabIndex={0}
variant='primary'
onClick={handleEmailPasswordLogin}
disabled={isLoading}
className="w-full"
>{t('login.signBtn')}</Button>
</div>
</form>
}

View File

@ -0,0 +1,52 @@
import { useTranslation } from 'react-i18next'
import style from '../page.module.css'
import Button from '@/app/components/base/button'
import { apiPrefix } from '@/config'
import { getPurifyHref } from '@/utils'
import classNames from '@/utils/classnames'
type SocialAuthProps = {
disabled?: boolean
}
export default function SocialAuth(props: SocialAuthProps) {
const { t } = useTranslation()
return <>
<div className='w-full'>
<a href={getPurifyHref(`${apiPrefix}/oauth/login/github`)}>
<Button
disabled={props.disabled}
className='w-full hover:!bg-gray-50'
>
<>
<span className={
classNames(
style.githubIcon,
'w-5 h-5 mr-2',
)
} />
<span className="truncate text-gray-800">{t('login.withGitHub')}</span>
</>
</Button>
</a>
</div>
<div className='w-full'>
<a href={getPurifyHref(`${apiPrefix}/oauth/login/google`)}>
<Button
disabled={props.disabled}
className='w-full hover:!bg-gray-50'
>
<>
<span className={
classNames(
style.googleIcon,
'w-5 h-5 mr-2',
)
} />
<span className="truncate text-gray-800">{t('login.withGoogle')}</span>
</>
</Button>
</a>
</div>
</>
}

View File

@ -1,34 +1,17 @@
'use client'
import React from 'react'
import { useSearchParams } from 'next/navigation'
import SSOAuthButton from './components/sso-auth'
import NormalForm from './normalForm'
import OneMoreStep from './oneMoreStep'
import cn from '@/utils/classnames'
import { API_PREFIX } from '@/config'
const Forms = () => {
const searchParams = useSearchParams()
const step = searchParams.get('step')
const getForm = () => {
switch (step) {
case 'next':
return <OneMoreStep />
default:
return <NormalForm />
}
export default function RenderFormBySystemFeatures() {
async function getFeatures() {
'use server'
const ret = await fetch(`${API_PREFIX}/system-features`).then((ret) => {
return ret.json()
})
return ret
}
return <div className={
cn(
'flex flex-col items-center w-full grow justify-center',
'px-6',
'md:px-[108px]',
)
}>
<div className='flex flex-col md:w-[400px]'>
{getForm()}
</div>
</div>
const systemFeatures = await getFeatures()
if (systemFeatures.isSsoEnabled)
return <SSOAuthButton />
return <NormalForm />
}
export default Forms

54
web/app/signin/layout.tsx Normal file
View File

@ -0,0 +1,54 @@
import Script from 'next/script'
import Header from './_header'
import style from './page.module.css'
import cn from '@/utils/classnames'
import { IS_CE_EDITION } from '@/config'
export default async function SignInLayout({ children }: any) {
return <>
{!IS_CE_EDITION && (
<>
<Script strategy="beforeInteractive" async src={'https://www.googletagmanager.com/gtag/js?id=AW-11217955271'}></Script>
<Script
id="ga-monitor-register"
dangerouslySetInnerHTML={{
__html: 'window.dataLayer2 = window.dataLayer2 || [];function gtag(){dataLayer2.push(arguments);}gtag(\'js\', new Date());gtag(\'config\', \'AW-11217955271"\');',
}}
>
</Script>
</>
)}
<div className={cn(
style.background,
'flex w-full min-h-screen',
'sm:p-4 lg:p-8',
'gap-x-20',
'justify-center lg:justify-start',
)}>
<div className={
cn(
'flex w-full flex-col bg-white shadow rounded-2xl shrink-0',
'space-between',
)
}>
<Header />
<div className={
cn(
'flex flex-col items-center w-full grow justify-center',
'px-6',
'md:px-[108px]',
)
}>
<div className='flex flex-col md:w-[400px]'>
{children}
</div>
</div>
<div className='px-8 py-6 text-sm font-normal text-gray-500'>
© {new Date().getFullYear()} LangGenius, Inc. All rights reserved.
</div>
</div>
</div>
</>
}

View File

@ -1,146 +1,47 @@
'use client'
import React, { useReducer, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import Toast from '../components/base/toast'
import SSOAuthButton from './components/sso-auth-button'
import GoogleAuthButton from './components/google-auth-button'
import GithubAuthButton from './components/github-auth-button'
import { IS_CE_EDITION, SUPPORT_MAIL_LOGIN, emailRegex } from '@/config'
import Button from '@/app/components/base/button'
import { login } from '@/service/common'
import Loading from '../components/base/loading'
import SSOAuthButton from './components/sso-auth'
import MailAndCodeAuth from './components/mail-and-code-auth'
import MailAndPasswordAuth from './components/mail-and-password-auth'
import SocialAuth from './components/social-auth'
import { IS_CE_EDITION } from '@/config'
import { defaultSystemFeatures } from '@/types/feature'
import { getSystemFeatures } from '@/service/common'
import cn from '@/utils/classnames'
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.')
}
}
type AuthType = 'password' | 'code' | 'sso' | 'social'
const NormalForm = () => {
const { t } = useTranslation()
const useEmailLogin = IS_CE_EDITION || SUPPORT_MAIL_LOGIN
const [authType, updateAuthType] = useState('code')
const [enabledAuthType, updateEnabledAuthType] = useState<AuthType[]>(['password', 'code', 'sso', 'social'])
const router = useRouter()
const [isLoading, setIsLoading] = useState(true)
const [systemFeatures, setSystemFeatures] = useState(defaultSystemFeatures)
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 (!emailRegex.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,
},
})
if (res.result === 'success') {
localStorage.setItem('console_token', res.data)
router.replace('/apps')
}
else {
Toast.notify({
type: 'error',
message: res.data,
})
}
}
finally {
useEffect(() => {
getSystemFeatures().then((res) => {
console.log('🚀 ~ getSystemFeatures ~ res:', res)
setSystemFeatures(res)
}).finally(() => {
setIsLoading(false)
}
})
}, [])
if (isLoading) {
return <div className={
cn(
'flex flex-col items-center w-full grow justify-center',
'px-6',
'md:px-[108px]',
)
}>
<Loading type='area' />
</div>
}
// 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_error])
return (
<>
<div className="w-full mx-auto">
@ -152,91 +53,32 @@ const NormalForm = () => {
<div className="bg-white ">
<div className="flex flex-col gap-3 mt-6">
<div className='w-full'>
<GithubAuthButton disabled={isLoading} />
</div>
<div className='w-full'>
<GoogleAuthButton disabled={isLoading} />
</div>
<div className='w-full'>
<SSOAuthButton />
</div>
{enabledAuthType.includes('social') && <SocialAuth />}
{enabledAuthType.includes('sso') && <div className='w-full'><SSOAuthButton /></div>}
</div>
<>
<div className="relative mt-6">
{(enabledAuthType.includes('code') || enabledAuthType.includes('password'))
&& <div className="relative mt-6">
<div className="absolute inset-0 flex items-center" aria-hidden="true">
<div className="w-full border-t border-gray-300" />
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 text-gray-300 bg-white">OR</span>
<span className="px-2 text-gray-300 bg-white">{t('login.or')}</span>
</div>
</div>
</div>}
{enabledAuthType.includes('code') && authType === 'code' && <>
<MailAndCodeAuth />
{enabledAuthType.includes('password') && <div className='cursor-pointer py-1 text-center' onClick={() => { updateAuthType('password') }}>
<span className='text-xs text-components-button-secondary-accent-text'>{t('login.usePassword')}</span>
</div>}
</>}
{enabledAuthType.includes('password') && authType === 'password' && <>
<MailAndPasswordAuth />
{enabledAuthType.includes('code') && <div className='cursor-pointer py-1 text-center' onClick={() => { updateAuthType('code') }}>
<span className='text-xs text-components-button-secondary-accent-text'>{t('login.useVerificationCode')}</span>
</div>}
</>}
<form onSubmit={() => { }}>
<div className='mb-5'>
<label htmlFor="email" className="my-2 block text-sm font-medium text-gray-900">
{t('login.email')}
</label>
<div className="mt-1">
<input
value={email}
onChange={e => setEmail(e.target.value)}
id="email"
type="email"
autoComplete="email"
placeholder={t('login.emailPlaceholder') || ''}
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'}
/>
</div>
</div>
<div className='mb-4'>
<label htmlFor="password" className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
<span>{t('login.password')}</span>
<Link href='/forgot-password' className='text-primary-600'>
{t('login.forget')}
</Link>
</label>
<div className="relative mt-1">
<input
id="password"
value={password}
onChange={e => setPassword(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter')
handleEmailPasswordLogin()
}}
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
placeholder={t('login.passwordPlaceholder') || ''}
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'}
/>
<div className="absolute inset-y-0 right-0 flex items-center pr-3">
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500"
>
{showPassword ? '👀' : '😝'}
</button>
</div>
</div>
</div>
<div className='mb-2'>
<Button
tabIndex={0}
variant='primary'
onClick={handleEmailPasswordLogin}
disabled={isLoading}
className="w-full"
>{t('login.signBtn')}</Button>
</div>
</form>
</>
{/* agree to our Terms and Privacy Policy. */}
<div className="w-hull text-center block mt-2 text-xs text-gray-600">
{t('login.tosDesc')}
&nbsp;

View File

@ -1,94 +1,16 @@
'use client'
import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import Loading from '../components/base/loading'
import Forms from './forms'
import Header from './_header'
import style from './page.module.css'
import UserSSOForm from './userSSOForm'
import cn from '@/utils/classnames'
import { IS_CE_EDITION } from '@/config'
import OneMoreStep from './oneMoreStep'
import NormalForm from './normalForm'
import type { SystemFeatures } from '@/types/feature'
import { defaultSystemFeatures } from '@/types/feature'
import { getSystemFeatures } from '@/service/common'
type Props = {
searchParams: { step?: 'next' }
}
const SignIn = () => {
const [loading, setLoading] = useState<boolean>(true)
const [systemFeatures, setSystemFeatures] = useState<SystemFeatures>(defaultSystemFeatures)
const SignIn = ({ searchParams }: Props) => {
if (searchParams?.step === 'next')
return <OneMoreStep />
useEffect(() => {
getSystemFeatures().then((res) => {
setSystemFeatures(res)
}).finally(() => {
setLoading(false)
})
}, [])
return (
<>
{!IS_CE_EDITION && (
<>
<Script strategy="beforeInteractive" async src={'https://www.googletagmanager.com/gtag/js?id=AW-11217955271'}></Script>
<Script
id="ga-monitor-register"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer2 = window.dataLayer2 || [];
function gtag(){dataLayer2.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-11217955271"');
`,
}}
>
</Script>
</>
)}
<div className={cn(
style.background,
'flex w-full min-h-screen',
'sm:p-4 lg:p-8',
'gap-x-20',
'justify-center lg:justify-start',
)}>
<div className={
cn(
'flex w-full flex-col bg-white shadow rounded-2xl shrink-0',
'space-between',
)
}>
<Header />
{loading && (
<div className={
cn(
'flex flex-col items-center w-full grow justify-center',
'px-6',
'md:px-[108px]',
)
}>
<Loading type='area' />
</div>
)}
{!loading && !systemFeatures.sso_enforced_for_signin && (
<>
<Forms />
<div className='px-8 py-6 text-sm font-normal text-gray-500'>
© {new Date().getFullYear()} LangGenius, Inc. All rights reserved.
</div>
</>
)}
{!loading && systemFeatures.sso_enforced_for_signin && (
<UserSSOForm protocol={systemFeatures.sso_enforced_for_signin_protocol} />
)}
</div>
</div>
</>
)
return <NormalForm />
}
export default SignIn

View File

@ -9,6 +9,10 @@ const translation = {
namePlaceholder: '输入用户名',
forget: '忘记密码?',
signBtn: '登录',
continueWithCode: '发送验证码',
usePassword: '使用密码登录',
useVerificationCode: '使用验证码登录',
or: '或',
installBtn: '设置',
setAdminAccount: '设置管理员账户',
setAdminAccountDesc: '管理员拥有的最大权限,可用于创建应用和管理 LLM 供应商等。',