Skip to content

Commit

Permalink
Restrict access to all animal management routes
Browse files Browse the repository at this point in the history
  • Loading branch information
karlhorky committed Mar 4, 2023
1 parent fa8e677 commit 353fa9f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions app/animal-management-naive-dont-copy/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { cookies, headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { getUserBySessionToken } from '../../database/users';

type Props = {
children: React.ReactNode;
};

export default async function AnimalManagementNaiveDontCopyLayout(
props: Props,
) {
const headersList = headers();
const cookieStore = cookies();
const sessionToken = cookieStore.get('sessionToken');

const user = !sessionToken?.value
? undefined
: await getUserBySessionToken(sessionToken.value);

if (!user) {
// Redirect user to custom x-pathname header from Middleware
redirect(`/login?returnTo=${headersList.get('x-pathname')}`);
}

return props.children;
}
13 changes: 13 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
// Store current request pathname in a custom header
requestHeaders.set('x-pathname', request.nextUrl.pathname);

return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}

0 comments on commit 353fa9f

Please sign in to comment.