completed oauth implementation on hub and dispatch

This commit is contained in:
PxlLoewe
2025-02-03 00:45:55 +01:00
parent 93804855f1
commit 71b401f8ab
18 changed files with 327 additions and 16 deletions

View File

@@ -0,0 +1,27 @@
import { NextPage } from 'next';
import { ReactNode } from 'react';
const AuthLayout: NextPage<
Readonly<{
children: React.ReactNode;
}>
> = ({ children }) => (
<div
className="hero min-h-screen"
style={{
backgroundImage:
'url(https://img.daisyui.com/images/stock/photo-1507358522600-9f71e620c44e.webp)',
}}
>
<div className="hero-overlay bg-opacity-60"></div>
<div className="hero-content text-neutral-content text-center ">
<div className="max-w-lg">
<div className="card bg-base-100 w-full min-w-[500px] shadow-2xl max-md:min-w-[400px]">
{children}
</div>
</div>
</div>
</div>
);
export default AuthLayout;

View File

@@ -0,0 +1,60 @@
'use client';
import { signIn } from 'next-auth/react';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { Toaster } from 'react-hot-toast';
export const Login = () => {
const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams();
useEffect(() => {
const signInWithCode = async () => {
const code = searchParams.get('code');
if (code) {
setIsLoading(true);
await signIn('credentials', {
code: code,
callbackUrl: '/',
});
setIsLoading(false);
}
};
signInWithCode();
}, [searchParams]);
return (
<div className="card-body">
<div>
<Toaster position="top-center" reverseOrder={false} />
</div>
<h1 className="text-3xl font-bold">Login</h1>
<span className="text-sm font-medium">
Noch keinen Account? Zur{' '}
<a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/register`}
className="link link-accent link-hover"
>
Registrierung
</a>
</span>
<div className="form-control mt-6">
<a
href={`${process.env.NEXT_PUBLIC_HUB_URL}/oauth?service=${encodeURIComponent(process.env.NEXT_PUBLIC_SERVICE_ID || '')}&redirect_uri=${encodeURIComponent(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/login`)}`}
>
<button
className="btn btn-primary"
name="loginBtn"
disabled={isLoading}
>
{isLoading && (
<span className="loading loading-spinner loading-sm"></span>
)}
Login{isLoading && '...'}
</button>
</a>
</div>
</div>
);
};

View File

@@ -0,0 +1,9 @@
import { Login } from './_components/Login';
export default async () => {
return (
<>
<Login />
</>
);
};

View File

@@ -0,0 +1,16 @@
'use client';
import { signOut } from 'next-auth/react';
import { useEffect } from 'react';
export default () => {
useEffect(() => {
signOut({
callbackUrl: '/login',
});
}, []);
return (
<div className="card-body">
<h1 className="text-5xl">logging out...</h1>
</div>
);
};

View File

@@ -0,0 +1,43 @@
'use client';
import { useSearchParams } from 'next/navigation';
import { Service } from '../page';
import { generateToken } from './action';
export const Authorize = ({ service }: { service: Service }) => {
const searchParams = useSearchParams();
const legitimeUrl = service.approvedUrls.some((url) =>
searchParams.get('redirect_uri')?.startsWith(url)
);
if (!legitimeUrl)
return (
<div className="card-body">
<h1 className="text-4xl font-bold">Unerlaubter Zugriff</h1>
<p>Du greifst von einem ncith genehmigtem Server auf diese URL zu</p>
</div>
);
return (
<form className="card-body" onSubmit={(e) => e.preventDefault()}>
<h1 className="text-4xl font-bold">Zugriff zulassen</h1>
<p>
Die Anwendung <strong>{service.name}</strong> möchte auf deine Daten
zugreifen.
</p>
<div className="space-x-4">
<button type="button" className="btn">
Verweigern
</button>
<button
type="submit"
className="btn btn-primary"
onClick={async () => {
const code = await generateToken(service);
window.location.href = `${searchParams.get('redirect_uri')}?code=${code}`;
}}
>
Zulassen
</button>
</div>
</form>
);
};

View File

@@ -0,0 +1,24 @@
'use server';
import { getServerSession } from '../../../api/auth/[...nextauth]/auth';
import { Service } from '../page';
import { PrismaClient } from '@repo/db';
const prisma = new PrismaClient();
export const generateToken = async (service: Service) => {
const session = await getServerSession();
if (!session) return null;
const accessToken = Array.from({ length: 10 }, () =>
Math.floor(Math.random() * 10)
).join('');
const code = await prisma.oAuthToken.create({
data: {
clientId: service.id,
userId: session.user.id,
accessToken: accessToken,
},
});
return code;
};

View File

@@ -0,0 +1,26 @@
import { Authorize } from './_components/Authorize';
export const services = [
{
id: '123456',
service: 'dispatch',
name: 'Leitstellendisposition',
approvedUrls: ['http://localhost:3001'],
},
];
export type Service = (typeof services)[number];
export default async ({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) => {
const { service: serviceId } = await searchParams;
const service = services.find((service) => service.id === serviceId);
if (!service) {
return <div>Service not found</div>;
}
return <Authorize service={service} />;
};