feat: oauth2 登录

This commit is contained in:
naiba
2024-12-28 23:50:24 +08:00
parent f48d0a6393
commit 718bff0abb
12 changed files with 926 additions and 753 deletions
+29 -1
View File
@@ -1,3 +1,4 @@
import { getOauth2RedirectURL, Oauth2RequestType } from "@/api/oauth2"
import { Button } from "@/components/ui/button"
import {
Form,
@@ -9,10 +10,13 @@ import {
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { useAuth } from "@/hooks/useAuth"
import useSetting from "@/hooks/useSetting"
import { zodResolver } from "@hookform/resolvers/zod"
import i18next from "i18next"
import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { z } from "zod"
const formSchema = z.object({
@@ -25,7 +29,17 @@ const formSchema = z.object({
})
function Login() {
const { login } = useAuth()
const { login, loginOauth2 } = useAuth()
const { data: settingData } = useSetting()
useEffect(() => {
const oauth2Code = new URLSearchParams(window.location.search).get("code")
const oauth2State = new URLSearchParams(window.location.search).get("state")
const oauth2Provider = new URLSearchParams(window.location.search).get("provider")
if (oauth2Code && oauth2State && oauth2Provider) {
loginOauth2(oauth2Provider, oauth2State, oauth2Code)
}
}, [window.location.search])
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -39,6 +53,15 @@ function Login() {
login(values.username, values.password)
}
async function loginWith(provider: string) {
try {
const redirectUrl = await getOauth2RedirectURL(provider, Oauth2RequestType.LOGIN)
window.location.href = redirectUrl.redirect!
} catch (error: any) {
toast.error(error.message)
}
}
const { t } = useTranslation()
return (
@@ -79,6 +102,11 @@ function Login() {
<Button type="submit">{t("Login")}</Button>
</form>
</Form>
<div className="mt-4">
{settingData?.config?.oauth2_providers?.map((p: string) =>
<Button onClick={() => loginWith(p)}>{p}</Button>
)}
</div>
</div>
)
}