Wechsel Ticketsystem → Projekt-Admin per Einmal-Link, Rückweg-Button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9b14a74fcc
commit
0555a2274d
7 files changed
+164
-1
No files matched your search
@@ -149,6 +149,7 @@
|
|||||||
<a class="portal-logo" href="/admin.html">Webklar <span style="opacity:.6">Admin</span></a>
|
<a class="portal-logo" href="/admin.html">Webklar <span style="opacity:.6">Admin</span></a>
|
||||||
<div class="portal-header-actions">
|
<div class="portal-header-actions">
|
||||||
<span class="portal-meta" id="admin-meta"></span>
|
<span class="portal-meta" id="admin-meta"></span>
|
||||||
|
<a class="portal-btn-outline" href="https://ticket.webklar.com/tickets">← Ticketsystem</a>
|
||||||
<button type="button" class="portal-btn-outline" id="logout-btn">Abmelden</button>
|
<button type="button" class="portal-btn-outline" id="logout-btn">Abmelden</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -265,6 +265,13 @@
|
|||||||
border-color 0.25s var(--ease-out);
|
border-color 0.25s var(--ease-out);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
a.portal-btn-outline {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
line-height: normal;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
.portal-btn-outline:hover {
|
.portal-btn-outline:hover {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #1c1c1c;
|
color: #1c1c1c;
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import adminCustomersRoutes from './routes/admin/customers.js'
|
|||||||
import adminEmployeesRoutes from './routes/admin/employees.js'
|
import adminEmployeesRoutes from './routes/admin/employees.js'
|
||||||
import adminInvoiceClientsRoutes from './routes/admin/invoiceClients.js'
|
import adminInvoiceClientsRoutes from './routes/admin/invoiceClients.js'
|
||||||
import adminPreviewOpenRoutes from './routes/admin/previewOpen.js'
|
import adminPreviewOpenRoutes from './routes/admin/previewOpen.js'
|
||||||
|
import adminSwitchLinkRoutes from './routes/admin/switchLink.js'
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
const publicDir = path.join(__dirname, '..', 'public')
|
const publicDir = path.join(__dirname, '..', 'public')
|
||||||
@@ -65,6 +66,7 @@ app.use('/api/admin/customers', adminCustomersRoutes)
|
|||||||
app.use('/api/admin/employees', adminEmployeesRoutes)
|
app.use('/api/admin/employees', adminEmployeesRoutes)
|
||||||
app.use('/api/admin/invoice-clients', adminInvoiceClientsRoutes)
|
app.use('/api/admin/invoice-clients', adminInvoiceClientsRoutes)
|
||||||
app.use('/api/admin/preview-open', adminPreviewOpenRoutes)
|
app.use('/api/admin/preview-open', adminPreviewOpenRoutes)
|
||||||
|
app.use('/api/admin/switch-link', adminSwitchLinkRoutes)
|
||||||
app.use('/webhook', giteaWebhookRoutes)
|
app.use('/webhook', giteaWebhookRoutes)
|
||||||
|
|
||||||
app.get('/api/health', async (_req, res) => {
|
app.get('/api/health', async (_req, res) => {
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
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
|
||||||
@@ -335,6 +335,19 @@ router.get('/staff-preview', async (req, res) => {
|
|||||||
return res.redirect(previewUrl)
|
return res.redirect(previewUrl)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Wechsel aus dem Ticketsystem (POST /api/admin/switch-link): Einmal-Link -> Admin-Sitzung
|
||||||
|
router.get('/staff-switch', async (req, res) => {
|
||||||
|
const tokenData = consumeStaffPreviewToken(String(req.query.token || ''), 'switch')
|
||||||
|
if (!tokenData) {
|
||||||
|
return res.redirect(`/login.html?error=${encodeURIComponent('Link abgelaufen, bitte anmelden')}`)
|
||||||
|
}
|
||||||
|
await startStaffPortalSession(res, {
|
||||||
|
userId: tokenData.userId,
|
||||||
|
staff: { isAdmin: Boolean(tokenData.isAdmin), name: tokenData.name, email: tokenData.email },
|
||||||
|
})
|
||||||
|
return res.redirect('/admin.html')
|
||||||
|
})
|
||||||
|
|
||||||
// Selbstheilung: Portal-Session lebt oft laenger als das preview_session-Cookie
|
// Selbstheilung: Portal-Session lebt oft laenger als das preview_session-Cookie
|
||||||
// (bzw. das Cookie fehlt nach WebView-/Browser-Datenverlust). Ohne gueltiges
|
// (bzw. das Cookie fehlt nach WebView-/Browser-Datenverlust). Ohne gueltiges
|
||||||
// Preview-Cookie laufen die *.project.webklar.com-Hosts in eine 302-Schleife.
|
// Preview-Cookie laufen die *.project.webklar.com-Hosts in eine 302-Schleife.
|
||||||
|
|||||||
@@ -20,11 +20,16 @@ export function createStaffPreviewToken(payload) {
|
|||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
||||||
export function consumeStaffPreviewToken(token) {
|
/**
|
||||||
|
* Einmal einloesen. purpose trennt Preview-Links ('preview', Standard) vom Wechsel ins Projekt-Admin
|
||||||
|
* ('switch'); ein Token fuer den falschen Zweck ist trotzdem verbraucht.
|
||||||
|
*/
|
||||||
|
export function consumeStaffPreviewToken(token, purpose = 'preview') {
|
||||||
purgeExpired()
|
purgeExpired()
|
||||||
const entry = tokens.get(token)
|
const entry = tokens.get(token)
|
||||||
if (!entry) return null
|
if (!entry) return null
|
||||||
tokens.delete(token)
|
tokens.delete(token)
|
||||||
if (entry.expiresAt <= Date.now()) return null
|
if (entry.expiresAt <= Date.now()) return null
|
||||||
|
if ((entry.purpose || 'preview') !== purpose) return null
|
||||||
return entry
|
return entry
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { test, after } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { startAppwriteMock } from './support/appwriteMock.js'
|
||||||
|
import { startFakeStripe } from './support/fakeStripe.js'
|
||||||
|
import { useTestEnv } from './support/testEnv.js'
|
||||||
|
|
||||||
|
// Wechsel Ticketsystem -> Projekt-Admin per Einmal-Link (purpose 'switch'), Rueckweg-Button im Admin
|
||||||
|
const aw = await startAppwriteMock()
|
||||||
|
const st = await startFakeStripe()
|
||||||
|
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
|
||||||
|
const { config } = await import('../server/config.js')
|
||||||
|
const { startTestApp, post, rawGet } = await import('./support/testApp.js')
|
||||||
|
const { default: authRoutes } = await import('../server/routes/auth.js')
|
||||||
|
const { default: switchLinkRoutes } = await import('../server/routes/admin/switchLink.js')
|
||||||
|
const { createStaffPreviewToken } = await import('../server/services/staffPreviewTokens.js')
|
||||||
|
const app = await startTestApp({ '/api/auth': authRoutes, '/api/admin/switch-link': switchLinkRoutes })
|
||||||
|
after(() => Promise.all([app.close(), aw.close(), st.close()]))
|
||||||
|
|
||||||
|
aw.seed('employees', { $id: 'e_staff2', userId: 'u_staff2', displayName: 'Andrej', email: 'andrej@webklar.com' })
|
||||||
|
|
||||||
|
const bearer = (jwt) => ({ headers: { authorization: `Bearer ${jwt}` } })
|
||||||
|
const switchLink = (jwt) => post('/api/admin/switch-link', {}, jwt ? bearer(jwt) : {})
|
||||||
|
const tokenOf = (openUrl) => new URL(openUrl).searchParams.get('token')
|
||||||
|
const portalSession = (res) => {
|
||||||
|
const cookie = res.headers.getSetCookie().find((c) => c.startsWith(`${config.cookieName}=`))
|
||||||
|
if (!cookie) return null
|
||||||
|
const raw = decodeURIComponent(cookie.split(';')[0].slice(config.cookieName.length + 1))
|
||||||
|
return JSON.parse(raw.slice(2, raw.lastIndexOf('.')))
|
||||||
|
}
|
||||||
|
|
||||||
|
test('switch-link: ohne, ungueltiges und halbes JWT -> 401', async () => {
|
||||||
|
assert.equal((await switchLink(null)).status, 401)
|
||||||
|
assert.equal((await switchLink('jwt-falsch')).status, 401)
|
||||||
|
assert.equal((await switchLink('jwt-halb')).status, 401)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('switch-link: kein Mitarbeiter -> 403', async () => {
|
||||||
|
assert.equal((await switchLink('jwt-kunde')).status, 403)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('switch-link: Mitarbeiter ohne Admin-Label bekommt einen Link', async () => {
|
||||||
|
const res = await switchLink('jwt-staff')
|
||||||
|
assert.equal(res.status, 200)
|
||||||
|
assert.match(res.body.openUrl, /^https:\/\/project\.webklar\.com\/api\/auth\/staff-switch\?token=[0-9a-f]{64}$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('staff-switch: gueltig -> Admin-Sitzung und /admin.html, zweites Mal -> Login', async () => {
|
||||||
|
const { body } = await switchLink('jwt-staff')
|
||||||
|
const path = `/api/auth/staff-switch?token=${tokenOf(body.openUrl)}`
|
||||||
|
const res = await rawGet(path)
|
||||||
|
assert.equal(res.status, 302)
|
||||||
|
assert.equal(res.headers.get('location'), '/admin.html')
|
||||||
|
const session = portalSession(res)
|
||||||
|
assert.equal(session.role, 'admin')
|
||||||
|
assert.equal(session.isAdmin, false)
|
||||||
|
assert.equal(session.appwriteUserId, 'u_staff2')
|
||||||
|
const again = await rawGet(path)
|
||||||
|
assert.equal(again.status, 302)
|
||||||
|
assert.equal(again.headers.get('location'), '/login.html?error=Link%20abgelaufen%2C%20bitte%20anmelden')
|
||||||
|
assert.equal(portalSession(again), null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('staff-switch: nach 61 Sekunden abgelaufen', async (t) => {
|
||||||
|
const { body } = await switchLink('jwt-staff')
|
||||||
|
const now = Date.now()
|
||||||
|
t.mock.method(Date, 'now', () => now + 61 * 1000)
|
||||||
|
const res = await rawGet(`/api/auth/staff-switch?token=${tokenOf(body.openUrl)}`)
|
||||||
|
assert.match(res.headers.get('location'), /^\/login\.html\?error=/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('Tokens nicht vertauschbar: Switch ueber staff-preview, Preview ueber staff-switch', async () => {
|
||||||
|
const { body } = await switchLink('jwt-staff')
|
||||||
|
assert.equal((await rawGet(`/api/auth/staff-preview?token=${tokenOf(body.openUrl)}`)).status, 410)
|
||||||
|
const previewToken = createStaffPreviewToken({ userId: 'u_admin', email: 'kenso@webklar.com', name: 'Kenso', previewUrl: 'https://x.project.webklar.com/' })
|
||||||
|
const res = await rawGet(`/api/auth/staff-switch?token=${previewToken}`)
|
||||||
|
assert.match(res.headers.get('location'), /^\/login\.html\?error=/)
|
||||||
|
assert.equal(portalSession(res), null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('admin.html: Rueckweg ins Ticketsystem in der Kopfzeile', () => {
|
||||||
|
const html = readFileSync(new URL('../public/admin.html', import.meta.url), 'utf8')
|
||||||
|
const actions = html.slice(html.indexOf('portal-header-actions'), html.indexOf('id="logout-btn"'))
|
||||||
|
assert.match(actions, /<a class="portal-btn-outline" href="https:\/\/ticket\.webklar\.com\/tickets">← Ticketsystem<\/a>/)
|
||||||
|
})
|
||||||
Reference in new issue
Block a user