Harden login, sessions, and media access before the dev deploy.
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 5m43s
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 5m43s
Limit brute-force attempts, require admin TOTP, and keep session tokens out of media URLs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6c7c24e887
commit
32b28a93f3
31 files changed
+1146
-101
No files matched your search
@@ -21,6 +21,7 @@ import AdminHomeRedirect from './components/AdminHomeRedirect'
|
||||
import PlatformAdminRoute from './components/PlatformAdminRoute'
|
||||
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
||||
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
|
||||
import TotpSetupCard from './components/TotpSetupCard'
|
||||
import './app.css'
|
||||
|
||||
const OnboardingPage = lazyWithRetry(() => import('./pages/OnboardingPage'))
|
||||
@@ -126,6 +127,29 @@ function Nav({ showAdminNav, onboardingOnly }) {
|
||||
)
|
||||
}
|
||||
|
||||
function TotpEnrollGate() {
|
||||
const { checkAuth, logout } = useAuth()
|
||||
return (
|
||||
<div className="page-padding" style={{ maxWidth: 520, margin: '2rem auto' }}>
|
||||
<h1 style={{ fontSize: '1.4rem' }}>Zwei-Faktor einrichten</h1>
|
||||
<p style={{ color: 'var(--text2)' }}>
|
||||
Plattform-Admins melden sich erst an, wenn ein Authenticator eingerichtet ist.
|
||||
</p>
|
||||
<TotpSetupCard onEnabled={() => checkAuth()} />
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={async () => {
|
||||
await logout()
|
||||
window.location.href = '/login'
|
||||
}}
|
||||
>
|
||||
Abmelden
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ProtectedLayout() {
|
||||
const { isAuthenticated, loading, user, logout } = useAuth()
|
||||
|
||||
@@ -155,6 +179,10 @@ function ProtectedLayout() {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
if (user?.totpEnrollmentRequired) {
|
||||
return <TotpEnrollGate />
|
||||
}
|
||||
|
||||
const location = useLocation()
|
||||
const onboardingOnly = isOnboardingRestricted(user)
|
||||
if (onboardingOnly && !isOnboardingAllowedPath(location.pathname)) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import ExerciseMediaEmbed from './ExerciseMediaEmbed'
|
||||
import ExerciseMediaThumbTile from './ExerciseMediaThumbTile'
|
||||
import MediaPreviewModal from './MediaPreviewModal'
|
||||
import ReportContentModal from './ReportContentModal'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { resolveExerciseMediaFileUrl, useMediaAccessToken } from '../utils/exerciseMediaUrl'
|
||||
import { collectInlineExerciseMediaIdsFromExercise } from '../utils/exerciseInlineMediaRefs'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
@@ -14,6 +14,7 @@ function isTrashHidden(m) {
|
||||
}
|
||||
|
||||
export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const [preview, setPreview] = useState(null)
|
||||
const [reportTarget, setReportTarget] = useState(null)
|
||||
const inlineIds = useMemo(() => collectInlineExerciseMediaIdsFromExercise(exercise), [exercise])
|
||||
@@ -66,7 +67,7 @@ export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
|
||||
<MediaPreviewModal
|
||||
title={(preview.title || '').trim() || preview.original_filename || `Medium #${preview.id}`}
|
||||
media={preview}
|
||||
fileUrl={preview.embed_url ? null : resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
fileUrl={preview.embed_url ? null : resolveExerciseMediaFileUrl(exerciseId, preview, mediaToken)}
|
||||
onClose={() => setPreview(null)}
|
||||
onReport={
|
||||
(preview.asset_lifecycle_state || 'active') === 'active' && !preview.asset_legal_hold_active
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback, useMemo } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { resolveMediaAssetFileUrl, useMediaAccessToken } from '../utils/exerciseMediaUrl'
|
||||
import {
|
||||
INLINE_MEDIA_SIZES,
|
||||
DEFAULT_INLINE_MEDIA_SIZE,
|
||||
@@ -12,8 +12,9 @@ import {
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
|
||||
function RtePickerAssetThumb({ asset }) {
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const id = asset.id
|
||||
const src = resolveMediaAssetFileUrl(id)
|
||||
const src = resolveMediaAssetFileUrl(id, mediaToken)
|
||||
const mt = (asset.mime_type || '').toLowerCase()
|
||||
if (mt.startsWith('image/') && src) {
|
||||
return <img alt="" src={src} className="rte-inline-asset-tile__thumb-img" />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { resolveExerciseMediaFileUrl, useMediaAccessToken } from '../utils/exerciseMediaUrl'
|
||||
import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'
|
||||
|
||||
/**
|
||||
@@ -7,6 +7,7 @@ import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'
|
||||
* @param {{ media: object, exerciseId: number, layoutSize?: string }} props
|
||||
*/
|
||||
export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'medium' }) {
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const sz = sanitizeInlineMediaSize(layoutSize)
|
||||
const box =
|
||||
sz === 'small'
|
||||
@@ -46,7 +47,7 @@ export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'me
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media, mediaToken)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
* Kachelvorschau: Video nutzt ersten Frame (metadata), Bild = img, Embed = Label.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { resolveExerciseMediaFileUrl, useMediaAccessToken } from '../utils/exerciseMediaUrl'
|
||||
|
||||
export default function ExerciseMediaThumbTile({ exerciseId, media, onOpenPreview, size = 72 }) {
|
||||
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media) : null
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media, mediaToken) : null
|
||||
const commonStyle = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
|
||||
/**
|
||||
* TOTP einrichten: Geheimnis anzeigen, Code bestätigen, Wiederherstellungscodes einmal zeigen.
|
||||
*/
|
||||
export default function TotpSetupCard({ onEnabled }) {
|
||||
const [secret, setSecret] = useState('')
|
||||
const [otpauthUri, setOtpauthUri] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [recoveryCodes, setRecoveryCodes] = useState([])
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const start = async () => {
|
||||
setError('')
|
||||
setBusy(true)
|
||||
try {
|
||||
const data = await api.setupTotp()
|
||||
setSecret(data.secret || '')
|
||||
setOtpauthUri(data.otpauth_uri || '')
|
||||
setRecoveryCodes([])
|
||||
} catch (err) {
|
||||
setError(err.message || 'Einrichtung fehlgeschlagen')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirm = async (e) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setBusy(true)
|
||||
try {
|
||||
const data = await api.confirmTotp(code.trim())
|
||||
if (data?.token) localStorage.setItem('authToken', data.token)
|
||||
setRecoveryCodes(Array.isArray(data?.recovery_codes) ? data.recovery_codes : [])
|
||||
setSecret('')
|
||||
setCode('')
|
||||
if (onEnabled) await onEnabled(data)
|
||||
} catch (err) {
|
||||
setError(err.message || 'Code nicht akzeptiert')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card" style={{ marginBottom: '1rem' }}>
|
||||
<h2 style={{ margin: '0 0 0.75rem', fontSize: '1.1rem' }}>Zwei-Faktor-Anmeldung</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', lineHeight: 1.5 }}>
|
||||
Authenticator-App (zum Beispiel Aegis, 1Password oder Microsoft Authenticator) öffnen und das
|
||||
Geheimnis manuell eintragen. Den otpauth-Link nicht an Dritte geben.
|
||||
</p>
|
||||
{error ? (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '0.875rem' }}>{error}</p>
|
||||
) : null}
|
||||
{!secret && recoveryCodes.length === 0 ? (
|
||||
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
|
||||
{busy ? 'Wird erzeugt…' : 'Geheimnis erzeugen'}
|
||||
</button>
|
||||
) : null}
|
||||
{secret ? (
|
||||
<form onSubmit={confirm}>
|
||||
<p style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: '0.04em' }}>{secret}</p>
|
||||
{otpauthUri ? (
|
||||
<p style={{ fontSize: '0.75rem', wordBreak: 'break-all', color: 'var(--text3)' }}>{otpauthUri}</p>
|
||||
) : null}
|
||||
<label className="form-label" htmlFor="totp-confirm-code">
|
||||
Code aus der App
|
||||
</label>
|
||||
<input
|
||||
id="totp-confirm-code"
|
||||
className="form-input"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={busy} style={{ marginTop: '0.75rem' }}>
|
||||
{busy ? 'Prüft…' : 'Aktivieren'}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{recoveryCodes.length > 0 ? (
|
||||
<div>
|
||||
<p style={{ fontSize: '0.875rem' }}>
|
||||
Diese Wiederherstellungscodes jetzt sichern. Sie werden nur dieses eine Mal angezeigt.
|
||||
</p>
|
||||
<ul>
|
||||
{recoveryCodes.map((item) => (
|
||||
<li key={item} style={{ fontFamily: 'ui-monospace, monospace' }}>
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useRef, useMemo, useCallback } from 'react'
|
||||
import { useNavigate, useParams, Link, useLocation } from 'react-router-dom'
|
||||
import api, { buildExerciseApiPayload } from '../../utils/api'
|
||||
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl } from '../../utils/exerciseMediaUrl'
|
||||
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl, useMediaAccessToken } from '../../utils/exerciseMediaUrl'
|
||||
import RichTextEditor from '../RichTextEditor'
|
||||
import ExerciseProgressionGraphPanel from '../ExerciseProgressionGraphPanel'
|
||||
import ExerciseMediaThumbTile from '../ExerciseMediaThumbTile'
|
||||
@@ -573,6 +573,7 @@ function detailToForm(exercise) {
|
||||
}
|
||||
|
||||
function ExerciseFormPageRoot() {
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const { id: routeId } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
@@ -2832,7 +2833,7 @@ function ExerciseFormPageRoot() {
|
||||
{a.mime_type?.startsWith('image/') ? (
|
||||
<img
|
||||
alt=""
|
||||
src={resolveMediaAssetFileUrl(a.id)}
|
||||
src={resolveMediaAssetFileUrl(a.id, mediaToken)}
|
||||
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
|
||||
/>
|
||||
) : a.mime_type?.startsWith('video/') ? (
|
||||
@@ -2880,7 +2881,7 @@ function ExerciseFormPageRoot() {
|
||||
<MediaPreviewModal
|
||||
title={(mediaPreview.title || '').trim() || mediaPreview.original_filename || `Medium #${mediaPreview.id}`}
|
||||
media={mediaPreview}
|
||||
fileUrl={mediaPreview.embed_url ? null : resolveExerciseMediaFileUrl(exerciseId, mediaPreview)}
|
||||
fileUrl={mediaPreview.embed_url ? null : resolveExerciseMediaFileUrl(exerciseId, mediaPreview, mediaToken)}
|
||||
onClose={() => setMediaPreview(null)}
|
||||
onReport={
|
||||
!mediaPreview.asset_legal_hold_active
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import api, { ACTIVE_CLUB_STORAGE_KEY } from '../utils/api'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
import { clearCoachSessionStorage } from '../utils/trainingPlanUtils'
|
||||
import { clearMediaGrant, refreshMediaGrant } from '../utils/exerciseMediaUrl'
|
||||
|
||||
const AuthContext = createContext(null)
|
||||
|
||||
@@ -63,9 +64,25 @@ export function AuthProvider({ children }) {
|
||||
const profile = await api.getCurrentProfile()
|
||||
syncStoredActiveClub(profile)
|
||||
setUser(profile)
|
||||
refreshMediaGrant().catch(() => {})
|
||||
} catch (err) {
|
||||
try {
|
||||
const status = await api.getTotpStatus()
|
||||
if (status?.enrollment_required && !status?.totp_enabled) {
|
||||
setUser({
|
||||
totpEnrollmentRequired: true,
|
||||
email: status.email || null,
|
||||
role: status.role || null,
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* kein Einrichtungs-Token */
|
||||
}
|
||||
console.error('Auth check failed:', err)
|
||||
localStorage.removeItem('authToken')
|
||||
clearMediaGrant()
|
||||
setUser(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -132,6 +149,7 @@ export function AuthProvider({ children }) {
|
||||
setUser(null)
|
||||
localStorage.removeItem('authToken')
|
||||
localStorage.removeItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
clearMediaGrant()
|
||||
clearCoachSessionStorage()
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
resolvePlanningModuleDisplayMode,
|
||||
} from '../config/planningModuleUx'
|
||||
import api from '../utils/api'
|
||||
import TotpSetupCard from '../components/TotpSetupCard'
|
||||
|
||||
/**
|
||||
* Persönliche Einstellungen (Anzeige/Name, Kontostatus, Passwort).
|
||||
@@ -27,6 +28,10 @@ function AccountSettingsPage() {
|
||||
PLANNING_MODULE_DISPLAY_MODES.COMPACT_TAG_LEGEND
|
||||
)
|
||||
|
||||
const [currentPw, setCurrentPw] = useState('')
|
||||
const [disablePw, setDisablePw] = useState('')
|
||||
const [disableCode, setDisableCode] = useState('')
|
||||
const [disablingTotp, setDisablingTotp] = useState(false)
|
||||
const [newPw1, setNewPw1] = useState('')
|
||||
const [newPw2, setNewPw2] = useState('')
|
||||
const [savingPw, setSavingPw] = useState(false)
|
||||
@@ -144,8 +149,8 @@ function AccountSettingsPage() {
|
||||
|
||||
const handleChangePassword = async (e) => {
|
||||
e.preventDefault()
|
||||
if (newPw1.length < 4) {
|
||||
showErr('Neues Passwort: mindestens 4 Zeichen.')
|
||||
if (newPw1.length < 8) {
|
||||
showErr('Neues Passwort: mindestens 8 Zeichen.')
|
||||
return
|
||||
}
|
||||
if (newPw1 !== newPw2) {
|
||||
@@ -154,10 +159,12 @@ function AccountSettingsPage() {
|
||||
}
|
||||
setSavingPw(true)
|
||||
try {
|
||||
await api.changePassword(newPw1)
|
||||
const result = await api.changePassword(currentPw, newPw1)
|
||||
if (result?.token) localStorage.setItem('authToken', result.token)
|
||||
setCurrentPw('')
|
||||
setNewPw1('')
|
||||
setNewPw2('')
|
||||
showOk('Passwort aktualisiert.')
|
||||
showOk('Passwort aktualisiert. Andere Geräte sind abgemeldet.')
|
||||
} catch (err) {
|
||||
showErr(err.message || 'Passwort konnte nicht geändert werden.')
|
||||
} finally {
|
||||
@@ -461,12 +468,72 @@ function AccountSettingsPage() {
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{user?.totp_enabled ? (
|
||||
<div className="card" style={{ marginBottom: '1rem' }}>
|
||||
<h2 style={{ margin: '0 0 0.75rem', fontSize: '1.1rem' }}>Zwei-Faktor ist aktiv</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem' }}>
|
||||
Beim Anmelden wird zusätzlich der Code aus der Authenticator-App verlangt.
|
||||
</p>
|
||||
{user?.role === 'admin' || user?.role === 'superadmin' ? (
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem' }}>
|
||||
Für Plattform-Admins bleibt das so.
|
||||
</p>
|
||||
) : (
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault()
|
||||
setDisablingTotp(true)
|
||||
try {
|
||||
await api.disableTotp(disablePw, disableCode.trim())
|
||||
setDisablePw('')
|
||||
setDisableCode('')
|
||||
showOk('Zwei-Faktor ist aus.')
|
||||
await checkAuth()
|
||||
} catch (err) {
|
||||
showErr(err.message || 'Abschalten fehlgeschlagen')
|
||||
} finally {
|
||||
setDisablingTotp(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="form-row" style={{ marginBottom: '0.75rem' }}>
|
||||
<label className="form-label" htmlFor="totp-off-pw">Aktuelles Passwort</label>
|
||||
<input id="totp-off-pw" type="password" className="form-input" value={disablePw} onChange={(e) => setDisablePw(e.target.value)} autoComplete="current-password" />
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: '0.75rem' }}>
|
||||
<label className="form-label" htmlFor="totp-off-code">Code oder Wiederherstellungscode</label>
|
||||
<input id="totp-off-code" className="form-input" value={disableCode} onChange={(e) => setDisableCode(e.target.value)} autoComplete="one-time-code" />
|
||||
</div>
|
||||
<button type="submit" className="btn btn-secondary" disabled={disablingTotp}>
|
||||
{disablingTotp ? 'Wird gespeichert…' : 'Zwei-Faktor ausschalten'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<TotpSetupCard onEnabled={() => checkAuth()} />
|
||||
)}
|
||||
|
||||
<div className="card">
|
||||
<h2 style={{ margin: '0 0 0.75rem', fontSize: '1.1rem' }}>Passwort ändern</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', marginBottom: '1rem', lineHeight: 1.5 }}>
|
||||
Wähle ein neues Passwort (mindestens 4 Zeichen, wie beim Login gewohnt empfehlen wir längere Passwörter).
|
||||
Das aktuelle Passwort wird geprüft. Danach sind andere Sitzungen ungültig. Mindestens 8 Zeichen.
|
||||
</p>
|
||||
<form onSubmit={handleChangePassword}>
|
||||
<div className="form-row" style={{ marginBottom: '0.75rem' }}>
|
||||
<label className="form-label" htmlFor="settings-pw-current">
|
||||
Aktuelles Passwort
|
||||
</label>
|
||||
<input
|
||||
id="settings-pw-current"
|
||||
type="password"
|
||||
className="form-input"
|
||||
value={currentPw}
|
||||
onChange={(e) => setCurrentPw(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: '0.75rem' }}>
|
||||
<label className="form-label" htmlFor="settings-pw1">
|
||||
Neues Passwort
|
||||
|
||||
@@ -15,6 +15,8 @@ function LoginPage() {
|
||||
const [publicClubs, setPublicClubs] = useState([])
|
||||
const [requestedClubId, setRequestedClubId] = useState('')
|
||||
const [resending, setResending] = useState(false)
|
||||
const [challengeToken, setChallengeToken] = useState('')
|
||||
const [totpCode, setTotpCode] = useState('')
|
||||
|
||||
const navigate = useNavigate()
|
||||
const { checkAuth } = useAuth()
|
||||
@@ -39,6 +41,17 @@ function LoginPage() {
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
const response = await api.login(email, password)
|
||||
if (response?.totp_required && response.challenge_token) {
|
||||
setChallengeToken(response.challenge_token)
|
||||
setTotpCode('')
|
||||
return
|
||||
}
|
||||
if (response?.totp_enrollment_required && response.token) {
|
||||
localStorage.setItem('authToken', response.token)
|
||||
await checkAuth()
|
||||
navigate('/')
|
||||
return
|
||||
}
|
||||
localStorage.setItem('authToken', response.token)
|
||||
await checkAuth()
|
||||
navigate('/')
|
||||
@@ -60,6 +73,23 @@ function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleTotp = async (e) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const response = await api.loginTotp(challengeToken, totpCode.trim())
|
||||
localStorage.setItem('authToken', response.token)
|
||||
setChallengeToken('')
|
||||
await checkAuth()
|
||||
navigate('/')
|
||||
} catch (err) {
|
||||
setError(err.message || 'Code nicht akzeptiert')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleResendVerification = async () => {
|
||||
if (!email.trim()) {
|
||||
setError('Zuerst die E-Mail-Adresse eintragen.')
|
||||
@@ -122,6 +152,49 @@ function LoginPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{challengeToken ? (
|
||||
<form onSubmit={handleTotp}>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem', lineHeight: 1.45 }}>
|
||||
Code aus der Authenticator-App oder ein Wiederherstellungscode.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="login-totp">
|
||||
Einmalcode
|
||||
</label>
|
||||
<input
|
||||
id="login-totp"
|
||||
className="form-input"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<div style={{ padding: '0.75rem', background: 'var(--danger)', color: 'white', borderRadius: '8px', marginBottom: '1rem' }}>
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn-primary btn-full" disabled={loading}>
|
||||
{loading ? 'Laden...' : 'Bestätigen'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-full"
|
||||
style={{ marginTop: '0.5rem' }}
|
||||
onClick={() => {
|
||||
setChallengeToken('')
|
||||
setTotpCode('')
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
Zurück
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{!challengeToken ? (
|
||||
<form onSubmit={handleSubmit}>
|
||||
{mode === 'register' && (
|
||||
<>
|
||||
@@ -215,8 +288,9 @@ function LoginPage() {
|
||||
{loading ? 'Laden...' : mode === 'login' ? 'Anmelden' : 'Registrieren'}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{mode === 'login' && (
|
||||
{mode === 'login' && !challengeToken && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '1.25rem',
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import { activeClubMemberships, getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { resolveMediaAssetFileUrl, useMediaAccessToken } from '../utils/exerciseMediaUrl'
|
||||
import RightsDeclarationDialog from '../components/RightsDeclarationDialog'
|
||||
import ReportContentModal from '../components/ReportContentModal'
|
||||
import MediaPreviewModal from '../components/MediaPreviewModal'
|
||||
@@ -159,7 +159,8 @@ function uploaderLabel(it, viewer) {
|
||||
}
|
||||
|
||||
function MediaThumb({ mediaId, mimeType }) {
|
||||
const url = resolveMediaAssetFileUrl(mediaId)
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const url = resolveMediaAssetFileUrl(mediaId, mediaToken)
|
||||
const mime = (mimeType || '').toLowerCase()
|
||||
/* iPhone-Fotos: Browser-Vorschau oft nicht nutzbar */
|
||||
if (mime.includes('heic') || mime.includes('heif')) {
|
||||
@@ -296,6 +297,7 @@ function JournalBoolField({ label, val, context }) {
|
||||
}
|
||||
|
||||
export default function MediaLibraryPage() {
|
||||
const mediaToken = useMediaAccessToken()
|
||||
const { user } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
@@ -1122,7 +1124,7 @@ export default function MediaLibraryPage() {
|
||||
<MediaPreviewModal
|
||||
title={preview.original_filename || `Medium #${preview.id}`}
|
||||
media={{ ...preview, asset_legal_hold_active: preview.legal_hold_active }}
|
||||
fileUrl={resolveMediaAssetFileUrl(preview.id)}
|
||||
fileUrl={resolveMediaAssetFileUrl(preview.id, mediaToken)}
|
||||
onClose={() => setPreview(null)}
|
||||
onReport={
|
||||
(preview.lifecycle_state || 'active') === 'active' && !preview.legal_hold_active
|
||||
|
||||
@@ -25,6 +25,39 @@ export async function login(email, password) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function loginTotp(challengeToken, code) {
|
||||
return request('/api/auth/login/totp', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ challenge_token: challengeToken, code }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getTotpStatus() {
|
||||
return request('/api/auth/totp/status')
|
||||
}
|
||||
|
||||
export async function setupTotp() {
|
||||
return request('/api/auth/totp/setup', { method: 'POST', body: '{}' })
|
||||
}
|
||||
|
||||
export async function confirmTotp(code) {
|
||||
return request('/api/auth/totp/confirm', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function disableTotp(currentPassword, code) {
|
||||
return request('/api/auth/totp/disable', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ current_password: currentPassword, code }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function issueMediaGrant() {
|
||||
return request('/api/auth/media-grant', { method: 'POST', body: '{}' })
|
||||
}
|
||||
|
||||
export async function register(email, password, name, extra = {}) {
|
||||
return request('/api/auth/register', {
|
||||
method: 'POST',
|
||||
@@ -126,10 +159,13 @@ export async function managementPasswordReset(profileId, newPassword = null) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function changePassword(newPassword) {
|
||||
export async function changePassword(currentPassword, newPassword) {
|
||||
return request('/api/auth/pin', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ pin: newPassword }),
|
||||
body: JSON.stringify({
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -992,6 +1028,12 @@ export async function healthCheck() {
|
||||
export const api = {
|
||||
// Auth
|
||||
login,
|
||||
loginTotp,
|
||||
getTotpStatus,
|
||||
setupTotp,
|
||||
confirmTotp,
|
||||
disableTotp,
|
||||
issueMediaGrant,
|
||||
register,
|
||||
logout,
|
||||
getCurrentProfile,
|
||||
|
||||
@@ -1,31 +1,77 @@
|
||||
/** URL für Übungs-Mediendateien: API mit Token (Legacy /media/ ohne Auth ist abgeschaltet). */
|
||||
/** URL für Übungs-Mediendateien. Query-Token ist ein kurzlebiges Medien-Grant, kein Sitzungstoken. */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import api from './api'
|
||||
|
||||
const API_BASE = (import.meta.env.VITE_API_URL || '').replace(/\/$/, '')
|
||||
|
||||
let grant = { token: '', expiresAt: 0 }
|
||||
const listeners = new Set()
|
||||
|
||||
function notify() {
|
||||
listeners.forEach((fn) => fn())
|
||||
}
|
||||
|
||||
export function peekMediaAccessToken() {
|
||||
if (grant.expiresAt > Date.now() + 15_000) return grant.token
|
||||
return ''
|
||||
}
|
||||
|
||||
export function clearMediaGrant() {
|
||||
grant = { token: '', expiresAt: 0 }
|
||||
notify()
|
||||
}
|
||||
|
||||
export async function refreshMediaGrant() {
|
||||
const data = await api.issueMediaGrant()
|
||||
const expiresAt = data?.expires_at ? new Date(data.expires_at).getTime() : Date.now() + 9 * 60 * 1000
|
||||
grant = { token: data?.token || '', expiresAt }
|
||||
notify()
|
||||
return grant.token
|
||||
}
|
||||
|
||||
export function useMediaAccessToken() {
|
||||
const [token, setToken] = useState(peekMediaAccessToken)
|
||||
useEffect(() => {
|
||||
const pull = () => setToken(peekMediaAccessToken())
|
||||
listeners.add(pull)
|
||||
pull()
|
||||
if (!peekMediaAccessToken()) {
|
||||
refreshMediaGrant().catch(() => {})
|
||||
}
|
||||
return () => listeners.delete(pull)
|
||||
}, [])
|
||||
return token
|
||||
}
|
||||
|
||||
function withGrant(path, accessToken) {
|
||||
const token = accessToken || peekMediaAccessToken()
|
||||
const q = token ? `?ssetoken=${encodeURIComponent(token)}` : ''
|
||||
return `${API_BASE}${path}${q}`
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number|string} exerciseId
|
||||
* @param {object} media — exercise_media Zeile mit id, file_path
|
||||
* @param {string} [accessToken]
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveExerciseMediaFileUrl(exerciseId, media) {
|
||||
export function resolveExerciseMediaFileUrl(exerciseId, media, accessToken) {
|
||||
if (!media?.file_path) return null
|
||||
const fp = String(media.file_path)
|
||||
if (fp.startsWith('http://') || fp.startsWith('https://')) return fp
|
||||
const token = typeof localStorage !== 'undefined' ? localStorage.getItem('authToken') : ''
|
||||
const q = token ? `?ssetoken=${encodeURIComponent(token)}` : ''
|
||||
const id = media.id
|
||||
if (id == null || exerciseId == null) return null
|
||||
return `${API_BASE}/api/exercises/${exerciseId}/media/${id}/file${q}`
|
||||
return withGrant(`/api/exercises/${exerciseId}/media/${id}/file`, accessToken)
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt-URL für Archiv-Asset (Picker/Vorschau ohne exercise_media-Zeile).
|
||||
* @param {number|string} assetId — media_assets.id
|
||||
* @param {string} [accessToken]
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveMediaAssetFileUrl(assetId) {
|
||||
export function resolveMediaAssetFileUrl(assetId, accessToken) {
|
||||
if (assetId == null) return null
|
||||
const token = typeof localStorage !== 'undefined' ? localStorage.getItem('authToken') : ''
|
||||
const q = token ? `?ssetoken=${encodeURIComponent(token)}` : ''
|
||||
return `${API_BASE}/api/media-assets/${assetId}/file${q}`
|
||||
return withGrant(`/api/media-assets/${assetId}/file`, accessToken)
|
||||
}
|
||||
Reference in new issue
Block a user