Finished Moodle oAuth service
READ Moodle section in README file
This commit is contained in:
2
apps/hub/.gitignore
vendored
2
apps/hub/.gitignore
vendored
@@ -38,3 +38,5 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
certificates
|
||||
@@ -10,7 +10,6 @@ export const Authorize = ({ service }: { service: Service }) => {
|
||||
searchParams.get("redirect_uri")?.startsWith(url),
|
||||
);
|
||||
const { data: session } = useSession();
|
||||
console.log(session);
|
||||
if (!session)
|
||||
redirect("/login?redirect=" + encodeURIComponent(window.location.href));
|
||||
if (!legitimeUrl)
|
||||
@@ -37,7 +36,14 @@ export const Authorize = ({ service }: { service: Service }) => {
|
||||
className="btn btn-primary"
|
||||
onClick={async () => {
|
||||
const code = await generateToken(service);
|
||||
window.location.href = `${searchParams.get("redirect_uri")}?code=${code?.accessToken}`;
|
||||
const url = new URL(searchParams.get("redirect_uri") as string);
|
||||
url.searchParams.append("code", code?.accessToken as string);
|
||||
url.searchParams.append(
|
||||
"state",
|
||||
searchParams.get("state") as string,
|
||||
);
|
||||
|
||||
window.location.href = url.href;
|
||||
}}
|
||||
>
|
||||
Zulassen
|
||||
|
||||
@@ -18,7 +18,10 @@ export const services = [
|
||||
secret: "d0f3e4e4",
|
||||
service: "moodle",
|
||||
name: "Moodle",
|
||||
approvedUrls: ["https://moodle.virtualairrescue.com"],
|
||||
approvedUrls: [
|
||||
"http://localhost:8081",
|
||||
"https://moodle.virtualairrescue.com",
|
||||
],
|
||||
},
|
||||
];
|
||||
export type Service = (typeof services)[number];
|
||||
@@ -28,8 +31,11 @@ export default async ({
|
||||
}: {
|
||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||
}) => {
|
||||
const { service: serviceId } = await searchParams;
|
||||
const service = services.find((service) => service.id === serviceId);
|
||||
const { service: serviceId, client_id: clientId } = await searchParams;
|
||||
|
||||
const service = services.find(
|
||||
(service) => service.id === serviceId || service.id === clientId,
|
||||
);
|
||||
|
||||
if (!service) {
|
||||
return <div>Service not found</div>;
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import { useSession } from 'next-auth/react';
|
||||
import Link from 'next/link';
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
|
||||
export const Header = () => {
|
||||
const session = useSession();
|
||||
console.log(session);
|
||||
return (
|
||||
<header className="flex justify-between items-center p-4">
|
||||
<h1 className="text-2xl font-bold">Hub</h1>
|
||||
<div>
|
||||
{session.status === 'authenticated' ? (
|
||||
<p>{session.data?.user.firstname}</p>
|
||||
) : (
|
||||
<Link href="/login">
|
||||
<button className="btn">Login</button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
const session = useSession();
|
||||
return (
|
||||
<header className="flex justify-between items-center p-4">
|
||||
<h1 className="text-2xl font-bold">Hub</h1>
|
||||
<div>
|
||||
{session.status === "authenticated" ? (
|
||||
<p>{session.data?.user.firstname}</p>
|
||||
) : (
|
||||
<Link href="/login">
|
||||
<button className="btn">Login</button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,30 +1,40 @@
|
||||
import { prisma, PrismaClient } from "@repo/db";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { sign } from "jsonwebtoken";
|
||||
import { services } from "../../../(auth)/oauth/page";
|
||||
|
||||
export const GET = async (req: NextRequest) => {
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const form = new URLSearchParams(await req.text());
|
||||
console.log("POST body:");
|
||||
const client = new PrismaClient();
|
||||
const accessToken =
|
||||
req.nextUrl.searchParams.get("token") ||
|
||||
req.nextUrl.searchParams.get("code");
|
||||
const client_id = req.nextUrl.searchParams.get("client_id");
|
||||
const client_secret = req.nextUrl.searchParams.get("client_secret");
|
||||
const accessToken = form.get("token") || form.get("code");
|
||||
const clientId = form.get("client_id");
|
||||
const clientSecret = form.get("client_secret");
|
||||
|
||||
console.log("Access token:", accessToken);
|
||||
console.log("Client ID:", clientId);
|
||||
console.log("Secret:", clientSecret);
|
||||
const service = services.find((s) => s.id === clientId);
|
||||
|
||||
if (!accessToken)
|
||||
return new Response("No access token provided", { status: 400 });
|
||||
|
||||
if (!client_id)
|
||||
if (!clientId)
|
||||
return new Response("No client ID token provided", { status: 400 });
|
||||
|
||||
const accessRequest = await client.oAuthToken.findFirst({
|
||||
where: {
|
||||
accessToken: accessToken,
|
||||
clientId: client_id,
|
||||
clientId: clientId,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!service || service.secret !== clientSecret)
|
||||
return new Response("Invalid client ID or secret", { status: 400 });
|
||||
|
||||
if (!accessRequest)
|
||||
return new Response("Access token not found", { status: 404 });
|
||||
|
||||
@@ -37,12 +47,18 @@ export const GET = async (req: NextRequest) => {
|
||||
return new Response("Code expired", { status: 400 });
|
||||
}
|
||||
|
||||
const jwt = sign(accessRequest.user, process.env.NEXTAUTH_SECRET as string, {
|
||||
expiresIn: "30d",
|
||||
});
|
||||
const jwt = sign(
|
||||
{
|
||||
...accessRequest.user,
|
||||
},
|
||||
process.env.NEXTAUTH_SECRET as string,
|
||||
{
|
||||
expiresIn: "30d",
|
||||
},
|
||||
);
|
||||
|
||||
return Response.json({
|
||||
user: accessRequest.user,
|
||||
jwt,
|
||||
access_token: jwt,
|
||||
token_type: "Bearer",
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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}`,
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user