initial commit - code moved to separate repo
This commit is contained in:
68
pages/api/data/[...nextcrud].ts
Normal file
68
pages/api/data/[...nextcrud].ts
Normal file
@ -0,0 +1,68 @@
|
||||
import NextCrud, { PrismaAdapter } from "@premieroctet/next-crud";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]";
|
||||
// import { getToken } from "next-auth/jwt";
|
||||
// import { getSession } from "next-auth/client";
|
||||
const common = require("../../../src/helpers/common");
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { decode } from 'next-auth/jwt';
|
||||
// import { getToken } from "next-auth/jwt";
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const prismaClient = common.getPrismaClient();
|
||||
|
||||
const nextCrudHandler = await NextCrud({
|
||||
adapter: new PrismaAdapter({ prismaClient }),
|
||||
models: {
|
||||
[Prisma.ModelName.CartEvent]: { name: "cartevents" },
|
||||
},
|
||||
});
|
||||
//1: check session
|
||||
const session = await getServerSession(req, res, authOptions);
|
||||
//console.log("Session:", session); // Log the session
|
||||
const authHeader = req.headers.authorization || '';
|
||||
//console.log('authHeader', authHeader);
|
||||
if (session) {
|
||||
return nextCrudHandler(req, res);
|
||||
}
|
||||
else {
|
||||
console.log('[nextCrud]: No session');
|
||||
}
|
||||
|
||||
//2: check jwt
|
||||
const secret = process.env.NEXTAUTH_SECRET;
|
||||
const bearerHeader = req.headers['authorization'];
|
||||
if (bearerHeader) {
|
||||
const token = bearerHeader.split(' ')[1]; // Assuming "Bearer <token>"
|
||||
try {
|
||||
const decoded = await decode({
|
||||
token: token,
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
});
|
||||
//console.log('Decoded JWT:');
|
||||
} catch (err) {
|
||||
console.error('[nextCrud]: Error decoding token:', err);
|
||||
}
|
||||
try {
|
||||
const verified = jwt.verify(token, secret);
|
||||
//console.log('Verified JWT:');
|
||||
|
||||
return nextCrudHandler(req, res);
|
||||
} catch (err) {
|
||||
console.error('[nextCrud]: Invalid token:', err);
|
||||
}
|
||||
}
|
||||
|
||||
//3. check X-From-Server header
|
||||
const xFromServer = req.headers['x-from-server'];
|
||||
if (xFromServer) {
|
||||
return nextCrudHandler(req, res);
|
||||
}
|
||||
|
||||
|
||||
return res.status(401).json({ message: '[nextCrud]: Unauthorized' });
|
||||
};
|
||||
|
||||
export default handler;
|
Reference in New Issue
Block a user