Finished Moodle oAuth service

READ Moodle section in README file
This commit is contained in:
PxlLoewe
2025-02-27 00:32:44 +01:00
parent b81bab1dc2
commit 9366f8f6b4
8 changed files with 149 additions and 50 deletions

View File

@@ -1,21 +1,47 @@
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) => {
const session = await getServerSession();
if (!session) {
return {
status: 401,
body: "Unauthorized",
};
// 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: session.user.id,
id: decoded.id,
},
});
return NextResponse.json(user);
return NextResponse.json({
...user,
moodleLastname: `${user?.lastname.split("")[0]}. - ${user?.publicId}`,
});
};