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,24 +1,45 @@
import User from '../models/User.js'
import UserClub from '../models/UserClub.js';
import jwt from 'jsonwebtoken';
import { Op } from 'sequelize';
import User from '../models/User.js';
import UserToken from '../models/UserToken.js';
import UserClub from '../models/UserClub.js'; // <-- hier hinzufügen
import HttpError from '../exceptions/HttpError.js';
import { config } from 'dotenv';
config(); // sorgt dafür, dass process.env.JWT_SECRET geladen wird
export const getUserByToken = async(token) => {
export const getUserByToken = async (token) => {
try {
const user = await User.findOne({
where: [
{auth_code: token}
]
});
return user;
} catch (error) {
console.log(error);
const err = new HttpError('noaccess', 403);
throw err;
}
}
// 1. JWT validieren
const payload = jwt.verify(token, process.env.JWT_SECRET);
export const hasUserClubAccess = async(userId, clubId) => {
// 2. Token-Eintrag prüfen (existiert und nicht abgelaufen)
const stored = await UserToken.findOne({
where: {
token,
expiresAt: { [Op.gt]: new Date() }
}
});
if (!stored) {
throw new HttpError('Token abgelaufen oder ungültig', 401);
}
// 3. User laden
const user = await User.findByPk(payload.userId);
if (!user) {
throw new HttpError('Benutzer nicht gefunden', 404);
}
return user;
} catch (err) {
console.error(err);
// Falls es ein HttpError ist, einfach weiterwerfen
if (err instanceof HttpError) throw err;
// ansonsten pauschal „noaccess“
throw new HttpError('noaccess', 403);
}
};
export const hasUserClubAccess = async (userId, clubId) => {
try {
console.log('[hasUserClubAccess]');
const userClub = await UserClub.findOne({
@@ -29,23 +50,23 @@ export const hasUserClubAccess = async(userId, clubId) => {
}
});
return userClub !== null;
} catch(error) {
} catch (error) {
console.log(error);
throw new HttpError('notfound', 500);
}
console.log('---- no user found');
}
export const checkAccess = async(userToken, clubId) => {
export const checkAccess = async (userToken, clubId) => {
try {
const user = await getUserByToken(userToken);
if (!await hasUserClubAccess(user.id, clubId)) {
const hasAccess = await hasUserClubAccess(user.id, clubId);
if (!hasAccess) {
console.log('no club access');
const err = new HttpError('noaccess', 403);
throw err;
throw new HttpError('noaccess', 403);
}
} catch (error) {
console.log(error);
throw error;
throw error;
}
}
};