import { config } from '../config.js' import { getEmployeeByEmail, getEmployeeByUserId } from '../services/appwriteAdmin.js' /** * Appwrite-Konto zum Bearer-JWT aus dem Ticketsystem (GET /account). null ohne Header oder wenn Appwrite * ablehnt - auch bei einer Sitzung ohne zweiten Faktor (401 user_more_factors_required). */ export async function appwriteAccountFromJwt(req) { const match = (req.get('Authorization') || '').match(/^Bearer\s+(.+)$/i) if (!match) return null const response = await fetch(`${config.appwrite.endpoint}/account`, { headers: { 'Content-Type': 'application/json', 'X-Appwrite-Project': config.appwrite.projectId, 'X-Appwrite-JWT': match[1], }, }) if (!response.ok) return null return response.json() } /** * Mitarbeiter fuer den Team-Eingang: employees-Eintrag zur Konto-ID, Label "admin" oder - nur mit bestaetigter * Konto-Mail - ein employees-Eintrag zur Mail. Kunden haben Konten im selben Appwrite-Projekt und koennen ihre * Mail ohne Bestaetigung aendern; eine unbestaetigte Mail zaehlt deshalb nie. */ export async function resolveTeamStaff(account) { if (!account?.$id) return null const isAdmin = Array.isArray(account.labels) && account.labels.includes('admin') let employee = await getEmployeeByUserId(account.$id).catch(() => null) if (!employee && !isAdmin && account.emailVerification === true && account.email) { employee = await getEmployeeByEmail(account.email).catch(() => null) } if (!employee && !isAdmin) return null return { isAdmin, name: employee?.displayName || account.name || 'Mitarbeiter', email: account.email || employee?.email || '', } } /** * Team-Eingang (/api/team): jeder Mitarbeiter mit gueltiger Ticketsystem-Anmeldung. req.session hat dieselbe Form * wie die Admin-Sitzung des Portals, damit die bestehenden Handler unveraendert laufen. */ export async function requireStaffJwt(req, res, next) { try { const account = await appwriteAccountFromJwt(req) if (!account?.$id) return res.status(401).json({ error: 'Bitte im Ticketsystem neu anmelden.' }) const staff = await resolveTeamStaff(account) if (!staff) return res.status(403).json({ error: 'Kein Mitarbeiterkonto.' }) const session = { role: 'admin', isAdmin: staff.isAdmin, appwriteUserId: account.$id, name: staff.name, email: staff.email } req.session = session req.staff = session return next() } catch (err) { return res.status(500).json({ error: err.message || 'Anmeldung konnte nicht geprüft werden' }) } }