mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-09-19 09:40:13 +00:00
91 lines
2.8 KiB
TypeScript
91 lines
2.8 KiB
TypeScript
import { getProfile, login as loginRequest } from "@/api/user"
|
|
import { AuthContextProps } from "@/types"
|
|
import { createContext, useCallback, useContext, useEffect, useMemo } from "react"
|
|
import { useTranslation } from "react-i18next"
|
|
import { useNavigate } from "react-router-dom"
|
|
import { toast } from "sonner"
|
|
|
|
import { useMainStore } from "./useMainStore"
|
|
|
|
const AuthContext = createContext<AuthContextProps>({
|
|
profile: undefined,
|
|
login: () => {},
|
|
loginOauth2: () => {},
|
|
logout: () => {},
|
|
})
|
|
|
|
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
|
|
const profile = useMainStore((store) => store.profile)
|
|
const setProfile = useMainStore((store) => store.setProfile)
|
|
const { t } = useTranslation()
|
|
|
|
useEffect(() => {
|
|
;(async () => {
|
|
try {
|
|
const user = await getProfile()
|
|
user.role = user.role || 0
|
|
setProfile(user)
|
|
} catch {
|
|
setProfile(undefined)
|
|
}
|
|
})()
|
|
}, [setProfile])
|
|
|
|
const navigate = useNavigate()
|
|
|
|
const login = useCallback(async (username: string, password: string) => {
|
|
try {
|
|
await loginRequest(username, password)
|
|
const user = await getProfile()
|
|
user.role = user.role || 0
|
|
setProfile(user)
|
|
navigate("/dashboard")
|
|
} catch (error: any) {
|
|
const msg = error?.message
|
|
if (msg === "ApiErrorUnauthorized" || msg === "Unauthorized") {
|
|
toast(t("InvalidUsernameOrPassword"))
|
|
} else {
|
|
toast(msg || t("NetworkError"))
|
|
}
|
|
}
|
|
}, [navigate, setProfile, t])
|
|
|
|
const loginOauth2 = useCallback(async () => {
|
|
try {
|
|
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)
|
|
}
|
|
}, [navigate, setProfile])
|
|
|
|
const logout = useCallback(() => {
|
|
document.cookie.split(";").forEach(function (c) {
|
|
document.cookie = c
|
|
.replace(/^ +/, "")
|
|
.replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/")
|
|
})
|
|
setProfile(undefined)
|
|
navigate("/dashboard/login", { replace: true })
|
|
}, [navigate, setProfile])
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
profile,
|
|
login,
|
|
loginOauth2,
|
|
logout,
|
|
}),
|
|
[profile, login, loginOauth2, logout],
|
|
)
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
|
}
|
|
|
|
export const useAuth = () => {
|
|
return useContext(AuthContext)
|
|
}
|