53 lines
1.2 KiB
TypeScript
53 lines
1.2 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||
|
|
import { pb, getCurrentUser, isAuthenticated } from '@/lib/pocketbase';
|
||
|
|
|
||
|
|
interface AuthContextType {
|
||
|
|
isLoggedIn: boolean;
|
||
|
|
user: ReturnType<typeof getCurrentUser>;
|
||
|
|
isLoading: boolean;
|
||
|
|
refresh: () => void;
|
||
|
|
}
|
||
|
|
|
||
|
|
const AuthContext = createContext<AuthContextType>({
|
||
|
|
isLoggedIn: false,
|
||
|
|
user: null,
|
||
|
|
isLoading: true,
|
||
|
|
refresh: () => {},
|
||
|
|
});
|
||
|
|
|
||
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||
|
|
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||
|
|
const [user, setUser] = useState<ReturnType<typeof getCurrentUser>>(null);
|
||
|
|
const [isLoading, setIsLoading] = useState(true);
|
||
|
|
|
||
|
|
const refresh = () => {
|
||
|
|
const valid = isAuthenticated();
|
||
|
|
setIsLoggedIn(valid);
|
||
|
|
setUser(getCurrentUser());
|
||
|
|
};
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
refresh();
|
||
|
|
setIsLoading(false);
|
||
|
|
|
||
|
|
// Listen for auth store changes
|
||
|
|
const unsubscribe = pb.authStore.onChange(() => {
|
||
|
|
refresh();
|
||
|
|
});
|
||
|
|
|
||
|
|
return () => {
|
||
|
|
unsubscribe();
|
||
|
|
};
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
return (
|
||
|
|
<AuthContext.Provider value={{ isLoggedIn, user, isLoading, refresh }}>
|
||
|
|
{children}
|
||
|
|
</AuthContext.Provider>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useAuth = () => useContext(AuthContext);
|