瀏覽代碼

seesion provider

production_process
MSI\2Fi 2 月之前
父節點
當前提交
b13b6d783b
共有 2 個檔案被更改,包括 15 行新增7 行删除
  1. +10
    -4
      src/app/(main)/layout.tsx
  2. +5
    -3
      src/config/authConfig.ts

+ 10
- 4
src/app/(main)/layout.tsx 查看文件

@@ -1,6 +1,6 @@
import AppBar from "@/components/AppBar";
import { getServerSession } from "next-auth";
import { authOptions } from "@/config/authConfig";
import { authOptions, SessionWithTokens } from "@/config/authConfig";
import { redirect } from "next/navigation";
import Box from "@mui/material/Box";
import { NAVIGATION_CONTENT_WIDTH } from "@/config/uiConfig";
@@ -10,23 +10,28 @@ import { AxiosProvider } from "@/app/(main)/axios/AxiosProvider";
import { SetupAxiosInterceptors } from "@/app/(main)/axios/axiosInstance";
import { CameraProvider } from "@/components/Cameras/CameraProvider";
import { UploadProvider } from "@/components/UploadProvider/UploadProvider";
import SessionProviderWrapper from "@/components/SessionProviderWrapper/SessionProviderWrapper";

export default async function MainLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const session = await getServerSession(authOptions) as SessionWithTokens;

if (!session?.user) {
redirect("/login");
}

console.log(session?.user);

// Verify if the session is valid
if (session) {
SetupAxiosInterceptors(session?.accessToken);
SetupAxiosInterceptors(session?.accessToken ?? null);
}

return (
<SessionProviderWrapper session={session}>
<UploadProvider>
<CameraProvider>
<AxiosProvider>
@@ -50,6 +55,7 @@ export default async function MainLayout({
</>
</AxiosProvider>
</CameraProvider>
</UploadProvider>
</UploadProvider>
</SessionProviderWrapper>
);
}

+ 5
- 3
src/config/authConfig.ts 查看文件

@@ -5,7 +5,8 @@ import { LOGIN_API_PATH } from "./api";
export interface SessionWithTokens extends Session {
accessToken?: string;
refreshToken?: string;
abilities: string[]
abilities: string[];
id?: string | null
}

export const authOptions: AuthOptions = {
@@ -26,6 +27,7 @@ export const authOptions: AuthOptions = {
});

const user = await res.json();

if (res.ok && user) {
return user;
@@ -42,18 +44,18 @@ export const authOptions: AuthOptions = {
// Add the data from user to the token
const { token, user } = params;
const newToken = { ...token, ...user };

return newToken;
},
session({ session, token }) {
const sessionWithToken: SessionWithTokens = {
...session,
// Add the data from the token to the session
id: token.id as string | undefined,
accessToken: token.accessToken as string | undefined,
refreshToken: token.refreshToken as string | undefined,
abilities: token.abilities as string[]
};
console.log(sessionWithToken);
return sessionWithToken;
},
},


Loading…
取消
儲存