Add Convex client setup and authentication handling
- Introduced a new module for Convex client configuration in `src/modules/convex.ts`. - Implemented an authentication token fetcher to manage user tokens. - Integrated the Convex client into the AuthProvider component in `src/pages/auth/index.tsx`.
This commit is contained in:
32
src/modules/convex.ts
Normal file
32
src/modules/convex.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { api } from "@kevisual/convex";
|
||||
import { ConvexClient, AuthTokenFetcher, ConvexHttpClient } from "convex/browser";
|
||||
const url = localStorage.getItem("CONVEX_URL") || 'https://convex.kevisual.cn'
|
||||
const client = new ConvexClient(url!);
|
||||
const httpClient = new ConvexHttpClient(url!);
|
||||
export const initConvex = async () => {
|
||||
const getToken = async () => {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
const res = await httpClient.action(api.token.create, { token: token! });
|
||||
if (res.code === 200) {
|
||||
return res.data.accessToken;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const authTokenFetcher: AuthTokenFetcher = async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
||||
console.log("AuthTokenFetcher called, forceRefreshToken:", forceRefreshToken);
|
||||
if (forceRefreshToken) {
|
||||
const token = await getToken();
|
||||
// console.log("fetch got token:", token);
|
||||
return token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
client.setAuth(authTokenFetcher, (isAuthenticated) => {
|
||||
console.log("Auth isAuthenticated:", isAuthenticated);
|
||||
});
|
||||
}
|
||||
|
||||
export { client, httpClient };
|
||||
@@ -5,6 +5,7 @@ import { LogIn, LockKeyhole } from "lucide-react"
|
||||
export { BaseHeader } from './modules/BaseHeader'
|
||||
import { useMemo } from 'react';
|
||||
import { useLocation, useNavigate } from '@tanstack/react-router';
|
||||
import { initConvex } from "@/modules/convex";
|
||||
|
||||
type Props = {
|
||||
children?: React.ReactNode,
|
||||
@@ -18,6 +19,7 @@ export const AuthProvider = ({ children, mustLogin }: Props) => {
|
||||
})));
|
||||
useEffect(() => {
|
||||
store.init()
|
||||
initConvex();
|
||||
}, [])
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate();
|
||||
|
||||
Reference in New Issue
Block a user