You've already forked nginx-proxy-manager
mirror of
https://github.com/NginxProxyManager/nginx-proxy-manager.git
synced 2025-11-02 16:53:15 +03:00
React
This commit is contained in:
72
frontend/src/context/AuthContext.tsx
Normal file
72
frontend/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { createContext, type ReactNode, useContext, useState } from "react";
|
||||
import { useIntervalWhen } from "rooks";
|
||||
import { getToken, refreshToken, type TokenResponse } from "src/api/backend";
|
||||
import AuthStore from "src/modules/AuthStore";
|
||||
|
||||
// Context
|
||||
export interface AuthContextType {
|
||||
authenticated: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
const initalValue = null;
|
||||
const AuthContext = createContext<AuthContextType | null>(initalValue);
|
||||
|
||||
// Provider
|
||||
interface Props {
|
||||
children?: ReactNode;
|
||||
tokenRefreshInterval?: number;
|
||||
}
|
||||
function AuthProvider({ children, tokenRefreshInterval = 5 * 60 * 1000 }: Props) {
|
||||
const queryClient = useQueryClient();
|
||||
const [authenticated, setAuthenticated] = useState(AuthStore.hasActiveToken());
|
||||
|
||||
const handleTokenUpdate = (response: TokenResponse) => {
|
||||
AuthStore.set(response);
|
||||
setAuthenticated(true);
|
||||
};
|
||||
|
||||
const login = async (identity: string, secret: string) => {
|
||||
const response = await getToken({ payload: { identity, secret } });
|
||||
handleTokenUpdate(response);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
AuthStore.clear();
|
||||
setAuthenticated(false);
|
||||
queryClient.clear();
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
const response = await refreshToken();
|
||||
handleTokenUpdate(response);
|
||||
};
|
||||
|
||||
useIntervalWhen(
|
||||
() => {
|
||||
if (authenticated) {
|
||||
refresh();
|
||||
}
|
||||
},
|
||||
tokenRefreshInterval,
|
||||
true,
|
||||
);
|
||||
|
||||
const value = { authenticated, login, logout };
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
function useAuthState() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error("useAuthState must be used within a AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export { AuthProvider, useAuthState };
|
||||
export default AuthContext;
|
||||
Reference in New Issue
Block a user