48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getServerSession } from "../auth/[...nextauth]/auth";
|
|
import { prisma } from "@repo/db";
|
|
import { generateToken } from "../../(auth)/oauth/_components/action";
|
|
import { decode, verify } from "jsonwebtoken";
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
const authHeader = req.headers.get("authorization");
|
|
|
|
if (authHeader?.startsWith("Bearer ")) {
|
|
const token = authHeader.split(" ")[1];
|
|
|
|
if (token) {
|
|
// Hier kannst du den Token validieren (optional)
|
|
|
|
req.headers.set("x-next-auth-token", token);
|
|
}
|
|
|
|
// Falls NextAuth keine Session hat, erstellen wir eine Fake-Session
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const GET = async (req: NextRequest) => {
|
|
// This route is only used by Moodle, so NextAuth is not used here
|
|
const authHeader = req.headers.get("Authorization");
|
|
const token = authHeader?.split(" ")[1];
|
|
if (!authHeader || !token) {
|
|
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
|
|
}
|
|
const decoded = await verify(token, process.env.NEXTAUTH_SECRET as string);
|
|
|
|
if (typeof decoded === "string")
|
|
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
id: decoded.id,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json({
|
|
...user,
|
|
moodleLastname: `${user?.lastname.split("")[0]}. - ${user?.publicId}`,
|
|
});
|
|
};
|