暂存
This commit is contained in:
@@ -8,13 +8,14 @@ import {
|
|||||||
} from "@refinedev/mui";
|
} from "@refinedev/mui";
|
||||||
import { SessionProvider, signIn, signOut, useSession } from "next-auth/react";
|
import { SessionProvider, signIn, signOut, useSession } from "next-auth/react";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import React from "react";
|
import React, { useEffect } from "react";
|
||||||
|
|
||||||
import routerProvider from "@refinedev/nextjs-router";
|
import routerProvider from "@refinedev/nextjs-router";
|
||||||
|
|
||||||
import { ColorModeContextProvider } from "@contexts/color-mode";
|
import { ColorModeContextProvider } from "@contexts/color-mode";
|
||||||
import { dataProvider } from "@providers/data-provider";
|
import { dataProvider } from "@providers/data-provider";
|
||||||
import { ProjectProvider } from "@/contexts/ProjectContext";
|
import { ProjectProvider } from "@/contexts/ProjectContext";
|
||||||
|
import { useAuthStore } from "@/store/authStore";
|
||||||
|
|
||||||
import { LiaNetworkWiredSolid } from "react-icons/lia";
|
import { LiaNetworkWiredSolid } from "react-icons/lia";
|
||||||
import { TbDatabaseEdit } from "react-icons/tb";
|
import { TbDatabaseEdit } from "react-icons/tb";
|
||||||
@@ -47,6 +48,11 @@ type AppProps = {
|
|||||||
const App = (props: React.PropsWithChildren<AppProps>) => {
|
const App = (props: React.PropsWithChildren<AppProps>) => {
|
||||||
const { data, status } = useSession();
|
const { data, status } = useSession();
|
||||||
const to = usePathname();
|
const to = usePathname();
|
||||||
|
const setAccessToken = useAuthStore((state) => state.setAccessToken);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setAccessToken(typeof data?.accessToken === "string" ? data.accessToken : null);
|
||||||
|
}, [data?.accessToken, setAccessToken]);
|
||||||
|
|
||||||
if (status === "loading") {
|
if (status === "loading") {
|
||||||
return <span>loading...</span>;
|
return <span>loading...</span>;
|
||||||
@@ -103,6 +109,7 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
|
|||||||
if (data?.user) {
|
if (data?.user) {
|
||||||
const { user } = data;
|
const { user } = data;
|
||||||
return {
|
return {
|
||||||
|
id: user.id,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
avatar: user.image,
|
avatar: user.image,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
|
import { NextAuthOptions } from "next-auth";
|
||||||
import KeycloakProvider from "next-auth/providers/keycloak";
|
import KeycloakProvider from "next-auth/providers/keycloak";
|
||||||
import Avatar from "@assets/avatar/avatar-small.jpeg";
|
import Avatar from "@assets/avatar/avatar-small.jpeg";
|
||||||
|
|
||||||
const authOptions = {
|
const authOptions: NextAuthOptions = {
|
||||||
// Configure one or more authentication providers
|
// Configure one or more authentication providers
|
||||||
providers: [
|
providers: [
|
||||||
KeycloakProvider({
|
KeycloakProvider({
|
||||||
@@ -19,6 +20,26 @@ const authOptions = {
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
secret: process.env.NEXTAUTH_SECRET,
|
secret: process.env.NEXTAUTH_SECRET,
|
||||||
|
callbacks: {
|
||||||
|
jwt: async ({ token, profile, account }) => {
|
||||||
|
if (profile?.sub) {
|
||||||
|
token.sub = profile.sub;
|
||||||
|
}
|
||||||
|
if (account?.access_token) {
|
||||||
|
token.accessToken = account.access_token;
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
session: async ({ session, token }) => {
|
||||||
|
if (session.user && token.sub) {
|
||||||
|
session.user.id = token.sub;
|
||||||
|
}
|
||||||
|
if (token.accessToken) {
|
||||||
|
session.accessToken = token.accessToken;
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default authOptions;
|
export default authOptions;
|
||||||
|
|||||||
@@ -25,9 +25,9 @@ import { setMapExtent, setMapWorkspace, setNetworkName } from "@config/config";
|
|||||||
import { useProjectStore } from "@/store/projectStore";
|
import { useProjectStore } from "@/store/projectStore";
|
||||||
|
|
||||||
type IUser = {
|
type IUser = {
|
||||||
id: number;
|
id?: string;
|
||||||
name: string;
|
name?: string;
|
||||||
avatar: string;
|
avatar?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
|
export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import { api } from "@/lib/api";
|
|||||||
import { config, NETWORK_NAME } from "@/config/config";
|
import { config, NETWORK_NAME } from "@/config/config";
|
||||||
|
|
||||||
type IUser = {
|
type IUser = {
|
||||||
id: number;
|
id: string;
|
||||||
name: string;
|
name?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const OptimizationParameters: React.FC = () => {
|
const OptimizationParameters: React.FC = () => {
|
||||||
@@ -83,7 +83,7 @@ const OptimizationParameters: React.FC = () => {
|
|||||||
|
|
||||||
setAnalyzing(true);
|
setAnalyzing(true);
|
||||||
|
|
||||||
if (!user || !user.name) {
|
if (!user || !user.id) {
|
||||||
open?.({
|
open?.({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: "用户信息无效",
|
message: "用户信息无效",
|
||||||
@@ -104,6 +104,7 @@ const OptimizationParameters: React.FC = () => {
|
|||||||
method: method,
|
method: method,
|
||||||
sensor_count: sensorCount,
|
sensor_count: sensorCount,
|
||||||
min_diameter: minDiameter,
|
min_diameter: minDiameter,
|
||||||
|
user_id: user.id,
|
||||||
user_name: user.name,
|
user_name: user.name,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,8 +44,8 @@ dayjs.extend(utc);
|
|||||||
dayjs.extend(timezone);
|
dayjs.extend(timezone);
|
||||||
|
|
||||||
type IUser = {
|
type IUser = {
|
||||||
id: number;
|
id: string;
|
||||||
name: string;
|
name?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface TimeSeriesPoint {
|
export interface TimeSeriesPoint {
|
||||||
@@ -459,7 +459,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user || !user.name) {
|
if (!user || !user.id) {
|
||||||
open?.({
|
open?.({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: "用户信息无效,请重新登录",
|
message: "用户信息无效,请重新登录",
|
||||||
|
|||||||
@@ -104,8 +104,8 @@ interface SCADADeviceListProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type IUser = {
|
type IUser = {
|
||||||
id: number;
|
id: string;
|
||||||
name: string;
|
name?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||||
@@ -601,7 +601,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user || !user.name) {
|
if (!user || !user.id) {
|
||||||
open?.({
|
open?.({
|
||||||
type: "error",
|
type: "error",
|
||||||
message: "用户信息无效,请重新登录",
|
message: "用户信息无效,请重新登录",
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ import {
|
|||||||
IconButton,
|
IconButton,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { apiFetch } from "@/lib/apiFetch";
|
||||||
|
import { config, NETWORK_NAME } from "@/config/config";
|
||||||
|
|
||||||
interface ProjectSelectorProps {
|
interface ProjectSelectorProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -28,45 +30,96 @@ interface ProjectSelectorProps {
|
|||||||
onClose?: () => void;
|
onClose?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const PROJECTS = [
|
type ProjectOption = {
|
||||||
{
|
id: string;
|
||||||
id: "tjwater",
|
label: string;
|
||||||
label: "默认",
|
workspace: string;
|
||||||
workspace: "tjwater",
|
networkName: string;
|
||||||
networkName: "tjwater",
|
extent: number[];
|
||||||
extent: [13508802, 3608164, 13555651, 3633686],
|
description?: string | null;
|
||||||
},
|
status?: string | null;
|
||||||
// {
|
projectRole?: string | null;
|
||||||
// label: "苏州河",
|
};
|
||||||
// workspace: "szh",
|
|
||||||
// networkName: "szh",
|
|
||||||
// extent: [13490131, 3630016, 13525879, 3666969],
|
|
||||||
// },
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
label: "测试项目",
|
|
||||||
workspace: "test",
|
|
||||||
networkName: "test",
|
|
||||||
extent: [13508849, 3608036, 13555781, 3633813],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
|
export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
|
||||||
open,
|
open,
|
||||||
onSelect,
|
onSelect,
|
||||||
onClose,
|
onClose,
|
||||||
}) => {
|
}) => {
|
||||||
const [projectId, setProjectId] = useState(PROJECTS[0].id);
|
const [projects, setProjects] = useState<ProjectOption[]>([]);
|
||||||
const [workspace, setWorkspace] = useState(PROJECTS[0].workspace);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [networkName, setNetworkName] = useState(PROJECTS[0].networkName);
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
const [extent, setExtent] = useState<number[]>(
|
const [projectId, setProjectId] = useState("");
|
||||||
PROJECTS[0].extent,
|
const [projectIdError, setProjectIdError] = useState<string | null>(null);
|
||||||
);
|
const [workspace, setWorkspace] = useState(config.MAP_WORKSPACE);
|
||||||
|
const [networkName, setNetworkName] = useState(NETWORK_NAME || "tjwater");
|
||||||
|
const [extent, setExtent] = useState<number[]>(config.MAP_EXTENT);
|
||||||
const [customMode, setCustomMode] = useState(false);
|
const [customMode, setCustomMode] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchProjects = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setLoadError(null);
|
||||||
|
try {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${config.BACKEND_URL}/api/v1/meta/projects`,
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
const data = await response.json();
|
||||||
|
const mapped: ProjectOption[] = Array.isArray(data)
|
||||||
|
? data.map((item) => {
|
||||||
|
const bbox = Array.isArray(item.map_extent?.bbox)
|
||||||
|
? item.map_extent.bbox.map((value: number) => Number(value))
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
id: item.project_id,
|
||||||
|
label: item.name || item.code || item.project_id,
|
||||||
|
workspace: item.gs_workspace || config.MAP_WORKSPACE,
|
||||||
|
networkName: item.code || NETWORK_NAME || config.MAP_WORKSPACE,
|
||||||
|
extent:
|
||||||
|
bbox && bbox.length === 4 ? bbox : config.MAP_EXTENT,
|
||||||
|
description: item.description,
|
||||||
|
status: item.status,
|
||||||
|
projectRole: item.project_role,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
setProjects(mapped);
|
||||||
|
const savedProjectId = localStorage.getItem("active_project");
|
||||||
|
const initial =
|
||||||
|
(savedProjectId &&
|
||||||
|
mapped.find((project) => project.id === savedProjectId)) ||
|
||||||
|
mapped[0];
|
||||||
|
if (initial) {
|
||||||
|
setProjectId(initial.id);
|
||||||
|
setWorkspace(initial.workspace);
|
||||||
|
setNetworkName(initial.networkName);
|
||||||
|
setExtent(initial.extent);
|
||||||
|
setCustomMode(false);
|
||||||
|
} else {
|
||||||
|
setCustomMode(true);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to load projects:", error);
|
||||||
|
setLoadError("项目列表加载失败,请使用自定义配置");
|
||||||
|
setCustomMode(true);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchProjects();
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleConfirm = () => {
|
const handleConfirm = () => {
|
||||||
const resolvedProjectId = projectId.trim() || workspace || networkName;
|
if (!projectId.trim()) {
|
||||||
onSelect(resolvedProjectId, workspace, networkName, extent);
|
setProjectIdError("项目 ID 不能为空");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setProjectIdError(null);
|
||||||
|
onSelect(projectId.trim(), workspace, networkName, extent);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -126,31 +179,46 @@ export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
|
|||||||
<FormControl fullWidth variant="outlined">
|
<FormControl fullWidth variant="outlined">
|
||||||
<InputLabel>项目</InputLabel>
|
<InputLabel>项目</InputLabel>
|
||||||
<Select
|
<Select
|
||||||
value={workspace}
|
value={projectId}
|
||||||
label="项目"
|
label="项目"
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value;
|
const val = e.target.value;
|
||||||
if (val === "custom") {
|
if (val === "custom") {
|
||||||
setCustomMode(true);
|
setCustomMode(true);
|
||||||
setProjectId(workspace);
|
setProjectIdError(null);
|
||||||
} else {
|
} else {
|
||||||
const p = PROJECTS.find((p) => p.workspace === val);
|
const p = projects.find((p) => p.id === val);
|
||||||
if (p) {
|
if (p) {
|
||||||
setProjectId(p.id);
|
setProjectId(p.id);
|
||||||
setWorkspace(p.workspace);
|
setWorkspace(p.workspace);
|
||||||
setNetworkName(p.networkName);
|
setNetworkName(p.networkName);
|
||||||
setExtent(p.extent);
|
setExtent(p.extent);
|
||||||
|
setProjectIdError(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{PROJECTS.map((p) => (
|
{projects.length === 0 && (
|
||||||
<MenuItem key={p.workspace} value={p.workspace}>
|
<MenuItem value="" disabled>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
{isLoading ? "正在加载项目..." : "暂无可用项目"}
|
||||||
|
</Typography>
|
||||||
|
</MenuItem>
|
||||||
|
)}
|
||||||
|
{projects.map((p) => (
|
||||||
|
<MenuItem key={p.id} value={p.id}>
|
||||||
<Box sx={{ display: "flex", flexDirection: "column" }}>
|
<Box sx={{ display: "flex", flexDirection: "column" }}>
|
||||||
<Typography variant="body1">{p.label}</Typography>
|
<Typography variant="body1">{p.label}</Typography>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
工作区: {p.workspace} | 管网: {p.networkName}
|
工作区: {p.workspace} | 管网: {p.networkName}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
{(p.status || p.projectRole) && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{p.status ? `状态: ${p.status}` : ""}
|
||||||
|
{p.status && p.projectRole ? " | " : ""}
|
||||||
|
{p.projectRole ? `角色: ${p.projectRole}` : ""}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
@@ -158,15 +226,26 @@ export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
|
|||||||
<Typography variant="body1">自定义配置...</Typography>
|
<Typography variant="body1">自定义配置...</Typography>
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
</Select>
|
</Select>
|
||||||
|
{loadError && (
|
||||||
|
<Typography variant="caption" color="error">
|
||||||
|
{loadError}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
</FormControl>
|
</FormControl>
|
||||||
) : (
|
) : (
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
<TextField
|
<TextField
|
||||||
label="项目 ID"
|
label="项目 ID"
|
||||||
value={projectId}
|
value={projectId}
|
||||||
onChange={(e) => setProjectId(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setProjectId(e.target.value);
|
||||||
|
setProjectIdError(null);
|
||||||
|
}}
|
||||||
fullWidth
|
fullWidth
|
||||||
helperText="例如: tjwater"
|
helperText={
|
||||||
|
projectIdError || "例如: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||||
|
}
|
||||||
|
error={Boolean(projectIdError)}
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
label="Geoserver 工作区"
|
label="Geoserver 工作区"
|
||||||
|
|||||||
@@ -69,9 +69,25 @@ export const ProjectProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
setIsConfigured(true);
|
setIsConfigured(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await apiFetch(`${config.BACKEND_URL}/openproject/?network=${net}`, {
|
const response = await apiFetch(
|
||||||
method: "POST",
|
`${config.BACKEND_URL}/openproject/?network=${net}`,
|
||||||
});
|
{
|
||||||
|
method: "POST",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
const data = await response.json();
|
||||||
|
const bbox = Array.isArray(data?.map_extent?.bbox)
|
||||||
|
? data.map_extent.bbox.map((value: number) => Number(value))
|
||||||
|
: null;
|
||||||
|
if (bbox && bbox.length === 4) {
|
||||||
|
setMapExtent(bbox);
|
||||||
|
localStorage.setItem("NEXT_PUBLIC_MAP_EXTENT", bbox.join(","));
|
||||||
|
localStorage.removeItem(`${ws}_map_view`);
|
||||||
|
setCurrentProject((prev) => ({ ...prev, extent: bbox }));
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to open project:", error);
|
console.error("Failed to open project:", error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { config } from "@config/config";
|
import { config } from "@config/config";
|
||||||
import { useProjectStore } from "@/store/projectStore";
|
import { useProjectStore } from "@/store/projectStore";
|
||||||
|
import { getAccessToken } from "@/lib/authToken";
|
||||||
|
|
||||||
export const API_URL = process.env.NEXT_PUBLIC_API_URL || config.BACKEND_URL;
|
export const API_URL = process.env.NEXT_PUBLIC_API_URL || config.BACKEND_URL;
|
||||||
|
|
||||||
@@ -8,11 +9,26 @@ export const api = axios.create({
|
|||||||
baseURL: API_URL,
|
baseURL: API_URL,
|
||||||
});
|
});
|
||||||
|
|
||||||
api.interceptors.request.use((request) => {
|
const isMetaProjectsRequest = (request: {
|
||||||
const projectId = useProjectStore.getState().currentProjectId;
|
baseURL?: string;
|
||||||
if (projectId) {
|
url?: string;
|
||||||
|
}) => {
|
||||||
|
const url = `${request.baseURL ?? ""}${request.url ?? ""}`;
|
||||||
|
return url.includes("/api/v1/meta/projects");
|
||||||
|
};
|
||||||
|
|
||||||
|
api.interceptors.request.use(async (request) => {
|
||||||
|
const accessToken = await getAccessToken();
|
||||||
|
if (accessToken) {
|
||||||
request.headers = request.headers ?? {};
|
request.headers = request.headers ?? {};
|
||||||
request.headers["X-Project-ID"] = projectId;
|
request.headers.Authorization = `Bearer ${accessToken}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const projectId = useProjectStore.getState().currentProjectId;
|
||||||
|
if (projectId && !isMetaProjectsRequest(request)) {
|
||||||
|
request.headers = request.headers ?? {};
|
||||||
|
request.headers["X-Project-Id"] = projectId;
|
||||||
|
}
|
||||||
|
|
||||||
return request;
|
return request;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +1,28 @@
|
|||||||
import { useProjectStore } from "@/store/projectStore";
|
import { useProjectStore } from "@/store/projectStore";
|
||||||
|
import { getAccessToken } from "@/lib/authToken";
|
||||||
|
|
||||||
export const apiFetch = (input: RequestInfo | URL, init: RequestInit = {}) => {
|
const resolveUrl = (input: RequestInfo | URL) => {
|
||||||
|
if (typeof input === "string") return input;
|
||||||
|
if (input instanceof URL) return input.toString();
|
||||||
|
if (input instanceof Request) return input.url;
|
||||||
|
return "";
|
||||||
|
};
|
||||||
|
|
||||||
|
const isMetaProjectsRequest = (input: RequestInfo | URL) =>
|
||||||
|
resolveUrl(input).includes("/api/v1/meta/projects");
|
||||||
|
|
||||||
|
export const apiFetch = async (
|
||||||
|
input: RequestInfo | URL,
|
||||||
|
init: RequestInit = {},
|
||||||
|
) => {
|
||||||
const projectId = useProjectStore.getState().currentProjectId;
|
const projectId = useProjectStore.getState().currentProjectId;
|
||||||
const headers = new Headers(init.headers ?? {});
|
const headers = new Headers(init.headers ?? {});
|
||||||
if (projectId) {
|
const accessToken = await getAccessToken();
|
||||||
headers.set("X-Project-ID", projectId);
|
if (accessToken) {
|
||||||
|
headers.set("Authorization", `Bearer ${accessToken}`);
|
||||||
|
}
|
||||||
|
if (projectId && !isMetaProjectsRequest(input)) {
|
||||||
|
headers.set("X-Project-Id", projectId);
|
||||||
}
|
}
|
||||||
return fetch(input, { ...init, headers });
|
return fetch(input, { ...init, headers });
|
||||||
};
|
};
|
||||||
|
|||||||
51
src/lib/authToken.ts
Normal file
51
src/lib/authToken.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { getSession } from "next-auth/react";
|
||||||
|
import { useAuthStore } from "@/store/authStore";
|
||||||
|
|
||||||
|
const decodeJwtPayload = (token: string) => {
|
||||||
|
const parts = token.split(".");
|
||||||
|
if (parts.length < 2) {
|
||||||
|
console.warn("Invalid JWT format.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
|
||||||
|
try {
|
||||||
|
const json =
|
||||||
|
typeof window !== "undefined"
|
||||||
|
? window.atob(padded)
|
||||||
|
: Buffer.from(padded, "base64").toString("utf-8");
|
||||||
|
return JSON.parse(json);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("Failed to decode JWT payload.", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isTokenExpired = (token: string) => {
|
||||||
|
const payload = decodeJwtPayload(token);
|
||||||
|
if (!payload) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (typeof payload.exp !== "number") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const now = Date.now();
|
||||||
|
return now >= payload.exp * 1000 - 30_000;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAccessToken = async () => {
|
||||||
|
const { accessToken, setAccessToken } = useAuthStore.getState();
|
||||||
|
if (accessToken && !isTokenExpired(accessToken)) {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
if (accessToken) {
|
||||||
|
setAccessToken(null);
|
||||||
|
}
|
||||||
|
const session = await getSession();
|
||||||
|
const token = typeof session?.accessToken === "string" ? session.accessToken : null;
|
||||||
|
if (token && !isTokenExpired(token)) {
|
||||||
|
setAccessToken(token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
11
src/store/authStore.ts
Normal file
11
src/store/authStore.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
accessToken: string | null;
|
||||||
|
setAccessToken: (token: string | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuthStore = create<AuthState>((set) => ({
|
||||||
|
accessToken: null,
|
||||||
|
setAccessToken: (token) => set({ accessToken: token }),
|
||||||
|
}));
|
||||||
25
src/types/next-auth.d.ts
vendored
Normal file
25
src/types/next-auth.d.ts
vendored
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import "next-auth";
|
||||||
|
import "next-auth/jwt";
|
||||||
|
|
||||||
|
declare module "next-auth" {
|
||||||
|
interface Session {
|
||||||
|
accessToken?: string;
|
||||||
|
user?: {
|
||||||
|
id?: string;
|
||||||
|
name?: string | null;
|
||||||
|
email?: string | null;
|
||||||
|
image?: string | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "next-auth/jwt" {
|
||||||
|
interface JWT {
|
||||||
|
sub?: string;
|
||||||
|
accessToken?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user