Desktop oAuth integration

Co-authored-by: RagingLightning <RagingLightningCode@gmail.com>
This commit is contained in:
PxlLoewe
2025-05-09 08:36:01 -07:00
parent 1948d34963
commit 654bdfbbaa
8 changed files with 95 additions and 62 deletions

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useDispatchConnectionStore } from "_store/pilot/connectionStore"; import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { import {
Disc, Disc,
Mic, Mic,
@@ -20,7 +20,7 @@ import { ConnectionQuality } from "livekit-client";
import { ROOMS } from "_data/livekitRooms"; import { ROOMS } from "_data/livekitRooms";
export const Audio = () => { export const Audio = () => {
const connection = useDispatchConnectionStore(); const connection = usePilotConnectionStore();
const { const {
isTalking, isTalking,
toggleTalking, toggleTalking,

View File

@@ -1,13 +1,13 @@
"use client"; "use client";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import { useDispatchConnectionStore } from "../../../_store/pilot/connectionStore"; import { usePilotConnectionStore } from "../../../_store/pilot/connectionStore";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { getStationsAPI } from "querys/stations"; import { getStationsAPI } from "querys/stations";
export const ConnectionBtn = () => { export const ConnectionBtn = () => {
const modalRef = useRef<HTMLDialogElement>(null); const modalRef = useRef<HTMLDialogElement>(null);
const connection = useDispatchConnectionStore((state) => state); const connection = usePilotConnectionStore((state) => state);
const [form, setForm] = useState<{ const [form, setForm] = useState<{
logoffTime: string | null; logoffTime: string | null;
selectedStationId: number | null; selectedStationId: number | null;

View File

@@ -1,4 +1,5 @@
"use server"; "use server";
import { generateUUID } from "../../../../helper/uuid";
import { getServerSession } from "../../../api/auth/[...nextauth]/auth"; import { getServerSession } from "../../../api/auth/[...nextauth]/auth";
import { Service } from "../page"; import { Service } from "../page";
import { PrismaClient } from "@repo/db"; import { PrismaClient } from "@repo/db";
@@ -9,15 +10,7 @@ export const generateToken = async (service: Service) => {
const session = await getServerSession(); const session = await getServerSession();
if (!session) return null; if (!session) return null;
const key = await crypto.subtle.generateKey( const accessToken = generateUUID(16);
{ name: "HMAC", hash: "SHA-256" },
true,
["sign"],
);
const exportedKey = await crypto.subtle.exportKey("raw", key);
const accessToken = Array.from(new Uint8Array(exportedKey))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const code = await prisma.oAuthToken.create({ const code = await prisma.oAuthToken.create({
data: { data: {

View File

@@ -9,9 +9,10 @@ export const services = [
}, },
{ {
id: "2", id: "2",
secret: "jp2k430fnv",
service: "desktop", service: "desktop",
name: "Desktop client", name: "Desktop client",
approvedUrls: ["var"], approvedUrls: ["var://oAuth"],
}, },
{ {
id: "3", id: "3",
@@ -26,7 +27,7 @@ export const services = [
]; ];
export type Service = (typeof services)[number]; export type Service = (typeof services)[number];
export default async ({ const Page = async ({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>; searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
@@ -43,3 +44,5 @@ export default async ({
return <Authorize service={service} />; return <Authorize service={service} />;
}; };
export default Page;

View File

@@ -1,60 +1,83 @@
import { prisma, PrismaClient } from "@repo/db"; import { NextRequest } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { sign } from "jsonwebtoken"; import { sign } from "jsonwebtoken";
import { services } from "../../../(auth)/oauth/page"; import { services } from "(auth)/oauth/page";
import { prisma } from "@repo/db";
export const POST = async (req: NextRequest) => { export const POST = async (req: NextRequest) => {
const form = new URLSearchParams(await req.text()); try {
const client = new PrismaClient(); if (
const accessToken = form.get("token") || form.get("code"); !req.headers
const clientId = form.get("client_id"); .get("content-type")
const clientSecret = form.get("client_secret"); ?.includes("application/x-www-form-urlencoded")
) {
return new Response("Unsupported Content-Type", { status: 415 });
}
const service = services.find((s) => s.id === clientId); const form = new URLSearchParams(await req.text());
const accessToken = form.get("token") || form.get("code");
const clientId = form.get("client_id");
const clientSecret = form.get("client_secret");
if (!accessToken) if (!accessToken) {
return new Response("No access token provided", { status: 400 }); console.log("No access token provided", accessToken);
return new Response("No access token provided", { status: 400 });
}
if (!clientId) if (!clientId) {
return new Response("No client ID token provided", { status: 400 }); console.log("No client ID provided", clientId);
return new Response("No client ID provided", { status: 400 });
}
const accessRequest = await client.oAuthToken.findFirst({ const service = services.find((s) => s.id === clientId);
where: {
accessToken: accessToken,
clientId: clientId,
},
include: {
user: true,
},
});
if (!service || service.secret !== clientSecret) if (!service || service.secret !== clientSecret) {
return new Response("Invalid client ID or secret", { status: 400 }); console.log("Invalid client ID or secret", clientId, clientSecret);
return new Response("Invalid client credentials", { status: 401 });
}
if (!accessRequest) const accessRequest = await prisma.oAuthToken.findFirst({
return new Response("Access token not found", { status: 404 });
if (new Date().getTime() - accessRequest?.createdAt.getTime() > 60 * 1000) {
await prisma.oAuthToken.delete({
where: { where: {
id: accessRequest.id, accessToken: accessToken,
clientId: clientId,
},
include: {
user: true,
}, },
}); });
return new Response("Code expired", { status: 400 });
if (!accessRequest) {
console.log("Access token not found", accessToken);
return new Response("Access token not found", { status: 404 });
}
if (new Date().getTime() - accessRequest.createdAt.getTime() > 60 * 1000) {
await prisma.oAuthToken.delete({
where: {
id: accessRequest.id,
},
});
console.log("Code expired", accessRequest.id);
return new Response("Code expired", { status: 410 });
}
const jwt = sign(
{
...accessRequest.user,
},
process.env.NEXTAUTH_SECRET as string,
{
expiresIn: "30d",
},
);
return Response.json({
access_token: jwt,
token_type: "Bearer",
});
} catch (error) {
console.error("Error in accessToken route:", error);
return new Response((error as Error).message || "Internal Server Error", {
status: 500,
});
} }
const jwt = sign(
{
...accessRequest.user,
},
process.env.NEXTAUTH_SECRET as string,
{
expiresIn: "30d",
},
);
return Response.json({
access_token: jwt,
token_type: "Bearer",
});
}; };

View File

@@ -5,7 +5,7 @@ import { getMoodleUserById } from "../../../helper/moodle";
import { inscribeToMoodleCourse } from "../../(app)/events/actions"; import { inscribeToMoodleCourse } from "../../(app)/events/actions";
export const GET = async (req: NextRequest) => { export const GET = async (req: NextRequest) => {
// This route is only used by Moodle, so NextAuth is not used here // This route is only used by Moodle and DEsktop-client, so NextAuth is not used here
const authHeader = req.headers.get("Authorization"); const authHeader = req.headers.get("Authorization");
const token = authHeader?.split(" ")[1]; const token = authHeader?.split(" ")[1];
if (!authHeader || !token) { if (!authHeader || !token) {

14
apps/hub/helper/uuid.ts Normal file
View File

@@ -0,0 +1,14 @@
export const generateUUID = (length: number) => {
// Base62-Version (a-z, A-Z, 0-9)
const base62 =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let string = "";
for (let i = 0; i < length; i++) {
string += base62.charAt(Math.floor(Math.random() * base62.length));
}
console.log(string);
return string;
};

Binary file not shown.