Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
add middleware to check if user is logged in
Marc Seitz2a39aaffb33f
diff --git a/lib/middleware/app.ts b/lib/middleware/app.tsnew file mode 100644index 00000000..6e2cb870--- /dev/null+++ b/lib/middleware/app.ts@@ -0,0 +1,40 @@+import { NextRequest, NextResponse } from "next/server";+import { getToken } from "next-auth/jwt";++export default async function AppMiddleware(req: NextRequest) {+ const path = req.nextUrl.pathname;+ const token = (await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ })) as {+ email?: string;+ user?: {+ createdAt?: string;+ };+ };++ // if there's no token and the path isn't /login, redirect to /login+ if (!token?.email && path !== "/login") {+ return NextResponse.redirect(+ new URL(+ `/login${path !== "/" ? `?next=${encodeURIComponent(path)}` : ""}`,+ req.url+ )+ );++ // if there's a token+ } else if (token?.email) {+ // if the user was created in the last 10 seconds, redirect to "/welcome"+ if (+ token?.user?.createdAt &&+ new Date(token?.user?.createdAt).getTime() > Date.now() - 1000000 &&+ path !== "/welcome"+ ) {+ return NextResponse.redirect(new URL("/welcome", req.url));++ // if the path is /login, redirect to "/documents"+ } else if (path === "/login") {+ return NextResponse.redirect(new URL("/documents", req.url));+ }+ }+}diff --git a/lib/types.ts b/lib/types.tsindex cddff898..92a103a6 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -3,6 +3,7 @@ import { Document, Link, View } from "@prisma/client";export interface CustomUser extends NextAuthUser {id: string;+ createdAt: Date;}export interface DocumentWithLinksAndLinkCount extends Document {diff --git a/middleware.ts b/middleware.tsnew file mode 100644index 00000000..71f3dae1--- /dev/null+++ b/middleware.ts@@ -0,0 +1,27 @@+import { NextFetchEvent, NextRequest, NextResponse } from "next/server";+import AppMiddleware from "@/lib/middleware/app";++export const config = {+ matcher: [+ /*+ * Match all paths except for:+ * 1. /api/ routes+ * 2. /_next/ (Next.js internals)+ * 3. /_proxy/, /_auth/ (special pages for OG tags proxying and password protection)+ * 4. /_static (inside /public)+ * 5. /_vercel (Vercel internals)+ * 6. /favicon.ico, /sitemap.xml (static files)+ */+ "/((?!api/|_next/|_proxy/|_auth/|_static|_vercel|favicon.ico|sitemap.xml).*)",+ ],+};++export default async function middleware(req: NextRequest, ev: NextFetchEvent) {+ const path = req.nextUrl.pathname;++ if (path !== "/") {+ return AppMiddleware(req);+ }++ return NextResponse.next();+}