Next.js Discord

Discord Forum

Ensuring User Authentication and Authorization for Links Containing Other Users' IDs

Answered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
Hey, thank you for your time in advance.

Problem: My code doesn't seem safe nor efficient... Are there any better alternatives to this?

My project has "home page" and "dashboard page - for authenticated users" once they signup/signin they are redirected to "/dashboard"

In "/dashboard" I handle that and redirect to "/dashboard/[id]" Code bellow

import getSession from "@/lib/getSession";
import { redirect } from "next/navigation";

const Dashboard = async () => {
  const session = await getSession();
  const user = session?.user;

  if (user && user.id) {
    redirect(`/dashboard/${user.id}`);
  }

  redirect("/api/auth/signin");
};

export default Dashboard;


Since someone could still come at "/dashboard/[id]" and access others person data i handle that in "/dashboard/[id]" code bellow

import getSession from "@/lib/getSession";
import { redirect } from "next/navigation";

const UserDashboard = async ({ params }: { params: { id: string } }) => {
  const session = await getSession();
  const user = session?.user;

  if (user?.id !== params.id) {
    redirect("/api/auth/signin");
  }

  return <div className="container w-full py-6">{user.name}</div>;
};

export default UserDashboard;


Extra
getSession() is just auth that is being cached for performace reasons code bellow
import { auth } from '@/auth';
import { cache } from 'react';

export default cache(auth);
Answered by Sun bear
I don't get this... You are checking whether the user is logged in by checking if the logged in user matches the id in the url.
if (user?.id !== params.id) {
  redirect("/api/auth/signin")
}

You can just check if the user id exists and based on that fetch the dashboard information or redirect to login:
const session = await getSession()
const user = session?.user

if (!user?.id) // if the user is not logged-in the user.id will not exist
  redirect("/api/auth/signin")

// ...fetch the rest of the dashboard information

Also ditch the whole dashboard id in url thing.
View full answer

2 Replies

Sun bear
I don't get this... You are checking whether the user is logged in by checking if the logged in user matches the id in the url.
if (user?.id !== params.id) {
  redirect("/api/auth/signin")
}

You can just check if the user id exists and based on that fetch the dashboard information or redirect to login:
const session = await getSession()
const user = session?.user

if (!user?.id) // if the user is not logged-in the user.id will not exist
  redirect("/api/auth/signin")

// ...fetch the rest of the dashboard information

Also ditch the whole dashboard id in url thing.
Answer
RhinelanderOP
Did thanks!