Fixed multiple bugs

This commit is contained in:
Torsten Schulz
2025-07-17 13:56:34 +02:00
parent 353b8386ee
commit e827964688
7 changed files with 105 additions and 67 deletions

View File

@@ -1,18 +1,23 @@
import User from '../models/User.js';
import jwt from 'jsonwebtoken';
import UserToken from '../models/UserToken.js';
export const authenticate = async (req, res, next) => {
try {
const { userid: userId, authcode: authCode } = req.headers;
if (!userId || !authCode) {
return res.status(401).json({ error: 'Unauthorized: Missing credentials' });
}
const user = await User.findOne({ where: { email: userId, authCode: authCode } });
if (!user) {
return res.status(401).json({ error: 'Unauthorized: Invalid credentials' });
}
next();
} catch(error) {
console.log(error);
return res.status(500).json({ error: 'Internal Server Error at auth' });
let token = req.headers['authorization']?.split(' ')[1];
if (!token) {
token = req.headers['authcode'];
}
if (!token) {
return res.status(401).json({ error: 'Unauthorized: Token fehlt' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const tokenRecord = await UserToken.findOne({ where: { token } });
if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
return res.status(401).json({ error: 'Unauthorized: Invalid credentials' });
}
req.user = { id: decoded.userId };
next();
} catch (err) {
return res.status(401).json({ error: 'Unauthorized: Invalid credentials' });
}
};