's'
This commit is contained in:
68
app/digital/lib/useAuthAndVip.ts
Normal file
68
app/digital/lib/useAuthAndVip.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { getStoredUser, getStoredToken } from "@/app/digital/lib/pocketbase";
|
||||
|
||||
export interface AuthAndVipState {
|
||||
user: { id: string; email: string } | null;
|
||||
vip: boolean;
|
||||
loading: boolean;
|
||||
refetch: () => Promise<{ user: { id: string; email: string } | null; vip: boolean }>;
|
||||
}
|
||||
|
||||
export function useAuthAndVip(): AuthAndVipState {
|
||||
const [user, setUser] = useState<{ id: string; email: string } | null>(null);
|
||||
const [vip, setVip] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refetch = useCallback(async (): Promise<{ user: { id: string; email: string } | null; vip: boolean }> => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const meRes = await fetch("/api/digital/auth/me", { credentials: "include" });
|
||||
const meData = await meRes.json();
|
||||
let newUser = meData?.user ?? null;
|
||||
|
||||
if (!newUser) {
|
||||
const storedUser = getStoredUser();
|
||||
const storedToken = getStoredToken();
|
||||
if (storedUser && storedToken) {
|
||||
newUser = storedUser;
|
||||
try {
|
||||
await fetch("/api/digital/auth/sync-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: storedToken, record: storedUser }),
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let newVip = false;
|
||||
if (newUser?.email) {
|
||||
const vipRes = await fetch(`/api/digital/vip/check?email=${encodeURIComponent(newUser.email)}`, { credentials: "include" });
|
||||
const vipData = await vipRes.json();
|
||||
newVip = vipData?.vip === true;
|
||||
}
|
||||
|
||||
setUser(newUser);
|
||||
setVip(newVip);
|
||||
return { user: newUser, vip: newVip };
|
||||
} catch {
|
||||
const storedUser = getStoredUser();
|
||||
setUser(storedUser);
|
||||
setVip(false);
|
||||
return { user: storedUser, vip: false };
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refetch();
|
||||
}, [refetch]);
|
||||
|
||||
return { user, vip, loading, refetch };
|
||||
}
|
||||
Reference in New Issue
Block a user