2025-08-18 12:42:20 +08:00

47 lines
1.6 KiB
TypeScript

// pages/api/auth/me.ts
import type { NextApiRequest, NextApiResponse } from "next";
import jwt, { JwtPayload } from "jsonwebtoken";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const SECRET_KEY = process.env.JWT_SECRET as string;
function readCookieToken(req: NextApiRequest) {
const cookie = req.headers.cookie || "";
const match = cookie.split("; ").find((c) => c.startsWith("token="));
return match?.split("=")[1];
}
function readAuthBearer(req: NextApiRequest) {
const auth = req.headers.authorization;
if (!auth?.startsWith("Bearer ")) return undefined;
return auth.slice("Bearer ".length);
}
function hasEmail(payload: string | JwtPayload): payload is JwtPayload & { email: string } {
return typeof payload === "object" && payload !== null && typeof (payload as any).email === "string";
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
try {
const token = readAuthBearer(req) ?? readCookieToken(req);
if (!token) return res.status(401).json({ message: "Unauthorized" });
const decoded = jwt.verify(token, SECRET_KEY);
if (!hasEmail(decoded)) return res.status(401).json({ message: "Invalid token" });
const user = await prisma.user.findUnique({
where: { email: decoded.email },
select: { id: true, email: true, createdAt: true },
});
if (!user) return res.status(401).json({ message: "User not found" });
return res.status(200).json({ user });
} catch {
return res.status(401).json({ message: "Invalid token" });
}
}