54 lines
1.9 KiB
JavaScript
54 lines
1.9 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.optionalAuth = exports.authenticate = void 0;
|
|
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
const index_1 = require("../index");
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key';
|
|
const authenticate = async (req, res, next) => {
|
|
try {
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return res.status(401).json({ error: 'No token provided' });
|
|
}
|
|
const token = authHeader.split(' ')[1];
|
|
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
|
|
const user = await index_1.prisma.user.findUnique({
|
|
where: { id: decoded.userId },
|
|
select: { id: true, email: true, name: true }
|
|
});
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'User not found' });
|
|
}
|
|
req.user = user;
|
|
next();
|
|
}
|
|
catch (error) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
};
|
|
exports.authenticate = authenticate;
|
|
const optionalAuth = async (req, res, next) => {
|
|
try {
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return next();
|
|
}
|
|
const token = authHeader.split(' ')[1];
|
|
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
|
|
const user = await index_1.prisma.user.findUnique({
|
|
where: { id: decoded.userId },
|
|
select: { id: true, email: true, name: true }
|
|
});
|
|
if (user) {
|
|
req.user = user;
|
|
}
|
|
next();
|
|
}
|
|
catch {
|
|
next();
|
|
}
|
|
};
|
|
exports.optionalAuth = optionalAuth;
|