Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middleware based auth for pages, robots.txt, sitemap.xml #164

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 2 additions & 14 deletions apps/web/app/(auth)/signin/page.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
import Image from "next/image";
import Link from "next/link";
import Logo from "@/public/logo.svg";
import { auth, signIn } from "@/server/auth";
import { signIn } from "@/server/auth";
import { Google } from "@repo/ui/components/icons";
import gradientStyle from "./_components/TextGradient/gradient.module.css";
import { cn } from "@repo/ui/lib/utils";
import { redirect } from "next/navigation";
import { toast } from "sonner";

export const runtime = "edge";

async function Signin({
searchParams,
}: {
searchParams: Record<string, string>;
}) {
const user = await auth();

if (user) {
redirect("/home");
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: Redirect logic in Signin function should handle more cases.

Solution: Add error handling to manage failed authentication attempts and provide user feedback.

Reason For Comment: The current implementation only checks if a user exists but does not handle cases where the authentication fails or if the user is not authorized.

Suggested change
async function Signin(){const user = await auth(); if (!user){return <ErrorComponent message='Authentication failed' />;}redirect('/home');}

async function Signin() {
return (
<div className="flex relative font-geistSans overflow-hidden items-center justify-between min-h-screen">
<div className="relative w-full lg:w-1/2 flex items-center min-h-screen bg-page-gradient p-8 border-r-[1px] border-white/5">
Expand Down
10 changes: 4 additions & 6 deletions apps/web/app/(dash)/(memories)/content.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import { Content, StoredSpace } from "@/server/db/schema";
import { MemoriesIcon, NextIcon, SearchIcon, UrlIcon } from "@repo/ui/icons";
import type { Content, StoredSpace } from "@/server/db/schema";
import { MemoriesIcon, NextIcon, UrlIcon } from "@repo/ui/icons";
import {
ArrowLeftIcon,
MenuIcon,
Expand All @@ -12,17 +12,15 @@ import {
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useMemo, useState } from "react";
import React, { useMemo, useState } from "react";
import Masonry from "react-layout-masonry";
import { getRawTweet } from "@repo/shared-types/utils";
import { MyTweet } from "../../../components/twitter/render-tweet";
import { MyTweet } from "@/components/twitter/render-tweet";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuPortal,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
Expand Down
3 changes: 0 additions & 3 deletions apps/web/app/(dash)/(memories)/space/[spaceid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import MemoriesPage from "../../content";
import { db } from "@/server/db";
import { and, eq } from "drizzle-orm";
import { spacesAccess } from "@/server/db/schema";
import { auth } from "@/server/auth";

async function Page({ params: { spaceid } }: { params: { spaceid: number } }) {
const user = await auth();

const { success, data } = await getMemoriesInsideSpace(spaceid);
if (!success ?? !data) return redirect("/home");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: The redirect logic in the Page function does not handle errors properly.

Solution: Change the condition to explicitly check for both success and data.

Reason For Comment: Using a nullish coalescing operator (??) in the condition might lead to unexpected behavior. It should explicitly check for both success and data.

Suggested change
if (!success ?? !data) return redirect("/home");
if (!success || !data) return redirect('/home');


Expand Down
1 change: 0 additions & 1 deletion apps/web/app/(dash)/chat/[chatid]/loading.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import { chatSearchParamsCache } from "../../../../lib/searchParams";
import ChatWindow from "../chatWindow";

async function Page({
Expand Down
6 changes: 3 additions & 3 deletions apps/web/app/(dash)/dialogContentContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { StoredSpace } from "@/server/db/schema";
import type { StoredSpace } from "@/server/db/schema";
import { useEffect, useMemo, useState } from "react";
import { createMemory, createSpace } from "../actions/doers";
import { createMemory, createSpace } from "@/app/actions/doers";
import ComboboxWithCreate from "@repo/ui/shadcn/combobox";
import { toast } from "sonner";
import { getSpaces } from "../actions/fetchers";
import { getSpaces } from "@/app/actions/fetchers";
import { MinusIcon, PlusCircleIcon } from "lucide-react";
import {
DialogContent,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/app/(dash)/header/header.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from "react";
import Image from "next/image";
import Link from "next/link";
import Logo from "../../../public/logo.svg";
import Logo from "@/public/logo.svg";

import { getChatHistory } from "../../actions/fetchers";
import { getChatHistory } from "@/app/actions/fetchers";
import NewChatButton from "./newChatButton";
import AutoBreadCrumbs from "./autoBreadCrumbs";
import SignOutButton from "./signOutButton";
Expand Down
6 changes: 4 additions & 2 deletions apps/web/app/(dash)/header/signOutButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ export default function SignOutButton() {
return (
<form
action={async () => {
"use server";
await signOut();
"use server"
await signOut({
redirectTo: "/",
});
}}
>
<Button
Expand Down
11 changes: 2 additions & 9 deletions apps/web/app/(dash)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
import Header from "./header/header";
import Menu from "./menu";
import { redirect } from "next/navigation";
import { auth } from "../../server/auth";
import { Toaster } from "@repo/ui/shadcn/sonner";
import BackgroundPlus from "../(landing)/GridPatterns/PlusGrid";
import { getUser } from "../actions/fetchers";
import BackgroundPlus from "@/app/(landing)/GridPatterns/PlusGrid";
import { getUser } from "@/app/actions/fetchers";

async function Layout({ children }: { children: React.ReactNode }) {
const info = await auth();

if (!info) {
return redirect("/signin");
}

const user = await getUser();
const hasOnboarded = user.data?.hasOnboarded;

Expand Down
10 changes: 4 additions & 6 deletions apps/web/app/(dash)/menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import Image from "next/image";
import Link from "next/link";
import {
MemoriesIcon,
ExploreIcon,
CanvasIcon,
AddIcon,
HomeIcon as HomeIconWeb,
CanvasIcon,
} from "@repo/ui/icons";
import { Button } from "@repo/ui/shadcn/button";
import { MinusIcon, PlusCircleIcon } from "lucide-react";
Expand All @@ -24,12 +23,11 @@ import {
import { Label } from "@repo/ui/shadcn/label";
import { Textarea } from "@repo/ui/shadcn/textarea";
import { toast } from "sonner";
import { getSpaces } from "../actions/fetchers";
import { getSpaces } from "@/app/actions/fetchers";
import { HomeIcon } from "@heroicons/react/24/solid";
import { createMemory, createSpace } from "../actions/doers";
import { createMemory, createSpace } from "@/app/actions/doers";
import ComboboxWithCreate from "@repo/ui/shadcn/combobox";
import { StoredSpace } from "@/server/db/schema";
import useMeasure from "react-use-measure";
import type { StoredSpace } from "@/server/db/schema";
import { useKeyPress } from "@/lib/useKeyPress";

function Menu() {
Expand Down
8 changes: 0 additions & 8 deletions apps/web/app/(landing)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,13 @@ import Cta from "./Cta";
import { Toaster } from "@repo/ui/shadcn/toaster";
import Features from "./Features";
import Footer from "./footer";
import { auth } from "@/server/auth";
import Services from "./Features/index";
import { Showcases } from "./Showcase";
import BackgroundPlus from "./GridPatterns/PlusGrid";
import { redirect } from "next/navigation";

export const runtime = "edge";

export default async function Home() {
const user = await auth();

if (user) {
await redirect("/home");
}

return (
<>
<BackgroundPlus />
Expand Down
13 changes: 13 additions & 0 deletions apps/web/app/robots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type MetadataRoute } from 'next'
import { routeGroups, routeTypes } from '@/routes'

export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: [...routeGroups.landing],
disallow: [...routeTypes.authed],
},
sitemap: 'https://supermemory.ai/sitemap.xml',
}
}
12 changes: 12 additions & 0 deletions apps/web/app/sitemap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { type MetadataRoute } from 'next'

export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://supermemory.ai/',
lastModified: new Date(),
changeFrequency: 'yearly',
priority: 1,
}
]
Comment on lines +4 to +11
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: The sitemap.xml generation logic is missing URLs for authenticated pages.

Solution: Add URLs for authenticated pages to the sitemap.xml generation logic.

Reason For Comment: The current implementation only includes the root URL, which is insufficient for SEO purposes. Authenticated pages should be included in the sitemap to improve discoverability by search engines.

Suggested change
return [
{
url: 'https://supermemory.ai/',
lastModified: new Date(),
changeFrequency: 'yearly',
priority: 1,
}
]
import{type MetadataRoute}from 'next'
export default function sitemap(): MetadataRoute.Sitemap{
return[
{url: 'https://supermemory.ai/', lastModified: new Date(), changeFrequency: 'yearly', priority: 1},
{url: 'https://supermemory.ai/app/home', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/memories', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/space', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/chat', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/note', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/canvas', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
]
}
```

}
42 changes: 30 additions & 12 deletions apps/web/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { type NextRequest, NextResponse } from "next/server";
import { auth } from "./server/auth";
import { routeTypes } from "@/routes";

const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export function middleware(request: NextRequest) {
if (request.method === "OPTIONS") {
return new NextResponse(null, { headers: corsHeaders });
}
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith("/api")) {
if (request.method === "OPTIONS") {
return new NextResponse(null, { headers: corsHeaders });
}

const response = NextResponse.next();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});

return response;
const response = NextResponse.next();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
}
const info = await auth();
if (routeTypes.authed.some((route) => request.nextUrl.pathname.startsWith(route))) {
if (!info) {
return NextResponse.redirect(new URL("/signin", request.nextUrl));
}
} else if (routeTypes.unAuthedOnly.some((route) => request.nextUrl.pathname.endsWith(route))) {
if (info) {
return NextResponse.redirect(new URL("/home", request.nextUrl));
}
}
return NextResponse.next();
Comment on lines +23 to +33
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: The middleware function should handle both authenticated and unauthenticated routes correctly.

Solution: Ensure that the authentication check is comprehensive and covers all necessary routes.

Reason For Comment: If the authentication logic fails or is misconfigured, users may gain unauthorized access or be incorrectly redirected.

Suggested change
const info = await auth();
if (routeTypes.authed.some((route) => request.nextUrl.pathname.startsWith(route))) {
if (!info) {
return NextResponse.redirect(new URL("/signin", request.nextUrl));
}
} else if (routeTypes.unAuthedOnly.some((route) => request.nextUrl.pathname.endsWith(route))) {
if (info) {
return NextResponse.redirect(new URL("/home", request.nextUrl));
}
}
return NextResponse.next();
if (routeTypes.authed.some((route) => request.nextUrl.pathname.startsWith(route))){/* existing logic */}else if (routeTypes.unAuthedOnly.some((route) => request.nextUrl.pathname.endsWith(route))){/* existing logic */}

}

export const config = {
matcher: "/api/:path*",
matcher: [
'/((?!_next/static|_next/image|image|favicon.ico).*)',
'/api/:path*',
'/.:path*',
]
};
13 changes: 13 additions & 0 deletions apps/web/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const routeGroups = {
auth: ["/privacy", "/signin", "/tos"],
canvas: ["/canvas"],
dash: ["/memories", "/space", "/chat", "/home", "/note"],
landing: ["/"],
other: ["/ref", "/onboarding"],
};

export const routeTypes = {
authed: [...routeGroups.canvas, ...routeGroups.dash, ...routeGroups.other],
unauthed: [...routeGroups.auth, ...routeGroups.landing],
unAuthedOnly: [...routeGroups.landing, "/signin"],
}