7 Commits

Author SHA1 Message Date
f1fc5eafc3 Merge pull request 'dev' (#47) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 3m57s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #47
2026-08-12 15:25:19 +02:00
Torsten Schulz (local)
7aadb5e215 Version increase
All checks were successful
Code Analysis and Production Deploy / analyze (push) Successful in 9m54s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Successful in 3m23s
2026-08-12 14:16:28 +02:00
Torsten Schulz (local)
76d7000735 optimized design
All checks were successful
Code Analysis and Production Deploy / analyze (push) Successful in 10m8s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Successful in 3m18s
2026-08-12 13:15:14 +02:00
Torsten Schulz (local)
51e59e85ef packages updated
All checks were successful
Code Analysis and Production Deploy / analyze (push) Successful in 10m32s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Successful in 3m50s
2026-08-12 12:22:22 +02:00
Torsten Schulz (local)
0475e3084d lint fehler behoben
Some checks failed
Code Analysis and Production Deploy / analyze (push) Failing after 10m21s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
2026-08-12 12:03:29 +02:00
Torsten Schulz (local)
9889430109 Overwork of design
Some checks failed
Code Analysis and Production Deploy / analyze (push) Failing after 6m5s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
2026-08-12 11:31:22 +02:00
Torsten Schulz (local)
cb89fdd911 Member registration fixed
Some checks failed
Code Analysis and Production Deploy / analyze (push) Failing after 6m17s
Code Analysis and Production Deploy / deploy-production (push) Has been skipped
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
2026-08-12 11:15:07 +02:00
26 changed files with 2828 additions and 791 deletions

View File

@@ -78,12 +78,12 @@ val ensureProductionApiBaseUrl = tasks.register("ensureProductionApiBaseUrl") {
android { android {
namespace = "de.harheimertc" namespace = "de.harheimertc"
compileSdk = 35 compileSdk = 36
defaultConfig { defaultConfig {
applicationId = "de.harheimertc" applicationId = "de.harheimertc"
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 36
versionCode = androidVersionCode versionCode = androidVersionCode
versionName = androidVersionName versionName = androidVersionName
} }

Binary file not shown.

View File

@@ -166,6 +166,7 @@ data class MembershipResponse(
val success: Boolean = false, val success: Boolean = false,
val message: String? = null, val message: String? = null,
val downloadUrl: String? = null, val downloadUrl: String? = null,
val downloadToken: String? = null,
) )
data class LoginRequest( data class LoginRequest(
val email: String, val email: String,
@@ -660,7 +661,10 @@ interface ApiService {
@Streaming @Streaming
@GET @GET
suspend fun downloadMembershipPdf(@Url downloadUrl: String): Response<ResponseBody> suspend fun downloadMembershipPdf(
@Url downloadUrl: String,
@retrofit2.http.Header("X-Membership-Download-Token") downloadToken: String? = null,
): Response<ResponseBody>
@POST("/api/auth/login") @POST("/api/auth/login")
suspend fun login(@Body request: LoginRequest): Response<LoginResponse> suspend fun login(@Body request: LoginRequest): Response<LoginResponse>

View File

@@ -16,14 +16,16 @@ import de.harheimertc.R
import de.harheimertc.ui.navigation.Destinations import de.harheimertc.ui.navigation.Destinations
object HarheimerNotifications { object HarheimerNotifications {
const val DEFAULT_CHANNEL_ID = "harheimer_tc_updates" // A new ID is intentional: Android does not allow an app update to raise
// the importance of an already-created notification channel.
const val DEFAULT_CHANNEL_ID = "harheimer_tc_updates_v2"
fun createChannels(context: Context) { fun createChannels(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel( val channel = NotificationChannel(
DEFAULT_CHANNEL_ID, DEFAULT_CHANNEL_ID,
"Harheimer TC", "Harheimer TC",
NotificationManager.IMPORTANCE_DEFAULT, NotificationManager.IMPORTANCE_HIGH,
).apply { ).apply {
description = "Benachrichtigungen des Harheimer TC" description = "Benachrichtigungen des Harheimer TC"
} }
@@ -47,7 +49,7 @@ object HarheimerNotifications {
.setContentTitle(title) .setContentTitle(title)
.setContentText(message) .setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message)) .setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(createContentIntent(context, notificationId, data)) .setContentIntent(createContentIntent(context, notificationId, data))
.setAutoCancel(true) .setAutoCancel(true)
.build() .build()

View File

@@ -9,7 +9,7 @@ import java.io.File
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
data class MembershipDocument(val message: String, val uri: String) data class MembershipDocument(val message: String, val uri: String? = null)
@Singleton @Singleton
class MembershipRepository @Inject constructor( class MembershipRepository @Inject constructor(
@@ -18,21 +18,33 @@ class MembershipRepository @Inject constructor(
) { ) {
suspend fun submit(request: MembershipRequest): Result<MembershipDocument> = runCatching { suspend fun submit(request: MembershipRequest): Result<MembershipDocument> = runCatching {
val response = api.generateMembershipPdf(request) val response = api.generateMembershipPdf(request)
if (!response.isSuccessful) error("HTTP ${response.code()}") if (!response.isSuccessful) {
val serverMessage = response.errorBody()?.string()
?.let { Regex("\\\"(?:statusMessage|message)\\\"\\s*:\\s*\\\"([^\\\"]+)\\\"").find(it)?.groupValues?.getOrNull(1) ?: it }
?.takeIf { it.isNotBlank() }
error(serverMessage ?: "Der Antrag konnte nicht übermittelt werden (HTTP ${response.code()}).")
}
val body = response.body() ?: error("Leere Antwort") val body = response.body() ?: error("Leere Antwort")
if (!body.success) error(body.message ?: "Antrag konnte nicht erstellt werden.") if (!body.success) error(body.message ?: "Antrag konnte nicht erstellt werden.")
val downloadUrl = body.downloadUrl ?: error("PDF-Download fehlt.") val uri = body.downloadUrl?.let { downloadUrl ->
val documentResponse = api.downloadMembershipPdf(downloadUrl) runCatching {
if (!documentResponse.isSuccessful) error("PDF konnte nicht heruntergeladen werden.") val documentResponse = api.downloadMembershipPdf(downloadUrl, body.downloadToken)
val directory = File(context.cacheDir, "membership").apply { mkdirs() } if (!documentResponse.isSuccessful) error("PDF konnte nicht heruntergeladen werden.")
val file = File(directory, "beitrittserklaerung.pdf") val directory = File(context.cacheDir, "membership").apply { mkdirs() }
documentResponse.body()?.byteStream()?.use { input -> val file = File(directory, "beitrittserklaerung.pdf")
file.outputStream().use { output -> input.copyTo(output) } documentResponse.body()?.byteStream()?.use { input ->
} ?: error("Leere PDF-Antwort") file.outputStream().use { output -> input.copyTo(output) }
val uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file) } ?: error("Leere PDF-Antwort")
FileProvider.getUriForFile(context, "${context.packageName}.files", file).toString()
}.getOrNull()
}
MembershipDocument( MembershipDocument(
message = body.message ?: "Beitrittsformular erfolgreich erstellt.", message = if (uri == null) {
uri = uri.toString(), "${body.message ?: "Mitgliedschaftsantrag erfolgreich übermittelt."} Das PDF konnte nicht auf diesem Gerät gespeichert werden."
} else {
body.message ?: "Beitrittsformular erfolgreich erstellt."
},
uri = uri,
) )
} }
} }

View File

@@ -81,7 +81,10 @@ class MembershipViewModel @Inject constructor(private val repository: Membership
_state.value = _state.value.copy(sending = false, fieldErrors = emptyMap(), message = document.message, pdfUri = document.uri) _state.value = _state.value.copy(sending = false, fieldErrors = emptyMap(), message = document.message, pdfUri = document.uri)
} }
.onFailure { .onFailure {
_state.value = _state.value.copy(sending = false, error = "Beitrittsformular konnte nicht erstellt werden.") _state.value = _state.value.copy(
sending = false,
error = it.message ?: "Beitrittsformular konnte nicht erstellt werden.",
)
} }
} }
} }

View File

@@ -8,8 +8,8 @@ LOCAL_API_BASE_URL=https://harheimertc.tsschulz.de/
PRODUCTION_API_BASE_URL=https://harheimertc.de/ PRODUCTION_API_BASE_URL=https://harheimertc.de/
# Android app versioning for Play Store uploads # Android app versioning for Play Store uploads
ANDROID_VERSION_CODE=29 ANDROID_VERSION_CODE=32
ANDROID_VERSION_NAME=0.9.24 ANDROID_VERSION_NAME=0.9.27
# Temporary hotfix: disable R8 minification for release to avoid Retrofit generic signature stripping. # Temporary hotfix: disable R8 minification for release to avoid Retrofit generic signature stripping.
RELEASE_MINIFY_ENABLED=false RELEASE_MINIFY_ENABLED=false

View File

@@ -1,7 +1,7 @@
<template> <template>
<div class="h-screen flex flex-col overflow-hidden"> <div class="h-screen flex flex-col overflow-hidden">
<Navigation /> <Navigation />
<main class="flex-1 overflow-y-auto pt-20"> <main class="flex-1 overflow-y-auto pt-20 pb-20 sm:pb-0">
<NuxtPage /> <NuxtPage />
</main> </main>
<Footer /> <Footer />

View File

@@ -1,11 +1,11 @@
<template> <template>
<footer class="fixed bottom-0 left-0 right-0 z-40 bg-gray-900 border-t border-gray-800 shadow-2xl"> <footer class="fixed bottom-0 left-0 right-0 z-40 bg-gray-900 border-t border-gray-800 shadow-2xl">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3"> <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-2 sm:py-3">
<div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0"> <div class="flex flex-col sm:flex-row justify-between items-center gap-y-1 sm:gap-y-0">
<p class="text-sm text-gray-400"> <p class="text-xs sm:text-sm text-gray-400 whitespace-nowrap">
© {{ currentYear }} Harheimer TC 1954 e.V. © {{ currentYear }} Harheimer TC 1954 e.V.
</p> </p>
<div class="flex items-center space-x-6 text-sm relative"> <div class="flex flex-wrap justify-center items-center gap-x-4 gap-y-1 text-xs sm:text-sm relative">
<span <span
v-if="isLoggedIn && appVersion" v-if="isLoggedIn && appVersion"
class="text-xs text-gray-600" class="text-xs text-gray-600"

View File

@@ -29,9 +29,9 @@
</div> </div>
<!-- Content --> <!-- Content -->
<div class="relative z-20 max-w-7xl mx-auto"> <div class="relative z-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center"> <div class="text-center">
<h1 class="text-5xl sm:text-6xl lg:text-7xl font-display font-bold text-gray-900 mb-6 leading-tight animate-fade-in"> <h1 class="text-4xl sm:text-6xl lg:text-7xl font-display font-bold text-gray-900 mb-6 leading-tight animate-fade-in">
Willkommen beim<br> Willkommen beim<br>
<span class="text-primary-600">Harheimer TC</span> <span class="text-primary-600">Harheimer TC</span>
</h1> </h1>
@@ -163,4 +163,3 @@ const yearsSinceFounding = new Date().getFullYear() - foundingYear
animation: fadeIn 0.8s ease-out 0.4s both; animation: fadeIn 0.8s ease-out 0.4s both;
} }
</style> </style>

View File

@@ -1,7 +1,7 @@
<template> <template>
<section class="py-16 sm:py-20 bg-gray-50"> <section class="py-8 sm:py-10 bg-gray-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center mb-12"> <div class="text-center mb-6 sm:mb-8">
<h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4"> <h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4">
Kommende Termine Kommende Termine
</h2> </h2>
@@ -12,7 +12,7 @@
<TermineVorschau /> <TermineVorschau />
</div> </div>
<div class="text-center mt-8"> <div class="text-center mt-5 sm:mt-6">
<NuxtLink <NuxtLink
to="/termine" to="/termine"
class="inline-flex items-center px-6 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors" class="inline-flex items-center px-6 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
@@ -32,4 +32,3 @@
import { ArrowRight } from 'lucide-vue-next' import { ArrowRight } from 'lucide-vue-next'
import TermineVorschau from './TermineVorschau.vue' import TermineVorschau from './TermineVorschau.vue'
</script> </script>

View File

@@ -1,9 +1,13 @@
<template> <template>
<section <section
class="py-16 sm:py-20 bg-white min-h-[32rem]" class="bg-white"
:class="news.length === 0 && !isLoading ? 'py-8 sm:py-10' : 'py-10 sm:py-12'"
> >
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center mb-16"> <div
class="text-center"
:class="news.length === 0 && !isLoading ? 'mb-6 sm:mb-8' : 'mb-8 sm:mb-10'"
>
<h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4"> <h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4">
Aktuelles Aktuelles
</h2> </h2>
@@ -67,7 +71,7 @@
<div <div
v-else v-else
class="max-w-xl mx-auto text-center bg-gray-50 border border-gray-200 rounded-xl p-8" class="max-w-xl mx-auto text-center bg-gray-50 border border-gray-200 rounded-xl p-5"
> >
<p class="text-gray-700 font-semibold mb-2"> <p class="text-gray-700 font-semibold mb-2">
Aktuell keine News Aktuell keine News
@@ -222,4 +226,3 @@ onUnmounted(() => {
opacity: 0; opacity: 0;
} }
</style> </style>

View File

@@ -1,7 +1,7 @@
<template> <template>
<section class="py-16 bg-white"> <section class="py-8 sm:py-10 bg-white">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center mb-12"> <div class="text-center mb-6 sm:mb-8">
<h2 class="text-3xl font-bold text-gray-900 mb-4"> <h2 class="text-3xl font-bold text-gray-900 mb-4">
Nächste Spiele Nächste Spiele
</h2> </h2>
@@ -10,7 +10,7 @@
<!-- Loading State --> <!-- Loading State -->
<div <div
v-if="isLoading" v-if="isLoading"
class="text-center py-8" class="text-center py-4"
> >
<svg <svg
class="w-8 h-8 text-gray-400 mx-auto mb-4 animate-spin" class="w-8 h-8 text-gray-400 mx-auto mb-4 animate-spin"
@@ -33,7 +33,7 @@
<!-- Error State --> <!-- Error State -->
<div <div
v-else-if="error" v-else-if="error"
class="text-center py-8" class="text-center py-4"
> >
<svg <svg
class="w-12 h-12 text-gray-400 mx-auto mb-4" class="w-12 h-12 text-gray-400 mx-auto mb-4"
@@ -62,7 +62,7 @@
<!-- Empty State --> <!-- Empty State -->
<div <div
v-else-if="!upcomingGames || upcomingGames.length === 0" v-else-if="!upcomingGames || upcomingGames.length === 0"
class="text-center py-8" class="text-center py-4"
> >
<svg <svg
class="w-12 h-12 text-gray-400 mx-auto mb-4" class="w-12 h-12 text-gray-400 mx-auto mb-4"

View File

@@ -45,7 +45,7 @@
<div <div
v-else v-else
class="text-center py-8 bg-gray-50 rounded-lg" class="text-center py-4 bg-gray-50 rounded-lg"
> >
<Calendar <Calendar
:size="32" :size="32"
@@ -123,4 +123,3 @@ onMounted(() => {
loadTermine() loadTermine()
}) })
</script> </script>

