Files
frigate/web/src/context/auth-provider.tsx
T

84 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-03-08 10:01:08 -06:00
import axios from "axios";
import { useEffect, useState } from "react";
2025-03-08 10:01:08 -06:00
import useSWR from "swr";
import { AuthContext, AuthState } from "./auth-context";
2025-03-08 10:01:08 -06:00
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [auth, setAuth] = useState<AuthState>({
user: null,
allowedCameras: [],
2025-03-08 10:01:08 -06:00
isLoading: true,
isAuthenticated: false,
});
const { data: profile, error } = useSWR("/profile", {
revalidateOnFocus: false,
revalidateOnReconnect: true,
fetcher: (url) =>
axios.get(url, { withCredentials: true }).then((res) => res.data),
});
useEffect(() => {
if (error) {
if (axios.isAxiosError(error) && error.response?.status === 401) {
// auth required but not logged in
setAuth({
user: null,
allowedCameras: [],
isLoading: false,
isAuthenticated: true,
});
2025-03-08 10:01:08 -06:00
}
return;
}
if (profile) {
if (profile.username && profile.username !== "anonymous") {
const newUser = {
username: profile.username,
role: profile.role || "viewer",
};
const allowedCameras = Array.isArray(profile.allowed_cameras)
? profile.allowed_cameras
: [];
setAuth({
user: newUser,
allowedCameras,
isLoading: false,
isAuthenticated: true,
});
2025-03-08 10:01:08 -06:00
} else {
// Unauthenticated mode (anonymous)
setAuth({
user: null,
allowedCameras: [],
isLoading: false,
isAuthenticated: false,
});
2025-03-08 10:01:08 -06:00
}
}
}, [profile, error]);
const login = (user: AuthState["user"]) => {
setAuth((current) => ({
...current,
user,
isLoading: false,
isAuthenticated: true,
}));
2025-03-08 10:01:08 -06:00
};
const logout = () => {
setAuth({
user: null,
allowedCameras: [],
isLoading: false,
isAuthenticated: true,
});
2025-03-08 10:01:08 -06:00
axios.get("/logout", { withCredentials: true });
};
2026-03-05 08:42:38 -06:00
return <AuthContext value={{ auth, login, logout }}>{children}</AuthContext>;
2025-03-08 10:01:08 -06:00
}