forked from mtusi2026/mtusi2026lab3
фронт и secure browser session
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
type PropsWithChildren,
|
||||
} from "react";
|
||||
|
||||
import { api, ApiError } from "../api/client";
|
||||
import type { LoginInput, RegisterInput, User } from "../api/types";
|
||||
|
||||
type AuthContextValue = {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
login: (input: LoginInput) => Promise<void>;
|
||||
register: (input: RegisterInput) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
const meQueryKey = ["current-user"] as const;
|
||||
|
||||
async function loadCurrentUser(): Promise<User | null> {
|
||||
try {
|
||||
return await api.me();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: PropsWithChildren) {
|
||||
const queryClient = useQueryClient();
|
||||
const meQuery = useQuery({
|
||||
queryKey: meQueryKey,
|
||||
queryFn: loadCurrentUser,
|
||||
retry: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
const login = useCallback(
|
||||
async (input: LoginInput) => {
|
||||
const session = await api.login(input);
|
||||
queryClient.setQueryData(meQueryKey, session.user);
|
||||
},
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const register = useCallback(
|
||||
async (input: RegisterInput) => {
|
||||
await api.register(input);
|
||||
const session = await api.login({
|
||||
username: input.username,
|
||||
password: input.password,
|
||||
});
|
||||
queryClient.setQueryData(meQueryKey, session.user);
|
||||
},
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api.logout();
|
||||
queryClient.setQueryData(meQueryKey, null);
|
||||
queryClient.removeQueries({ queryKey: ["chats"] });
|
||||
}, [queryClient]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user: meQuery.data ?? null,
|
||||
isLoading: meQuery.isLoading,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used within AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user