28 lines
871 B
TypeScript
28 lines
871 B
TypeScript
import { NextApiRequest, NextApiResponse } from "next";
|
|
import jwt from "jsonwebtoken";
|
|
import { PrismaClient } from "@prisma/client";
|
|
|
|
const prisma = new PrismaClient();
|
|
const SECRET_KEY = process.env.JWT_SECRET as string;
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
return res.status(401).json({ message: "Unauthorized" });
|
|
}
|
|
|
|
const token = authHeader.split(" ")[1]; // Extract token
|
|
|
|
try {
|
|
const decoded: any = jwt.verify(token, SECRET_KEY);
|
|
const user = await prisma.user.findUnique({ where: { id: decoded.userId } });
|
|
|
|
if (!user) return res.status(401).json({ message: "User not found" });
|
|
|
|
res.json({ user });
|
|
} catch (error) {
|
|
res.status(401).json({ message: "Invalid token" });
|
|
}
|
|
}
|