Finished Moodle oAuth service
READ Moodle section in README file
This commit is contained in:
11
README.md
11
README.md
@@ -85,10 +85,17 @@ Learn more about the power of Turborepo:
|
|||||||
|
|
||||||
## Execution policy
|
## Execution policy
|
||||||
|
|
||||||
## Scope ExecutionPolicy
|
|
||||||
|
|
||||||
MachinePolicy Undefined
|
MachinePolicy Undefined
|
||||||
UserPolicy Undefined
|
UserPolicy Undefined
|
||||||
Process Undefined
|
Process Undefined
|
||||||
CurrentUser RemoteSigned
|
CurrentUser RemoteSigned
|
||||||
LocalMachine RemoteSigned
|
LocalMachine RemoteSigned
|
||||||
|
|
||||||
|
## Moodle:
|
||||||
|
|
||||||
|
1. Im docker volume gehe in lib -> Classes -> OAuth2 -> Endpoint.php
|
||||||
|
2. überspringe die https enforcement rule am Ende der Datei (true in if abfrage)
|
||||||
|
3. Moodle Admin -> General -> HTTP Security -> Curl einschränkungen löschen
|
||||||
|
4. http://localhost:8081/admin/category.php?category=authsettings -> Guest login button -> Hide
|
||||||
|
5. http://localhost:8081/admin/settings.php?section=sitepolicies -> emailchangeconfirmation -> False
|
||||||
|
6. Beim anlegen des Auth-Services Require Email verification deaktivieren
|
||||||
|
|||||||
2
apps/hub/.gitignore
vendored
2
apps/hub/.gitignore
vendored
@@ -38,3 +38,5 @@ yarn-error.log*
|
|||||||
# typescript
|
# typescript
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
|
certificates
|
||||||
@@ -10,7 +10,6 @@ export const Authorize = ({ service }: { service: Service }) => {
|
|||||||
searchParams.get("redirect_uri")?.startsWith(url),
|
searchParams.get("redirect_uri")?.startsWith(url),
|
||||||
);
|
);
|
||||||
const { data: session } = useSession();
|
const { data: session } = useSession();
|
||||||
console.log(session);
|
|
||||||
if (!session)
|
if (!session)
|
||||||
redirect("/login?redirect=" + encodeURIComponent(window.location.href));
|
redirect("/login?redirect=" + encodeURIComponent(window.location.href));
|
||||||
if (!legitimeUrl)
|
if (!legitimeUrl)
|
||||||
@@ -37,7 +36,14 @@ export const Authorize = ({ service }: { service: Service }) => {
|
|||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
const code = await generateToken(service);
|
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
|
Zulassen
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ export const services = [
|
|||||||
secret: "d0f3e4e4",
|
secret: "d0f3e4e4",
|
||||||
service: "moodle",
|
service: "moodle",
|
||||||
name: "Moodle",
|
name: "Moodle",
|
||||||
approvedUrls: ["https://moodle.virtualairrescue.com"],
|
approvedUrls: [
|
||||||
|
"http://localhost:8081",
|
||||||
|
"https://moodle.virtualairrescue.com",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
export type Service = (typeof services)[number];
|
export type Service = (typeof services)[number];
|
||||||
@@ -28,8 +31,11 @@ export default async ({
|
|||||||
}: {
|
}: {
|
||||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||||
}) => {
|
}) => {
|
||||||
const { service: serviceId } = await searchParams;
|
const { service: serviceId, client_id: clientId } = await searchParams;
|
||||||
const service = services.find((service) => service.id === serviceId);
|
|
||||||
|
const service = services.find(
|
||||||
|
(service) => service.id === serviceId || service.id === clientId,
|
||||||
|
);
|
||||||
|
|
||||||
if (!service) {
|
if (!service) {
|
||||||
return <div>Service not found</div>;
|
return <div>Service not found</div>;
|
||||||
|
|||||||
@@ -1,16 +1,15 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useSession } from 'next-auth/react';
|
import { useSession } from "next-auth/react";
|
||||||
import Link from 'next/link';
|
import Link from "next/link";
|
||||||
|
|
||||||
export const Header = () => {
|
export const Header = () => {
|
||||||
const session = useSession();
|
const session = useSession();
|
||||||
console.log(session);
|
|
||||||
return (
|
return (
|
||||||
<header className="flex justify-between items-center p-4">
|
<header className="flex justify-between items-center p-4">
|
||||||
<h1 className="text-2xl font-bold">Hub</h1>
|
<h1 className="text-2xl font-bold">Hub</h1>
|
||||||
<div>
|
<div>
|
||||||
{session.status === 'authenticated' ? (
|
{session.status === "authenticated" ? (
|
||||||
<p>{session.data?.user.firstname}</p>
|
<p>{session.data?.user.firstname}</p>
|
||||||
) : (
|
) : (
|
||||||
<Link href="/login">
|
<Link href="/login">
|
||||||
|
|||||||
@@ -1,30 +1,40 @@
|
|||||||
import { prisma, PrismaClient } from "@repo/db";
|
import { prisma, PrismaClient } from "@repo/db";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { sign } from "jsonwebtoken";
|
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 client = new PrismaClient();
|
||||||
const accessToken =
|
const accessToken = form.get("token") || form.get("code");
|
||||||
req.nextUrl.searchParams.get("token") ||
|
const clientId = form.get("client_id");
|
||||||
req.nextUrl.searchParams.get("code");
|
const clientSecret = form.get("client_secret");
|
||||||
const client_id = req.nextUrl.searchParams.get("client_id");
|
|
||||||
const client_secret = req.nextUrl.searchParams.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)
|
if (!accessToken)
|
||||||
return new Response("No access token provided", { status: 400 });
|
return new Response("No access token provided", { status: 400 });
|
||||||
|
|
||||||
if (!client_id)
|
if (!clientId)
|
||||||
return new Response("No client ID token provided", { status: 400 });
|
return new Response("No client ID token provided", { status: 400 });
|
||||||
|
|
||||||
const accessRequest = await client.oAuthToken.findFirst({
|
const accessRequest = await client.oAuthToken.findFirst({
|
||||||
where: {
|
where: {
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
clientId: client_id,
|
clientId: clientId,
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
user: true,
|
user: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!service || service.secret !== clientSecret)
|
||||||
|
return new Response("Invalid client ID or secret", { status: 400 });
|
||||||
|
|
||||||
if (!accessRequest)
|
if (!accessRequest)
|
||||||
return new Response("Access token not found", { status: 404 });
|
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 });
|
return new Response("Code expired", { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const jwt = sign(accessRequest.user, process.env.NEXTAUTH_SECRET as string, {
|
const jwt = sign(
|
||||||
|
{
|
||||||
|
...accessRequest.user,
|
||||||
|
},
|
||||||
|
process.env.NEXTAUTH_SECRET as string,
|
||||||
|
{
|
||||||
expiresIn: "30d",
|
expiresIn: "30d",
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
user: accessRequest.user,
|
access_token: jwt,
|
||||||
jwt,
|
token_type: "Bearer",
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,21 +1,47 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getServerSession } from "../auth/[...nextauth]/auth";
|
import { getServerSession } from "../auth/[...nextauth]/auth";
|
||||||
import { prisma } from "@repo/db";
|
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) => {
|
export const GET = async (req: NextRequest) => {
|
||||||
const session = await getServerSession();
|
// This route is only used by Moodle, so NextAuth is not used here
|
||||||
if (!session) {
|
const authHeader = req.headers.get("Authorization");
|
||||||
return {
|
const token = authHeader?.split(" ")[1];
|
||||||
status: 401,
|
if (!authHeader || !token) {
|
||||||
body: "Unauthorized",
|
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({
|
const user = await prisma.user.findUnique({
|
||||||
where: {
|
where: {
|
||||||
id: session.user.id,
|
id: decoded.id,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(user);
|
return NextResponse.json({
|
||||||
|
...user,
|
||||||
|
moodleLastname: `${user?.lastname.split("")[0]}. - ${user?.publicId}`,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
# docker-compose.dev.yml
|
|
||||||
|
|
||||||
version: "3.8"
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:13
|
image: postgres:13
|
||||||
@@ -13,6 +10,7 @@ services:
|
|||||||
POSTGRES_DB: var
|
POSTGRES_DB: var
|
||||||
volumes:
|
volumes:
|
||||||
- postgres-data:/var/lib/postgresql/data
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
|
||||||
pgadmin:
|
pgadmin:
|
||||||
image: dpage/pgadmin4:latest
|
image: dpage/pgadmin4:latest
|
||||||
container_name: pgadmin
|
container_name: pgadmin
|
||||||
@@ -23,5 +21,44 @@ services:
|
|||||||
- "8080:80"
|
- "8080:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- postgres
|
||||||
|
|
||||||
|
moodle_database:
|
||||||
|
container_name: moodle_database
|
||||||
|
image: docker.io/bitnami/mariadb:latest
|
||||||
|
environment:
|
||||||
|
# ALLOW_EMPTY_PASSWORD is recommended only for development.
|
||||||
|
- ALLOW_EMPTY_PASSWORD=yes
|
||||||
|
- MARIADB_USER=bn_moodle
|
||||||
|
- MARIADB_DATABASE=bitnami_moodle
|
||||||
|
- MARIADB_CHARACTER_SET=utf8mb4
|
||||||
|
- MARIADB_COLLATE=utf8mb4_unicode_ci
|
||||||
|
volumes:
|
||||||
|
- "moodle_database:/bitnami/mariadb"
|
||||||
|
moodle:
|
||||||
|
image: bitnami/moodle:latest
|
||||||
|
container_name: moodle
|
||||||
|
ports:
|
||||||
|
- "8081:8080" # Moodle läuft auf http://localhost:8081
|
||||||
|
environment:
|
||||||
|
- MOODLE_DATABASE_HOST=moodle_database
|
||||||
|
- MOODLE_DATABASE_PORT_NUMBER=3306
|
||||||
|
- MOODLE_DATABASE_USER=bn_moodle
|
||||||
|
- MOODLE_DATABASE_NAME=bitnami_moodle
|
||||||
|
|
||||||
|
- MOODLE_USERNAME=admin
|
||||||
|
- MOODLE_PASSWORD=admin123
|
||||||
|
- MOODLE_EMAIL=admin@example.com
|
||||||
|
- MOODLE_SITE_NAME="Mein Lokales Moodle"
|
||||||
|
- MOODLE_SSLPROXY=false
|
||||||
|
- ALLOW_EMPTY_PASSWORD=yes
|
||||||
|
depends_on:
|
||||||
|
- moodle_database
|
||||||
|
volumes:
|
||||||
|
- moodle_data:/bitnami/moodle
|
||||||
|
- moodle_moodledata:/bitnami/moodledata
|
||||||
|
# Für den Zugriff auf den Host
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
|
moodle_data:
|
||||||
|
moodle_database:
|
||||||
|
moodle_moodledata:
|
||||||
|
|||||||
Reference in New Issue
Block a user