#How to protect a api ?

1 messages · Page 1 of 1 (latest)

tough elk
#

Hy everyone, i make several api and i want to protect this but i don't now how to make ?

import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";

export const GET = async (req: Request) => {
  try {
    const prisma = new PrismaClient();

    const socialLink = await prisma.link.findMany({});

    if (!socialLink)
      return NextResponse.json({ message: "No link found !" }, { status: 422 });

    return NextResponse.json(socialLink, { status: 201 });
  } catch (error) {
    return NextResponse.json({ message: "Server Error ! " }, { status: 500 });
  }
};

export const POST = async (req: Request) => {
  try {
    const prisma = new PrismaClient();

    const { social, link, href } = await req.json();

    if (!social || !link || !href)
      return NextResponse.json({ message: "Invalid Data" }, { status: 422 });

    const socialLink = await prisma.link.create({
      data: {
        social: social,
        link: link,
        href: href,
      },
    });

    return NextResponse.json(socialLink, { status: 201 });
  } catch (error) {
    return NextResponse.json({ message: "Server Error ! " }, { status: 500 });
  }
};
gleaming oakBOT
#

Hi @tough elk. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To protect your API routes in Next.js, you need to ensure that only authenticated and authorized users can access them. This typically involves verifying the user's authentication status and their role-based permissions. Below is an example of how you can secure your API routes by checking for an active session and verifying the user's role.

Here's an example of securing an API Route:

import { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
 req: NextApiRequest,
 res: NextApiResponse
) {
 const session = await getSession(req)
 
 // Check if the user is authenticated
 if (!session) {
 res.status(401).json({
 error: 'User is not authenticated',
 })
 return
 }
 
 // Check if the user has the 'admin' role
 if (session.user.role !== 'admin') {
 res.status(401).json({
 error: 'Unauthorized access: User does not have admin privileges.',
 })
 return
 }
 
 // Proceed with the route for authorized users
 // ... implementation of the API Route
}

In your case, you can modify your existing API routes to include these security checks. Here is how you can integrate the authentication and authorization checks into your GET and POST handlers:

import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
import { getSession } from "next-auth/client"; // Assuming you are using next-auth for session management

export const GET = async (req: Request) => {
  const session = await getSession({ req });

  // Check if the user is authenticated
  if (!session) {
    return NextResponse.json({ error: 'User is not authenticated' }, { status: 401 });
  }

  // Check if the user has the 'admin' role
  if (session.user.role !== 'admin') {
    return NextResponse.json({ error: 'Unauthorized access: User does not have admin privileges.' }, { status: 401 });
  }
#

try {
const prisma = new PrismaClient();
const socialLink = await prisma.link.findMany({});

if (!socialLink)
  return NextResponse.json({ message: "No link found !" }, { status: 422 });

return NextResponse.json(socialLink, { status: 201 });

} catch (error) {
return NextResponse.json({ message: "Server Error ! " }, { status: 500 });
}
};

export const POST = async (req: Request) => {
const session = await getSession({ req });

// Check if the user is authenticated
if (!session) {
return NextResponse.json({ error: 'User is not authenticated' }, { status: 401 });
}

// Check if the user has the 'admin' role
if (session.user.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized access: User does not have admin privileges.' }, { status: 401 });
}

try {
const prisma = new PrismaClient();
const { social, link, href } = await req.json();

if (!social || !link || !href)
  return NextResponse.json({ message: "Invalid Data" }, { status: 422 });

const socialLink = await prisma.link.create({
  data: {
    social: social,
    link: link,
    href: href,
  },
});

return NextResponse.json(socialLink, { status: 201 });

} catch (error) {
return NextResponse.json({ message: "Server Error ! " }, { status: 500 });
}
};


This example demonstrates an API Route with a two-tier security check for authentication
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------