Reputation: 1
I am trying to make a getProfile page for my nextjs app. However I want to protect the API route. The api route is as follows http://localhost:3000/api/user/123456 . I do not want any other user other than the current employee logged in with employeeid 123456 to access the route. I am handling sesssions by NextAuth.
I tried making a middleware file and passing hte handler through it. But I am unable to handle the routing now. help me with this. This is the middleware file
import { getSession } from 'next-auth/react';
import { NextResponse } from 'next/server';
const requireAuth = (handler) => async (req, res) => {
const session = await getSession({ req });
if (!session) {
return NextResponse.redirect('/login');
}
if (session.user.EmployeeID !== req.params.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return handler(req, res);
};
export default requireAuth;
This below is the route/employeeId/route.js
import User from "@models/user";
import { ConnectToDb } from "@utils/db";
import { NextResponse } from "next/server";
import requireAuth from "@utils/middleware";
export default requireAuth(async (req, res) => {
if (req.method === 'GET') {
return handleGet(req, res);
}
// Handle other HTTP methods if needed
return NextResponse.json({ error: 'Method not allowed' }, { status: 405 });
});
async function handleGet(req, res) {
const { params } = req;
const { EmployeeID } = params;
try {
await ConnectToDb();
const user = await User.findOne({ EmployeeID });
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 401 });
}
return NextResponse.json({ user }, { status: 200 });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
Upvotes: 0
Views: 407
Reputation: 11
I am not sure about this its work for me
in your middleware.js
import { getSession } from 'next-auth/react';
import { NextResponse } from 'next/server';
export async function middleware(request) {
const session = await getSession({ request });
if (!session) {
return NextResponse.redirect('/login');
}
const { pathname } = request.nextUrl;
// Get employee ID from path
const pathParts = pathname.split('/');
const employeeId = pathParts[pathParts.length - 1];
// Validate employee ID
if (!employeeId.match(/^\d+$/)) {
return NextResponse.redirect('/invalid-employee');
}
return NextResponse.next();
}
export const config = {
matcher: ['/employee/:employeeId'], // Provide your client side page folder name
};
In the matcher please provide the route of your clientside id page like this
Upvotes: 0