View File

@@ -219,7 +219,10 @@
> >
<span class="text-sm text-gray-800">{{ team.label }}</span> <span class="text-sm text-gray-800">{{ team.label }}</span>
</label> </label>
<p v-if="!spielplanTeams.length" class="px-4 py-3 text-sm text-gray-500"> <p
v-if="!spielplanTeams.length"
class="px-4 py-3 text-sm text-gray-500"
>
Noch keine importierten Spielplan-Teams verfügbar. Noch keine importierten Spielplan-Teams verfügbar.
</p> </p>
</div> </div>

3243
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "harheimertc-website", "name": "harheimertc-website",
"version": "1.8.4", "version": "1.8.5",
"description": "Moderne Webseite für den Harheimer Tischtennis Club", "description": "Moderne Webseite für den Harheimer Tischtennis Club",
"private": true, "private": true,
"type": "module", "type": "module",
@@ -40,12 +40,12 @@
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^2.0.2", "multer": "^2.0.2",
"nodemailer": "^9.0.1", "nodemailer": "^9.0.1",
"nuxt": "^4.1.3", "nuxt": "^4.5.1",
"pdf-lib": "^1.17.1", "pdf-lib": "^1.17.1",
"pdf-parse": "^2.4.5", "pdf-parse": "^2.4.5",
"pinia": "^3.0.3", "pinia": "^3.0.3",
"quill": "^2.0.2", "quill": "2.0.2",
"sharp": "^0.34.5", "sharp": "^0.35.3",
"vue": "^3.5.22" "vue": "^3.5.22"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -216,7 +216,7 @@
class="relative z-30 px-4 sm:px-6 lg:px-8" class="relative z-30 px-4 sm:px-6 lg:px-8"
:class="hasHeroSection ? '-mt-44 sm:-mt-48 lg:-mt-52' : 'mt-8'" :class="hasHeroSection ? '-mt-44 sm:-mt-48 lg:-mt-52' : 'mt-8'"
> >
<div class="featured-widget-shell max-w-6xl mx-auto rounded-2xl border border-gray-200 bg-white/25 backdrop-blur-md overflow-hidden min-h-[22rem] sm:min-h-[25rem]"> <div class="featured-widget-shell max-w-6xl mx-auto rounded-2xl border border-gray-200 bg-white/25 backdrop-blur-md overflow-hidden">
<HomeSpielplanTeamWidget <HomeSpielplanTeamWidget
v-if="featuredWidgetSection.id === 'spielplan_team'" v-if="featuredWidgetSection.id === 'spielplan_team'"
:season="featuredWidgetSection.config?.season" :season="featuredWidgetSection.config?.season"
@@ -627,9 +627,15 @@ async function saveEditor() {
background-color: transparent !important; background-color: transparent !important;
} }
.featured-widget-shell :deep(.py-8),
.featured-widget-shell :deep(.py-10),
.featured-widget-shell :deep(.py-12),
.featured-widget-shell :deep(.py-16), .featured-widget-shell :deep(.py-16),
.featured-widget-shell :deep(.sm\:py-10),
.featured-widget-shell :deep(.sm\:py-12),
.featured-widget-shell :deep(.sm\:py-16),
.featured-widget-shell :deep(.sm\:py-20) { .featured-widget-shell :deep(.sm\:py-20) {
padding-top: 1.5rem !important; padding-top: 1.5rem !important;
padding-bottom: 2rem !important; padding-bottom: 1.5rem !important;
} }
</style> </style>

