Next.js Discord

Discord Forum

Is this secured ?

Unanswered
Sphynx posted this in #help-forum
Open in Discord
SphynxOP
Hi, I have this code to check if an user is admin or not, I struggled a lot with getServerSession, so the only way I found to add some properties of my mongo database was to directly make the request before sending the page.
I'd just want to know if you think there's a better way to do this or not :)

import { getServerSession } from 'next-auth/next';
import { connect } from '../lib/connect';

export default async function IndexPage({
  searchParams,
}: {
  searchParams: { q: string };
}) {
  const session = await getServerSession();
  console.log(session)
  
  const users: any = []
  console.log(!session || !session.user)
  if (!session || !session.user) {
    return (
      <main className="p-4 md:p-10 mx-auto max-w-7xl">
        <Title>Please login in order to access the admin panel</Title>
      </main>
    );
  } 
  await connect();
  if (!(await UserModel.findOne({ email: session.user.email }))?.admin) {
    return (
      <main className="p-4 md:p-10 mx-auto max-w-7xl">
        <Title>This panel is only accessible to admin users.</Title>
      </main>
    );
  } else {
    return (
      <main className="p-4 md:p-10 mx-auto max-w-7xl">
        <Title>Users</Title>
        <Text>
          Blabala
        </Text>
        <Search />
        <Card className="mt-6">
          <UsersTable users={users} />
        </Card>
      </main>
    );
  }
}

0 Replies