This commit is contained in:
NotII
2025-03-10 17:39:37 +00:00
parent c08df8919d
commit 20d5559832
69 changed files with 7676 additions and 78 deletions

View File

@@ -0,0 +1,10 @@
export const protectCrypto = async (req, res, next) => {
if (
req.headers.authorization &&
req.headers.authorization === process.env.INTERNAL_API_KEY
) {
return next();
}
return res.status(403).json({ error: "Forbidden: Invalid API key" });
};

View File

@@ -0,0 +1,32 @@
import jwt from "jsonwebtoken";
import Vendor from "../models/Vendor.model.js";
export const protectVendor = async (req, res, next) => {
if (req.method === "OPTIONS") {
return res.status(200).end();
}
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const vendor = await Vendor.findById(decoded.id);
if (!vendor) return res.status(401).json({ message: "Unauthorized" });
req.user = vendor;
req.user.storeId = vendor.storeId;
next();
} catch (error) {
return res.status(401).json({ message: "Token failed" });
}
} else {
return res.status(401).json({ message: "Not authorized, no token" });
}
};

View File

@@ -0,0 +1,49 @@
import jwt from "jsonwebtoken";
import Staff from "../models/Staff.model.js";
/**
* Middleware to protect staff-only routes - Verify JWT from DB
*/
export const protectStaff = async (req, res, next) => {
let token = req.headers.authorization;
if (!token || !token.startsWith("Bearer ")) {
return res.status(401).json({ error: "Not authorized, no token" });
}
try {
token = token.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Verify staff user exists and token matches stored value
const staff = await Staff.findById(decoded.id);
if (!staff || staff.currentToken !== token) {
return res.status(401).json({ error: "Invalid or expired session" });
}
req.user = staff; // Attach staff user data to request
next();
} catch (error) {
res.status(401).json({ error: "Token is invalid or expired" });
}
};
/**
* 📌 Staff Logout - Remove JWT from Database
*/
export const logoutStaff = async (req, res) => {
try {
const staff = await Staff.findById(req.user.id);
if (!staff) {
return res.status(401).json({ error: "User not found" });
}
// Clear stored token
staff.currentToken = null;
await staff.save();
res.json({ message: "Logged out successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
};

View File

@@ -0,0 +1,70 @@
import logger from "../utils/logger.js";
// Middleware for protecting Telegram API routes
export const protectTelegramApi = async (req, res, next) => {
// Log the headers for debugging
logger.info("Telegram API request headers:", {
authorization: req.headers.authorization ? req.headers.authorization.substring(0, 10) + "..." : "undefined",
"x-api-key": req.headers['x-api-key'] ? req.headers['x-api-key'].substring(0, 10) + "..." : "undefined",
method: req.method,
path: req.path,
allHeaders: JSON.stringify(req.headers)
});
// Full debug for non-production environments
logger.info("FULL HEADER DEBUG (KEYS ONLY):", Object.keys(req.headers));
logger.info("AUTH HEADER TYPE:", typeof req.headers.authorization);
const expectedKey = process.env.INTERNAL_API_KEY;
logger.info("Expected API Key (first 10 chars):", expectedKey ? expectedKey.substring(0, 10) + "..." : "undefined");
// Check if the environment variable is actually defined
if (!expectedKey) {
logger.error("INTERNAL_API_KEY environment variable is not defined");
return res.status(500).json({ error: "Server configuration error" });
}
// Check if API key is in the expected header
if (req.headers.authorization === expectedKey) {
logger.info("Telegram API auth successful via Authorization header");
return next();
}
// Also try x-api-key as a fallback
if (req.headers['x-api-key'] === expectedKey) {
logger.info("Telegram API auth successful via x-api-key header");
return next();
}
// Try trimming whitespace
if (req.headers.authorization && req.headers.authorization.trim() === expectedKey) {
logger.info("Telegram API auth successful via Authorization header (after trimming)");
return next();
}
// Also try x-api-key with trimming
if (req.headers['x-api-key'] && req.headers['x-api-key'].trim() === expectedKey) {
logger.info("Telegram API auth successful via x-api-key header (after trimming)");
return next();
}
// Check for Bearer prefix and try to extract the token
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
const token = req.headers.authorization.substring(7).trim();
if (token === expectedKey) {
logger.info("Telegram API auth successful via Bearer token in Authorization header");
return next();
}
}
logger.warn("Telegram API auth failed:", {
expectedKeyPrefix: expectedKey ? expectedKey.substring(0, 5) + "..." : "undefined",
expectedKeyLength: expectedKey ? expectedKey.length : 0,
authHeaderPrefix: req.headers.authorization ? req.headers.authorization.substring(0, 5) + "..." : "undefined",
authHeaderLength: req.headers.authorization ? req.headers.authorization.length : 0,
xApiKeyPrefix: req.headers['x-api-key'] ? req.headers['x-api-key'].substring(0, 5) + "..." : "undefined",
xApiKeyLength: req.headers['x-api-key'] ? req.headers['x-api-key'].length : 0
});
return res.status(401).json({ error: "Unauthorized: Invalid API key" });
};

View File

@@ -0,0 +1,32 @@
import jwt from "jsonwebtoken";
import Vendor from "../models/Vendor.model.js";
export const protectVendor = async (req, res, next) => {
if (req.method === "OPTIONS") {
return res.status(200).end();
}
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const vendor = await Vendor.findById(decoded.id);
if (!vendor) return res.status(401).json({ message: "Unauthorized" });
req.user = vendor;
req.user.storeId = vendor.storeId;
next();
} catch (error) {
return res.status(401).json({ message: "Token failed" });
}
} else {
return res.status(401).json({ message: "Not authorized, no token" });
}
};