feat: oauth2 登录

This commit is contained in:
naiba
2024-12-28 23:50:24 +08:00
parent fbf931293e
commit 97a5deb648
12 changed files with 926 additions and 753 deletions

View File

@@ -5,11 +5,13 @@ import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { useMainStore } from "./useMainStore"
import { oauth2callback } from "@/api/oauth2"
const AuthContext = createContext<AuthContextProps>({
profile: undefined,
login: () => {},
logout: () => {},
login: () => { },
loginOauth2: () => { },
logout: () => { },
})
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
@@ -17,7 +19,7 @@ export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
const setProfile = useMainStore((store) => store.setProfile)
useEffect(() => {
;(async () => {
; (async () => {
try {
const user = await getProfile()
user.role = user.role || 0
@@ -43,6 +45,20 @@ export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
}
}
const loginOauth2 = async (provider: string, state: string, code: string) => {
try {
await oauth2callback(provider, state, code)
const user = await getProfile()
user.role = user.role || 0
setProfile(user)
navigate("/dashboard")
} catch (error: any) {
toast(error.message)
} finally {
window.history.replaceState({}, document.title, window.location.pathname)
}
}
const logout = () => {
document.cookie.split(";").forEach(function (c) {
document.cookie = c
@@ -57,6 +73,7 @@ export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
() => ({
profile,
login,
loginOauth2,
logout,
}),
[profile],

View File

@@ -1,7 +1,8 @@
import { swrFetcher } from "@/api/api"
import { ModelSettingResponse } from "@/types"
import { GithubComNezhahqNezhaModelSettingResponseModelConfig } from "@/types"
import useSWR from "swr"
export default function useSetting() {
return useSWR<ModelSettingResponse>("/api/v1/setting", swrFetcher)
return useSWR<GithubComNezhahqNezhaModelSettingResponseModelConfig>("/api/v1/setting", swrFetcher)
}