View File

@@ -2,6 +2,7 @@ import fs from 'fs/promises'
import path from 'path' import path from 'path'
import { requireUserWithAnyRole } from '../../utils/auth.js' import { requireUserWithAnyRole } from '../../utils/auth.js'
import { decryptObject } from '../../utils/encryption.js' import { decryptObject } from '../../utils/encryption.js'
import { getServerDataPath } from '../../utils/paths.js'
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
try { try {
@@ -17,7 +18,7 @@ export default defineEventHandler(async (event) => {
}) })
} }
const dataDir = path.join(process.cwd(), 'server/data/membership-applications') const dataDir = getServerDataPath('membership-applications')
// Prüfen ob Verzeichnis existiert // Prüfen ob Verzeichnis existiert
try { try {

View File

@@ -1,5 +1,6 @@
import fs from 'fs/promises' import fs from 'fs/promises'
import path from 'path' import path from 'path'
import { createHmac, timingSafeEqual } from 'crypto'
import { getUserFromToken } from '../../../utils/auth.js' import { getUserFromToken } from '../../../utils/auth.js'
import { getServerDataPath } from '../../../utils/paths.js' import { getServerDataPath } from '../../../utils/paths.js'
@@ -47,7 +48,27 @@ export default defineEventHandler(async (event) => {
} }
} }
// Prüfen ob es sich um eine aktuelle Session handelt (innerhalb der letzten 24 Stunden) // Native apps cannot reliably reuse the httpOnly browser cookie that is
// set when the application is created. They receive the same short-lived
// authorization as a signed response token instead.
const signedDownloadToken = getHeader(event, 'x-membership-download-token')
if (signedDownloadToken) {
try {
const [payload, signature] = signedDownloadToken.split('.')
const secret = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
const expected = createHmac('sha256', secret).update(payload).digest('base64url')
const validSignature = signature && timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
const tokenAge = Date.now() - Number(decoded.issuedAt)
if (validSignature && decoded.fileId === fileId && tokenAge >= 0 && tokenAge < 24 * 60 * 60 * 1000) {
isAuthorized = true
}
} catch (_error) {
// Invalid download tokens are treated as unauthorized.
}
}
// Browser clients continue to use the httpOnly cookie.
const downloadToken = getCookie(event, 'download_token') const downloadToken = getCookie(event, 'download_token')
if (downloadToken) { if (downloadToken) {

View File

@@ -1,11 +1,13 @@
import { exec } from 'child_process' import { exec } from 'child_process'
import { promisify } from 'util' import { promisify } from 'util'
import { createHmac } from 'crypto'
import fs from 'fs/promises' import fs from 'fs/promises'
import path from 'path' import path from 'path'
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib' import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
import { getDownloadCookieOptionsWithMaxAge } from '../../utils/cookies.js' import { getDownloadCookieOptionsWithMaxAge } from '../../utils/cookies.js'
import { sendMembershipEmail as sendMembershipEmailUtil } from '../../utils/email-service.js' import { sendMembershipEmail as sendMembershipEmailUtil } from '../../utils/email-service.js'
import { getProjectPath, getServerDataPath } from '../../utils/paths.js' import { getProjectPath, getServerDataPath } from '../../utils/paths.js'
import { createMembershipApplication, removeMembershipApplication } from '../../utils/membership-applications.js'
// const require = createRequire(import.meta.url) // Nicht verwendet // const require = createRequire(import.meta.url) // Nicht verwendet
const execAsync = promisify(exec) const execAsync = promisify(exec)
@@ -310,9 +312,18 @@ function getDataPath(filename) {
return getServerDataPath(filename) return getServerDataPath(filename)
} }
function createMembershipDownloadToken(fileId) {
const issuedAt = Date.now()
const payload = Buffer.from(JSON.stringify({ fileId, issuedAt })).toString('base64url')
const secret = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
const signature = createHmac('sha256', secret).update(payload).digest('base64url')
return `${payload}.${signature}`
}
// Use central email service // Use central email service
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
let application = null
try { try {
const body = await readBody(event) const body = await readBody(event)
@@ -338,6 +349,10 @@ export default defineEventHandler(async (event) => {
...body, ...body,
isVolljaehrig isVolljaehrig
} }
// Persist the pending application before generating files or sending mail.
// This also makes repeated taps and concurrent requests idempotently fail.
application = await createMembershipApplication(data)
// Eindeutige Datei-ID generieren // Eindeutige Datei-ID generieren
const timestamp = Date.now() const timestamp = Date.now()
@@ -630,9 +645,11 @@ export default defineEventHandler(async (event) => {
success: true, success: true,
message: 'Beitrittsformular erfolgreich aus Template erzeugt und E-Mail gesendet.', message: 'Beitrittsformular erfolgreich aus Template erzeugt und E-Mail gesendet.',
downloadUrl: `/api/membership/download/${filename}.pdf`, downloadUrl: `/api/membership/download/${filename}.pdf`,
downloadToken: createMembershipDownloadToken(`${filename}.pdf`),
emailSuccess: emailResult.success, emailSuccess: emailResult.success,
emailMessage: emailResult.message, emailMessage: emailResult.message,
usedTemplate: true usedTemplate: true,
applicationId: application.id
} }
} }
@@ -690,8 +707,10 @@ export default defineEventHandler(async (event) => {
success: true, success: true,
message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet.', message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet.',
downloadUrl: `/api/membership/download/${filename}.pdf`, downloadUrl: `/api/membership/download/${filename}.pdf`,
downloadToken: createMembershipDownloadToken(`${filename}.pdf`),
emailSuccess: emailResult.success, emailSuccess: emailResult.success,
emailMessage: emailResult.message, emailMessage: emailResult.message,
applicationId: application.id
} }
} catch (latexError) { } catch (latexError) {
@@ -726,16 +745,22 @@ export default defineEventHandler(async (event) => {
success: true, success: true,
message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet (Fallback-Lösung).', message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet (Fallback-Lösung).',
downloadUrl: `/api/membership/download/${fallbackFilename}`, downloadUrl: `/api/membership/download/${fallbackFilename}`,
downloadToken: createMembershipDownloadToken(fallbackFilename),
emailSuccess: emailResult.success, emailSuccess: emailResult.success,
emailMessage: emailResult.message, emailMessage: emailResult.message,
applicationId: application.id
} }
} }
} catch (error) { } catch (error) {
// A failed generation must not leave a pending application that prevents
// the applicant from trying again.
await removeMembershipApplication(application?.id)
console.error('Fehler beim Generieren des PDFs:', error) console.error('Fehler beim Generieren des PDFs:', error)
if (error?.statusCode) throw error
throw createError({ throw createError({
statusCode: 500, statusCode: 500,
statusMessage: 'Fehler beim Generieren des PDFs' statusMessage: 'Fehler beim Generieren des PDFs'
}) })
} }
}) })

