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} />;
};

View File

@@ -2,7 +2,7 @@
import { ToggleTalkButton } from '../_components/ToggleTalkButton';
import { ChangeRufgruppe } from '../_components/ChangeRufgruppe';
import { Notifications } from '../_components/Notifications';
import { MoonIcon, SunIcon } from '@radix-ui/react-icons';
import Link from 'next/link';
export default function Navbar() {
return (
@@ -61,7 +61,9 @@ export default function Navbar() {
<a>Einstellungen</a>
</li>
<li>
<a>Logout</a>
<Link href={'/logout'}>
<p>Logout</p>
</Link>
</li>
</ul>
</div>

View File

@@ -1,16 +1,23 @@
import type { Metadata } from 'next';
import Navbar from './_components/Navbar';
import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';
import { getServerSession } from '../api/auth/[...nextauth]/auth';
export const metadata: Metadata = {
title: 'VAR Leitstelle v2',
description: 'Die neue VAR Leitstelle.',
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getServerSession();
if (!session) {
redirect('/login');
}
return (
<>
<Navbar />

View File

@@ -0,0 +1,12 @@
'use client';
import { SessionProvider } from 'next-auth/react';
import { Session } from 'next-auth';
export const NextAuthSessionProvider = ({
children,
session,
}: {
children: React.ReactNode;
session: Session | null;
}) => <SessionProvider session={session}>{children}</SessionProvider>;

View File

@@ -0,0 +1,71 @@
import {
AuthOptions,
getServerSession as getNextAuthServerSession,
} from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import Credentials from 'next-auth/providers/credentials';
import { PrismaClient } from '@repo/db';
const prisma = new PrismaClient();
export const options: AuthOptions = {
providers: [
Credentials({
credentials: {
code: { label: 'code', type: 'code' },
},
async authorize(credentials, req) {
try {
if (!credentials) throw new Error('No credentials provided');
const code = await prisma.oAuthToken.findFirstOrThrow({
where: {
accessToken: credentials.code,
},
});
const user = await prisma.user.findFirstOrThrow({
where: {
id: code.userId,
},
});
console.log(code, user);
if (!user) return null;
return user;
} catch (error) {
return null;
}
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60,
},
adapter: PrismaAdapter(prisma),
callbacks: {
jwt: async ({ token, user }) => {
if (user && 'firstname' in user) {
return {
...token,
...user,
};
}
return token;
},
session: async ({ session, user, token }) => {
return {
...session,
user: token,
};
},
},
pages: {
signIn: '/login',
signOut: '/logout',
error: '/authError',
},
} satisfies AuthOptions;
export const getServerSession = async () => getNextAuthServerSession(options);

View File

@@ -0,0 +1,6 @@
import NextAuth from 'next-auth';
import { options } from './auth';
const handler = NextAuth(options);
export { handler as GET, handler as POST };

View File

@@ -1,6 +1,8 @@
import type { Metadata } from 'next';
import localFont from 'next/font/local';
import './globals.css';
import { NextAuthSessionProvider } from './_components/AuthSessionProvider';
import { getServerSession } from './api/auth/[...nextauth]/auth';
const geistSans = localFont({
src: './fonts/GeistVF.woff',
@@ -16,17 +18,20 @@ export const metadata: Metadata = {
description: 'Die neue VAR Leitstelle.',
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getServerSession();
return (
<html lang="de" data-theme="light">
<html lang="de" data-theme="dark">
<body
className={`${geistSans.variable} ${geistMono.variable} h-screen flex flex-col`}
>
<NextAuthSessionProvider session={session}>
{children}
</NextAuthSessionProvider>
</body>
</html>
);

View File

@@ -1,5 +0,0 @@
import { redirect } from "next/navigation";
export default function Login() {
redirect("/");
}

View File

@@ -16,6 +16,7 @@
"@tailwindcss/postcss": "^4.0.2",
"leaflet": "^1.9.4",
"next": "^15.1.0",
"next-auth": "^4.24.11",
"postcss": "^8.5.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",

View File

@@ -2,6 +2,7 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { Toaster, toast } from 'react-hot-toast';
@@ -9,7 +10,7 @@ import { z } from 'zod';
export const Login = () => {
const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams();
const schema = z.object({
email: z.string().email(),
password: z.string(),
@@ -20,14 +21,14 @@ export const Login = () => {
const form = useForm<schemaType>({
resolver: zodResolver(schema),
});
console.log(form.formState.errors);
return (
<form
className="card-body"
onSubmit={form.handleSubmit(async () => {
setIsLoading(true);
const data = await signIn('credentials', {
callbackUrl: '/',
callbackUrl: searchParams.get('redirect') || '/',
email: form.getValues('email'),
password: form.getValues('password'),
});

View File

@@ -1,13 +1,18 @@
'use client';
import { useSearchParams } from 'next/navigation';
import { redirect, useSearchParams } from 'next/navigation';
import { Service } from '../page';
import { generateToken } from './action';
import { useSession } from 'next-auth/react';
export const Authorize = ({ service }: { service: Service }) => {
const searchParams = useSearchParams();
const legitimeUrl = service.approvedUrls.some((url) =>
searchParams.get('redirect_uri')?.startsWith(url)
);
const { data: session } = useSession();
console.log(session);
if (!session)
redirect('/login?redirect=' + encodeURIComponent(window.location.href));
if (!legitimeUrl)
return (
<div className="card-body">
@@ -32,7 +37,7 @@ 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}`;
window.location.href = `${searchParams.get('redirect_uri')}?code=${code?.accessToken}`;
}}
>
Zulassen

1
package-lock.json generated
View File

@@ -26,6 +26,7 @@
"@tailwindcss/postcss": "^4.0.2",
"leaflet": "^1.9.4",
"next": "^15.1.0",
"next-auth": "^4.24.11",
"postcss": "^8.5.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",