51 lines
1.7 KiB
JavaScript
51 lines
1.7 KiB
JavaScript
import { Router } from 'express'
|
|
import { config } from '../../config.js'
|
|
import { createStaffPreviewToken } from '../../services/staffPreviewTokens.js'
|
|
import { resolveStaffAccount } from '../../services/staffAccount.js'
|
|
|
|
const router = Router()
|
|
|
|
/**
|
|
* Wechsel Ticketsystem -> Projekt-Admin ohne zweiten Login. Wie requireAppwriteStaff wird das JWT
|
|
* ueber /account geprueft (eine Sitzung ohne zweiten Faktor bekommt dort 401), aber ohne Label-Pflicht:
|
|
* jeder Mitarbeiter darf rueber, wie beim normalen Portal-Login.
|
|
*/
|
|
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()
|
|
}
|
|
|
|
router.post('/', async (req, res) => {
|
|
try {
|
|
const user = await appwriteAccountFromJwt(req)
|
|
if (!user?.$id) return res.status(401).json({ error: 'Bitte im Ticketsystem neu anmelden.' })
|
|
|
|
const staff = await resolveStaffAccount(user.$id, user.email || '', user)
|
|
if (!staff) return res.status(403).json({ error: 'Kein Mitarbeiterkonto.' })
|
|
|
|
const token = createStaffPreviewToken({
|
|
purpose: 'switch',
|
|
userId: user.$id,
|
|
email: staff.email,
|
|
name: staff.name,
|
|
isAdmin: staff.isAdmin,
|
|
})
|
|
return res.json({
|
|
openUrl: `https://${config.preview.baseHost}/api/auth/staff-switch?token=${encodeURIComponent(token)}`,
|
|
})
|
|
} catch (err) {
|
|
return res.status(500).json({ error: err.message || 'Wechsel fehlgeschlagen' })
|
|
}
|
|
})
|
|
|
|
export default router
|