View File

@@ -1,8 +1,8 @@
import fs from 'fs/promises' import fs from 'fs/promises'
import path from 'path'
import { requireUserWithAnyRole } from '../../utils/auth.js' import { requireUserWithAnyRole } from '../../utils/auth.js'
import { decryptObject } from '../../utils/encryption.js' import { decryptObject } from '../../utils/encryption.js'
import { saveMember } from '../../utils/members.js' import { saveMember } from '../../utils/members.js'
import { getServerDataPath } from '../../utils/paths.js'
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
try { try {
@@ -43,9 +43,7 @@ export default defineEventHandler(async (event) => {
} }
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const dataDir = path.join(process.cwd(), 'server/data/membership-applications') const filePath = getServerDataPath('membership-applications', `${id}.json`)
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const filePath = path.join(dataDir, `${id}.json`)
// Antrag laden // Antrag laden
const fileContent = await fs.readFile(filePath, 'utf8') const fileContent = await fs.readFile(filePath, 'utf8')
@@ -67,6 +65,7 @@ export default defineEventHandler(async (event) => {
const newMember = { const newMember = {
firstName: decryptedData.vorname, firstName: decryptedData.vorname,
lastName: decryptedData.nachname, lastName: decryptedData.nachname,
geburtsdatum: decryptedData.geburtsdatum,
email: decryptedData.email, email: decryptedData.email,
phone: decryptedData.telefon_privat || decryptedData.telefon_mobil || '', phone: decryptedData.telefon_privat || decryptedData.telefon_mobil || '',
address: `${decryptedData.strasse}, ${decryptedData.plz} ${decryptedData.ort}`, address: `${decryptedData.strasse}, ${decryptedData.plz} ${decryptedData.ort}`,

View File

@@ -221,14 +221,23 @@ export function normalizeDate(dateString) {
} }
// Check for duplicate member based on firstName, lastName, and geburtsdatum // Check for duplicate member based on firstName, lastName, and geburtsdatum
function findDuplicateMember(members, firstName, lastName, geburtsdatum) { function normalizeIdentityPart(value) {
const normalizedFirstName = (firstName || '').trim().toLowerCase() return String(value || '')
const normalizedLastName = (lastName || '').trim().toLowerCase() .normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.toLowerCase()
}
export function findDuplicateMember(members, firstName, lastName, geburtsdatum) {
const normalizedFirstName = normalizeIdentityPart(firstName)
const normalizedLastName = normalizeIdentityPart(lastName)
const normalizedDate = normalizeDate(geburtsdatum) const normalizedDate = normalizeDate(geburtsdatum)
return members.find(m => { return members.find(m => {
const mFirstName = (m.firstName || '').trim().toLowerCase() const mFirstName = normalizeIdentityPart(m.firstName)
const mLastName = (m.lastName || '').trim().toLowerCase() const mLastName = normalizeIdentityPart(m.lastName)
const mDate = normalizeDate(m.geburtsdatum) const mDate = normalizeDate(m.geburtsdatum)
return mFirstName === normalizedFirstName && return mFirstName === normalizedFirstName &&
@@ -307,4 +316,3 @@ export async function deleteMember(id) {
await writeMembers(filtered) await writeMembers(filtered)
return true return true
} }

View File

@@ -0,0 +1,104 @@
import { createHash, randomUUID } from 'crypto'
import { promises as fs } from 'fs'
import { decryptObject, encryptObject } from './encryption.js'
import { readMembers, findDuplicateMember, normalizeDate } from './members.js'
import { getServerDataPath } from './paths.js'
const APPLICATIONS_DIR = getServerDataPath('membership-applications')
const LOCKS_DIR = getServerDataPath('membership-application-locks')
function encryptionKey() {
return process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
}
function normalizeName(value) {
return String(value || '')
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.toLowerCase()
}
function identityHash(data) {
const identity = [normalizeName(data.vorname), normalizeName(data.nachname), normalizeDate(data.geburtsdatum)].join('|')
return createHash('sha256').update(identity).digest('hex')
}
async function withIdentityLock(hash, operation) {
await fs.mkdir(LOCKS_DIR, { recursive: true })
const lockPath = `${LOCKS_DIR}/${hash}.lock`
let handle
try {
handle = await fs.open(lockPath, 'wx')
} catch (error) {
if (error?.code === 'EEXIST') {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person wird bereits ein Mitgliedschaftsantrag bearbeitet.' })
}
throw error
}
try {
return await operation()
} finally {
await handle.close().catch(() => {})
await fs.unlink(lockPath).catch(() => {})
}
}
async function findMatchingApplication(data) {
try {
const files = await fs.readdir(APPLICATIONS_DIR)
const target = identityHash(data)
for (const file of files.filter(file => file.endsWith('.json'))) {
try {
const application = JSON.parse(await fs.readFile(`${APPLICATIONS_DIR}/${file}`, 'utf8'))
if (application.identityHash === target) return application
if (application.encryptedData) {
const personalData = decryptObject(application.encryptedData, encryptionKey())
if (identityHash(personalData) === target) return application
}
} catch (error) {
console.warn('Mitgliedschaftsantrag konnte bei der Duplikatprüfung nicht gelesen werden:', { file, message: error.message })
}
}
return null
} catch (error) {
if (error?.code !== 'ENOENT') throw error
return null
}
}
export async function createMembershipApplication(data) {
const hash = identityHash(data)
if (!normalizeName(data.vorname) || !normalizeName(data.nachname) || !normalizeDate(data.geburtsdatum)) {
throw createError({ statusCode: 400, statusMessage: 'Vorname, Nachname und ein gültiges Geburtsdatum sind erforderlich.' })
}
return withIdentityLock(hash, async () => {
const members = await readMembers()
if (findDuplicateMember(members, data.vorname, data.nachname, data.geburtsdatum)) {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person besteht bereits eine Mitgliedschaft.' })
}
const existing = await findMatchingApplication(data)
if (existing) {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person liegt bereits ein Mitgliedschaftsantrag vor.' })
}
await fs.mkdir(APPLICATIONS_DIR, { recursive: true })
const application = {
id: randomUUID(),
timestamp: new Date().toISOString(),
status: 'pending',
identityHash: hash,
metadata: { mitgliedschaftsart: data.mitgliedschaftsart },
encryptedData: encryptObject(data, encryptionKey())
}
await fs.writeFile(`${APPLICATIONS_DIR}/${application.id}.json`, `${JSON.stringify(application, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' })
return application
})
}
export async function removeMembershipApplication(applicationId) {
if (!applicationId) return
await fs.unlink(`${APPLICATIONS_DIR}/${applicationId}.json`).catch(error => {
if (error?.code !== 'ENOENT') throw error
})
}

View File

@@ -102,7 +102,7 @@ export function upsertPushToken(user, { token, platform = 'android', appVersion
return user return user
} }
async function sendFcmMessage({ serviceAccount, accessToken, token, title, body, data = {} }) { async function sendFcmMessage({ serviceAccount, accessToken, token, data = {} }) {
const projectId = projectIdFromServiceAccount(serviceAccount) const projectId = projectIdFromServiceAccount(serviceAccount)
if (!projectId) throw new Error('FCM project_id fehlt.') if (!projectId) throw new Error('FCM project_id fehlt.')
const response = await fetch(`https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`, { const response = await fetch(`https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`, {
@@ -114,14 +114,14 @@ async function sendFcmMessage({ serviceAccount, accessToken, token, title, body,
body: JSON.stringify({ body: JSON.stringify({
message: { message: {
token, token,
notification: { title, body },
data, data,
android: { android: {
priority: 'high', priority: 'high',
notification: { // Keep this as a data message. With a `notification` payload FCM
channel_id: 'harheimer_tc_updates', // renders background messages itself, bypassing our notification
click_action: 'OPEN_NEWS' // channel and HarheimerMessagingService. Data messages use the
} // same app-controlled channel while the app is foregrounded and
// backgrounded.
} }
} }
}) })
@@ -185,7 +185,7 @@ export async function sendPushToUsers({ title, body, data = {}, predicate, bodyF
const validTokens = [] const validTokens = []
for (const entry of tokens) { for (const entry of tokens) {
try { try {
await sendFcmMessage({ serviceAccount, accessToken, token: entry.token, title, body: userBody, data: payload }) await sendFcmMessage({ serviceAccount, accessToken, token: entry.token, data: payload })
sent += 1 sent += 1
validTokens.push(entry) validTokens.push(entry)
} catch (error) { } catch (error) {
@@ -206,7 +206,11 @@ export async function sendPushToUsers({ title, body, data = {}, predicate, bodyF
} }
} }
if (changed) await writeUsers(users) if (changed) await writeUsers(users)
return { sent, failed, removed, recipients, tokenCount, skipped: false } const result = { sent, failed, removed, recipients, tokenCount, skipped: false }
// This makes an absent registration immediately visible in the production
// log without exposing tokens or user data.
console.info('FCM Push Ergebnis:', { failureLabel, ...result })
return result
} }
export async function sendNewNewsPush(news) { export async function sendNewNewsPush(news) {

View File

@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
const originalAppRoot = process.env.APP_ROOT
const createdRoots = []
afterEach(async () => {
vi.resetModules()
if (originalAppRoot === undefined) delete process.env.APP_ROOT
else process.env.APP_ROOT = originalAppRoot
await Promise.all(createdRoots.splice(0).map(root => fs.rm(root, { recursive: true, force: true })))
})
describe('membership applications', () => {
it('rejects a second pending application with the same name and birth date', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'harheimertc-membership-'))
createdRoots.push(root)
await fs.mkdir(path.join(root, 'server', 'data'), { recursive: true })
process.env.APP_ROOT = root
const { createMembershipApplication } = await import('../server/utils/membership-applications.js')
const data = {
vorname: 'Jörg',
nachname: 'Beispiel',
geburtsdatum: '1990-02-03',
mitgliedschaftsart: 'aktiv'
}
const application = await createMembershipApplication(data)
expect(application.status).toBe('pending')
await expect(createMembershipApplication({ ...data, vorname: ' JÖRG ' }))
.rejects.toMatchObject({ statusCode: 409 })
})
})