From 42dd1f2d4a2d1e8573b613b900009158d289e8db Mon Sep 17 00:00:00 2001 From: Marco Morath Date: Wed, 25 Nov 2026 18:46:04 +0100 Subject: [PATCH] Initial Commit: Status Testing --- .dockerignore | 15 + .env.example | 83 + .gitea/workflows/ci.yml | 127 + .gitignore | 178 +- Dockerfile | 78 + LICENSE | 816 ++- README.md | 939 ++- alembic.ini | 33 + babel.cfg | 5 + compose.yaml | 88 + docs/betrieb.md | 81 + docs/datenschutz.md | 98 + docs/sicherheit.md | 95 + pyproject.toml | 38 + requirements-dev.in | 8 + requirements.in | 23 + scripts/loadtest.py | 79 + scripts/lock.sh | 35 + scripts/upgrade-test.sh | 98 + scripts/zap-baseline.sh | 25 + scripts/zap-rules.tsv | 10 + surveybox/__init__.py | 4 + surveybox/accounts/__init__.py | 2 + surveybox/accounts/audit.py | 101 + surveybox/accounts/groups.py | 228 + surveybox/accounts/passkeys.py | 278 + surveybox/accounts/ratelimit.py | 51 + surveybox/accounts/registration.py | 181 + surveybox/accounts/scope.py | 212 + surveybox/accounts/service.py | 497 ++ surveybox/accounts/sessions.py | 159 + surveybox/appearance.py | 386 + surveybox/backup.py | 409 ++ surveybox/branding.py | 148 + surveybox/cli.py | 288 + surveybox/db.py | 52 + surveybox/erasure_journal.py | 183 + surveybox/forms/__init__.py | 2 + surveybox/forms/booking.py | 317 + surveybox/forms/calendar.py | 99 + surveybox/forms/changes.py | 85 + surveybox/forms/comments.py | 190 + surveybox/forms/conditions.py | 480 ++ surveybox/forms/digest.py | 62 + surveybox/forms/erasure.py | 247 + surveybox/forms/evaluation.py | 236 + surveybox/forms/export.py | 283 + surveybox/forms/followups.py | 637 ++ surveybox/forms/groups.py | 180 + surveybox/forms/guests.py | 376 + surveybox/forms/notes.py | 72 + surveybox/forms/ods.py | 270 + surveybox/forms/participant_pdf.py | 248 + surveybox/forms/pdf_export.py | 362 + surveybox/forms/public_results.py | 67 + surveybox/forms/reminders.py | 84 + surveybox/forms/retention.py | 264 + surveybox/forms/service.py | 900 +++ surveybox/forms/subject_export.py | 210 + surveybox/forms/summary.py | 160 + surveybox/forms/team.py | 296 + surveybox/forms/types.py | 867 +++ surveybox/forms/uploads.py | 168 + surveybox/forms/xlsx.py | 298 + surveybox/i18n.py | 100 + surveybox/locale/de/LC_MESSAGES/messages.po | 6332 ++++++++++++++++ surveybox/locale/en/LC_MESSAGES/messages.po | 6256 ++++++++++++++++ surveybox/locale/fr/LC_MESSAGES/messages.po | 6368 ++++++++++++++++ surveybox/locale/messages.pot | 6461 +++++++++++++++++ surveybox/mail/__init__.py | 2 + surveybox/mail/config.py | 207 + surveybox/mail/custom.py | 232 + surveybox/mail/notify.py | 635 ++ surveybox/mail/outbox.py | 247 + surveybox/mail/render.py | 115 + surveybox/mail/smtp.py | 146 + surveybox/media/__init__.py | 2 + surveybox/media/config.py | 93 + surveybox/media/embeds.py | 278 + surveybox/media/images.py | 69 + surveybox/media/service.py | 269 + surveybox/media/sniff.py | 147 + surveybox/media/storage.py | 114 + surveybox/migrations/env.py | 51 + surveybox/migrations/script.py.mako | 33 + surveybox/migrations/versions/0001_initial.py | 47 + .../migrations/versions/0002_accounts.py | 173 + .../versions/0003_passkeys_groups.py | 122 + surveybox/migrations/versions/0004_forms.py | 231 + .../migrations/versions/0005_media_team.py | 126 + .../migrations/versions/0006_group_roles.py | 25 + .../versions/0007_group_hierarchy.py | 75 + .../versions/0008_polls_slots_comments.py | 140 + surveybox/migrations/versions/0009_mail.py | 96 + surveybox/migrations/versions/0010_guests.py | 65 + .../versions/0011_guest_email_question.py | 34 + .../migrations/versions/0012_followups.py | 101 + .../versions/0013_followup_catch_up.py | 25 + .../migrations/versions/0014_retention.py | 36 + surveybox/migrations/versions/0015_erasure.py | 25 + .../migrations/versions/0016_slot_names.py | 28 + .../migrations/versions/0017_response_note.py | 46 + surveybox/models/__init__.py | 96 + surveybox/models/accounts.py | 314 + surveybox/models/base.py | 22 + surveybox/models/followups.py | 107 + surveybox/models/forms.py | 457 ++ surveybox/models/mail.py | 110 + surveybox/models/system.py | 38 + surveybox/security/__init__.py | 3 + surveybox/security/client_ip.py | 48 + surveybox/security/csrf.py | 46 + surveybox/security/headers.py | 64 + surveybox/security/passwords.py | 61 + surveybox/security/recovery.py | 32 + surveybox/security/secretbox.py | 40 + surveybox/security/tokens.py | 46 + surveybox/security/totp.py | 77 + surveybox/settings.py | 208 + surveybox/upgrade.py | 247 + surveybox/web/__init__.py | 1 + surveybox/web/app.py | 169 + surveybox/web/deps.py | 217 + surveybox/web/downloads.py | 22 + surveybox/web/fill_page.py | 72 + surveybox/web/form_deps.py | 33 + surveybox/web/limits.py | 82 + surveybox/web/media_response.py | 36 + surveybox/web/routes/__init__.py | 1 + surveybox/web/routes/account.py | 356 + surveybox/web/routes/admin.py | 462 ++ surveybox/web/routes/admin_appearance.py | 174 + surveybox/web/routes/admin_mail.py | 148 + surveybox/web/routes/admin_mail_templates.py | 140 + surveybox/web/routes/admin_settings.py | 200 + surveybox/web/routes/auth.py | 294 + surveybox/web/routes/branding.py | 61 + surveybox/web/routes/fill.py | 819 +++ surveybox/web/routes/form_comments.py | 51 + surveybox/web/routes/form_followups.py | 322 + surveybox/web/routes/form_media.py | 289 + surveybox/web/routes/form_results.py | 268 + surveybox/web/routes/form_team.py | 157 + surveybox/web/routes/forms.py | 806 ++ surveybox/web/routes/groups.py | 392 + surveybox/web/routes/health.py | 39 + surveybox/web/routes/pages.py | 74 + surveybox/web/routes/passkeys.py | 185 + surveybox/web/routes/personal.py | 388 + surveybox/web/routes/register.py | 120 + surveybox/web/routes/unsubscribe.py | 99 + surveybox/web/static/css/app.css | 559 ++ surveybox/web/static/img/apple-touch-icon.png | Bin 0 -> 5729 bytes surveybox/web/static/img/favicon-32.png | Bin 0 -> 933 bytes surveybox/web/static/img/logo-128.png | Bin 0 -> 3668 bytes surveybox/web/static/img/logo.svg | 7 + surveybox/web/static/js/admin.js | 25 + surveybox/web/static/js/designer.js | 88 + surveybox/web/static/js/fill.js | 412 ++ surveybox/web/static/js/passkeys.js | 184 + surveybox/web/static/js/preview.js | 36 + surveybox/web/static/js/question.js | 98 + surveybox/web/templates/_comments.html | 51 + surveybox/web/templates/_erasure_summary.html | 25 + surveybox/web/templates/_fill_fields.html | 426 ++ surveybox/web/templates/account.html | 170 + surveybox/web/templates/account_delete.html | 44 + .../web/templates/account_notifications.html | 42 + surveybox/web/templates/admin_appearance.html | 153 + surveybox/web/templates/admin_audit.html | 38 + surveybox/web/templates/admin_group_edit.html | 154 + surveybox/web/templates/admin_groups.html | 54 + surveybox/web/templates/admin_mail.html | 99 + .../templates/admin_mail_template_edit.html | 56 + .../web/templates/admin_mail_templates.html | 25 + surveybox/web/templates/admin_settings.html | 74 + .../web/templates/admin_user_delete.html | 39 + surveybox/web/templates/admin_user_edit.html | 77 + surveybox/web/templates/admin_user_link.html | 19 + surveybox/web/templates/admin_user_new.html | 39 + surveybox/web/templates/admin_users.html | 52 + surveybox/web/templates/base.html | 101 + surveybox/web/templates/error.html | 17 + surveybox/web/templates/fill.html | 99 + surveybox/web/templates/fill_closed.html | 16 + surveybox/web/templates/fill_done.html | 50 + surveybox/web/templates/fill_password.html | 16 + surveybox/web/templates/followup_edit.html | 121 + .../web/templates/followup_recipients.html | 51 + surveybox/web/templates/forgot.html | 22 + surveybox/web/templates/form_access.html | 28 + surveybox/web/templates/form_comments.html | 32 + surveybox/web/templates/form_designer.html | 152 + surveybox/web/templates/form_followups.html | 36 + surveybox/web/templates/form_preview.html | 21 + surveybox/web/templates/form_responses.html | 180 + surveybox/web/templates/form_settings.html | 167 + surveybox/web/templates/form_team.html | 54 + surveybox/web/templates/forms_list.html | 65 + surveybox/web/templates/guest_confirm.html | 25 + surveybox/web/templates/guest_erase.html | 24 + surveybox/web/templates/guest_export.html | 18 + surveybox/web/templates/guest_links.html | 49 + surveybox/web/templates/index.html | 49 + surveybox/web/templates/login.html | 27 + surveybox/web/templates/login_mfa.html | 32 + surveybox/web/templates/mail/changed.txt | 16 + surveybox/web/templates/mail/comment_new.txt | 10 + .../web/templates/mail/comment_published.txt | 6 + surveybox/web/templates/mail/confirmed.txt | 20 + surveybox/web/templates/mail/deadline.txt | 6 + surveybox/web/templates/mail/digest.txt | 11 + surveybox/web/templates/mail/followup.txt | 12 + surveybox/web/templates/mail/guest_erase.txt | 7 + surveybox/web/templates/mail/guest_export.txt | 7 + surveybox/web/templates/mail/guest_links.txt | 11 + .../web/templates/mail/guest_receipt.txt | 32 + surveybox/web/templates/mail/invite.txt | 8 + .../web/templates/mail/participation.txt | 7 + .../web/templates/mail/password_reset.txt | 8 + surveybox/web/templates/mail/promoted.txt | 12 + surveybox/web/templates/mail/register.txt | 8 + .../web/templates/mail/register_exists.txt | 10 + surveybox/web/templates/mail/reminder.txt | 6 + .../web/templates/mail/retention_notice.txt | 14 + surveybox/web/templates/mail/slot_full.txt | 6 + surveybox/web/templates/mail/test.txt | 6 + surveybox/web/templates/personal.html | 96 + surveybox/web/templates/question_edit.html | 389 + surveybox/web/templates/recovery_codes.html | 20 + surveybox/web/templates/register.html | 26 + surveybox/web/templates/register_finish.html | 28 + surveybox/web/templates/response_view.html | 69 + surveybox/web/templates/results_public.html | 67 + surveybox/web/templates/setup.html | 28 + surveybox/web/templates/totp_setup.html | 28 + surveybox/web/templates/unsubscribe.html | 34 + surveybox/web/templating.py | 177 + surveybox/worker.py | 309 + tests/conftest.py | 62 + tests/helpers.py | 175 + tests/test_accounts.py | 224 + tests/test_appearance.py | 105 + tests/test_appearance_units.py | 80 + tests/test_audit_actions.py | 83 + tests/test_backup.py | 237 + tests/test_branding.py | 54 + tests/test_branding_units.py | 64 + tests/test_calendar.py | 50 + tests/test_conditions.py | 176 + tests/test_embed.py | 70 + tests/test_erasure.py | 196 + tests/test_erasure_journal_units.py | 58 + tests/test_evaluation.py | 141 + tests/test_followups.py | 343 + tests/test_form_files.py | 57 + tests/test_forms.py | 423 ++ tests/test_group_scope.py | 222 + tests/test_groups.py | 264 + tests/test_guests.py | 279 + tests/test_guests_units.py | 123 + tests/test_i18n.py | 105 + tests/test_mail.py | 313 + tests/test_mail_custom_units.py | 52 + tests/test_mail_templates.py | 61 + tests/test_mail_units.py | 261 + tests/test_media_team.py | 437 ++ tests/test_media_units.py | 322 + tests/test_participant_name_units.py | 46 + tests/test_passkeys_groups.py | 216 + tests/test_phase4.py | 208 + tests/test_phase5.py | 263 + tests/test_phase8c.py | 226 + tests/test_phase8c_units.py | 114 + tests/test_question_groups.py | 134 + tests/test_question_types.py | 245 + tests/test_retention.py | 143 + tests/test_retention_units.py | 62 + tests/test_scope_units.py | 51 + tests/test_security_matrix.py | 136 + tests/test_security_units.py | 187 + tests/test_slot_names.py | 51 + tests/test_subject_export.py | 99 + tests/test_upgrade.py | 168 + tests/test_web.py | 82 + tests/test_xlsx_units.py | 73 + 286 files changed, 64800 insertions(+), 369 deletions(-) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitea/workflows/ci.yml create mode 100644 Dockerfile create mode 100644 alembic.ini create mode 100644 babel.cfg create mode 100644 compose.yaml create mode 100644 docs/betrieb.md create mode 100644 docs/datenschutz.md create mode 100644 docs/sicherheit.md create mode 100644 pyproject.toml create mode 100644 requirements-dev.in create mode 100644 requirements.in create mode 100755 scripts/loadtest.py create mode 100755 scripts/lock.sh create mode 100755 scripts/upgrade-test.sh create mode 100755 scripts/zap-baseline.sh create mode 100644 scripts/zap-rules.tsv create mode 100644 surveybox/__init__.py create mode 100644 surveybox/accounts/__init__.py create mode 100644 surveybox/accounts/audit.py create mode 100644 surveybox/accounts/groups.py create mode 100644 surveybox/accounts/passkeys.py create mode 100644 surveybox/accounts/ratelimit.py create mode 100644 surveybox/accounts/registration.py create mode 100644 surveybox/accounts/scope.py create mode 100644 surveybox/accounts/service.py create mode 100644 surveybox/accounts/sessions.py create mode 100644 surveybox/appearance.py create mode 100644 surveybox/backup.py create mode 100644 surveybox/branding.py create mode 100644 surveybox/cli.py create mode 100644 surveybox/db.py create mode 100644 surveybox/erasure_journal.py create mode 100644 surveybox/forms/__init__.py create mode 100644 surveybox/forms/booking.py create mode 100644 surveybox/forms/calendar.py create mode 100644 surveybox/forms/changes.py create mode 100644 surveybox/forms/comments.py create mode 100644 surveybox/forms/conditions.py create mode 100644 surveybox/forms/digest.py create mode 100644 surveybox/forms/erasure.py create mode 100644 surveybox/forms/evaluation.py create mode 100644 surveybox/forms/export.py create mode 100644 surveybox/forms/followups.py create mode 100644 surveybox/forms/groups.py create mode 100644 surveybox/forms/guests.py create mode 100644 surveybox/forms/notes.py create mode 100644 surveybox/forms/ods.py create mode 100644 surveybox/forms/participant_pdf.py create mode 100644 surveybox/forms/pdf_export.py create mode 100644 surveybox/forms/public_results.py create mode 100644 surveybox/forms/reminders.py create mode 100644 surveybox/forms/retention.py create mode 100644 surveybox/forms/service.py create mode 100644 surveybox/forms/subject_export.py create mode 100644 surveybox/forms/summary.py create mode 100644 surveybox/forms/team.py create mode 100644 surveybox/forms/types.py create mode 100644 surveybox/forms/uploads.py create mode 100644 surveybox/forms/xlsx.py create mode 100644 surveybox/i18n.py create mode 100644 surveybox/locale/de/LC_MESSAGES/messages.po create mode 100644 surveybox/locale/en/LC_MESSAGES/messages.po create mode 100644 surveybox/locale/fr/LC_MESSAGES/messages.po create mode 100644 surveybox/locale/messages.pot create mode 100644 surveybox/mail/__init__.py create mode 100644 surveybox/mail/config.py create mode 100644 surveybox/mail/custom.py create mode 100644 surveybox/mail/notify.py create mode 100644 surveybox/mail/outbox.py create mode 100644 surveybox/mail/render.py create mode 100644 surveybox/mail/smtp.py create mode 100644 surveybox/media/__init__.py create mode 100644 surveybox/media/config.py create mode 100644 surveybox/media/embeds.py create mode 100644 surveybox/media/images.py create mode 100644 surveybox/media/service.py create mode 100644 surveybox/media/sniff.py create mode 100644 surveybox/media/storage.py create mode 100644 surveybox/migrations/env.py create mode 100644 surveybox/migrations/script.py.mako create mode 100644 surveybox/migrations/versions/0001_initial.py create mode 100644 surveybox/migrations/versions/0002_accounts.py create mode 100644 surveybox/migrations/versions/0003_passkeys_groups.py create mode 100644 surveybox/migrations/versions/0004_forms.py create mode 100644 surveybox/migrations/versions/0005_media_team.py create mode 100644 surveybox/migrations/versions/0006_group_roles.py create mode 100644 surveybox/migrations/versions/0007_group_hierarchy.py create mode 100644 surveybox/migrations/versions/0008_polls_slots_comments.py create mode 100644 surveybox/migrations/versions/0009_mail.py create mode 100644 surveybox/migrations/versions/0010_guests.py create mode 100644 surveybox/migrations/versions/0011_guest_email_question.py create mode 100644 surveybox/migrations/versions/0012_followups.py create mode 100644 surveybox/migrations/versions/0013_followup_catch_up.py create mode 100644 surveybox/migrations/versions/0014_retention.py create mode 100644 surveybox/migrations/versions/0015_erasure.py create mode 100644 surveybox/migrations/versions/0016_slot_names.py create mode 100644 surveybox/migrations/versions/0017_response_note.py create mode 100644 surveybox/models/__init__.py create mode 100644 surveybox/models/accounts.py create mode 100644 surveybox/models/base.py create mode 100644 surveybox/models/followups.py create mode 100644 surveybox/models/forms.py create mode 100644 surveybox/models/mail.py create mode 100644 surveybox/models/system.py create mode 100644 surveybox/security/__init__.py create mode 100644 surveybox/security/client_ip.py create mode 100644 surveybox/security/csrf.py create mode 100644 surveybox/security/headers.py create mode 100644 surveybox/security/passwords.py create mode 100644 surveybox/security/recovery.py create mode 100644 surveybox/security/secretbox.py create mode 100644 surveybox/security/tokens.py create mode 100644 surveybox/security/totp.py create mode 100644 surveybox/settings.py create mode 100644 surveybox/upgrade.py create mode 100644 surveybox/web/__init__.py create mode 100644 surveybox/web/app.py create mode 100644 surveybox/web/deps.py create mode 100644 surveybox/web/downloads.py create mode 100644 surveybox/web/fill_page.py create mode 100644 surveybox/web/form_deps.py create mode 100644 surveybox/web/limits.py create mode 100644 surveybox/web/media_response.py create mode 100644 surveybox/web/routes/__init__.py create mode 100644 surveybox/web/routes/account.py create mode 100644 surveybox/web/routes/admin.py create mode 100644 surveybox/web/routes/admin_appearance.py create mode 100644 surveybox/web/routes/admin_mail.py create mode 100644 surveybox/web/routes/admin_mail_templates.py create mode 100644 surveybox/web/routes/admin_settings.py create mode 100644 surveybox/web/routes/auth.py create mode 100644 surveybox/web/routes/branding.py create mode 100644 surveybox/web/routes/fill.py create mode 100644 surveybox/web/routes/form_comments.py create mode 100644 surveybox/web/routes/form_followups.py create mode 100644 surveybox/web/routes/form_media.py create mode 100644 surveybox/web/routes/form_results.py create mode 100644 surveybox/web/routes/form_team.py create mode 100644 surveybox/web/routes/forms.py create mode 100644 surveybox/web/routes/groups.py create mode 100644 surveybox/web/routes/health.py create mode 100644 surveybox/web/routes/pages.py create mode 100644 surveybox/web/routes/passkeys.py create mode 100644 surveybox/web/routes/personal.py create mode 100644 surveybox/web/routes/register.py create mode 100644 surveybox/web/routes/unsubscribe.py create mode 100644 surveybox/web/static/css/app.css create mode 100644 surveybox/web/static/img/apple-touch-icon.png create mode 100644 surveybox/web/static/img/favicon-32.png create mode 100644 surveybox/web/static/img/logo-128.png create mode 100644 surveybox/web/static/img/logo.svg create mode 100644 surveybox/web/static/js/admin.js create mode 100644 surveybox/web/static/js/designer.js create mode 100644 surveybox/web/static/js/fill.js create mode 100644 surveybox/web/static/js/passkeys.js create mode 100644 surveybox/web/static/js/preview.js create mode 100644 surveybox/web/static/js/question.js create mode 100644 surveybox/web/templates/_comments.html create mode 100644 surveybox/web/templates/_erasure_summary.html create mode 100644 surveybox/web/templates/_fill_fields.html create mode 100644 surveybox/web/templates/account.html create mode 100644 surveybox/web/templates/account_delete.html create mode 100644 surveybox/web/templates/account_notifications.html create mode 100644 surveybox/web/templates/admin_appearance.html create mode 100644 surveybox/web/templates/admin_audit.html create mode 100644 surveybox/web/templates/admin_group_edit.html create mode 100644 surveybox/web/templates/admin_groups.html create mode 100644 surveybox/web/templates/admin_mail.html create mode 100644 surveybox/web/templates/admin_mail_template_edit.html create mode 100644 surveybox/web/templates/admin_mail_templates.html create mode 100644 surveybox/web/templates/admin_settings.html create mode 100644 surveybox/web/templates/admin_user_delete.html create mode 100644 surveybox/web/templates/admin_user_edit.html create mode 100644 surveybox/web/templates/admin_user_link.html create mode 100644 surveybox/web/templates/admin_user_new.html create mode 100644 surveybox/web/templates/admin_users.html create mode 100644 surveybox/web/templates/base.html create mode 100644 surveybox/web/templates/error.html create mode 100644 surveybox/web/templates/fill.html create mode 100644 surveybox/web/templates/fill_closed.html create mode 100644 surveybox/web/templates/fill_done.html create mode 100644 surveybox/web/templates/fill_password.html create mode 100644 surveybox/web/templates/followup_edit.html create mode 100644 surveybox/web/templates/followup_recipients.html create mode 100644 surveybox/web/templates/forgot.html create mode 100644 surveybox/web/templates/form_access.html create mode 100644 surveybox/web/templates/form_comments.html create mode 100644 surveybox/web/templates/form_designer.html create mode 100644 surveybox/web/templates/form_followups.html create mode 100644 surveybox/web/templates/form_preview.html create mode 100644 surveybox/web/templates/form_responses.html create mode 100644 surveybox/web/templates/form_settings.html create mode 100644 surveybox/web/templates/form_team.html create mode 100644 surveybox/web/templates/forms_list.html create mode 100644 surveybox/web/templates/guest_confirm.html create mode 100644 surveybox/web/templates/guest_erase.html create mode 100644 surveybox/web/templates/guest_export.html create mode 100644 surveybox/web/templates/guest_links.html create mode 100644 surveybox/web/templates/index.html create mode 100644 surveybox/web/templates/login.html create mode 100644 surveybox/web/templates/login_mfa.html create mode 100644 surveybox/web/templates/mail/changed.txt create mode 100644 surveybox/web/templates/mail/comment_new.txt create mode 100644 surveybox/web/templates/mail/comment_published.txt create mode 100644 surveybox/web/templates/mail/confirmed.txt create mode 100644 surveybox/web/templates/mail/deadline.txt create mode 100644 surveybox/web/templates/mail/digest.txt create mode 100644 surveybox/web/templates/mail/followup.txt create mode 100644 surveybox/web/templates/mail/guest_erase.txt create mode 100644 surveybox/web/templates/mail/guest_export.txt create mode 100644 surveybox/web/templates/mail/guest_links.txt create mode 100644 surveybox/web/templates/mail/guest_receipt.txt create mode 100644 surveybox/web/templates/mail/invite.txt create mode 100644 surveybox/web/templates/mail/participation.txt create mode 100644 surveybox/web/templates/mail/password_reset.txt create mode 100644 surveybox/web/templates/mail/promoted.txt create mode 100644 surveybox/web/templates/mail/register.txt create mode 100644 surveybox/web/templates/mail/register_exists.txt create mode 100644 surveybox/web/templates/mail/reminder.txt create mode 100644 surveybox/web/templates/mail/retention_notice.txt create mode 100644 surveybox/web/templates/mail/slot_full.txt create mode 100644 surveybox/web/templates/mail/test.txt create mode 100644 surveybox/web/templates/personal.html create mode 100644 surveybox/web/templates/question_edit.html create mode 100644 surveybox/web/templates/recovery_codes.html create mode 100644 surveybox/web/templates/register.html create mode 100644 surveybox/web/templates/register_finish.html create mode 100644 surveybox/web/templates/response_view.html create mode 100644 surveybox/web/templates/results_public.html create mode 100644 surveybox/web/templates/setup.html create mode 100644 surveybox/web/templates/totp_setup.html create mode 100644 surveybox/web/templates/unsubscribe.html create mode 100644 surveybox/web/templating.py create mode 100644 surveybox/worker.py create mode 100644 tests/conftest.py create mode 100644 tests/helpers.py create mode 100644 tests/test_accounts.py create mode 100644 tests/test_appearance.py create mode 100644 tests/test_appearance_units.py create mode 100644 tests/test_audit_actions.py create mode 100644 tests/test_backup.py create mode 100644 tests/test_branding.py create mode 100644 tests/test_branding_units.py create mode 100644 tests/test_calendar.py create mode 100644 tests/test_conditions.py create mode 100644 tests/test_embed.py create mode 100644 tests/test_erasure.py create mode 100644 tests/test_erasure_journal_units.py create mode 100644 tests/test_evaluation.py create mode 100644 tests/test_followups.py create mode 100644 tests/test_form_files.py create mode 100644 tests/test_forms.py create mode 100644 tests/test_group_scope.py create mode 100644 tests/test_groups.py create mode 100644 tests/test_guests.py create mode 100644 tests/test_guests_units.py create mode 100644 tests/test_i18n.py create mode 100644 tests/test_mail.py create mode 100644 tests/test_mail_custom_units.py create mode 100644 tests/test_mail_templates.py create mode 100644 tests/test_mail_units.py create mode 100644 tests/test_media_team.py create mode 100644 tests/test_media_units.py create mode 100644 tests/test_participant_name_units.py create mode 100644 tests/test_passkeys_groups.py create mode 100644 tests/test_phase4.py create mode 100644 tests/test_phase5.py create mode 100644 tests/test_phase8c.py create mode 100644 tests/test_phase8c_units.py create mode 100644 tests/test_question_groups.py create mode 100644 tests/test_question_types.py create mode 100644 tests/test_retention.py create mode 100644 tests/test_retention_units.py create mode 100644 tests/test_scope_units.py create mode 100644 tests/test_security_matrix.py create mode 100644 tests/test_security_units.py create mode 100644 tests/test_slot_names.py create mode 100644 tests/test_subject_export.py create mode 100644 tests/test_upgrade.py create mode 100644 tests/test_web.py create mode 100644 tests/test_xlsx_units.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..70aa44f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +.git +.gitea +.env +.env.* +!.env.example +**/__pycache__ +**/*.pyc +**/*.mo +.pytest_cache +.mypy_cache +.ruff_cache +.venv +tests +scripts +docs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..420229f --- /dev/null +++ b/.env.example @@ -0,0 +1,83 @@ +# Surveybox – Einstellungen für den Start +# Kopieren nach .env und ausfüllen. Die .env enthält Geheimnisse: +# chmod 600 .env + +# --- Docker Compose ------------------------------------------------------- +# Name des Stacks; bei mehreren Instanzen auf einem Host je Instanz eindeutig. +COMPOSE_PROJECT_NAME=surveybox +# "db" startet den mitgelieferten PostgreSQL-Container. +# Leer lassen, wenn ein vorhandener Datenbankserver genutzt wird. +COMPOSE_PROFILES=db +# Adresse und Port, unter denen der Reverse Proxy die App erreicht. +# 127.0.0.1 = nur Programme direkt auf dem Host. Läuft der Proxy auf einem +# anderen Rechner ODER selbst als Container (z. B. Nginx Proxy Manager), +# hier die interne IP des Docker-Hosts eintragen. +SURVEYBOX_HTTP_BIND=127.0.0.1 +SURVEYBOX_HTTP_PORT=8000 +# Subnetz des Docker-Netzes dieses Stacks. Muss frei sein: keine +# Überschneidung mit LAN, VPN oder anderen Docker-Netzen. Jede Instanz +# bekommt ein eigenes. Gateway ist automatisch die erste Adresse (.1). +# Private Bereiche: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. +SURVEYBOX_NET_SUBNET=172.30.40.0/24 + +# --- Instanz -------------------------------------------------------------- +# Öffentliche Adresse, wie Nutzer sie aufrufen. Später nicht mehr ändern: +# Passkeys sind an diese Domain gebunden. +SURVEYBOX_PUBLIC_URL=https://foo.bar +# Mindestens 32 Zeichen. Erzeugen mit: openssl rand -hex 32 +# NIE ÄNDERN, sobald Konten existieren: Daraus abgeleitet sind u. a. die +# Verschlüsselung der TOTP-Geheimnisse und die Wiederherstellungscodes. +SURVEYBOX_SECRET_KEY= +SURVEYBOX_DEFAULT_LANGUAGE=de +SURVEYBOX_TIMEZONE=Europe/Berlin +# Quellcode der Instanz (AGPL), erscheint als Link in der Fußzeile. Leer: kein Link. +#SURVEYBOX_SOURCE_URL=https://git.example.de/surveybox + +# --- Datenbank ------------------------------------------------------------ +# Mitgelieferter Container: Host "db", Passwort frei wählen. +# Erzeugen mit: openssl rand -base64 32 +SURVEYBOX_DB_HOST=db +SURVEYBOX_DB_PORT=5432 +SURVEYBOX_DB_NAME=surveybox +SURVEYBOX_DB_USER=surveybox +SURVEYBOX_DB_PASSWORD= +# Externer Server: mindestens "require", besser "verify-full" mit +# SURVEYBOX_DB_SSLROOTCERT (Pfad im Container, z. B. unter /data). +SURVEYBOX_DB_SSLMODE=prefer +#SURVEYBOX_DB_SSLROOTCERT=/data/db-ca.crt + +# --- Sicherungen ---------------------------------------------------------- +# Tägliche Sicherung ab dieser Stunde (Ortszeit) +SURVEYBOX_BACKUP_HOUR=3 +SURVEYBOX_BACKUP_KEEP_DAILY=14 +SURVEYBOX_BACKUP_KEEP_PRE_UPGRADE=10 + +# --- Reverse Proxy ---------------------------------------------------------- +# Adresse(n), von denen der Reverse Proxy bei Surveybox ankommt. Nur von dort +# wird X-Forwarded-For geglaubt; das braucht die Begrenzung von Fehlversuchen +# je Besucher. Läuft der Proxy auf demselben Docker-Host, ist das meist das +# Gateway des Surveybox-Netzes (erste Adresse von SURVEYBOX_NET_SUBNET). +# Leer lassen, wenn kein Proxy davor steht. +SURVEYBOX_TRUSTED_PROXIES=172.30.40.1 +# Seiten, die Surveybox in einem Rahmen anzeigen dürfen (z. B. die Nextcloud über +# die App "External sites"). Nur https, durch Leerzeichen getrennt, und nur unter +# derselben Domain (cloud.example.de neben umfrage.example.de). Leer: verboten. +#SURVEYBOX_FRAME_ANCESTORS=https://cloud.example.de + +# --- Uploads ----------------------------------------------------------------- +# Obergrenze für eine Anfrage mit Dateien (MB). Die Grenzen je Dateiart +# (Bilder, Videos, Uploads) stellt der Administrator unter Einstellungen ein, +# höchstens bis hier. Der Reverse Proxy muss so große Anfragen zulassen, +# bei nginx z. B. "client_max_body_size 250m;". +SURVEYBOX_MAX_UPLOAD_MB=250 + +# --- Sitzungen --------------------------------------------------------------- +# Abmeldung nach so vielen Minuten ohne Aktivität, spätestens nach so vielen Tagen +SURVEYBOX_SESSION_IDLE_MINUTES=480 +SURVEYBOX_SESSION_MAX_DAYS=14 +# Aufbewahrung des Protokolls (Anmeldungen, Verwaltungsaktionen) +SURVEYBOX_AUDIT_RETENTION_DAYS=365 + +# --- Betrieb -------------------------------------------------------------- +SURVEYBOX_WEB_WORKERS=2 +SURVEYBOX_LOG_LEVEL=info diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..9c740da --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# Gitea Actions (act_runner). +# +# checks: Codeprüfung, Sicherheitsprüfung der Abhängigkeiten, Tests gegen +# echtes PostgreSQL. Läuft in einem Python-Container; der +# PostgreSQL-Dienst ist dort unter dem Namen "postgres" erreichbar. +# image: Image bauen, Installation/Update/Wiederherstellung im Wegwerf-Stack. +# Braucht Zugriff auf den Docker-Daemon des Runners (act_runner reicht +# ihn standardmäßig in den Job-Container durch). Wer Zugriff auf den +# Docker-Socket hat, hat Root auf dem Host: dafür einen eigenen Runner +# auf einem Test-Host verwenden, nicht den Produktiv-Host. +# audit: wöchentlich bekannte Sicherheitslücken in den Abhängigkeiten prüfen +# (ersetzt den bei Gitea fehlenden Dependabot). + +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + schedule: + - cron: "17 5 * * 1" + +jobs: + checks: + if: github.event_name != 'schedule' + runs-on: ubuntu-latest + container: + image: python:3.13-slim-trixie + services: + postgres: + image: postgres:18-alpine + env: + POSTGRES_DB: surveybox + POSTGRES_USER: surveybox + POSTGRES_PASSWORD: surveybox-ci + env: + SURVEYBOX_TEST_DB: "1" + SURVEYBOX_PUBLIC_URL: http://localhost + SURVEYBOX_SECRET_KEY: ci-secret-key-ci-secret-key-ci-secret-key + SURVEYBOX_DB_HOST: postgres + SURVEYBOX_DB_PASSWORD: surveybox-ci + SURVEYBOX_DB_SSLMODE: disable + SURVEYBOX_DATA_DIR: /tmp/surveybox-data + steps: + - name: Werkzeuge (git, Node für Actions, PostgreSQL-Client 18) + run: | + set -eux + apt-get update + apt-get install -y --no-install-recommends git nodejs ca-certificates curl gnupg + install -d /usr/share/postgresql-common/pgdg + curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \ + https://www.postgresql.org/media/keys/ACCC4CF8.asc + echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt trixie-pgdg main" \ + > /etc/apt/sources.list.d/pgdg.list + apt-get update + apt-get install -y --no-install-recommends postgresql-client-18 + - uses: actions/checkout@v4 + - name: Abhängigkeiten + run: | + pip install --require-hashes --no-deps -r requirements.lock + pip install --require-hashes --no-deps -r requirements-dev.lock + - name: Auf PostgreSQL warten + run: | + for i in $(seq 1 30); do + pg_isready -h postgres -U surveybox -d surveybox && exit 0 + sleep 2 + done + exit 1 + - name: Bekannte Sicherheitslücken in Abhängigkeiten + run: pip-audit --strict --disable-pip --no-deps -r requirements.lock + - name: Ruff + run: ruff check . + - name: Mypy + run: mypy + - name: Übersetzungen kompilieren + run: pybabel compile --statistics -D messages -d surveybox/locale + - name: Modelle und Migrationen stimmen überein + run: | + python -m surveybox.cli migrate + alembic check + - name: Tests + run: pytest -q + + image: + if: github.event_name != 'schedule' + needs: checks + runs-on: ubuntu-latest + container: + image: docker:cli + steps: + - name: Werkzeuge + run: apk add --no-cache bash git nodejs coreutils + - uses: actions/checkout@v4 + - name: Docker erreichbar? + run: docker version && docker compose version + - name: Installations- und Update-Test + env: + # Ab dem ersten Release das zuletzt veröffentlichte Image eintragen. + OLD_IMAGE: "" + UPGRADE_TEST_SUBNET: 172.30.254.0/24 + run: ./scripts/upgrade-test.sh + - name: Image auf bekannte Lücken prüfen (Trivy) + env: + # Feste Version eintragen, sobald der Runner sie vorhält + TRIVY_IMAGE: aquasec/trivy:latest + run: | + docker build -q -t surveybox:scan . + docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$TRIVY_IMAGE" \ + image --exit-code 1 --severity HIGH,CRITICAL --ignore-unfixed --no-progress \ + --scanners vuln surveybox:scan + + audit: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + container: + image: python:3.13-slim-trixie + steps: + - name: Werkzeuge + run: apt-get update && apt-get install -y --no-install-recommends git nodejs ca-certificates + - uses: actions/checkout@v4 + - name: pip-audit + run: | + pip install --require-hashes --no-deps -r requirements-dev.lock + pip-audit --strict --disable-pip --no-deps -r requirements.lock diff --git a/.gitignore b/.gitignore index 36b13f1..4db7d0e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,176 +1,8 @@ -# ---> Python -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -#uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/latest/usage/project/#working-with-version-control -.pdm.toml -.pdm-python -.pdm-build/ - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments .env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy +__pycache__/ +*.pyc +*.mo +.pytest_cache/ .mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - -# Ruff stuff: .ruff_cache/ - -# PyPI configuration file -.pypirc - +.venv/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4266ea9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,78 @@ +# syntax=docker/dockerfile:1 +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# Ein Image für Web und Worker. Läuft ohne Root und mit schreibgeschütztem +# Dateisystem; beschreibbar sind nur /data (Volume) und /tmp (tmpfs). + +ARG PYTHON_VERSION=3.13 +ARG DEBIAN_SUITE=trixie + +# --------------------------------------------------------------------------- +# Bauen: Abhängigkeiten aus der Lock-Datei (nur mit passenden Hashes) +# --------------------------------------------------------------------------- +FROM python:${PYTHON_VERSION}-slim-${DEBIAN_SUITE} AS build + +ENV PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 + +WORKDIR /build +COPY requirements.lock ./ +RUN python -m venv /opt/venv \ + && /opt/venv/bin/pip install --require-hashes --no-deps --only-binary=:all: -r requirements.lock + +COPY surveybox ./surveybox +RUN /opt/venv/bin/pybabel compile --statistics -D messages -d surveybox/locale \ + && /opt/venv/bin/python -m compileall -q surveybox + +# --------------------------------------------------------------------------- +# Laufzeit +# --------------------------------------------------------------------------- +FROM python:${PYTHON_VERSION}-slim-${DEBIAN_SUITE} AS runtime + +ARG DEBIAN_SUITE +# PostgreSQL-Client-Werkzeuge für die Sicherung. Mehrere Hauptversionen, +# damit zu jedem unterstützten Server ein passendes pg_dump vorhanden ist. +ARG PG_CLIENT_VERSIONS="17 18 19" + +RUN set -eux; \ + apt-get update; \ + apt-get install -y --no-install-recommends ca-certificates curl gnupg; \ + install -d /usr/share/postgresql-common/pgdg; \ + curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \ + https://www.postgresql.org/media/keys/ACCC4CF8.asc; \ + echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${DEBIAN_SUITE}-pgdg main" \ + > /etc/apt/sources.list.d/pgdg.list; \ + apt-get update; \ + pkgs=""; for v in ${PG_CLIENT_VERSIONS}; do pkgs="$pkgs postgresql-client-$v"; done; \ + apt-get install -y --no-install-recommends $pkgs; \ + apt-get purge -y --auto-remove curl gnupg; \ + rm -rf /var/lib/apt/lists/* + +RUN groupadd --system --gid 10001 surveybox \ + && useradd --system --uid 10001 --gid surveybox --home-dir /nonexistent \ + --no-create-home --shell /usr/sbin/nologin surveybox \ + && install -d -o surveybox -g surveybox -m 0750 /data /data/backups + +COPY --from=build /opt/venv /opt/venv +COPY --from=build /build/surveybox /app/surveybox + +ENV PATH=/opt/venv/bin:$PATH \ + PYTHONPATH=/app \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + SURVEYBOX_DATA_DIR=/data + +WORKDIR /app +USER surveybox:surveybox +VOLUME ["/data"] +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=10s --start-period=300s --retries=3 \ + CMD ["python", "-m", "surveybox.cli", "healthcheck"] + +ENTRYPOINT ["python", "-m", "surveybox.cli"] +CMD ["web"] + +LABEL org.opencontainers.image.title="Surveybox" \ + org.opencontainers.image.description="Formulare und Abstimmungen, selbst gehostet" \ + org.opencontainers.image.licenses="AGPL-3.0-or-later" diff --git a/LICENSE b/LICENSE index 15ee351..be3f7b2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,235 +1,661 @@ -GNU AFFERO GENERAL PUBLIC LICENSE -Version 3, 19 November 2007 + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Copyright (C) 2007 Free Software Foundation, Inc. - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. Preamble -The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. -Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. -A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. -The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. -An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. -The precise terms and conditions for copying, distribution and modification follow. + The precise terms and conditions for copying, distribution and +modification follow. TERMS AND CONDITIONS -0. Definitions. + 0. Definitions. -"This License" refers to version 3 of the GNU Affero General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. -"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. -"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. -To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. -A "covered work" means either the unmodified Program or a work based on the Program. + A "covered work" means either the unmodified Program or a work based +on the Program. -To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. -To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. -An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. -1. Source Code. -The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + 1. Source Code. -A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. -The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. -The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those subprograms and other parts of the work. -The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". - - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or - - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. - -All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - -8. Termination. - -You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - -11. Patents. - -A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - -12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - -13. Remote Network Interaction; Use with the GNU General Public License. - -Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. - -14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs -If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. -To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. - surveybox - Copyright (C) 2026 marco.morath + + Copyright (C) - This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. -You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 733a02d..faace9f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,939 @@ -# surveybox +# Surveybox +Formulare und Abstimmungen in einer selbst gehosteten Anwendung. +Lizenz: AGPL-3.0-or-later. + +## Aufbau + +| Dienst | Aufgabe | +| --- | --- | +| `web` | Webserver (FastAPI). Bringt beim Start die Datenbank auf den aktuellen Stand. | +| `worker` | Hintergrundaufgaben, zurzeit die tägliche Sicherung. Startet erst, wenn `web` gesund ist. | +| `db` | PostgreSQL 18. Entfällt bei einem externen Datenbankserver. | + +`web` und `worker` nutzen dasselbe Image. Die Container laufen ohne Root, +mit schreibgeschütztem Dateisystem und ohne Linux-Capabilities. Beschreibbar +sind nur das Volume `/data` (Sicherungen, später Uploads) und `/tmp`. + +Alle Tabellen liegen im Datenbankschema `surveybox`. Surveybox kann daher +auch eine vorhandene Datenbank mitbenutzen, und Sicherung und +Wiederherstellung betreffen nie etwas anderes. + +## Erstinstallation + +Voraussetzungen: Docker Engine mit Compose v2.24 oder neuer, ein Reverse +Proxy mit TLS (z. B. Nginx Proxy Manager). + +```bash +git clone surveybox && cd surveybox + +# Einmalig: Lizenztext der AGPL ablegen +curl -fsSL -o LICENSE https://www.gnu.org/licenses/agpl-3.0.txt + +# Einmalig (und nach jeder Änderung an requirements*.in): +# Abhängigkeiten mit Versionen und Hashes festschreiben +./scripts/lock.sh + +cp .env.example .env +chmod 600 .env +# In .env eintragen: +# SURVEYBOX_SECRET_KEY → openssl rand -hex 32 +# SURVEYBOX_DB_PASSWORD → openssl rand -base64 32 +# SURVEYBOX_PUBLIC_URL → endgültige Adresse, später nicht mehr ändern +# SURVEYBOX_NET_SUBNET → freies Subnetz für dieses Stack-Netz (siehe unten) + +docker compose build +docker compose up -d +docker compose ps # web und worker müssen "healthy" melden +``` + +Im Reverse Proxy einen Host für die öffentliche Adresse anlegen, Ziel ist +`http://:8000`. Läuft der Proxy auf einem anderen Rechner oder selbst als +Container (z. B. Nginx Proxy Manager), in der `.env` `SURVEYBOX_HTTP_BIND` auf +die interne IP des Docker-Hosts setzen; `127.0.0.1` ist aus einem anderen +Container heraus nicht erreichbar. + +### Netz + +Das Docker-Netz des Stacks hat ein festes Subnetz aus `SURVEYBOX_NET_SUBNET`. +Ohne diese Angabe sucht Docker sich selbst einen Bereich aus, der mit dem LAN, +einem VPN oder anderen Stacks kollidieren kann. Das Subnetz muss frei sein und +sollte aus einem privaten Bereich stammen (`10.0.0.0/8`, `172.16.0.0/12`, +`192.168.0.0/16`); Gateway ist automatisch die erste Adresse. Jede Instanz +braucht ihr eigenes Subnetz. Wer das Subnetz eines bestehenden Stacks ändert, +muss ihn einmal mit `docker compose down` und `docker compose up -d` neu anlegen +(die Volumes bleiben erhalten). + +Tipp für den ganzen Host: In `/etc/docker/daemon.json` legt +`"default-address-pools"` fest, aus welchem Bereich Docker für alle Stacks ohne +eigene Angabe Subnetze vergibt. + +Prüfen: `https:///health/ready` antwortet mit `{"status":"ready"}`. + +### Erster Administrator + +```bash +docker compose exec web python -m surveybox.cli create-admin \ + --email admin@example.de --name "Vorname Nachname" +``` + +Der Befehl gibt einen einmaligen Link aus (7 Tage gültig). Darüber das +Passwort setzen, anmelden, dann verlangt Surveybox einen zweiten Faktor: +einen Passkey oder eine Authenticator-App. Für Administratoren ist der +zweite Faktor Pflicht. + +### Gruppen, Gruppenadministratoren und Gruppenersteller + +Gruppen lassen sich verschachteln (z. B. Gesamtwehr → Abteilung → Jugend). +Je Gruppe gibt es unter *Gruppen* zwei Rollen: + +- **Gruppenadministrator:** verwaltet die Gruppe und alle Untergruppen: + Konten anlegen (als Teilnehmer, mit Einladungslink), Mitglieder zuordnen, + Untergruppen anlegen, Gruppenrollen vergeben, Umfragen der Gruppen + verwalten. Andere Benutzer und Umfragen sieht er nicht. Er braucht einen + zweiten Faktor. Ohne Gruppenadministrator verwalten die + Instanzadministratoren die Gruppe. +- **Gruppenersteller:** legt Umfragen für die Gruppe und ihre Untergruppen an. + Jede solche Umfrage gehört zu einer Gruppe und ist zunächst für sie + freigegeben. Als Zugriff stehen eigene Gruppen und Mitglieder sowie Links + zur Wahl, nicht „alle angemeldeten Benutzer“. + +Rechte wirken nach unten, Freigaben auch: Eine Umfrage für eine Gruppe +erreicht die Mitglieder aller Untergruppen. Die instanzweite Rolle +*Ersteller* bleibt und darf Umfragen für alle anlegen. + +Jede Gruppe gibt außerdem an, für welche Benutzertypen sie passt. Beim +Anlegen eines Benutzers erscheinen nach der Wahl des Typs die passenden +Gruppen. + +### Passkeys + +Ein Passkey ersetzt Passwort und Code; bestätigt wird mit Fingerabdruck, +Gesicht oder Geräte-PIN. Er gilt nur für die Domain aus +`SURVEYBOX_PUBLIC_URL`. Surveybox speichert nur den öffentlichen Schlüssel. +Im Browser läuft dafür ein kleines Skript (`static/js/passkeys.js`); ohne +JavaScript funktioniert die Anmeldung mit Passwort weiterhin. + +### Zugang verloren + +Passwort vergessen oder Telefon mit der Authenticator-App verloren, und kein +Wiederherstellungscode zur Hand: + +```bash +docker compose exec web python -m surveybox.cli user-link \ + --email admin@example.de --reset-2fa +``` + +Das entfernt alle zweiten Faktoren (Authenticator-App und Passkeys) und gibt +einen Link zum Setzen eines neuen Passworts aus (24 Stunden gültig). Für andere Benutzer geht das auch in der +Verwaltung unter *Benutzer → Anmeldung zurücksetzen*. + +### Formulare + +Administratoren und Ersteller legen Formulare unter *Formulare* an. Ein +neues Formular ist ein Entwurf und für niemanden sonst sichtbar. Nach dem +Veröffentlichen gilt die Adresse `/f/`; die Kennung ist zufällig und +nicht erratbar. Wer ausfüllen darf, steht in den Einstellungen: + +| Zugriff | Anmeldung nötig | Hinweis | +|---|---|---| +| Alle angemeldeten Benutzer | ja | Erscheint auf deren Startseite | +| Ausgewählte Benutzer und Gruppen | ja | Erscheint auf deren Startseite; neue Gruppenmitglieder haben sofort Zugang | +| Alle mit dem Link | nein | Gäste ohne Konto | +| Link und Passwort | nein | Freischaltung gilt 12 Stunden; ein neues Passwort sperrt alte Freischaltungen | + +Bei anonymen Formularen speichert Surveybox die Antworten ohne Bezug zur +Person. Damit angemeldete Benutzer trotzdem nur einmal teilnehmen, merkt es +sich einen nicht umkehrbaren Prüfwert aus Formular und Benutzer. Die +Anonymität lässt sich nach der ersten Antwort nicht mehr umschalten; anonyme +Antworten können nicht nachträglich geändert werden. + +**Seiten.** Ein Seitenumbruch beginnt eine neue Seite. Teilnehmende blättern +mit *Weiter* und *Zurück*; jede Seite wird vor dem Weiterblättern geprüft. +Ohne JavaScript stehen alle Seiten untereinander. + +**Bedingungen.** Im Frage-Editor unter *Bedingung*: anzeigen oder +ausblenden, wenn alle (UND) oder mindestens eine (ODER) Regel zutrifft. Eine +Regel vergleicht eine frühere Frage: ist, ist nicht, enthält, enthält nicht, +größer, kleiner, beantwortet, nicht beantwortet. Bei einer Überschrift gilt +die Bedingung für den ganzen Abschnitt, bei einem Seitenumbruch für die ganze +Seite. Der Browser blendet sofort ein und aus; beim Absenden prüft der Server +alles noch einmal: Ausgeblendete Fragen sind nie Pflicht, und ihre Antworten +werden verworfen, auch wenn jemand sie trotzdem schickt. Regeln dürfen nur +auf frühere Fragen zeigen; Verschiebungen, die das brechen würden, lehnt der +Designer ab. Wird eine Frage gelöscht, entfallen Regeln, die auf sie zeigen. +Der Designer zeigt bei jeder Frage, wann sie erscheint und wie viele +Bedingungen sie steuert. + +**Abstimmung (Fragetyp).** Optionen sind Texte oder Termine (Datum, +optional Uhrzeit und Dauer). Je Option Ja/Nein oder Ja/Vielleicht/Nein. +Teilnehmende können weitere Optionen vorschlagen, wenn das eingeschaltet ist; +ein Vorschlag zählt als ihr Ja. Unter *Antworten* steht eine Ergebnistabelle, +die beste Option ist markiert; dort lassen sich Optionen bestätigen. Wer die +Ergebnisse sehen darf, steuert *Teilnehmende sehen die Ergebnisse* in den +Einstellungen. + +**Kalender.** In den Einstellungen: aus, Kalenderdatei (ICS) für +Teilnehmende oder zusätzlich ein Abo-Link für Kalenderprogramme. Enthalten +sind nur bestätigte Termine, ohne Angaben zu Personen. Der Abo-Link +funktioniert ohne Anmeldung; wer ihn kennt, sieht die Termine. Er lässt sich +erneuern, dann gilt der alte nicht mehr. + +**Teilnahme mit Plätzen (Fragetyp).** Ein Eintrag mit einem Häkchen +*Anmelden* und einer Platzzahl (leer: unbegrenzt), wahlweise mit Warteliste +und Ausblenden, wenn ausgebucht. Für mehrere Schichten oder Termine legt man +eine Fragengruppe an (siehe unten), darin je Eintrag eine Frage. Ältere +Fragen mit mehreren Optionen bleiben unverändert nutzbar und bearbeitbar. +Freie Plätze stehen auf der Seite und werden alle +20 Sekunden aktualisiert. Beim Absenden wird die Frage in der Datenbank +gesperrt; zwei gleichzeitige Buchungen können den letzten Platz nicht doppelt +belegen. Ist ein Platz inzwischen weg, bleibt das Formular ausgefüllt und +zeigt einen Hinweis. Wird ein Platz frei (Antwort geändert, mehr Plätze im +Designer), rückt die am längsten wartende Person nach. Eine Höchstzahl an +Plätzen je Person über alle Teilnahme-Felder steht in den Einstellungen. + +**Teilnehmer-Name (Fragetyp).** Vor- und Nachname (immer Pflicht) und +wahlweise eine E-Mail-Adresse (freiwillig, Pflicht oder gar nicht). Bei +Angemeldeten sind die Felder aus dem Konto vorausgefüllt. Die Frage ist als +personenbezogen markiert. Steht unter *E-Mail-Adresse von Gästen* „aus der +Antwort“, nimmt Surveybox auch die Adresse aus diesem Feld. + +**Eingetragene Namen anzeigen.** Für Schichtpläne und Anmeldelisten zeigt das +Formular auf Wunsch bei jedem Eintrag, wer sich schon eingetragen hat (auch +die Warteliste): mit vollem Namen oder datensparsam als Vorname und +Anfangsbuchstabe des Nachnamens (Einstellungen → Plätze, Kalender und +Kommentare). Der Name kommt aus dem Teilnehmer-Namen, sonst aus dem Konto; +Gäste ohne Namen erscheinen als „Gast“. E-Mail-Adressen erscheinen nie. Das +Formular weist oben darauf hin. Bei anonymen Formularen ist das abgeschaltet. + +**Fragengruppen.** Das Element *Fragengruppe* fasst gleichartige Fragen +zusammen: Teilnahme mit Plätzen, Ja/Nein, Bewertungsskala oder +Einfachauswahl. Zur Gruppe gehören alle direkt folgenden Fragen des gewählten +Typs; eine andere Frageart, eine Überschrift, ein Seitenumbruch oder eine +weitere Gruppe beendet sie. Damit die Tabelle stimmt, müssen die Fragen +zueinander passen (gleiche Skala, gleiche Ja/Nein-Texte, gleiche +Antwortmöglichkeiten ohne *Sonstiges*); eine unpassende Frage beendet die +Gruppe ebenfalls. Im Designer sind die Fragen der Gruppe eingerückt; +*Frage in die Gruppe einfügen* legt eine neue Frage direkt am Ende der Gruppe +an und übernimmt Skala bzw. Texte. Teilnehmende sehen die Gruppe als Tabelle +mit einer Zeile je Frage (z. B. Schicht | freie Plätze | Häkchen). +*Mindestens auswählen* (0 = freiwillig) und *Höchstens auswählbar* +(0 = unbegrenzt) gelten bei Teilnahme für die Anmeldungen und bei Ja/Nein für +die Zahl der „Ja“ in der Gruppe; ist die Höchstzahl erreicht, sperrt die Seite +weitere Häkchen, verbindlich prüft der Server beim Absenden. Blendet eine +Bedingung Zeilen aus, verlangt die Gruppe höchstens so viele Einträge, wie +sichtbar sind. + +Pflicht in Gruppen: Bei Teilnahme-Gruppen legt allein die Gruppe fest, ob und +wie viele Einträge gewählt werden müssen; *Antwort erforderlich* gibt es an den +einzelnen Einträgen dort nicht (eine Pflicht-Schicht hieße „genau diese +buchen“ und widerspräche der Höchstzahl). Bei Ja/Nein, Bewertung und +Einfachauswahl bleibt *Antwort erforderlich* je Zeile und heißt „diese Zeile +beantworten“; das verträgt sich mit der Höchstzahl, weil auch „Nein“ eine +Antwort ist. Eine Bedingung an der Gruppe gilt für alle ihre Fragen; einzelne +Fragen können zusätzlich eigene Bedingungen haben. Bilder und Videos einer +Frage erscheinen in der Tabelle nicht. + +**Kommentare.** Je Formular aus, moderiert (Standard) oder öffentlich, auf +Wunsch ohne Namen für andere (Verwalter sehen ihn). Unter *Kommentare* im +Designer schalten Verwalter frei oder löschen. Autoren ändern und löschen +eigene Kommentare; im moderierten Modus muss ein geänderter Kommentar neu +freigegeben werden. Reiner Text, höchstens zehn Kommentare je Person und +Stunde. + +Benachrichtigungen per E-Mail siehe *E-Mail und Benachrichtigungen*. + +**Zusammenfassung.** Unter *Antworten* zählt Surveybox jede Auswahl- und +Ja/Nein-Frage automatisch aus; bei Zahlen und Bewertungen stehen Summe und +Durchschnitt dabei. + +Auswertung mit Diagrammen und Export folgt in Phase 8. + +**Team und Vorlagen.** Unter *Team* nimmt der Eigentümer Benutzer oder +Gruppen auf: Mitbearbeitende ändern Fragen und Einstellungen und sehen die +Antworten, Auswertende sehen nur die Antworten. Team verwalten und löschen +darf nur der Eigentümer (und Administratoren). *Kopieren* legt einen Entwurf +mit allen Fragen, Einstellungen und Medien an, ohne Antworten. *Als Vorlage +speichern* legt eine Vorlage an; sie erscheint in der Formularliste und ist +für andere Ersteller erst sichtbar, wenn der Eigentümer sie freigibt. + +**Designer.** Fragen lassen sich am Griff ⠿ ziehen oder mit dem Griff im +Fokus per Pfeiltaste verschieben; ohne JavaScript bleiben die Pfeil-Knöpfe. +Im Optionen- und Termin-Editor fügt *Zeile hinzufügen* weitere leere Zeilen an. +Die *Live-Vorschau* öffnet sich in einem eigenen Fenster, zeigt das Formular +als Handy, Tablet oder Desktop und lädt sich nach jeder Änderung neu. + +### E-Mail und Benachrichtigungen + +**SMTP-Relay.** Unter *Verwaltung → E-Mail* (nicht in der `.env`): Server, +Port, STARTTLS oder TLS, Benutzer und Passwort, Absenderadresse und -name, +Antwort-an-Adresse. Unverschlüsselte Verbindungen gibt es nicht, das +Zertifikat wird immer geprüft. Das Passwort liegt verschlüsselt in der +Datenbank (Schlüssel aus `SURVEYBOX_SECRET_KEY`) und wird nicht wieder +angezeigt; ändert sich der Schlüssel, muss es neu eingegeben werden. +*Testnachricht jetzt senden* schickt sofort eine Mail und zeigt den Fehler +des Servers, falls es nicht klappt. Jede Änderung und jede Testmail steht im +Protokoll. + +Absender ist immer die Adresse des Relays (SPF, DKIM, DMARC). Antworten auf +Mails lenkt die Antwort-an-Adresse um: ein Standard in den E-Mail-Einstellungen, +je Formular in dessen Einstellungen überschreibbar. + +**Warteschlange.** Mails werden in derselben Transaktion eingetragen wie die +auslösende Aktion und vom Worker alle 30 Sekunden versendet. Ist kein Relay +eingerichtet, bleiben sie liegen; die Admin-Seite zeigt das an. Bei +vorübergehenden Fehlern versucht der Worker es nach 1, 5 und 15 Minuten und +nach 1, 4 und 12 Stunden erneut, eine endgültige Ablehnung (5xx) beendet die +Zustellung sofort. Der Inhalt einer Mail liegt verschlüsselt in der Datenbank +und wird nach dem Versand gelöscht (Links zum Setzen eines Passworts gehören +nicht in eine Sicherung). Das Zustellprotokoll (Art, Empfänger, Status, +letzter Fehler) bleibt 90 Tage. + +**Passwort vergessen.** Auf der Anmeldeseite. Die Seite antwortet immer gleich, +ob es ein Konto gibt oder nicht; Anfragen sind je IP und je Adresse begrenzt +(drei Links je Adresse und Stunde). Der Link gilt 24 Stunden und einmal; ein +eingerichteter zweiter Faktor bleibt aktiv. + +**Einladungen.** Beim Anlegen eines Benutzers ist *Einladung per E-Mail +senden* vorbelegt. Auf der Seite eines Benutzers lässt sich ein neuer Link +per Mail senden oder wie bisher anzeigen. + +**Benachrichtigungen.** Für angemeldete Benutzer und Gäste mit bestätigter +Adresse (Gäste nur die Ereignisse für Teilnehmende): + +| Ereignis | Empfänger | +|---|---| +| Teilnahme eingegangen (mit Link zum Formular) | Teilnehmende | +| Von der Warteliste nachgerückt | Teilnehmende | +| Termin einer Abstimmung bestätigt | Teilnehmende | +| Eigener Kommentar freigeschaltet | Kommentierende | +| Neuer Kommentar (wenn im Formular eingeschaltet) | Eigentümer und Mitbearbeitende | +| Eintrag ausgebucht (höchstens einmal je Tag und Eintrag) | Eigentümer | +| Enddatum erreicht | Eigentümer | +| Folge-Mail eines Formulars (siehe unten) | Teilnehmende | +| Gewählter Eintrag oder Termin gestrichen (Buchungen darauf entfallen) | Teilnehmende | +| Erinnerung vor dem Enddatum (je Formular einstellbar) | Eingeladene ohne Teilnahme | +| Tägliche Zusammenfassung neuer und geänderter Antworten (ab 7 Uhr) | Eigentümer und Mitbearbeitende | + +Alle sind voreingestellt an. Jede Person schaltet sie unter *Mein Konto → +Benachrichtigungen* einzeln ab. Jede Benachrichtigung enthält einen +Abmeldelink: für dieses Formular oder für diese Art von Benachrichtigung; das +Mailprogramm kann per `List-Unsubscribe` mit einem Klick abbestellen (RFC 8058). +Mails enthalten Links statt Antwortinhalten. Bei anonymen Formularen gibt es +keine Mails an Teilnehmende, weil die Mail Person und Teilnahme verbinden +würde. Ein Fehler beim Erzeugen einer Benachrichtigung verhindert nie die +eigentliche Aktion; er steht im Log des Dienstes. + +Mails gehen in der Sprache des Profils, bei „wie mein Browser“ in der +Standardsprache (`SURVEYBOX_DEFAULT_LANGUAGE`). + +**Erinnerung.** In den Formulareinstellungen unter *Teilnahme*: so viele Tage +vor dem Enddatum (1 bis 30) erinnert Surveybox alle Personen der Zugriffsliste +(Benutzer und Gruppen samt Untergruppen), die noch nicht teilgenommen haben; +nur bei Zugriff „Ausgewählte Benutzer und Gruppen“ und mit Enddatum. Jede +Person einmal je Enddatum. + +### Eigene Mail-Vorlagen + +*E-Mail → E-Mail-Vorlagen* (`/admin/mail/templates`): Jede Mail (Einladung, +Passwort zurücksetzen, Teilnahmebestätigungen, Warteliste, Erinnerung, Hinweise +an Verwalter usw.) kann je Sprache einen eigenen Betreff und Text bekommen. +Ohne eigenen Text gilt der Standardtext. Test-Mail und Folge-Mails haben ihre +eigenen Texte und sind nicht dabei. + +Eigene Vorlagen sind reiner Text mit Platzhaltern in geschweiften Klammern, +bewusst kein Jinja: Administratoren können darüber nichts ausführen. + +- `{greeting}`: Anrede („Hallo Erika,“ oder „Hallo,“) +- `{details}`: der Standardtext der Mail ohne Anrede, mit allem, was je nach + Lage dazugehört (Listen, Hinweise für Gäste, Bestätigungslinks) +- `{app}`: Name der Anwendung, `{title}`: Titel des Formulars +- je Mailart die einfachen Werte, etwa `{name}`, `{link}`, `{entry}`, + `{closes}`; die Seite listet sie mit Beschreibung auf + +Der Vorschlag beim ersten Bearbeiten ist `{greeting}` + `{details}`: eigener +Text davor oder danach, der Rest bleibt wie gewohnt. Wer `{details}` weglässt, +muss die Links der Mailart selbst einsetzen (z. B. `{link}`); unbekannte +Platzhalter werden abgelehnt. Die Seite zeigt eine Vorschau mit Beispieldaten +und den Standardtext daneben. Die Fußzeile mit Abmeldelink hängt Surveybox +immer an. Jede Änderung steht im Protokoll („E-Mail-Vorlage geändert“); die +Vorlagen liegen in der Datenbank und sind damit Teil der Sicherung. + +### Folge-Mails mit Dokumenten + +Im Designer unter *Folge-Mails*: je Formular bis zu 20 Mails mit Betreff, Text +(Platzhalter `{name}` und `{form}`) und bis zu 20 Dokumenten (PDF, +Office-Formate, Bilder, ZIP; Bilder werden ohne Metadaten neu berechnet). +Dokumente lassen sich schon beim Anlegen hochladen, weitere nach dem Speichern. +Zeitpunkt: direkt nach der Teilnahme, beim Schließen des Formulars, zu einem +festen Zeitpunkt oder nur von Hand. *Jetzt senden* zeigt die Zahl der +Empfänger, die die Mail noch nicht haben, und darüber eine Vorschau. + +Empfänger sind alle Teilnehmenden mit bekannter Adresse (Konto oder +bestätigte Gast-Adresse), wahlweise nur mit bestätigtem Platz. Jede Person +erhält jede Folge-Mail höchstens einmal, auch wenn sie ihre Antwort ändert; +Gäste bekommen eine Mail „direkt nach der Teilnahme“, sobald sie ihre Adresse +bestätigt haben. Bei anonymen Formularen gibt es keine Folge-Mails. + +Die Mail enthält Links statt Anhängen. Jeder Link ist persönlich, signiert und +läuft ab (Standard 90 Tage, einstellbar). Angemeldete finden die Dokumente +zusätzlich auf der Seite des Formulars, Gäste auf der Seite ihres persönlichen +Links. Surveybox zählt nur, wie oft ein Dokument heruntergeladen wurde, ohne +Bezug zur Person. *Kopieren* übernimmt Folge-Mails und Dokumente, aber nicht +den Versandstand. + +*Empfänger* zeigt je Folge-Mail alle Teilnehmenden mit ihrem Stand: erhalten +(mit Zeitpunkt und Zustand in der Mail-Warteschlange), noch nicht gesendet, +kein bestätigter Platz, Adresse nicht bestätigt, keine Adresse oder abbestellt. +Wer die Mail bekommen darf, hat daneben *Senden* bzw. *Erneut senden*. + +Bei „beim Schließen“, „zu einem festen Zeitpunkt“ und „nur von Hand“ fragt der +Editor, ob *später Hinzukommende* die Mail automatisch erhalten. Bei „Ja“ geht +sie an alle, die nach dem ersten Versand teilnehmen oder ihre Gast-Adresse +bestätigen. Bei „Nein“ sendet man sie bei Bedarf über die Empfängerseite. +Folge-Mails aus früheren Versionen fragen das beim nächsten Speichern ab. Gäste +erscheinen ohne Adresse, weil das Formular ihnen das zusagt; nur bei der +Einstellung „Adresse aus einer E-Mail-Frage“ steht die Adresse dabei. + +Folge-Mails erreichen Gäste nur mit bestätigter Adresse. Ist mindestens eine +Folge-Mail eingerichtet, die noch versendet werden kann, weist das Formular +Gäste darauf hin. Wer ohne Adresse absendet, bekommt den Hinweis einmal und +kann danach bewusst ohne Adresse teilnehmen. Die Eingangsbestätigung und die +Dankeseite sagen, dass die Informationen erst nach der Bestätigung ankommen. +Können Gäste gar keine Adresse angeben, zeigt die Übersicht der Folge-Mails +das an. + +### Gäste und persönliche Links + +Gäste nehmen ohne Konto teil (Zugriff per Link). Jede Gast-Antwort bekommt +einen persönlichen Link `/r/…` (256 Bit Zufall, in der Datenbank nur als +Hash). Damit sieht der Gast seine Antwort und kann sie ändern oder löschen, +solange das Formular Änderungen erlaubt und offen ist; beim Löschen werden +Plätze frei und Wartende rücken nach. Nach dem Absenden zeigt die Dankeseite +den Link einmal an. + +*E-Mail-Adresse von Gästen* in den Formulareinstellungen: nicht fragen, +optional, Pflicht (eigenes Feld am Ende des Formulars, das die Verwalter nicht +sehen) oder *Antwort auf die Frage „E-Mail-Adresse“ verwenden* (die erste Frage +dieses Typs; die Adresse ist dann Teil der Antwort, und ändert der Gast sie +über seinen Link, gilt die neue). Hat ein Formular eine E-Mail-Frage, steht +die Einstellung aber auf „nicht fragen“, weisen die Einstellungen darauf hin. +Mit Adresse bekommt der Gast eine Mail mit seinem Link und einem +Bestätigungslink. Benachrichtigungen (nachgerückt, Termin bestätigt) +gibt es erst nach der Bestätigung (Double-Opt-in); jede enthält einen +Abmeldelink. Unbestätigte Adressen löscht der Worker nach sieben Tagen; die +Antwort bleibt, der Link auch. Die Adresse sehen die Verwalter nicht; brauchen +sie Kontaktdaten, gehört eine Frage *E-Mail-Adresse* ins Formular. Bei +anonymen Formularen gibt es weder Adresse noch Link. + +*Meine Links anfordern* (`/links`): Der Gast gibt seine Adresse ein und +erhält alle Links neu; die alten werden ungültig. Die Seite antwortet immer +gleich. Falsche Links (`/r/…`) und Anfragen sind je IP und Adresse begrenzt. + +Surveybox selbst protokolliert keine Aufrufe (Zugriffslog aus). Schreibt der +Reverse-Proxy ein Zugriffslog, stehen persönliche Links (`/r/`), Einladungen +(`/setup/`) und Registrierungslinks (`/register/`) darin; dort am besten +kürzen oder ausschließen. + +### Selbstregistrierung + +Unter *Verwaltung → Einstellungen → Selbstregistrierung*: + +- *Aus*: Konten legen nur Administratoren an. +- *Gäste* (Standard): wer als Gast seine Adresse bestätigt hat. Die + Bestätigungsseite und die Seite des persönlichen Links bieten *Konto + anlegen* an. +- *Offen*: jede Person; die Anmeldeseite zeigt *Konto anlegen*. + +Ablauf: Name und Adresse eingeben, Mail mit Link (24 Stunden), Passwort +setzen. Das Konto entsteht erst dann; unbestätigte Anfragen hinterlassen +nichts in der Datenbank. Neue Konten sind Teilnehmer. Gast-Antworten mit +derselben bestätigten Adresse gehen auf das Konto über (auch wenn ein +Administrator das Konto anlegt und die Person die Einladung annimmt); die +einzelnen Links entfallen dann. Gibt es schon ein Konto, bekommt die Adresse +einen Hinweis mit Link zur Anmeldung statt eines zweiten Kontos. + +### Auswertung und Export + +Die Seite *Antworten* eines Formulars zeigt: + +- **Filter** nach Eingangszeitraum und nach einer Antwort (Ja/Nein, Auswahl, + Bewertung, Teilnahme). Übersicht, Listen und Export richten sich danach; der + Filter steht in der Adresse und lässt sich verlinken. +- **Übersicht je Frage:** Balken für Auswahl, Ja/Nein und Bewertung, Summe und + Durchschnitt für Zahlen, Matrix für Abstimmungen, Freitexte als Liste (die + ersten 50), bei Teilnahme-Feldern eine Teilnehmerliste je Eintrag mit + Warteliste. Verwalter sehen dort immer den vollen Namen (Teilnehmer-Name, + sonst Kontoname). +- **Alle Antworten im Überblick:** dieselbe Tabelle wie im Export direkt auf + der Seite (die Nummer öffnet die einzelne Antwort). Bei Zugriff „Ausgewählte + Benutzer und Gruppen“ stehen auch die Eingeladenen ohne Antwort darin + (Spalte *Rückmeldung*: eingegangen / noch keine Rückmeldung, Gruppen samt + Untergruppen); „Nur fehlende Rückmeldungen“ zeigt nur diese. Bei anonymen + Formularen bleibt offen, wer teilgenommen hat. Mit aktivem Filter erscheinen + nur passende Antworten. +- **Einzelantworten** zum Blättern (vor und zurück). Wer das Formular + bearbeiten darf, kann eine Antwort löschen; Plätze werden frei, die + Warteliste rückt nach. Die Löschung steht im Protokoll und im Löschjournal. +- **Antwort ändern** (wer das Formular bearbeiten darf), etwa wenn jemand + telefonisch um eine Änderung bittet: dasselbe Formular wie beim Ausfüllen, + dazu ein **Vermerk** als Pflichtfeld (warum, auf wessen Wunsch). Gespeichert + werden Vermerk, Zeitpunkt, wer geändert hat und welche Fragen sich geändert + haben; die Liste steht unter der Antwort („Änderungen durch Verwalter“). + Plätze werden neu vergeben, die Warteliste rückt nach. Die Änderung steht im + Protokoll (ohne Inhalte). Vermerke gehören zur Datenauskunft der Person + (ohne Namen der Verwalter) und werden beim Anonymisieren gelöscht, mit der + Antwort ohnehin. +- **Teilnehmerlisten als PDF** (nur mit Teilnahme-Feldern, nicht bei anonymen + Formularen), etwa zum Abzeichnen vor Ort: je Eintrag eines Teilnahme-Feldes + eine Tabelle mit Nummer und Name, freie Plätze als leere Zeilen, darunter + die Warteliste. Wahlweise mit Spalte für Unterschriften und jeder + Eintrag auf einer neuen Seite. A4 hoch, Ränder wie beim XLSX-Export, oben + Logo und Titel, unten „Seite X von Y“, Überschriftenzeile auf jeder Seite. + Richtet sich nach dem Filter und steht im Protokoll (Format `lists`). + Schrift ist Bitstream Vera aus reportlab (eingebettet); Zeichen, die sie + nicht kennt, erscheinen als Grundbuchstabe (ř → r). +- **Export** als XLSX, ODS (OpenDocument), PDF oder CSV: eine Zeile je Antwort, + eine Spalte je Frage, also dieselbe Tabelle wie in der Übersicht + (Teilnehmer-Name in drei Spalten, Abstimmungen eine Spalte je Option, Plätze + mit Hinweis auf die Warteliste). „Personenbezogene Daten weglassen“ lässt + personenbezogene Fragen und den Kontonamen weg. XLSX und ODS haben ein + einziges Blatt: oben Logo, Titel, Filter und Zeitpunkt, darunter die + Tabelle mit Autofilter. Das PDF zeigt dieselbe Tabelle im Querformat; die + Spalten werden nach Inhalt verteilt, lange Texte umbrochen, bei vielen + Spalten wird die Schrift kleiner. Die CSV-Datei verwendet + Semikolons und UTF-8 mit BOM. Zellen, die mit `=`, `+`, `-` oder `@` + beginnen, werden in der CSV-Datei entschärft. Adressen von Gästen, die das + Formular verborgen hält, erscheinen nie. Eingeladene ohne Antwort stehen + auch im Export (nicht ohne personenbezogene Daten). Jeder Export steht im Protokoll + (Format, Anzahl, mit oder ohne personenbezogene Daten). + +Die PDF-Dateien erzeugt das Paket `reportlab` (neu in `requirements.in`; +nach dem Update einmal `scripts/lock.sh` ausführen und beide `.lock`-Dateien +einchecken). Fehlt es im Image, zeigt die Seite statt des Knopfes einen +Hinweis. XLSX und ODS schreibt Surveybox selbst (ohne zusätzliches Paket). Beide +sind für den Druck eingerichtet: A4 quer, Ränder 2 cm oben, 1,2 cm unten, je 1 cm +links und rechts, alle Spalten auf einer Seitenbreite (Höhe beliebig), +Überschriftenzeile (fett, 20 % grau) auf jeder Seite wiederholt und unten +zentriert „Seite X von Y“. + +### Ergebnisse für Teilnehmende + +In den Einstellungen des Formulars legt „Teilnehmende sehen die Ergebnisse“ +fest, ob und wann: *nie*, *nach der eigenen Teilnahme* oder *nach dem Ende +des Formulars*. Die Ergebnisseite (`/f//results`, mit persönlichem +Link `/r//results`) zeigt nur Zahlen: Balken, Summen, Durchschnitte, +Abstimmungen mit bestätigten Terminen, Reihenfolgen und die Belegung von +Teilnahme-Feldern. Nie gezeigt werden Freitexte, Dateien und als +personenbezogen markierte Fragen; Namen bei Einträgen nur, wenn das Formular +sie ohnehin allen zeigt. Der Knopf „Ergebnisse ansehen“ erscheint nach dem +Absenden, auf der Seite eines beendeten Formulars und beim persönlichen Link. + +Wer teilgenommen hat, erkennt Surveybox am Konto oder am persönlichen Link. +Gäste ohne Link erhalten nach dem Absenden ein Cookie +(`surveybox_done_…`, eine Woche, nur für dieses Formular, enthält nur eine +Prüfsumme über das Formular und nichts zur Person). Bei sehr wenigen Antworten +lassen die Zahlen Rückschlüsse auf einzelne Personen zu; darauf weist die +Einstellung hin. + +### Löschfristen + +Antworten bleiben nicht unbegrenzt gespeichert. Die Frist beginnt mit dem Ende +des Formulars: dem Enddatum oder dem Zeitpunkt, an dem es von Hand geschlossen +wurde. Ein Formular ohne Ende (offen ohne Enddatum, Entwurf, Vorlage) läuft nie +ab; wird ein geschlossenes Formular wieder geöffnet, ruht die Frist. + +- Dauer: je Formular in den Einstellungen; leer heißt Standard der Instanz + (2 Jahre, unter *Administration → Einstellungen → Aufbewahrung der Antworten*). +- Danach, je nach Einstellung „Wenn die Löschfrist abläuft oder eine Person + gelöscht wird“: + - *anonymisieren*: Konto, Gast-Adresse und persönlicher Link werden von der + Antwort getrennt, Antworten auf personenbezogene Fragen (und deren Dateien) + gelöscht; der Rest bleibt für das Ergebnis. + - *löschen*: die Antworten verschwinden vollständig. + - In beiden Fällen entfallen die Merker gegen doppelte Teilnahme und der + Versandstand der Folge-Mails. Kommentare verlieren ihre Autorenangabe bzw. + werden beim Löschen mitgelöscht. +- Der Eigentümer bekommt 14 Tage vorher eine Mail. Kommt der Hinweis später + (kurze Frist, oder bei bestehenden Formularen direkt nach dem Update), wird + frühestens sieben Tage nach dem Hinweis gelöscht. +- Einstellungen und Antwortenseite zeigen das geplante Datum. Das Protokoll + vermerkt jede Anwendung (Formular, Art, Anzahl), ohne Inhalte. +- Gast-Adressen ohne Antwort werden nach sieben Tagen gelöscht. + +Der Worker prüft die Fristen stündlich beim Aufräumen. + +### Personen löschen + +- *Eigenes Konto*: unter *Konto → Konto löschen*. Nur innerhalb von zehn + Minuten nach der Anmeldung; sonst meldet die Seite ab und fragt erneut nach + der Anmeldung. Für jedes eigene Formular wählt man, ob es an eine Person + übergeht, die es mitbearbeitet, oder mit allen Antworten gelöscht wird. +- *Administrator*: in der Benutzerverwaltung bei der Person, ebenfalls nur kurz + nach der Anmeldung. Die Formulare der Person gehen gesammelt an einen + Ersteller oder Administrator oder werden gelöscht. Der letzte aktive + Administrator lässt sich nicht löschen. +- *Gäste*: auf *Meine Links* unter „Meine Daten löschen“. Ein Link per Mail + (24 Stunden gültig) führt zu einer Übersicht; erst die Bestätigung dort + löscht alles, was an der Adresse hängt. Unbekannte Adressen bekommen + dieselbe Antwort, aber keine Mail. + +Vor jeder Löschung zeigt eine Übersicht, was geschieht: + +| Daten | Verhalten | +| --- | --- | +| Konto, Passkeys, Sitzungen, Einstellungen, Mailprotokoll | gelöscht | +| Gast-Adresse, Bestätigung, Mailprotokoll | gelöscht | +| Antworten | je Formular anonymisiert oder gelöscht (wie bei der Löschfrist) | +| Plätze in laufenden Formularen | freigegeben, die Warteliste rückt nach | +| Plätze in beendeten Formularen | bleiben beim Anonymisieren als anonyme Teilnahme gezählt | +| Kommentare eines Kontos | bleiben, Autor „Gelöschter Benutzer“ | +| Protokoll | nur „Gelöschtes Konto Nr. …“, ohne Namen oder Adresse | + +Gelöschte Daten bleiben bis zur Rotation in den Sicherungen. Jede Löschung +steht deshalb zusätzlich im Löschjournal `/data/erasures.jsonl` (nur Kennungen). +Die Wiederherstellung (`… web restore …`, siehe Sicherungen) legt eine Marke ab; sobald Web und Worker wieder laufen +und das Schema aktuell ist, wendet der Worker alle Löschungen seit dem +Zeitpunkt der Sicherung erneut an. Auch angewendete Löschfristen und über den +persönlichen Link gelöschte Antworten stehen im Journal. Einträge, die älter +als die älteste vorhandene Sicherung sind, entfernt der Worker. Wer `/data` +mit einem eigenen Werkzeug zurückspielt, spielt auch das Journal zurück; dann +greift dieser Schutz nicht. + +### Datenexport für Betroffene + +Auskunft (Art. 15 DSGVO) und Datenübertragbarkeit (Art. 20) als JSON-Datei: + +- *Angemeldete*: *Konto → Meine Daten herunterladen*: Konto, Passkeys (nur + Namen und Daten), Sitzungen, Benachrichtigungseinstellungen, Gruppen, + Antworten mit Plätzen und Vermerken, Kommentare, eigene Formulare, erhaltene Folge-Mails, + Mailprotokoll (ohne Inhalte) und die eigenen Einträge im Protokoll. +- *Gäste*: auf *Meine Links* unter „Meine Daten herunterladen“ per Mail-Link + (24 Stunden gültig): Adresse, Antworten, Folge-Mails, Mailprotokoll. Auf der + Seite des persönlichen Links lässt sich außerdem diese eine Antwort + herunterladen, auch ohne Adresse. +- *Administratoren*: in der Benutzerverwaltung bei der Person („Daten + exportieren“) und für Gast-Adressen unter der Benutzerliste. + +Hochgeladene Dateien stehen mit Name und Größe in der Datei; ihr Inhalt bleibt +über die Antwort abrufbar. Antworten in anonymen Formularen und anonymisierte +Antworten lassen sich niemandem zuordnen und fehlen deshalb. Jeder Export +steht ohne Inhalte im Protokoll. Die Datei wird nie zwischengespeichert +(`Cache-Control: no-store`). + +### Gestaltung (White-Labeling) + +*Administration → Einstellungen → Gestaltung* (`/admin/appearance`): + +- **Logo:** Ohne eigenes Logo zeigt Surveybox sein eigenes Zeichen (eine Box mit + Haken) in der Kopfzeile und als Favicon. Ein eigenes Logo (PNG, JPEG oder WebP, + höchstens 5 MB; kein SVG, weil SVG-Dateien Skripte enthalten können) wird wie + jedes Bild neu berechnet und ohne Metadaten in drei Fassungen unter + `/data/branding` abgelegt: Logo für Kopfzeile und Exporte, Favicon (64 x 64) + und Icon für den Startbildschirm (180 x 180). Leere Ränder werden + abgeschnitten. Zusätzlich lässt sich ein **Logo für die dunkle Darstellung** + hochladen (z. B. mit heller Schrift). +- **Name der Anwendung:** ersetzt „Surveybox“ in Kopfzeile, Browser-Tab, + Startseite und in E-Mails (Betreff und Fußzeile). Der Absendername der Mails + steht weiter unter *E-Mail*. +- **Darstellung:** automatisch (wie im Browser), immer hell oder immer dunkel. +- **Farben:** Primärfarbe (Knöpfe, Links), Akzentfarbe (Balken, Sterne, + Auswahl, Hinweiskästen), Hintergrund und Text, jeweils mit „Standard“. Die + Farben gelten für die helle Darstellung; die dunkle leitet lesbare Töne der + Primär- und Akzentfarbe ab. Hinweise und Linien werden aus Text und + Hintergrund berechnet. Der Kontrast wird nach WCAG 2.1 (AA) geprüft; ist er + zu gering, warnt die Seite, speichert aber trotzdem. +- **Schrift:** eigene Schriftdatei (WOFF2, WOFF, TTF oder OTF, höchstens 2 MB), + ausgeliefert vom eigenen Server. Die Datei wird an ihren ersten Bytes geprüft. +- **Startseite:** eigener Text für alle Besucher. +- **Fußzeile:** eigener Text, Links zu Impressum und Datenschutzerklärung (nur + `https://`), auf jeder Seite, auch in eingebetteten Formularen. Dahinter steht + immer „Surveybox “; mit `SURVEYBOX_SOURCE_URL` wird daraus ein Link + zum Quellcode (AGPL: Wer eine geänderte Fassung als Dienst anbietet, muss den + Nutzern den Quellcode zugänglich machen). +- **Eigenes CSS** für Sonderfälle (bis 20 000 Zeichen), nach allen anderen + Stilen geladen. Die Content-Security-Policy bleibt streng: fremde Adressen für + Bilder oder Schriften blockiert der Browser. +- **Export und Import:** alles samt Logos und Schrift als eine JSON-Datei, etwa + für eine zweite Instanz. Beim Import werden Eingaben und Bilder wie beim + Hochladen geprüft; Logo und Schrift werden nur ersetzt, wenn die Datei sie + enthält. „Name, Farben und Texte zurücksetzen“ stellt den Standard wieder her. + +Farben, Schrift und eigenes CSS liefert `/branding/theme.css` aus, nach +`app.css` geladen und über die Version im Link zwischengespeichert. Alle Texte +landen escaped im HTML; nichts davon wird als Skript ausgeführt. Jede Änderung +steht im Protokoll („Gestaltung geändert“). Der Stand liegt in +`/data/branding` (Logo, Schrift, `appearance.json`) im Volume, nicht in der +Datenbanksicherung: Wer `/data` nicht als Ganzes sichert, legt den Export der +Gestaltung zu den Sicherungen. + +### Einbinden in die Nextcloud + +Surveybox lässt sich als Menüeintrag in die Nextcloud einbinden (App +„External sites“), ohne Single Sign-on: Man meldet sich im Rahmen einmal bei +Surveybox an. + +1. **Gleiche Domain:** Surveybox und Nextcloud müssen unter derselben + Hauptdomain laufen, z. B. `umfrage.example.de` neben `cloud.example.de`. + Sonst gelten die Cookies im Rahmen als fremd, und Browser blockieren sie: + Anmelden und Absenden gehen dann nicht. +2. **Einbetten erlauben:** in der `.env` + `SURVEYBOX_FRAME_ANCESTORS=https://cloud.example.de` (nur `https`, mehrere + durch Leerzeichen getrennt), dann `docker compose up -d`. Ohne Eintrag ist + Einbetten verboten (`frame-ancestors 'none'`, `X-Frame-Options: DENY`). Mit + Eintrag erlaubt die Content-Security-Policy genau diese Seiten; + `X-Frame-Options` entfällt dann, weil es nur eine Adresse kennt. +3. **Nextcloud:** App „External sites“ installieren, unter *Verwaltung → + Externe Seiten* einen Eintrag anlegen: Name z. B. „Umfragen“, Adresse + `https://umfrage.example.de/?embed=1`, Symbol nach Wahl; die Option zum + Umleiten (Öffnen außerhalb der Nextcloud) bleibt aus. Die App erlaubt die + Adresse in der Content-Security-Policy der Nextcloud selbst. + +Im Rahmen zeigt Surveybox eine **kompakte Darstellung**: schmale Leiste mit +Navigation und Sprachen, ohne Logo und Fußzeile (Impressum und +Datenschutzerklärung bleiben als Links unten), weniger Abstände. Erkannt wird +der Rahmen am Browser (`Sec-Fetch-Dest: iframe`); `?embed=1` schaltet die +Darstellung zusätzlich fest ein (Cookie `surveybox_embed`), `?embed=0` wieder +aus. „Neuer Tab ↗“ öffnet die aktuelle Seite außerhalb des Rahmens. + +Einschränkungen: **Passkeys** funktionieren im Rahmen nicht, weil die +Nextcloud dem Rahmen die nötige Berechtigung nicht gibt; im Rahmen mit Passwort +(und Authenticator-App) anmelden oder über „Neuer Tab“. Einzelne Formulare +lassen sich auf freigegebenen Seiten derselben Domain per +` + + {% elif info %} +
+

{{ _('This video is provided by %(provider)s. When you load it, data such as your IP address is sent to %(provider)s.', provider=info.provider) }}

+

+ + {{ _('Watch at %(provider)s', provider=info.provider) }} +

+
+ {% endif %} +{% endif %} +{% endmacro %} + +{% macro option_tiles(q, name, vals, multiple, media_base, required) %} +
+ {% for o in q.config.options %} + + {% endfor %} +
+{% endmacro %} + +{% macro question_block(q, values, errors, errors_text, media_base='', embed_policy=none, files={}, accept_for=none, places={}, own_status={}) %} +{{ question_media(q, media_base, embed_policy) }} +{% set name = 'q' ~ q.id %} +{% set err = errors.get(q.id) %} +{% set val = (values.get(name) or [''])[0] %} +{% set vals = values.get(name) or [] %} +{% set other = (values.get(name ~ '_other') or [''])[0] %} +{% set cfg = q.config %} +{% if q.type == 'heading' %} +

{{ q.label }}

+{% elif q.type == 'info' %} +
{{ q.label }}
+{% elif q.type == 'page_break' %} +
+ {% if q.label %}

{{ q.label }}

{% endif %} +{% elif q.type in ('yes_no', 'single_choice', 'multiple_choice', 'ranking', 'rating', 'file_upload', 'slots', 'poll') and not (q.type == 'single_choice' and cfg.display == 'dropdown') %} +
+ {{ q.label }}{{ required_mark(q) }} + {{ help_and_error(name, q, err, errors_text) }} + {% if q.type == 'yes_no' %} +
+ + +
+ {% elif q.type == 'single_choice' and cfg.display == 'images' %} + {{ option_tiles(q, name, [val], false, media_base, q.required) }} + {% if cfg.allow_other %} +
+ + +
+ {% endif %} + {% elif q.type == 'single_choice' %} +
+ {% for o in cfg.options %} + + {% endfor %} + {% if cfg.allow_other %} + + + {% endif %} +
+ {% elif q.type == 'multiple_choice' and cfg.display == 'images' %} + {{ option_tiles(q, name, vals, true, media_base, false) }} + {% if cfg.allow_other %} +
+ + +
+ {% endif %} + {% if cfg.min_select or cfg.max_select %} +

+ {% if cfg.min_select and cfg.max_select %}{{ _('Choose between %(a)s and %(b)s options.', a=cfg.min_select, b=cfg.max_select) }} + {% elif cfg.min_select %}{{ _('Choose at least %(a)s options.', a=cfg.min_select) }} + {% else %}{{ _('Choose at most %(b)s options.', b=cfg.max_select) }}{% endif %} +

+ {% endif %} + {% elif q.type == 'multiple_choice' %} +
+ {% for o in cfg.options %} + + {% endfor %} + {% if cfg.allow_other %} + + + {% endif %} +
+ {% if cfg.min_select or cfg.max_select %} +

+ {% if cfg.min_select and cfg.max_select %}{{ _('Choose between %(a)s and %(b)s options.', a=cfg.min_select, b=cfg.max_select) }} + {% elif cfg.min_select %}{{ _('Choose at least %(a)s options.', a=cfg.min_select) }} + {% else %}{{ _('Choose at most %(b)s options.', b=cfg.max_select) }}{% endif %} +

+ {% endif %} + {% elif q.type == 'ranking' %} +

{{ _('Give each option a place: 1 is your first choice.') }}

+
+ {% set n = cfg.options | length %} + {% for o in cfg.options %} + {% set rank_name = name ~ '_rank_' ~ o.id %} + {% set rank_val = (values.get(rank_name) or [''])[0] %} + + {% endfor %} +
+ {% elif q.type == 'slots' and cfg.single %} + {% set a = places.get(q.id, {}).get('single') %} + {% set st = own_status.get((q.id, 'single')) %} + {% set mine = 'single' in vals %} + {% set full = a is not none and a.full %} +
+ +
+ {% elif q.type == 'slots' %} + {% set avail = places.get(q.id, {}) %} +
+ {% for o in cfg.options %} + {% set a = avail.get(o.id) %} + {% set mine = o.id in vals %} + {% set st = own_status.get((q.id, o.id)) %} + {% set full = a is not none and a.full %} + {% if not (full and cfg.hide_full and not mine) %} + + {% endif %} + {% endfor %} +
+ {% elif q.type == 'poll' %} + {% set allowed_votes = ['yes', 'maybe', 'no'] if cfg.answers == 'ynm' else ['yes', 'no'] %} + {% set vote_names = {'yes': _('Yes'), 'maybe': _('Maybe'), 'no': _('No')} %} +
+ {% for o in cfg.options %} + {% set vname = name ~ '_' ~ o.id %} + {% set cur = (values.get(vname) or [''])[0] %} +
+ {{ option_text(o) }}{% if o.proposed %} {{ _('proposed') }}{% endif %}{% if o.id in (cfg.confirmed or []) %} {{ _('confirmed') }}{% endif %} + + {% for v in allowed_votes %}{% endfor %} + +
+ {% endfor %} +
+ {% if cfg.allow_proposals %} +
+ {% if cfg.mode == 'dates' %} + + + {% else %} + + {% endif %} +

{{ _('Your proposal is added for everyone and counts as your “yes”.') }}

+
+ {% endif %} + {% elif q.type == 'file_upload' %} + {% set kept = values.get(name ~ '_keep') or [] %} + {% set kept_files = files.get(q.id) or [] %} + {% if kept %} +
    + {% for token in kept %} + {% set f = kept_files[loop.index0] if loop.index0 < kept_files | length else none %} +
  • + {% endfor %} +
+

{{ _('Uncheck a file to remove it.') }}

+ {% endif %} + 1 %}multiple{% endif %} {% if accept_for %}accept="{{ accept_for(q) }}"{% endif %} {% if q.required and not kept %}required{% endif %} aria-label="{{ q.label }}"> +

+ {{ ngettext('At most %(num)d file', 'At most %(num)d files', cfg.max_files or 1) }}, {{ _('each at most %(mb)s MB.', mb=cfg.max_mb or 10) }} +

+ {% elif q.type == 'rating' %} +
+ {% if cfg.label_min %}{{ cfg.label_min }}{% endif %} + {% for i in range(1, (cfg.scale_max or 5) + 1) %} + + {% endfor %} + {% if cfg.label_max %}{{ cfg.label_max }}{% endif %} +
+ {% endif %} +
+{% elif q.type == 'participant_name' %} + {# Vorbelegung für Angemeldete: Name und Adresse aus dem Konto #} + {% set acct_parts = (user.display_name.rsplit(' ', 1) if user and user.display_name else []) %} + {% set first = (values.get(name ~ '_first') or [acct_parts[0] if acct_parts | length == 2 else ''])[0] %} + {% set last = (values.get(name ~ '_last') or [acct_parts[1] if acct_parts | length == 2 else ''])[0] %} + {% set email = (values.get(name ~ '_email') or [user.email if user and not values else ''])[0] %} + {% set email_mode = cfg.email or 'optional' %} +
+ {{ q.label }}{{ required_mark(q) }} + {{ help_and_error(name, q, err, errors_text) }} +
+ + + {% if email_mode != 'off' %} + + {% endif %} +
+
+{% else %} +
+ + {{ help_and_error(name, q, err, errors_text) }} + {% set common %}id="{{ name }}-input" name="{{ name }}"{{ describedby(name, q, err) }}{% if q.required %} required{% endif %}{% if err %} aria-invalid="true"{% endif %}{% endset %} + {% if q.type == 'short_text' %} + + {% elif q.type == 'long_text' %} + + {% elif q.type == 'email' %} + + {% elif q.type == 'phone' %} + + {% elif q.type == 'number' %} +
+ + {% if cfg.unit %}{{ cfg.unit }}{% endif %} +
+ {% elif q.type == 'date' %} + + {% elif q.type == 'time' %} + + {% elif q.type == 'datetime' %} + + {% elif q.type == 'single_choice' %} + + {% if cfg.allow_other %} + + {% endif %} + {% endif %} +
+{% endif %} +{% endmacro %} + +{# Eintrag "Teilnahme mit Plätzen" mit genau einer Option: Zustand als Text #} +{# Wer sich schon eingetragen hat (nur wenn das Formular Namen zeigt) #} +{% macro slot_names_line(q, option_id) -%} + {%- set by_q = (slot_names.get(q.id) if slot_names is defined and slot_names else none) or {} -%} + {%- set who = by_q.get(option_id) -%} + {%- if who and (who.confirmed or who.waiting) -%} + + {%- if who.confirmed %}{{ _('Signed up:') }} {{ who.confirmed | join(', ') }}{% endif -%} + {%- if who.waiting %}{% if who.confirmed %} · {% endif %}{{ _('Waiting list:') }} {{ who.waiting | join(', ') }}{% endif -%} + + {%- endif -%} +{%- endmacro %} + +{% macro slot_state(a, st, full, waitlist) -%} + {%- if st == 'waiting' %}{{ _('you are on the waiting list') }} + {%- elif st == 'confirmed' %}{{ _('booked for you') }} + {%- elif a is not none and a.capacity %} + {%- if full %}{% if waitlist %}{{ _('booked up, waiting list possible') }}{% else %}{{ _('booked up') }}{% endif %} + {%- else %}{{ ngettext('%(num)d place left', '%(num)d places left', a.free) }}{% endif %} + {%- endif -%} +{%- endmacro %} + +{% macro cond_attr(q) %}{% if q.config.get('condition') %} data-cond='{{ q.config.condition | tojson }}'{% endif %}{% endmacro %} + +{# Fragengruppe: eine Tabellenzeile je Frage. Die Prüfung macht der Server. #} +{% macro group_block(g, members, values, errors, errors_text, places={}, own_status={}) %} +{% set gname = 'q' ~ g.id %} +{% set gerr = errors.get(g.id) %} +{% set kind = g.config.get('member_type') or 'slots' %} +{% set counting = kind in ('slots', 'yes_no') %} +{% set limit = (g.config.get('max_select') or 0) if counting else 0 %} +{% set least = (g.config.get('min_select') or 0) if counting else 0 %} +{% set group_rules = kind == 'slots' %} +
+ {{ g.label }}{% if least %}{% endif %} + {{ help_and_error(gname, g, gerr, errors_text) }} + {% if limit or least %} +

+ {%- if kind == 'yes_no' %} + {%- if least and limit %}{{ _('Between %(a)s and %(b)s “Yes” in this group.', a=least, b=limit) }} + {%- elif least %}{{ ngettext('At least %(num)d “Yes” in this group.', 'At least %(num)d “Yes” in this group.', least) }} + {%- else %}{{ ngettext('At most %(num)d “Yes” in this group.', 'At most %(num)d “Yes” in this group.', limit) }}{% endif %} + {%- else %} + {%- if least and limit and least == limit %}{{ ngettext('Please choose exactly %(num)d entry here.', 'Please choose exactly %(num)d entries here.', least) }} + {%- elif least and limit %}{{ _('Please choose between %(a)s and %(b)s entries here.', a=least, b=limit) }} + {%- elif least %}{{ ngettext('Please choose at least %(num)d entry here.', 'Please choose at least %(num)d entries here.', least) }} + {%- else %}{{ ngettext('You can choose at most %(num)d entry here.', 'You can choose at most %(num)d entries here.', limit) }}{% endif %} + {%- endif -%} +

+ {% endif %} + {% if members %} + {% set first = members[0].config %} +
+ + + + + {% if kind == 'slots' %} + + + {% elif kind == 'yes_no' %} + + + {% elif kind == 'rating' %} + {% set top = first.scale_max or 5 %} + {% for i in range(1, top + 1) %} + + {% endfor %} + {% else %} + {% for o in first.options %}{% endfor %} + {% endif %} + + + + {% for q in members %} + {% set name = 'q' ~ q.id %} + {% set err = errors.get(q.id) %} + {% set val = (values.get(name) or [''])[0] %} + {% set cfg = q.config %} + {% set row_id = name ~ '-row' %} + {% set must = q.required and not group_rules %} + {% if kind == 'slots' %} + {% set a = places.get(q.id, {}).get('single') %} + {% set st = own_status.get((q.id, 'single')) %} + {% set mine = 'single' in (values.get(name) or []) %} + {% set full = a is not none and a.full %} + {% endif %} + + + {% if kind == 'slots' %} + + + {% elif kind == 'yes_no' %} + + + {% elif kind == 'rating' %} + {% for i in range(1, (first.scale_max or 5) + 1) %} + + {% endfor %} + {% else %} + {% for o in cfg.options %} + + {% endfor %} + {% endif %} + + {% endfor %} + +
{{ _('Question') }}{{ _('Places') }}{{ _('Sign up') }}{{ first.label_yes or _('Yes') }}{{ first.label_no or _('No') }}{{ i }}{% if loop.first and first.label_min %}{{ first.label_min }}{% elif loop.last and first.label_max %}{{ first.label_max }}{% endif %}{{ o.label }}
+ {{ q.label }}{% if must %}{% endif %} + {% if q.help_text %}{{ q.help_text }}{% endif %} + {% if err %}{{ _(errors_text[err]) }}{% endif %} + {% if kind == 'slots' %}{{ slot_names_line(q, 'single') }}{% endif %} + {{ slot_state(a, st, full, cfg.waitlist) }}
+
+ {% endif %} +
+{% endmacro %} diff --git a/surveybox/web/templates/account.html b/surveybox/web/templates/account.html new file mode 100644 index 0000000..15a3841 --- /dev/null +++ b/surveybox/web/templates/account.html @@ -0,0 +1,170 @@ +{% extends "base.html" %} +{% block title %}{{ _('My account') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

{{ _('My account') }}

+ +
+

{{ _('Profile') }}

+ {% if profile_error %}{% endif %} +
+ {{ csrf_field(request) }} + +

{{ account.email }}

+ + + + + +
+
+ +
+

{{ _('Notifications') }}

+

{{ _('Choose which emails you receive, e.g. when you move up from a waiting list or a comment is waiting for approval.') }}

+

{{ _('Notification settings') }}

+
+ +
+

{{ _('Password') }}

+ {% if password_error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + + +

{{ _('Changing the password signs out all your other sessions.') }}

+ +
+
+ +
+

{{ _('Two-factor authentication') }}

+

{{ _('A second factor protects your account even if your password becomes known.') }}

+ {% if mfa_error %}{% endif %} + +

{{ _('Passkeys') }}

+

{{ _('A passkey replaces password and code: you confirm with fingerprint, face or device PIN. It is stored on your device or in your password manager.') }}

+ {% if passkey_error %}{% endif %} + {% if account.passkeys %} + + + + + + {% for pk in account.passkeys %} + + + + + + + {% endfor %} + +
{{ _('Name') }}{{ _('Added') }}{{ _('Last used') }}
{{ pk.name }}{% if pk.backed_up %} {{ _('synced') }}{% endif %}{{ pk.created_at | datetime }}{{ pk.last_used_at | datetime }} +
+ {{ _('Remove') }} +
+ {{ csrf_field(request) }} + {% if account.password_hash %} + + + + {% endif %} + +
+
+
+ {% endif %} + + +

{{ _('Authenticator app') }}

+ {% if account.has_totp %} +

{{ _('Turned on since %(date)s.', date=account.totp_enabled_at | datetime) }}

+ {% if not account.is_admin or account.has_passkey %} +
+ {{ csrf_field(request) }} + + + + +
+ {% endif %} + {% else %} +

{{ _('Set up authenticator app') }}

+ {% endif %} + + {% if account.has_second_factor %} +

{{ _('Recovery codes') }}

+

{{ ngettext('%(num)d recovery code left.', '%(num)d recovery codes left.', remaining_codes) }}

+
+ {{ csrf_field(request) }} + + + + +
+ {% endif %} +
+ +
+

{{ _('Sessions') }}

+ + + + + + {% for s in user_sessions %} + + + + + + {% endfor %} + +
{{ _('Device') }}{{ _('Signed in') }}{{ _('Last active') }}
{{ s.user_agent or _('Unknown') }}{% if s.id == current_session_id %} {{ _('this session') }}{% endif %}{{ s.created_at | datetime }}{{ s.last_seen_at | datetime }}
+ {% if user_sessions | length > 1 %} +
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+ +
+

{{ _('My data') }}

+

{{ _('Download everything stored about you as a JSON file: your account, your answers with places, comments, follow-up emails received and the email log.') }}

+
+ {{ csrf_field(request) }} + +
+
+ +
+

{{ _('Delete account') }}

+

{{ _('Deletes your account with all your data. Before anything happens, you see exactly what will be deleted and decide what happens to your own forms.') }}

+

{{ _('Delete account …') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/account_delete.html b/surveybox/web/templates/account_delete.html new file mode 100644 index 0000000..f2e7ec1 --- /dev/null +++ b/surveybox/web/templates/account_delete.html @@ -0,0 +1,44 @@ +{% extends "base.html" %} +{% from "_erasure_summary.html" import erasure_summary %} +{% block title %}{{ _('Delete account') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Delete account') }}

+ {% if deleted %} +

{{ _('Your account has been deleted.') }}

+

{{ _('To the start page') }}

+ {% elif reauth %} +

{{ _('For your protection, please sign in again before deleting your account.') }}

+
+ {{ csrf_field(request) }} + + +
+

{{ _('Cancel') }}

+ {% else %} + {% if error %}{% endif %} +

{{ _('What happens') }}

+ {{ erasure_summary(summary, 'user') }} +
+ {{ csrf_field(request) }} + {% if summary.forms %} +

{{ _('Your forms') }}

+

{{ _('A form can be handed over to someone who edits it with you; otherwise it is deleted with all its answers.') }}

+ {% for f in summary.forms %} + + + {% endfor %} + {% endif %} + + +
+

{{ _('Cancel') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/account_notifications.html b/surveybox/web/templates/account_notifications.html new file mode 100644 index 0000000..41641af --- /dev/null +++ b/surveybox/web/templates/account_notifications.html @@ -0,0 +1,42 @@ +{% extends "base.html" %} +{% block title %}{{ _('Notifications') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('My account') }}

+
+

{{ _('Notifications') }}

+

{{ _('Emails go to %(address)s in the language of your profile.', address=user.email) }}

+
+ {{ csrf_field(request) }} + {% for audience, title in (('participant', _('When I take part')), ('manager', _('For forms I manage'))) %} +
+ {{ title }} + {% for key, event in events.items() if event.audience == audience %} + + {% endfor %} +
+ {% endfor %} +

{{ _('Messages about your account (invitation, password reset) are always sent. For anonymous forms you get no emails about your participation.') }}

+ +
+
+ +
+

{{ _('Unsubscribed forms') }}

+ {% if muted %} +

{{ _('You get no notifications about these forms:') }}

+
    + {% for f in muted %} +
  • + {{ f.title }} +
    + {{ csrf_field(request) }} +
    +
  • + {% endfor %} +
+ {% else %} +

{{ _('None. You can unsubscribe from a single form with the link at the end of each notification.') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/admin_appearance.html b/surveybox/web/templates/admin_appearance.html new file mode 100644 index 0000000..005b80a --- /dev/null +++ b/surveybox/web/templates/admin_appearance.html @@ -0,0 +1,153 @@ +{% extends "base.html" %} +{% block title %}{{ _('Design') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('Settings') }}

+

{{ _('Design') }}

+ + + +
+

{{ _('Name, colours and texts') }}

+ {% for message in errors %}{% endfor %} + {% for message, ratio in contrast_warnings %}

{{ _(message, ratio=ratio) }}

{% endfor %} +
+ {{ csrf_field(request) }} + + +

{{ _('Appears in the header (without own logo), in the browser tab and in emails.') }}

+ + + + + {% set color_fields = [ + ('primary', _('Primary colour'), _('Buttons and links.'), look.primary, defaults.primary), + ('accent', _('Accent colour'), _('Markings: bars in the results, stars, selected tiles, info boxes.'), look.accent, look.primary or defaults.primary), + ('background', _('Background colour'), _('Page background; cards stay white on light backgrounds.'), look.background, defaults.bg), + ('text', _('Text colour'), '', look.text, defaults.text), + ] %} + {% for key, label, hint, value, fallback in color_fields %} + +
+ + +
+ {% if hint %}

{{ hint }}

{% endif %} + {% endfor %} +

{{ _('A chosen colour only applies when “Standard” is not ticked. The colours apply to the light display; the dark display derives readable shades of the primary and accent colour. Contrast is checked against WCAG 2.1 (level AA); if it is too low, a warning appears above.') }}

+ + + +

{{ _('Shown to everyone on the start page, e.g. who runs this service. Plain text.') }}

+ + + + + + + + + +

{{ _('Both links appear in the footer of every page, also on forms embedded in other pages.') }}

+ + + +

{{ _('For special cases; loaded after all other styles. External addresses are blocked by the security settings of the page, so fonts and images must come from this server.') }}

+ + +
+
    +
  • {{ _('Primary colour') }}
  • +
  • {{ _('Accent colour') }}
  • +
  • {{ _('Background colour') }}
  • +
  • {{ _('Cards') }}
  • +
  • {{ _('Text colour') }}
  • +
  • {{ _('Hints') }}
  • +
+
+ {{ csrf_field(request) }} + +
+
+ +
+

{{ _('Font') }}

+ {% if look.font_format %} +

{{ _('An own font is used (%(format)s).', format=look.font_format | upper) }}

+ {% else %} +

{{ _('The system font of each device is used.') }}

+ {% endif %} +
+ {{ csrf_field(request) }} + + +

{{ _('WOFF2 (recommended), WOFF, TTF or OTF, at most 2 MB, for example Open Sans. The font is delivered by this server, never loaded from elsewhere. Make sure its licence allows use on a website.') }}

+ +
+ {% if look.font_format %} +
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+ +
+

{{ _('Export and import') }}

+

{{ _('The design – settings, logos and font – as one file, e.g. to transfer it to a second instance.') }}

+

{{ _('Export design') }}

+
+ {{ csrf_field(request) }} + + +

{{ _('Replaces name, colours, texts and own CSS. Logo and font are replaced only if the file contains them. Images are checked and re-encoded as with an upload.') }}

+ +
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_audit.html b/surveybox/web/templates/admin_audit.html new file mode 100644 index 0000000..3e26bb9 --- /dev/null +++ b/surveybox/web/templates/admin_audit.html @@ -0,0 +1,38 @@ +{% extends "base.html" %} +{% block title %}{{ _('Log') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

{{ _('Log') }}

+

{{ _('Sign-ins and administrative actions. Contains no form content, email addresses or IP addresses.') }}

+
+ + + + + + {% for event, actor_name in events %} + + + + + + + {% else %} + + {% endfor %} + +
{{ _('Time') }}{{ _('Action') }}{{ _('By') }}{{ _('Concerns') }}
{{ event.occurred_at | datetime }}{{ _(action_names[event.action]) if event.action in action_names else event.action }}{% if actor_name %}{{ actor_name }}{% elif event.actor_id %}{{ _('Deleted user') }}{% else %}–{% endif %} + {% if event.target_type == 'user' and event.target_id %} + {{ targets.get('user:' ~ event.target_id, _('Deleted account no. %(n)s', n=event.target_id)) }} + {% elif event.target_type == 'guest' and event.target_id %} + {{ _('Guest address no. %(n)s', n=event.target_id) }} + {% elif event.target_type == 'group' and event.target_id %} + {{ _('Group') }}: {{ targets.get('group:' ~ event.target_id, _('deleted')) }} + {% else %}–{% endif %} +
{{ _('No entries yet.') }}
+
+ +{% endblock %} diff --git a/surveybox/web/templates/admin_group_edit.html b/surveybox/web/templates/admin_group_edit.html new file mode 100644 index 0000000..5c29172 --- /dev/null +++ b/surveybox/web/templates/admin_group_edit.html @@ -0,0 +1,154 @@ +{% extends "base.html" %} +{% block title %}{{ group.name }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('All groups') }}{% if parent %} · {{ _('Parent group') }}: {{ parent.name }}{% endif %}

+
+

{{ group.name }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + {% if parent_choices is not none %} + + + {% endif %} +
+ {{ _('Suitable for these user types') }} + {% for value, label in role_names.items() %} + + {% endfor %} +

{{ _('Shown when creating a user of that type. None or all checked: suitable for everyone.') }}

+
+ +
+
+ +
+

{{ _('Group administrators and creators') }}

+

{{ _('Group administrators manage members, subgroups and forms of this group and all subgroups. Group creators create forms for them. Without a group administrator, the instance administrators manage the group.') }}

+ {% if role_rows %} + + + {% for u, role in role_rows %} + + + + + + {% endfor %} + +
{{ u.display_name }}{{ _(group_role_names[role]) }} +
+ {{ csrf_field(request) }} + + + +
+
+ {% else %} +

{{ _('No group roles yet.') }}

+ {% endif %} + {% if role_candidates %} +
+ {{ csrf_field(request) }} + + + + +

{{ _('Group administrators need a second factor (passkey or authenticator app).') }}

+ +
+ {% endif %} +
+ +
+

{{ _('Members') }}

+ + + {% for member in members %} + + + + + {% else %} + + {% endfor %} + +
{% if is_instance_admin %}{{ member.display_name }}{% else %}{{ member.display_name }}{% endif %} {{ member.email }} + {% if member.id in editable and not is_instance_admin %} +
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+ {{ csrf_field(request) }} + +
+
{{ _('No members yet.') }}
+ {% if candidates %} +
+ {{ csrf_field(request) }} + + + +
+ {% endif %} +
+ {{ csrf_field(request) }} +

{{ _('New account in this group') }}

+ + + + +

{{ _('The account is created as participant. You get a personal link for the person.') }}

+ +
+
+ +
+

{{ _('Subgroups') }}

+ {% if subgroups %} + + {% else %} +

{{ _('No subgroups yet.') }}

+ {% endif %} +
+ {{ csrf_field(request) }} + + + + +
+
+ +{% if can_delete %} +
+

{{ _('Delete group') }}

+
+ {{ csrf_field(request) }} + + +
+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/admin_groups.html b/surveybox/web/templates/admin_groups.html new file mode 100644 index 0000000..0f53333 --- /dev/null +++ b/surveybox/web/templates/admin_groups.html @@ -0,0 +1,54 @@ +{% extends "base.html" %} +{% block title %}{{ _('Groups') }} · {{ appearance.name }}{% endblock %} + +{% macro parent_select(choices, selected, required) %} + + +{% endmacro %} + +{% block content %} +

{{ _('Groups') }}

+

{{ _('Groups bundle users, for example a department. Subgroups inherit: administrators and creators of a group also act in its subgroups, and a form shared with a group reaches the members of its subgroups.') }}

+
+ + + + {% for group, depth, count in tree %} + + + + + + + {% else %} + + {% endfor %} + +
{{ _('Name') }}{{ _('Description') }}{{ _('User types') }}{{ _('Members') }}
{% if depth %}{% endif %}{{ group.name }}{{ group.description or '' }}{% if group.roles %}{% for r in group.roles %}{{ _(role_names[r]) }}{% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ _('all') }}{% endif %}{{ count }}
{{ _('No groups yet.') }}
+
+
+

{{ _('New group') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + {{ parent_select(parent_choices, form.parent, parent_required) }} +
+ {{ _('Suitable for these user types') }} + {% for value, label in role_names.items() %} + + {% endfor %} +

{{ _('Shown when creating a user of that type. None or all checked: suitable for everyone.') }}

+
+ +
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_mail.html b/surveybox/web/templates/admin_mail.html new file mode 100644 index 0000000..ae35686 --- /dev/null +++ b/surveybox/web/templates/admin_mail.html @@ -0,0 +1,99 @@ +{% extends "base.html" %} +{% block title %}{{ _('Email') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

{{ _('Email') }}

+{% if not cfg.configured %} + +{% endif %} + +
+

{{ _('SMTP relay') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + +

{{ _('The certificate of the server is always checked. Unencrypted connections are not possible.') }}

+ + + + + {% if cfg.has_password %}{% endif %} +

{{ _('The password is stored encrypted and is not shown again.') }}

+ + + + + + +

{{ _('Replies to messages from Surveybox go to this address, e.g. a mailbox someone reads. Each form can set its own. The sender stays the relay address so that SPF, DKIM and DMARC fit.') }}

+ +
+
+ +
+

{{ _('Test message') }}

+ {% if test_ok %}

{{ test_ok }}

{% endif %} + {% if test_error %}{% endif %} +
+ {{ csrf_field(request) }} + + + +
+
+ +
+

{{ _('Email templates') }}

+

{{ _('Own texts for invitations, confirmations, reminders and the other emails, per language.') }}

+

{{ _('Edit email templates') }}

+
+
+

{{ _('Queue and delivery log') }}

+

+ {{ _('Waiting') }}: {{ counts.queued }} · + {{ _('Sent') }}: {{ counts.sent }} · + {{ _('Failed') }}: {{ counts.failed }} +

+ {% if counts.queued and cfg.configured %} +
+ {{ csrf_field(request) }} +
+ {% endif %} +

{{ _('Failed attempts are retried after 1, 5 and 15 minutes, then after 1, 4 and 12 hours. The content of a message is stored encrypted and deleted after sending; the log keeps type, recipient and status for 90 days.') }}

+ {% if recent %} +
+ + + + + + {% for m in recent %} + + + + + + + + + {% endfor %} + +
{{ _('Created') }}{{ _('Type') }}{{ _('Recipient') }}{{ _('Status') }}{{ _('Attempts') }}{{ _('Last error') }}
{{ m.created_at | datetime }}{{ _(kind_names.get(m.kind, m.kind)) }}{{ m.recipient }}{{ _(status_names.get(m.status, m.status)) }}{% if m.sent_at %}
{{ m.sent_at | datetime }}{% endif %}
{{ m.attempts }}{% if m.last_error %}{{ m.last_error }}{% endif %}
+
+ {% else %} +

{{ _('No messages yet.') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/admin_mail_template_edit.html b/surveybox/web/templates/admin_mail_template_edit.html new file mode 100644 index 0000000..37fc184 --- /dev/null +++ b/surveybox/web/templates/admin_mail_template_edit.html @@ -0,0 +1,56 @@ +{% extends "base.html" %} +{% block title %}{{ _(label) }} · {{ _('Email templates') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('Email templates') }}

+

{{ _(label) }}

+ + +
+

{% if stored %}{{ _('Own text') }}{% else %}{{ _('Write own text') }}{% endif %}

+ {% for message, names in errors %}{% endfor %} +
+ {{ csrf_field(request) }} + + + + + +

{{ _('Plain text; empty lines separate paragraphs, web addresses become links. The footer with the unsubscribe link is added automatically.') }}

+ +
+ {% if stored %} +
+ {{ csrf_field(request) }} + + +
+ {% endif %} +

{{ _('Placeholders') }}

+
+ {% for key, text in placeholders.items() %} +
{{ '{' ~ key ~ '}' }}{% if key in required %} {{ _('needed without {details}') }}{% endif %}
+
{{ _(text) }}
+ {% endfor %} +
+
+ +{% if preview %} +
+

{{ _('Preview with sample data') }}

+

{{ preview.subject }}

+
{{ preview.text }}
+
+{% endif %} + +
+

{{ _('Standard text') }}

+

{{ _('With sample data. Parts that depend on the situation (e.g. notes for guests) can differ.') }}

+

{{ default.subject }}

+
{{ default.text }}
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_mail_templates.html b/surveybox/web/templates/admin_mail_templates.html new file mode 100644 index 0000000..ae68157 --- /dev/null +++ b/surveybox/web/templates/admin_mail_templates.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block title %}{{ _('Email templates') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('Email') }}

+

{{ _('Email templates') }}

+
+

{{ _('Each email can get its own text per language. Without its own text, the standard text of Surveybox is used. Placeholders such as {greeting} or {details} insert the greeting and the standard text with all links and lists.') }}

+ + + {% for code, label in language_names.items() %}{% endfor %} + + + {% for kind, label in kinds.items() %} + + + {% for code in language_names %} + + {% endfor %} + + {% endfor %} + +
{{ _('Email') }}{{ label }}
{{ _(label) }}{% if customized.get(kind, {}).get(code) %}{{ _('own text') }}{% else %}{{ _('standard') }}{% endif %}
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_settings.html b/surveybox/web/templates/admin_settings.html new file mode 100644 index 0000000..d3a2232 --- /dev/null +++ b/surveybox/web/templates/admin_settings.html @@ -0,0 +1,74 @@ +{% extends "base.html" %} +{% block title %}{{ _('Settings') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

{{ _('Settings') }}

+
+

{{ _('Design') }}

+

{{ _('Name, logo, colours, font, start page, footer with legal notice and privacy policy, own CSS, export and import.') }}

+

{{ _('Edit design') }}

+
+
+

{{ _('Images, videos and uploads') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + +

{{ _('Upper limit of this installation: %(n)s MB (SURVEYBOX_MAX_UPLOAD_MB). The reverse proxy must allow requests of this size, too.', n=hard_cap) }}

+ +

{{ _('External videos') }}

+

{{ _('Only enabled providers can be embedded. Participants load such a video only after a click; until then no data goes to the provider.') }}

+ + + + + +

{{ _('Own video sources') }}

+

{{ _('For example MediaCMS or your own NAS. Only HTTPS. Enter the host, optionally with port (nas.example.org:5001). Empty rows are ignored; to remove a source, clear its host.') }}

+ {% for src in (sources or []) + [{}, {}] %} + {% set i = loop.index0 %} +
+ {{ _('Source %(n)s', n=loop.index) }} + + + + + +
+ {% endfor %} + +
+
+
+

{{ _('Self-registration') }}

+
+ {{ csrf_field(request) }} +
+ {{ _('Who may create an account without an administrator?') }} + {% for key, label in registration_levels.items() %} + + {% endfor %} +
+

{{ _('New accounts are always participants and are created only after the person has confirmed their address by email. Earlier guest answers with the same confirmed address move to the account.') }}

+ +
+
+
+

{{ _('Retention of answers') }}

+ {% if retention_error %}{% endif %} +
+ {{ csrf_field(request) }} + + +

{{ _('Applies to all forms without their own period. Afterwards the answers are anonymized or deleted, as set in the form. The owner is notified 14 days before; if the notice comes later, at least 7 days pass before anything is deleted.') }}

+ +
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_user_delete.html b/surveybox/web/templates/admin_user_delete.html new file mode 100644 index 0000000..4425ef1 --- /dev/null +++ b/surveybox/web/templates/admin_user_delete.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} +{% from "_erasure_summary.html" import erasure_summary %} +{% block title %}{{ _('Delete user') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ target.display_name }}

+
+

{{ _('Delete user: %(name)s', name=target.display_name) }}

+ {% if reauth %} +

{{ _('For your protection, please sign in again before deleting a user.') }}

+
+ {{ csrf_field(request) }} + + +
+ {% else %} + {% if error %}{% endif %} +

{{ _('What happens') }}

+ {{ erasure_summary(summary, 'user') }} +
+ {{ csrf_field(request) }} + {% if summary.forms %} +

{{ _('Forms of this user') }}

+
    {% for f in summary.forms %}
  • {{ f.title }}
  • {% endfor %}
+ + + {% endif %} + + +
+ {% endif %} +

{{ _('Cancel') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/admin_user_edit.html b/surveybox/web/templates/admin_user_edit.html new file mode 100644 index 0000000..4da27e0 --- /dev/null +++ b/surveybox/web/templates/admin_user_edit.html @@ -0,0 +1,77 @@ +{% extends "base.html" %} +{% block title %}{{ target.display_name }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('All users') }}

+
+

{{ target.display_name }}

+

{{ target.email }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + +
+
+
{{ _('Created') }}
{{ target.created_at | datetime }}
+
{{ _('Last sign-in') }}
{{ target.last_login_at | datetime }}
+
{{ _('Two-factor authentication') }}
+
+ {% if target.has_totp %}{{ _('Authenticator app') }}{% endif %} + {% if target.has_passkey %}{{ ngettext('%(num)d passkey', '%(num)d passkeys', target.passkeys | length) }}{% endif %} + {% if not target.has_second_factor %}{{ _('off') }}{% endif %} +
+
{{ _('Groups') }}
+
{% for g in groups %}{{ g.name }}{% if not loop.last %}, {% endif %}{% else %}–{% endfor %}
+
+
+ +
+

{% if target.password_hash %}{{ _('Reset sign-in') }}{% else %}{{ _('Invitation link') }}{% endif %}

+

+ {% if target.password_hash %} + {{ _('Creates a one-time link with which the person sets a new password. Valid for 24 hours.') }} + {% else %} + {{ _('Creates a new invitation link. Valid for 7 days; earlier links become invalid.') }} + {% endif %} +

+
+ {{ csrf_field(request) }} + {% if target.has_second_factor %} + + {% endif %} +
+ + +
+

{{ _('By email, the link goes to %(address)s and is not shown here.', address=target.email) }}

+
+
+ {{ csrf_field(request) }} + +
+
+
+

{{ _('Data of this user') }}

+

{{ _('For a request for access: everything stored about this person, as a JSON file. The export is recorded in the log.') }}

+
+ {{ csrf_field(request) }} + +
+
+{% if user and target.id != user.id %} +
+

{{ _('Delete user') }}

+

{{ _('Deletes the account with all its data. You see beforehand exactly what will be deleted and decide what happens to the forms of this user.') }}

+

{{ _('Delete user …') }}

+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/admin_user_link.html b/surveybox/web/templates/admin_user_link.html new file mode 100644 index 0000000..b6c448a --- /dev/null +++ b/surveybox/web/templates/admin_user_link.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} +{% block title %}{{ _('Personal link') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Personal link for %(name)s', name=target.display_name) }}

+

+ {% if purpose == 'invite' %} + {{ _('Send this link to the person. With it they choose their password.') }} + {% else %} + {{ _('Send this link to the person. With it they set a new password.') }} + {% endif %} + {{ _('Valid until %(date)s, usable once.', date=expires_at | datetime) }} +

+ +

{{ _('The link is shown only now. On the user page you can also send a new link by email.') }}

+

{{ _('Done') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/admin_user_new.html b/surveybox/web/templates/admin_user_new.html new file mode 100644 index 0000000..cf87a0e --- /dev/null +++ b/surveybox/web/templates/admin_user_new.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} +{% block title %}{{ _('New user') }} · {{ appearance.name }}{% endblock %} +{% block scripts %}{% endblock %} + +{% block content %} +
+

{{ _('New user') }}

+

{{ _('The person gets a personal link with which they choose their own password: by email, or shown to you after saving so that you can pass it on.') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + + {% if groups %} +
+ {{ _('Groups') }} +

{{ _('Only groups suitable for the chosen user type are accepted.') }}

+ {% for g in groups %} + + {% endfor %} + +
+ {% endif %} + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/admin_users.html b/surveybox/web/templates/admin_users.html new file mode 100644 index 0000000..4384cb4 --- /dev/null +++ b/surveybox/web/templates/admin_users.html @@ -0,0 +1,52 @@ +{% extends "base.html" %} +{% block title %}{{ _('Users') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Users') }}

+ {{ _('New user') }} +
+ +
+ + + + + + + + + {% for u in users %} + + + + + + + + {% else %} + + {% endfor %} + +
{{ _('Name') }}{{ _('Email address') }}{{ _('Role') }}{{ _('Status') }}{{ _('Last sign-in') }}
{{ u.display_name }}{{ u.email }}{{ _(role_names[u.role]) }} + {% if not u.is_active %}{{ _('deactivated') }} + {% elif not u.password_hash %}{{ _('invited') }} + {% else %}{{ _('active') }}{% endif %} + {% if u.has_second_factor %}2FA{% endif %} + {{ u.last_login_at | datetime }}
{{ _('No users found.') }}
+
+
+

{{ _('Export the data of a guest') }}

+

{{ _('For a request for access by someone who took part as a guest: everything stored for this email address, as a JSON file. The export is recorded in the log.') }}

+
+ {{ csrf_field(request) }} + + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/base.html b/surveybox/web/templates/base.html new file mode 100644 index 0000000..912c9cb --- /dev/null +++ b/surveybox/web/templates/base.html @@ -0,0 +1,101 @@ + + + + + + + {% block title %}{{ appearance.name }}{% endblock %} + + + {% if appearance.themed %}{% endif %} + {% if brand.custom %} + + + {% else %} + + + + {% endif %} + + {% block scripts %}{% endblock %} + + + {% if not frame %} +
+ {% if not compact %} + + {% if brand.custom %} + {% if brand.dark and appearance.mode == 'dark' %} + + {% elif brand.dark and appearance.mode == 'auto' %} + + {% else %} + + {% endif %} + {% else %} + + {{ appearance.name }} + {% endif %} + + {% endif %} + + {% if compact %}{{ _('New tab') }} ↗{% endif %} + +
+ {% endif %} +
+ {% if notice %} +

{{ _(notice) }}

+ {% endif %} + {% block content %}{% endblock %} +
+ {% if not frame and not compact %} + + {% elif appearance.imprint_url or appearance.privacy_url %} + + {% endif %} + + diff --git a/surveybox/web/templates/error.html b/surveybox/web/templates/error.html new file mode 100644 index 0000000..5f557bc --- /dev/null +++ b/surveybox/web/templates/error.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% block content %} +
+ {% if code == 403 %} +

{{ _('Access denied') }}

+

{{ _('You do not have permission to open this page.') }}

+ {% elif code == 404 %} +

{{ _('Not found') }}

+

{{ _('This page does not exist.') }}

+ {% elif code == 'csrf' %} +

{{ _('Request rejected') }}

+

{{ _('The form could not be verified. Please reload the page and try again.') }}

+ {% endif %} +

{{ _('Back to the start page') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/fill.html b/surveybox/web/templates/fill.html new file mode 100644 index 0000000..773d2f7 --- /dev/null +++ b/surveybox/web/templates/fill.html @@ -0,0 +1,99 @@ +{% extends "base.html" %} +{% from "_fill_fields.html" import question_block, group_block, cond_attr with context %} +{% from "_comments.html" import comment_section with context %} +{% block title %}{{ form.title }} · {{ appearance.name }}{% endblock %} +{% block scripts %}{% endblock %} + +{% block content %} +
+ {% if preview %} +

{{ _('Preview: answers are not saved.') }}{% if not frame %} {{ _('Back to the form') }}{% endif %}

+ {% endif %} + {% if manager_edit %} +

{% if participant %}{{ _('You are changing the answer of %(name)s as a manager.', name=participant) }}{% else %}{{ _('You are changing this answer as a manager.') }}{% endif %} {{ _('Please describe in the note at the end why you change it.') }} {{ _('Cancel') }}

+ {% endif %} +

{{ form.title }}

+ {% if form.description %}
{{ form.description }}
{% endif %} + {% if form.anonymous %}

{{ _('This form is anonymous: your answers are stored without reference to you.') }}

{% endif %} + {% if results_url and not edit %}

{{ _('Show results') }}

{% endif %} + {% if form.slot_names in ('full', 'short') and not form.anonymous and form.questions | selectattr('type', 'equalto', 'slots') | list %} +

{% if form.slot_names == 'short' %}{{ _('For the entries, everyone who opens this form sees who has already signed up: first name and the initial of the last name.') }}{% else %}{{ _('For the entries, everyone who opens this form sees who has already signed up, with first and last name.') }}{% endif %}

+ {% endif %} + {% if errors or consent_error or guest_email_error %} + + {% endif %} + {% if followup_missing %} + + {% endif %} +
+ {{ csrf_field(request) }} + {% if followup_missing %}{% endif %} + {% for page in pages %} +
+ {% if page['break'] %}{{ question_block(page['break'], values, errors, errors_text, media_base, embed_policy, files, accept_for, places, own_status) }}{% endif %} + {% for section in page.sections %} +
+ {% if section.heading %}{{ question_block(section.heading, values, errors, errors_text, media_base, embed_policy, files, accept_for, places, own_status) }}{% endif %} + {% for q in section['items'] %} +
+ {% if q.type == 'question_group' %} + {{ group_block(q, group_members.get(q.id) or [], values, errors, errors_text, places, own_status) }} + {% else %} + {{ question_block(q, values, errors, errors_text, media_base, embed_policy, files, accept_for, places, own_status) }} + {% endif %} +
+ {% endfor %} +
+ {% endfor %} +
+ {% endfor %} +
+ {% if form.privacy_notice %} +
+

{{ _('Privacy') }}

+
{{ form.privacy_notice }}
+
+ {% endif %} + {% set guest_mode = form.guest_email if (not user and not form.anonymous and not edit) else 'none' %} + {% set followup_hint = followups_planned is defined and followups_planned and not preview %} + {% if guest_mode == 'question' and form.questions | selectattr('type', 'in', ['email', 'participant_name']) | list %} +

{{ _('We send a confirmation with your personal link to the email address you entered above. With it you can view or change your answer.') }}

+ {% if followup_hint %}

{{ _('After you submit the form, the organisers plan to send you further information by email. You only receive it if you enter your email address and confirm it with the link in the confirmation email.') }}

{% endif %} + {% endif %} + {% if guest_mode in ('optional', 'required') %} +
+ + {% if guest_email_error %}

{{ _(errors_text[guest_email_error]) }}

{% endif %} + +

{{ _('You get a confirmation with your personal link to view or change your answer. The organisers do not see this address; if they need your contact details, the form asks for them separately.') }}

+ {% if followup_hint %}

{{ _('After you submit the form, the organisers plan to send you further information by email. You only receive it if you enter your email address and confirm it with the link in the confirmation email.') }}

{% endif %} +
+ {% endif %} + {% if form.require_consent and not edit %} + + {% endif %} + {% if manager_edit %} +
+ + {% if note_error %}

{{ _(note_error) }}

{% endif %} + +

{{ _('Why do you change this answer, and at whose request? The note and the changed questions are kept with the answer. Managers see them; the person receives them with a data export.') }}

+
+ {% endif %} + {% if preview %} + + {% elif edit %} + + {% else %} + + {% endif %} +
+
+
+{% if comments_enabled and not preview %}{{ comment_section(form, comment_list, comment_back, comment_guest, comment_error) }}{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/fill_closed.html b/surveybox/web/templates/fill_closed.html new file mode 100644 index 0000000..57fec33 --- /dev/null +++ b/surveybox/web/templates/fill_closed.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block title %}{{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ form.title }}

+ {% if state == 'scheduled' %} +

{{ _('This form opens on %(date)s.', date=form.opens_at | datetime) }}

+ {% else %} +

{{ _('This form is closed. Answers can no longer be submitted.') }}

+ {% endif %} + {% if results_url %} +

{{ _('Show results') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/fill_done.html b/surveybox/web/templates/fill_done.html new file mode 100644 index 0000000..7d75803 --- /dev/null +++ b/surveybox/web/templates/fill_done.html @@ -0,0 +1,50 @@ +{% extends "base.html" %} +{% from "_comments.html" import comment_section with context %} +{% block title %}{{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ form.title }}

+ {% if already %} +

{{ _('You have already filled in this form.') }}

+ {% elif edited %} +

{{ _('Your changes have been saved.') }}

+ {% else %} +

{{ _('Thank you! Your answers have been submitted.') }}

+ {% endif %} + {% if mail_notice == 'confirm' %} +

{{ _('Please confirm your email address with the link in the email we have just sent you. Only then do you receive the further information the organisers plan to send by email.') }}

+ {% elif mail_notice == 'none' %} +

{{ _('You took part without an email address, so you do not receive the further information the organisers plan to send by email.') }}

+ {% endif %} + {% if personal_link %} + + {% endif %} + {% if can_edit %} +

{{ _('Change my answers') }}

+ {% endif %} + {% if documents %} +

{{ _('Documents') }}

+
    + {% for doc, media in documents %} +
  • {{ doc.title }} ({{ media.size | filesize }})
  • + {% endfor %} +
+ {% endif %} + {% if calendar_url %} +

{{ _('Add confirmed dates to my calendar') }}

+ {% endif %} + {% if results_url %} +

{{ _('Show results') }}

+ {% endif %} + {% if form.allow_multiple and not already %} +

{{ _('Fill in again') }}

+ {% endif %} +
+{% if comments_enabled %}{{ comment_section(form, comment_list, comment_back, comment_guest, comment_error) }}{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/fill_password.html b/surveybox/web/templates/fill_password.html new file mode 100644 index 0000000..ccca8e1 --- /dev/null +++ b/surveybox/web/templates/fill_password.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block title %}{{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ form.title }}

+

{{ _('This form is protected with a password.') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/followup_edit.html b/surveybox/web/templates/followup_edit.html new file mode 100644 index 0000000..5fb81ad --- /dev/null +++ b/surveybox/web/templates/followup_edit.html @@ -0,0 +1,121 @@ +{% extends "base.html" %} +{% block title %}{{ _('Follow-up email') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% macro val(name, default='') %}{% if values %}{{ (values.get(name) or [''])[0] }}{% else %}{{ default }}{% endif %}{% endmacro %} + +{% block content %} +

← {{ _('Follow-up emails') }}

+{% set trigger = (values.get('trigger') or ['manual'])[0] if values else (followup.trigger if followup else 'manual') %} +
+

{% if followup %}{{ _('Follow-up email') }}{% else %}{{ _('New follow-up email') }}{% endif %}

+ {% if form.anonymous %} +

{{ _('This form is anonymous. No addresses are stored with the answers, so follow-up emails cannot be sent.') }}

+ {% endif %} + {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + +

{{ _('Placeholders: {name} (name of the person; empty for guests) and {form} (title of the form). Plain text; web addresses become links.') }}

+ {% if not followup %} +
+ {{ _('Documents') }} + {% if doc_error %}{% endif %} + +

{{ _('Documents are not attached to the email. Each recipient gets personal download links at the end of the text instead; this keeps emails small.') }} {{ _('PDF, Office documents, images or ZIP, at most %(n)s MB each. Images are re-encoded without metadata such as location. The email contains personal links, no attachments. Surveybox only counts downloads, without reference to the person.', n=upload_max_mb) }}

+

{{ _('After saving you can add more documents, give them titles and remove them.') }}

+
+ {% else %} +

{{ _('The documents below are not attached; each recipient gets personal download links at the end of the text.') }} {{ _('Documents') }}

+ {% endif %} + +
+ {{ _('When is the email sent?') }} + {% for key, label in trigger_names.items() %} + + {% endfor %} + + +
+

{{ _('Each person gets each follow-up email at most once, also after changing their answer. With “Right after taking part”, guests get it once they have confirmed their address.') }}

+ + {% set catch_up = (values.get('catch_up') or [''])[0] if values else ('' if not followup or followup.catch_up is none else ('yes' if followup.catch_up else 'no')) %} + + + {% set only = (values.get('only_confirmed') or [''])[0] == 'on' if values else (followup.only_confirmed if followup else false) %} + + + + +
+

{{ _('Recipients are all participants with a known address: their account or a confirmed guest address. People who have switched off follow-up emails are left out.') }}

+
+ +{% if followup %} +
+

{{ _('Documents') }}

+ {% if doc_error %}{% endif %} + {% if documents %} +
    + {% for doc, media in documents %} +
  • + {{ doc.title }} + ({{ media.size | filesize }}, {{ ngettext('%(num)d download', '%(num)d downloads', doc.downloads) }}) +
    + {{ csrf_field(request) }} +
    +
  • + {% endfor %} +
+ {% endif %} +
+ {{ csrf_field(request) }} + + + + +

{{ _('PDF, Office documents, images or ZIP, at most %(n)s MB each. Images are re-encoded without metadata such as location. The email contains personal links, no attachments. Surveybox only counts downloads, without reference to the person.', n=upload_max_mb) }}

+ +
+
+ +
+

{{ _('Preview and sending') }}

+ {% if sent is defined and sent is not none %}

{{ ngettext('Sent to %(num)d person.', 'Sent to %(num)d people.', sent) }}

{% endif %} +

{{ ngettext('Already sent to %(num)d person.', 'Already sent to %(num)d people.', stats.delivered) }} + {% if followup.sent_at %}{{ _('Scheduled sending done on %(date)s.', date=followup.sent_at | datetime) }}{% endif %}

+ {% if not form.anonymous %}

{{ _('Show recipients and send to individual people') }}

{% endif %} + {% if preview %} +
+

{{ _('Subject') }}: {{ preview.subject }}

+
{{ preview.text }}
+
+ {% endif %} + {% if send_error %}{% endif %} + {% if not form.anonymous %} +
+ {{ csrf_field(request) }} + + +
+ {% endif %} +
+ +
+

{{ _('Delete follow-up email') }}

+
+ {{ csrf_field(request) }} +

{{ _('Download links in emails already sent stop working.') }}

+ +
+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/followup_recipients.html b/surveybox/web/templates/followup_recipients.html new file mode 100644 index 0000000..7990fa6 --- /dev/null +++ b/surveybox/web/templates/followup_recipients.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% block title %}{{ _('Recipients') }} · {{ followup.subject }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ followup.subject }}

+
+

{{ _('Recipients') }}

+

{{ _('All participants of “%(title)s” and whether they have received this follow-up email.', title=form.title) }} + {{ ngettext('%(num)d person has received it so far.', '%(num)d people have received it so far.', received) }}

+ {% if result == 'sent' %}

{{ _('The email has been queued for sending.') }}

{% endif %} + {% if result == 'failed' %}{% endif %} + {% if rows %} +
+ + + + + + + + + + {% for row in rows %} + + + + + + + + {% endfor %} + +
{{ _('Participant') }}{{ _('Taken part') }}{{ _('Status') }}{{ _('Email') }}{{ _('Action') }}
{% if row.label %}{{ row.label }}{% else %}{{ _('Guest') }}{% endif %}{% if row.guest and row.label %} {{ _('Guest') }}{% endif %}{{ row.submitted_at | datetime }}{{ _(state_names[row.state]) }} + {% if row.delivered_at %}
{{ _('last sent %(date)s', date=row.delivered_at | datetime) }}{% endif %}
{% if row.mail_status %}{{ _(mail_names[row.mail_status]) }}{% if row.mail_status == 'sent' and row.mail_sent_at %}
{{ row.mail_sent_at | datetime }}{% endif %}{% else %}–{% endif %}
+ {% if row.can_send %} +
+ {{ csrf_field(request) }} + + +
+ {% endif %} +
+
+ {% else %} +

{{ _('No answers yet.') }}

+ {% endif %} +

{{ _('Guests appear without their address unless the form asks for it in an email question: the form promises them that the organisers do not see it.') }}

+

{{ _('Guests who have not confirmed their address cannot receive follow-up emails. Once they confirm, they receive this email automatically if it is sent “right after taking part” or “People who join later” is set to yes; otherwise you can send it here.') }}

+

{{ _('The email column shows the state of the most recent sending, as long as the mail log keeps it (90 days).') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/forgot.html b/surveybox/web/templates/forgot.html new file mode 100644 index 0000000..f5b907f --- /dev/null +++ b/surveybox/web/templates/forgot.html @@ -0,0 +1,22 @@ +{% extends "base.html" %} +{% block title %}{{ _('Forgot your password?') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Forgot your password?') }}

+ {% if sent %} +

{{ _('If an account exists for this address, we have sent a link to set a new password. Please also check your spam folder. The link is valid for 24 hours.') }}

+

{{ _('Back to sign-in') }}

+ {% else %} +

{{ _('Enter the email address of your account. You will receive a link to set a new password.') }}

+
+ {{ csrf_field(request) }} + + + +
+

{{ _('Your second factor (authenticator app or passkey) stays active. If you have lost it, use a recovery code or ask an administrator.') }}

+

{{ _('Back to sign-in') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/form_access.html b/surveybox/web/templates/form_access.html new file mode 100644 index 0000000..158558f --- /dev/null +++ b/surveybox/web/templates/form_access.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block title %}{{ _('Access') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ form.title }}

+

{{ _('Who may fill in') }}

+

{{ _('Choose groups and individual users. Members of a chosen group always have access, also if they join later.') }}

+
+ {{ csrf_field(request) }} +
+

{{ _('Groups') }}

+ {% for g in groups %} + + {% else %} +

{{ _('No groups yet.') }}

+ {% endfor %} +
+
+

{{ _('Users') }}

+
+ {% for u in users %} + + {% endfor %} +
+
+ +
+{% endblock %} diff --git a/surveybox/web/templates/form_comments.html b/surveybox/web/templates/form_comments.html new file mode 100644 index 0000000..2060597 --- /dev/null +++ b/surveybox/web/templates/form_comments.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} +{% block title %}{{ _('Comments') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ form.title }}

+

{{ _('Comments') }}

+
+ {% if form.comments_mode == 'moderated' %}

{{ _('New comments are visible to others only after you approve them.') }}

{% endif %} + {% for item in comment_list %} +
+
+ {{ item.author or _('Participant') }}{% if not item.comment.user_id %} {{ _('Guest') }}{% endif %} + · {{ item.comment.created_at | datetime }} + {% if item.pending %}{{ _('waiting for approval') }}{% endif %} +
+
{{ item.comment.body }}
+
+ {% if item.pending %} +
+ {{ csrf_field(request) }} +
+ {% endif %} +
+ {{ csrf_field(request) }} +
+
+
+ {% else %} +

{{ _('No comments yet.') }}

+ {% endfor %} +
+{% endblock %} diff --git a/surveybox/web/templates/form_designer.html b/surveybox/web/templates/form_designer.html new file mode 100644 index 0000000..0f88611 --- /dev/null +++ b/surveybox/web/templates/form_designer.html @@ -0,0 +1,152 @@ +{% extends "base.html" %} +{% block title %}{{ form.title }} · {{ appearance.name }}{% endblock %} +{% block scripts %}{% endblock %} + +{% block content %} +

← {{ _('All forms') }}

+
+

{{ form.title }}

+ {% if form.is_template %} + {{ _('Template') }} + {% else %} + {{ _(status_names[state]) }} + {% endif %} +
+{% set is_owner = request.state.form_level >= 3 %} +{% set is_creator = user.role in ('admin', 'creator') %} +{% if error %}{% endif %} + +
+
+ {{ _('Settings') }} + {{ _('Live preview') }} + {% if not form.is_template %} + {{ _('Answers') }} ({{ responses }}) + {% endif %} + {% if is_owner %}{{ _('Team') }}{% endif %} + {% if not form.is_template %}{{ _('Follow-up emails') }}{% endif %} + {% if form.comments_mode != 'off' and not form.is_template %}{{ _('Comments') }}{% if pending_comments %} ({{ ngettext('%(num)d new', '%(num)d new', pending_comments) }}){% endif %}{% endif %} + {% if is_creator %} +
+ {{ csrf_field(request) }} +
+ {% if not form.is_template %} +
+ {{ csrf_field(request) }} +
+ {% endif %} + {% endif %} + {% if form.is_template %} + {% if is_owner %} +
+ {{ csrf_field(request) }} + + +
+ {% endif %} + {% else %} +
+ {{ csrf_field(request) }} + {% if form.status == 'draft' %} + + + {% elif form.status == 'open' %} + + + {% else %} + + + {% endif %} +
+ {% endif %} +
+
+
{{ _('Who may fill in') }}
{{ _(access_names[form.access]) }}
+ {% if form.opens_at %}
{{ _('Opens') }}
{{ form.opens_at | datetime }}
{% endif %} + {% if form.closes_at %}
{{ _('Closes') }}
{{ form.closes_at | datetime }}
{% endif %} +
{{ _('Link') }}
+
+ {% if form.status == 'draft' %} + {{ _('Available after publishing.') }} + {% else %} + {{ link }} + {% endif %} +
+ {% if embed_allowed and form.status != 'draft' %} +
{{ _('Embed') }}
+
<iframe src="{{ link }}?embed=1" title="{{ form.title }}" width="100%" height="800"></iframe> +

{{ _('Only on pages that the administrator has allowed for embedding and that belong to the same domain (e.g. the Nextcloud). Elsewhere, browsers block the cookies the form needs: link to the form there instead.') }}

+ {% endif %} +
+
+ +
+

{{ _('Questions') }}

+ {% if not form.questions %} +

{{ _('No questions yet. Add the first one below.') }}

+ {% endif %} +

+
    + {% for q in form.questions %} +
  1. + +
    + {{ _(types[q.type].label) }} + {% if q.required and q.id not in required_by_group %}{{ _('required') }}{% endif %} + {% if q.personal %}{{ _('personal data') }}{% endif %} + {% set qm = q.config.get('media') or {} %} + {% if qm.kind == 'images' %}{{ _('Images') }}{% elif qm.kind in ('video', 'embed') %}{{ _('Video') }}{% endif %} + {% if q.config.get('display') == 'images' %}{{ _('Image tiles') }}{% endif %} + {% if dependents.get(q.id) %}{{ ngettext('controls %(num)d condition', 'controls %(num)d conditions', dependents[q.id]) }}{% endif %} +
    {{ q.label or '—' }}
    + {% if q.type == 'question_group' %} + {% set members = group_members.get(q.id) or [] %} + {% set kind = q.config.get('member_type') or 'slots' %} +
    + {{ _(member_types.get(kind, '')) }} · + {{ ngettext('%(num)d question', '%(num)d questions', members | length) }} + {%- if q.config.get('min_select') %} · {{ _('at least %(n)s required', n=q.config.min_select) }}{% endif %} + {%- if q.config.get('max_select') %} · {{ _('at most %(n)s selectable', n=q.config.max_select) }}{% endif %} + {% if not members %}
    {{ _('No questions yet: add questions of this type directly below the group.') }}{% endif %} +
    + {% endif %} + {% set summary = summaries.get(q.id) %} + {% if summary %} +
    + {{ summary.head }} +
      {% for line in summary.lines %}
    • {{ line }}
    • {% endfor %}
    + {% if q.type == 'page_break' %}{{ _('Applies to the whole page.') }}{% elif q.type == 'heading' %}{{ _('Applies to the whole section up to the next heading or page.') }}{% elif q.type == 'question_group' %}{{ _('Applies to all questions of the group.') }}{% endif %} +
    + {% endif %} +
    +
    + {{ _('Edit') }} + {% if q.type == 'question_group' %} + {{ _('Add question to group') }} + {% endif %} + {% if not loop.first %} +
    + {{ csrf_field(request) }} + +
    + {% endif %} + {% if not loop.last %} +
    + {{ csrf_field(request) }} + +
    + {% endif %} +
    +
  2. + {% endfor %} +
+ +

{{ _('Questions that should appear only in certain cases (e.g. “How many people?” only after “Yes”): add the question, open it with “Edit” and set the rule under “Condition” at the bottom. The condition always belongs to the question that appears or disappears.') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/form_followups.html b/surveybox/web/templates/form_followups.html new file mode 100644 index 0000000..790f5ef --- /dev/null +++ b/surveybox/web/templates/form_followups.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% block title %}{{ _('Follow-up emails') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ form.title }}

+
+

{{ _('Follow-up emails') }}

+

{{ _('For example after a registration for an event: participants receive an email with links to documents such as the programme, directions or presentations.') }}

+ {% if form.anonymous %} +

{{ _('This form is anonymous. No addresses are stored with the answers, so follow-up emails cannot be sent.') }}

+ {% endif %} + {% if guests_unreachable and not form.anonymous %} +

{{ _('Guests cannot enter an email address in this form, so they do not receive follow-up emails. You can change this in the settings under “Email address of guests”.') }}

+ {% endif %} + {% if rows %} +
+ + + + {% for f, s, docs in rows %} + + + + + + + {% endfor %} + +
{{ _('Subject') }}{{ _('When') }}{{ _('Documents') }}{{ _('Sent to') }}
{{ f.subject }}{{ _(trigger_names[f.trigger]) }}{% if f.trigger == 'at' and f.send_at %}
{{ f.send_at | datetime }}{% endif %}{% if f.sent_at %}
{{ _('sent %(date)s', date=f.sent_at | datetime) }}{% endif %}
{{ docs }}{{ ngettext('%(num)d person', '%(num)d people', s.delivered) }}
+
+ {% else %} +

{{ _('No follow-up emails yet.') }}

+ {% endif %} +

{{ _('New follow-up email') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/form_preview.html b/surveybox/web/templates/form_preview.html new file mode 100644 index 0000000..f2f5f26 --- /dev/null +++ b/surveybox/web/templates/form_preview.html @@ -0,0 +1,21 @@ +{% extends "base.html" %} +{% block title %}{{ _('Live preview') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} +{% block scripts %}{% endblock %} + +{% block content %} +

← {{ form.title }}

+
+

{{ _('Live preview') }}

+
+ + + +
+
+

{{ _('Keep this window open next to the designer: the preview updates by itself after every change.') }}

+
+ +
+{% endblock %} diff --git a/surveybox/web/templates/form_responses.html b/surveybox/web/templates/form_responses.html new file mode 100644 index 0000000..d1a7c96 --- /dev/null +++ b/surveybox/web/templates/form_responses.html @@ -0,0 +1,180 @@ +{% extends "base.html" %} +{% block title %}{{ _('Answers') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ form.title }}

+

{{ _('Answers') }}

+{% if retention_date and rows %} +

{% if form.deletion_mode == 'delete' %}{{ _('The retention period ends: the answers will be deleted on %(date)s.', date=retention_date | date) }}{% else %}{{ _('The retention period ends: the answers will be anonymized on %(date)s.', date=retention_date | date) }}{% endif %} {{ _('Settings') }}

+{% endif %} +
+

{{ _('Filter') }}

+
+ + + + + {% if filter_choices %} + + + {% endif %} +
+ + {% if flt.active %}{{ _('Show all') }}{% endif %} +
+
+

{% if flt.active %}{{ ngettext('%(num)d of %(total)s answer matches the filter.', '%(num)d of %(total)s answers match the filter.', rows | length, total=total) }}{% else %}{{ ngettext('%(num)d answer so far.', '%(num)d answers so far.', total) }}{% endif %} {{ _('Summary, lists and export follow the filter.') }}

+
+ +
+
+

{{ _('Overview of all answers') }}

+ {% if table.status_column %} + {% if only_missing %}{{ _('Show everyone') }} + {% elif pending %}{{ _('Only missing responses') }}{% endif %} + {% endif %} +
+ {% if table.status_column and not flt.active %} +

{{ ngettext('%(num)d invited person has not responded yet.', '%(num)d invited people have not responded yet.', pending) }}

+ {% endif %} + {% if table.rows %} +
+ + {% for h in table.headers %}{% endfor %} + + {% for row in table.rows %} + {% set rid = table.row_ids[loop.index0] %} + + {% for cell in row %} + {% if loop.first %} + + {% elif table.status_column and loop.index0 == 4 %} + + {% else %} + + {% endif %} + {% endfor %} + + {% endfor %} + +
{{ h }}
{% if rid %}{{ cell }}{% endif %}{{ cell }}{{ '' if cell is none else cell }}
+
+

{{ _('The same table as in the export. The number opens the single answer.') }}

+ {% else %} +

{{ _('No answers yet.') }}

+ {% endif %} +
+ + + +
+

{{ _('Summary') }}

+ {% for s in summary %} +
+

{{ s.question.label }} · {{ ngettext('%(num)d answer', '%(num)d answers', s.answered) }}

+ {% if s.poll_rows %} +
+ {{ csrf_field(request) }} + + {% if s.question.config.answers == 'ynm' %}{% endif %} + + {% for row in s.poll_rows %} + + + + {% if s.question.config.answers == 'ynm' %}{% endif %} + + + + {% endfor %} + +
{{ _('Option') }}{{ _('Yes') }}{{ _('Maybe') }}{{ _('No') }}{{ _('Confirmed') }}
{{ row.text }}{% if row.proposed %} {{ _('proposed') }}{% endif %}{{ row.yes }}{{ row.maybe }}{{ row.no }}
+

{{ _('★ marks the option with the most “yes”. Confirm one or more options, usually after the poll has closed. Confirmed dates appear in the calendar file if it is enabled in the settings.') }} {{ _('Participants with an account get an email about newly confirmed dates (unless the form is anonymous).') }}

+ +
+ {% endif %} + {% set lists = slot_lists.get(s.question.id) %} + {% if lists %} + + + + {% for item in lists %} + + + + + + + {% endfor %} + +
{{ _('Entry') }}{{ _('Places') }}{{ _('Signed up') }}{{ _('Waiting list') }}
{{ item.text }}{{ item.confirmed | length }}{% if item.capacity %} / {{ item.capacity }}{% endif %}{{ item.confirmed | join(', ') or '–' }}{{ item.waiting | join(', ') or '–' }}
+ {% elif s.slot_rows %} + + + {% for row in s.slot_rows %} + + + + + + {% endfor %} + +
{{ row.text }}{% if row.capacity %}{{ row.confirmed }}{% endif %}{{ row.confirmed }}{% if row.capacity %} / {{ row.capacity }}{% endif %}{% if row.waiting %} · {{ ngettext('%(num)d waiting', '%(num)d waiting', row.waiting) }}{% endif %}
+ {% endif %} + {% if s.bars %} + + + {% for bar in s.bars %} + + + + + + {% endfor %} + +
{{ bar.label }}{{ bar.count }}{{ bar.count }}
+ {% endif %} + {% if s.total is not none %}

{{ _('Sum') }}: {{ s.total }}

{% endif %} + {% if s.average is not none %}

{{ _('Average') }}: {{ s.average }}

{% endif %} + {% if s.note %}

{{ _('Order by average place') }}: {{ s.note }}

{% endif %} + {% if s.texts %} +
    {% for text in s.texts %}
  • {{ text }}
  • {% endfor %}
+ {% if s.more_texts %}

{{ ngettext('and %(num)d more; see the export.', 'and %(num)d more; see the export.', s.more_texts) }}

{% endif %} + {% endif %} +
+ {% endfor %} +
+ +
+

{{ _('Export') }}

+
+ {{ csrf_field(request) }} + {% for key, value in query.items() %}{% endfor %} + +
+ + + {% if pdf_available %}{% endif %} + +
+ {% if not pdf_available %}

{{ _('The PDF export needs the package reportlab. The administrator adds it with scripts/lock.sh and a new image.') }}

{% endif %} +

{{ _('One row per answer, one column per question – the same table as above. XLSX, ODS and PDF carry the logo, the filter and the time of the export above the table and are set up for printing: landscape, all columns on one page width, the header row repeated on every page and page numbers in the footer. The CSV file uses semicolons and UTF-8, as Excel expects in German. Every export is recorded in the log.') }}

+
+ {% if not form.anonymous and has_slots and pdf_available %} +

{{ _('Participant lists (PDF)') }}

+
+ {{ csrf_field(request) }} + {% for key, value in query.items() %}{% endfor %} + + +
+ +
+

{{ _('For printing, e.g. to sign in on site: one list per entry of the participation questions, with free places as empty rows and the waiting list below. A4 portrait with logo, page numbers and the header row repeated on every page. Follows the filter; recorded in the log.') }}

+
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/form_settings.html b/surveybox/web/templates/form_settings.html new file mode 100644 index 0000000..3043ffd --- /dev/null +++ b/surveybox/web/templates/form_settings.html @@ -0,0 +1,167 @@ +{% extends "base.html" %} +{% block title %}{{ _('Settings') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% macro radio(name, value, current, label) %} + +{% endmacro %} + +{% block content %} +

← {{ form.title }}

+

{{ _('Settings') }}

+{% if error %}{% endif %} +
+ {{ csrf_field(request) }} +
+

{{ _('General') }}

+ + + + + + + + + {% if group_choices %} + + +

{{ _('Group administrators of this group and the groups above manage the form too.') }}

+ {% endif %} +
+ +
+

{{ _('Who may fill in') }}

+
+ {{ _('Access') }} + {% for value, label in access_names.items() %}{{ radio('access', value, form.access, _(label)) }}{% endfor %} +
+ + +

+ {% if form.link_password_hash %}{{ _('A password is set. Leave empty to keep it.') }}{% else %}{{ _('Only needed for “link and password”.') }}{% endif %} +

+

{{ _('For “selected users and groups” you choose them on the next page.') }}

+
+ +
+

{{ _('Participation') }}

+ + + {% if has_responses and form.anonymous %}{% endif %} + {% if has_responses %}

{{ _('Anonymity cannot be changed once answers exist.') }}

{% endif %} + + +

{{ _('For signed-in participants and for guests with their personal link; not for anonymous forms.') }}

+ + +

{{ _('Only for access “Selected users and groups” and with an end date. Each person gets the reminder once, by email; they can switch reminders off in their account.') }}

+ + +

{{ _('Participants see counts, bars, averages, polls and the occupancy of entries – never free-text answers, files or questions marked as personal. Names at entries appear only if the form shows them anyway. Guests without an account see the results for a week after taking part, or with their personal link. With very few answers, results can reveal how individuals answered.') }}

+
+ +
+

{{ _('Places, calendar and comments') }}

+ + + + + +

{{ _('For shift plans and sign-up lists: participants see at each entry who has already signed up. The name comes from the question “Participant name”, otherwise from the account; email addresses are never shown. The form tells participants about it. Not for anonymous forms.') }}

+ +
+ {{ _('Confirmed dates as calendar') }} + {{ radio('calendar_mode', 'off', form.calendar_mode, _('Off')) }} + {{ radio('calendar_mode', 'file', form.calendar_mode, _('Calendar file (ICS) to download for participants')) }} + {{ radio('calendar_mode', 'feed', form.calendar_mode, _('Calendar file and subscription link')) }} +
+ {% if form.calendar_mode != 'off' and form.status != 'draft' %} +

{{ _('Download for participants:') }} {{ calendar_file_url }}

+ {% endif %} + {% if form.calendar_mode == 'feed' and calendar_feed_url %} +

{{ _('Subscription link (works without sign-in; whoever knows it sees the confirmed dates):') }} {{ calendar_feed_url }}

+ {% endif %} + +
+ {{ _('Comments') }} + {{ radio('comments_mode', 'off', form.comments_mode, _('Off')) }} + {{ radio('comments_mode', 'moderated', form.comments_mode, _('Moderated: new comments are visible after approval')) }} + {{ radio('comments_mode', 'public', form.comments_mode, _('Public: new comments are visible at once')) }} + + +
+ + + +

{{ _('Replies to messages about this form go to this address. Empty: the address from the email settings.') }}

+
+ +
+

{{ _('Data protection') }}

+ + + + + + + +

{{ _('Empty: default of this installation (%(n)s days). The period starts at the end date or when the form is closed.', n=retention_default) }} + {% if retention_date %}{% if form.deletion_mode == 'delete' %}{{ _('The answers will be deleted on %(date)s.', date=retention_date | date) }}{% else %}{{ _('The answers will be anonymized on %(date)s.', date=retention_date | date) }}{% endif %}{% endif %}

+ + + + + {% set has_email_question = form.questions | selectattr('type', 'in', ['email', 'participant_name']) | list | length > 0 %} + {% if form.guest_email == 'question' and not has_email_question %} +

{{ _('The form has no question of type “Email address” yet. Add one, otherwise guests get no email.') }}

+ {% elif form.guest_email == 'none' and has_email_question and not form.anonymous %} +

{{ _('The form asks for an email address. To send guests their personal link to it, choose “Use the answer to the question “Email address””.') }}

+ {% endif %} +

{{ _('Guests (participants without an account) always get a personal link to view, change or delete their answer. With an email address they also get it by email and, after confirming the address, notifications. With “Optional” and “Required” a separate field is shown that you do not see; with the question, the address is part of the answer. Not used for anonymous forms.') }}

+
+ + +
+ +{% if form.calendar_mode == 'feed' and calendar_feed_url %} +
+

{{ _('Renew subscription link') }}

+

{{ _('The old link stops working. Calendars that subscribed to it must subscribe again.') }}

+
+ {{ csrf_field(request) }} + +
+
+{% endif %} + +
+

{{ _('Delete form') }}

+ {% if delete_error %}{% endif %} +
+ {{ csrf_field(request) }} + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/form_team.html b/surveybox/web/templates/form_team.html new file mode 100644 index 0000000..10aa18b --- /dev/null +++ b/surveybox/web/templates/form_team.html @@ -0,0 +1,54 @@ +{% extends "base.html" %} +{% block title %}{{ _('Team') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ form.title }}

+

{{ _('Team') }}

+
+

{{ _('Co-editors change questions and settings and see the answers. Evaluators only see the answers. Only the owner manages the team and deletes the form.') }}

+ {% if members %} + + + + {% for m, name in members %} + + + + + + {% endfor %} + +
{{ _('Person or group') }}{{ _('Role') }}
{{ name }}{% if m.group_id %} {{ _('Group') }}{% endif %}{{ _(role_names[m.role]) }} +
+ {{ csrf_field(request) }} +
+
+ {% else %} +

{{ _('Nobody else yet.') }}

+ {% endif %} +
+
+

{{ _('Add to the team') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/forms_list.html b/surveybox/web/templates/forms_list.html new file mode 100644 index 0000000..23474a9 --- /dev/null +++ b/surveybox/web/templates/forms_list.html @@ -0,0 +1,65 @@ +{% extends "base.html" %} +{% block title %}{{ _('Forms') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

{{ _('Forms') }}

+
+ + + + + + {% for form, count, level in forms %} + {% set state = fill_state(form) %} + + + + + + + {% else %} + + {% endfor %} + +
{{ _('Title') }}{{ _('Status') }}{{ _('Answers') }}{{ _('Last changed') }}
+ {{ form.title }} + {% if level == 1 %}{{ _('Evaluator') }}{% elif level == 2 %}{{ _('Co-editor') }}{% endif %} + {{ _(status_names[state]) }}{{ count }}{{ form.updated_at | datetime }}
{{ _('No forms yet.') }}
+
+{% if can_create %} +{% if templates %} +
+

{{ _('Templates') }}

+
    + {% for t in templates %} +
  • + {{ t.title }} + {% if t.template_shared %}{{ _('shared') }}{% endif %} +
    + {{ csrf_field(request) }} +
    +
  • + {% endfor %} +
+
+{% endif %} +
+

{{ _('New form') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + {% if group_choices %} + + +

{% if group_required %}{{ _('The form belongs to this group and is shared with it at first. Its group administrators manage it too.') }}{% else %}{{ _('Optional. Group administrators of the chosen group manage the form too.') }}{% endif %}

+ {% endif %} + +
+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/guest_confirm.html b/surveybox/web/templates/guest_confirm.html new file mode 100644 index 0000000..6ac7d45 --- /dev/null +++ b/surveybox/web/templates/guest_confirm.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block title %}{{ _('Confirm email address') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Confirm email address') }}

+ {% if invalid %} + + {% elif done %} +

{{ _('Thank you, your address %(email)s is confirmed. You will now be notified by email about your participations, for example when you move up from a waiting list.', email=email) }}

+

{{ _('Each email contains a link to unsubscribe.') }}

+ {% if can_register %} +

{{ _('Create an account') }}

+

{{ _('Optional: with an account you see all your participations in one place and no longer need individual links.') }}

+

{{ _('Create an account') }}

+ {% endif %} + {% else %} +

{{ _('Please confirm that you want to receive notifications about your participations at this address.') }}

+
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/guest_erase.html b/surveybox/web/templates/guest_erase.html new file mode 100644 index 0000000..119d2be --- /dev/null +++ b/surveybox/web/templates/guest_erase.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% from "_erasure_summary.html" import erasure_summary %} +{% block title %}{{ _('Delete my data') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Delete my data') }}

+ {% if invalid %} +

{{ _('This link is invalid, has expired or the data has already been deleted.') }}

+

{{ _('Request a new link') }}

+ {% elif done %} +

{{ _('Your data has been deleted.') }}

+ {% else %} +

{{ _('What happens') }}

+ {{ erasure_summary(summary, 'guest') }} +
+ {{ csrf_field(request) }} + {% if confirm_error %}

{{ _('Please confirm the deletion.') }}

{% endif %} + + +
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/guest_export.html b/surveybox/web/templates/guest_export.html new file mode 100644 index 0000000..3d97892 --- /dev/null +++ b/surveybox/web/templates/guest_export.html @@ -0,0 +1,18 @@ +{% extends "base.html" %} +{% block title %}{{ _('Download my data') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Download my data') }}

+ {% if invalid %} +

{{ _('This link is invalid or has expired.') }}

+

{{ _('Request a new link') }}

+ {% else %} +

{{ _('The file contains everything stored for your email address: the address, your answers with places, follow-up emails received and the email log. It is a JSON file that other programs can read.') }}

+
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/guest_links.html b/surveybox/web/templates/guest_links.html new file mode 100644 index 0000000..1b27c08 --- /dev/null +++ b/surveybox/web/templates/guest_links.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} +{% block title %}{{ _('Request my links') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Request my links') }}

+ {% if sent %} +

{{ _('If we have answers for this address, we have sent all personal links to it. Links sent earlier no longer work. Please also check your spam folder.') }}

+ {% else %} +

{{ _('Did you take part as a guest and enter your email address? Enter it here to receive all your personal links again.') }}

+
+ {{ csrf_field(request) }} + + + +
+

{{ _('New links replace the old ones. Answers without an email address cannot be found again.') }}

+ {% endif %} +
+
+

{{ _('Download my data') }}

+ {% if export_sent %} +

{{ _('If we have data for this address, we have sent a link to download it. Please also check your spam folder.') }}

+ {% else %} +

{{ _('Get a copy of everything stored for your email address as a file. You receive a link by email.') }}

+
+ {{ csrf_field(request) }} + + + +
+ {% endif %} +
+
+

{{ _('Delete my data') }}

+ {% if erase_sent %} +

{{ _('If we have data for this address, we have sent a link to delete it. Please also check your spam folder.') }}

+ {% else %} +

{{ _('Deletes everything stored for your email address: your answers as a guest and the address itself. You receive a link by email; before anything is deleted, you see what happens.') }}

+
+ {{ csrf_field(request) }} + + + +
+

{{ _('Answers without an email address can be deleted with their personal link, as long as the form allows changes.') }}

+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/index.html b/surveybox/web/templates/index.html new file mode 100644 index 0000000..48746c0 --- /dev/null +++ b/surveybox/web/templates/index.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} + +{% block content %} +
+ {% if user %} +

{{ _('Welcome, %(name)s', name=user.display_name) }}

+ {% if appearance.welcome %}

{{ appearance.welcome }}

{% endif %} + {% if open_forms %} +

{{ _('Open forms for you') }}

+ + {% else %} +

{{ _('There are currently no open forms for you.') }}

+ {% endif %} + {% if team_forms %} +

{{ _('Forms you help with') }}

+ + {% endif %} + {% else %} +

{{ appearance.name }}

+ {% if appearance.welcome %}

{{ appearance.welcome }}

{% else %}

{{ _('Forms and polls, self-hosted.') }}

{% endif %} +

{{ _('Sign in') }}

+ {% endif %} + {% if db_ok is not none %} +
+
{{ _('Version') }}
+
{{ surveybox_version }}
+
{{ _('Database') }}
+
+ {% if db_ok %} + {{ _('connected and up to date') }} + {% else %} + {{ _('not reachable or not up to date') }} + {% endif %} +
+
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/login.html b/surveybox/web/templates/login.html new file mode 100644 index 0000000..0b91595 --- /dev/null +++ b/surveybox/web/templates/login.html @@ -0,0 +1,27 @@ +{% extends "base.html" %} +{% block title %}{{ _('Sign in') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Sign in') }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + + +
+

{{ _('Forgot your password?') }}{% if can_register %} · {{ _('Create an account') }}{% endif %}

+ +
+{% endblock %} diff --git a/surveybox/web/templates/login_mfa.html b/surveybox/web/templates/login_mfa.html new file mode 100644 index 0000000..50b477c --- /dev/null +++ b/surveybox/web/templates/login_mfa.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} +{% block title %}{{ _('Second factor') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Second factor') }}

+ {% if error %}{% endif %} + {% if has_passkey %} + + {% endif %} + {% if has_totp %} +

{{ _('Enter the 6-digit code from your authenticator app, or one of your recovery codes.') }}

+ {% else %} +

{{ _('If your passkey is not at hand, enter one of your recovery codes.') }}

+ {% endif %} +
+ {{ csrf_field(request) }} + + + + +
+
+{% endblock %} diff --git a/surveybox/web/templates/mail/changed.txt b/surveybox/web/templates/mail/changed.txt new file mode 100644 index 0000000..a2404fc --- /dev/null +++ b/surveybox/web/templates/mail/changed.txt @@ -0,0 +1,16 @@ +{% set subject = _('Change in “%(title)s”', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ ngettext('In “%(title)s”, the following entry you had chosen under “%(question)s” has been removed:', 'In “%(title)s”, the following entries you had chosen under “%(question)s” have been removed:', options | length, title=form.title, question=question) }} + +{% for option in options %} +- {{ option_text(option) }} +{% endfor %} + +{{ _('Please check your answer:') }} +{{ link }} +{% if guest %} + +{{ _('Your personal link to your answer is in your confirmation email. You can request it again here:') }} +{{ links_url }} +{% endif %} diff --git a/surveybox/web/templates/mail/comment_new.txt b/surveybox/web/templates/mail/comment_new.txt new file mode 100644 index 0000000..cf90d9f --- /dev/null +++ b/surveybox/web/templates/mail/comment_new.txt @@ -0,0 +1,10 @@ +{% set subject = _('New comment: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{% if pending %} +{{ _('There is a new comment on “%(title)s”. It waits for your approval.', title=form.title) }} +{% else %} +{{ _('There is a new comment on “%(title)s”.', title=form.title) }} +{% endif %} + +{{ link }} diff --git a/surveybox/web/templates/mail/comment_published.txt b/surveybox/web/templates/mail/comment_published.txt new file mode 100644 index 0000000..0773176 --- /dev/null +++ b/surveybox/web/templates/mail/comment_published.txt @@ -0,0 +1,6 @@ +{% set subject = _('Your comment has been published: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Your comment on “%(title)s” has been approved and is now visible to others.', title=form.title) }} + +{{ link }} diff --git a/surveybox/web/templates/mail/confirmed.txt b/surveybox/web/templates/mail/confirmed.txt new file mode 100644 index 0000000..c9fa2bd --- /dev/null +++ b/surveybox/web/templates/mail/confirmed.txt @@ -0,0 +1,20 @@ +{% set subject = _('Date confirmed: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ ngettext('The following date has been confirmed in “%(title)s”:', 'The following dates have been confirmed in “%(title)s”:', options | length, title=form.title) }} + +{% for option in options %} +- {{ option_text(option) }} +{% endfor %} + +{{ link }} +{% if calendar %} + +{{ _('Calendar file with the confirmed dates:') }} +{{ calendar }} +{% endif %} +{% if guest %} + +{{ _('Your personal link to your answer is in your confirmation email. You can request it again here:') }} +{{ links_url }} +{% endif %} diff --git a/surveybox/web/templates/mail/deadline.txt b/surveybox/web/templates/mail/deadline.txt new file mode 100644 index 0000000..0aa5012 --- /dev/null +++ b/surveybox/web/templates/mail/deadline.txt @@ -0,0 +1,6 @@ +{% set subject = _('End date reached: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ ngettext('“%(title)s” has reached its end date. It has %(num)d answer.', '“%(title)s” has reached its end date. It has %(num)d answers.', responses, title=form.title) }} + +{{ link }} diff --git a/surveybox/web/templates/mail/digest.txt b/surveybox/web/templates/mail/digest.txt new file mode 100644 index 0000000..c3edadf --- /dev/null +++ b/surveybox/web/templates/mail/digest.txt @@ -0,0 +1,11 @@ +{% set subject = _('Daily summary of your forms') %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Since the last summary:') }} + +{% for item in items %} +{{ item.title }}: {{ ngettext('%(num)d new answer', '%(num)d new answers', item.new) }}{% if item.changed %}, {{ ngettext('%(num)d changed', '%(num)d changed', item.changed) }}{% endif %} + + {{ item.link }} + +{% endfor %} diff --git a/surveybox/web/templates/mail/followup.txt b/surveybox/web/templates/mail/followup.txt new file mode 100644 index 0000000..1c70aa0 --- /dev/null +++ b/surveybox/web/templates/mail/followup.txt @@ -0,0 +1,12 @@ +{% set subject = custom_subject %} +{{ body }} +{% if documents %} + +{{ _('Documents:') }} +{% for title, url in documents %} +- {{ title }} + {{ url }} +{% endfor %} + +{{ _('The download links are personal; please do not pass them on. They are valid until %(date)s.', date=expires) }} +{% endif %} diff --git a/surveybox/web/templates/mail/guest_erase.txt b/surveybox/web/templates/mail/guest_erase.txt new file mode 100644 index 0000000..5a7f61e --- /dev/null +++ b/surveybox/web/templates/mail/guest_erase.txt @@ -0,0 +1,7 @@ +{% set subject = _('Delete your data') %} +{{ _('Hello,') }} + +{{ _('Someone has asked to delete all data stored for this email address: your answers as a guest and the address itself. To see what will be deleted and to confirm, open this link:') }} +{{ link }} + +{{ _('The link is valid for 24 hours. If you did not ask for this, ignore this email; nothing will be deleted.') }} diff --git a/surveybox/web/templates/mail/guest_export.txt b/surveybox/web/templates/mail/guest_export.txt new file mode 100644 index 0000000..33e3630 --- /dev/null +++ b/surveybox/web/templates/mail/guest_export.txt @@ -0,0 +1,7 @@ +{% set subject = _('Download your data') %} +{{ _('Hello,') }} + +{{ _('Someone has asked for a copy of all data stored for this email address. To download it as a file, open this link:') }} +{{ link }} + +{{ _('The link is valid for 24 hours. If you did not ask for this, ignore this email.') }} diff --git a/surveybox/web/templates/mail/guest_links.txt b/surveybox/web/templates/mail/guest_links.txt new file mode 100644 index 0000000..0ca10d3 --- /dev/null +++ b/surveybox/web/templates/mail/guest_links.txt @@ -0,0 +1,11 @@ +{% set subject = _('Your personal links') %} +{{ _('Hello,') }} + +{{ _('Here are your personal links. Links sent earlier no longer work.') }} + +{% for form, link in links %} +{{ form.title }} +{{ link }} + +{% endfor %} +{{ _('Keep these links to yourself: anyone who has them can see your answers.') }} diff --git a/surveybox/web/templates/mail/guest_receipt.txt b/surveybox/web/templates/mail/guest_receipt.txt new file mode 100644 index 0000000..15cf6e1 --- /dev/null +++ b/surveybox/web/templates/mail/guest_receipt.txt @@ -0,0 +1,32 @@ +{% if edited %} +{% set subject = _('Your answer has been changed: %(title)s', title=form.title) %} +{% else %} +{% set subject = _('Thank you for taking part: %(title)s', title=form.title) %} +{% endif %} +{{ _('Hello,') }} + +{% if edited %} +{{ _('Your changed answer to “%(title)s” has been saved.', title=form.title) }} +{% else %} +{{ _('Your answer to “%(title)s” has been received.', title=form.title) }} +{% endif %} + +{% if can_edit %} +{{ _('With your personal link you can view your answer and, while the form is open, change or delete it:') }} +{% else %} +{{ _('With your personal link you can view your answer:') }} +{% endif %} +{{ link }} + +{{ _('Keep this link to yourself: anyone who has it can see your answer.') }} +{% if confirm %} + +{% if followups_planned is defined and followups_planned %} +{{ _('The organisers plan to send further information by email after you have taken part, for example documents to download. You only receive it if you confirm your email address with this link:') }} +{% else %} +{{ _('Do you want to be notified by email, for example when you move up from a waiting list? Please confirm your address:') }} +{% endif %} +{{ confirm }} + +{{ _('Without confirmation you get no further emails, and your address is deleted after 7 days.') }} +{% endif %} diff --git a/surveybox/web/templates/mail/invite.txt b/surveybox/web/templates/mail/invite.txt new file mode 100644 index 0000000..7b306a9 --- /dev/null +++ b/surveybox/web/templates/mail/invite.txt @@ -0,0 +1,8 @@ +{% set subject = _('Your access to %(app)s', app=app_name) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('An account has been created for you. Use this link to set your password:') }} + +{{ link }} + +{{ _('The link is valid for 7 days and can be used once. If it has expired, ask the administrator for a new one.') }} diff --git a/surveybox/web/templates/mail/participation.txt b/surveybox/web/templates/mail/participation.txt new file mode 100644 index 0000000..506aaab --- /dev/null +++ b/surveybox/web/templates/mail/participation.txt @@ -0,0 +1,7 @@ +{% set subject = _('Thank you for taking part: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Your answer to “%(title)s” has been received.', title=form.title) }} + +{{ _('You can view the form here; if the form allows it, you can also change your answer:') }} +{{ link }} diff --git a/surveybox/web/templates/mail/password_reset.txt b/surveybox/web/templates/mail/password_reset.txt new file mode 100644 index 0000000..6745590 --- /dev/null +++ b/surveybox/web/templates/mail/password_reset.txt @@ -0,0 +1,8 @@ +{% set subject = _('Reset your password for %(app)s', app=app_name) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Someone asked to reset the password of your account. Use this link to set a new password:') }} + +{{ link }} + +{{ _('The link is valid for 24 hours and can be used once. If you did not ask for this, you can ignore this message; your password stays unchanged.') }} diff --git a/surveybox/web/templates/mail/promoted.txt b/surveybox/web/templates/mail/promoted.txt new file mode 100644 index 0000000..cdfe325 --- /dev/null +++ b/surveybox/web/templates/mail/promoted.txt @@ -0,0 +1,12 @@ +{% set subject = _('You have a place: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('A place has become free in “%(title)s”. You have moved up from the waiting list and are now signed up for: %(entry)s', title=form.title, entry=entry) }} + +{{ _('If you can no longer come, please change your answer so that the next person can move up:') }} +{{ link }} +{% if guest %} + +{{ _('Your personal link to your answer is in your confirmation email. You can request it again here:') }} +{{ links_url }} +{% endif %} diff --git a/surveybox/web/templates/mail/register.txt b/surveybox/web/templates/mail/register.txt new file mode 100644 index 0000000..4c9da86 --- /dev/null +++ b/surveybox/web/templates/mail/register.txt @@ -0,0 +1,8 @@ +{% set subject = _('Create your account at %(app)s', app=app_name) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Use this link to set your password and create your account:') }} + +{{ link }} + +{{ _('The link is valid for 24 hours. If you did not ask for an account, you can ignore this message; no account is created.') }} diff --git a/surveybox/web/templates/mail/register_exists.txt b/surveybox/web/templates/mail/register_exists.txt new file mode 100644 index 0000000..466cc25 --- /dev/null +++ b/surveybox/web/templates/mail/register_exists.txt @@ -0,0 +1,10 @@ +{% set subject = _('Your account at %(app)s', app=app_name) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('Someone asked to create an account with this address, but there already is one. Sign in here:') }} +{{ login_url }} + +{{ _('Forgot your password? Request a new one here:') }} +{{ forgot_url }} + +{{ _('If you did not ask for this, you can ignore this message.') }} diff --git a/surveybox/web/templates/mail/reminder.txt b/surveybox/web/templates/mail/reminder.txt new file mode 100644 index 0000000..fa7740a --- /dev/null +++ b/surveybox/web/templates/mail/reminder.txt @@ -0,0 +1,6 @@ +{% set subject = _('Reminder: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('You have been invited to “%(title)s” and have not taken part yet. The form is open until %(date)s.', title=form.title, date=closes) }} + +{{ link }} diff --git a/surveybox/web/templates/mail/retention_notice.txt b/surveybox/web/templates/mail/retention_notice.txt new file mode 100644 index 0000000..b452b98 --- /dev/null +++ b/surveybox/web/templates/mail/retention_notice.txt @@ -0,0 +1,14 @@ +{% set subject = _('Retention period ends soon: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{% if mode == 'delete' %} +{{ ngettext('The retention period of “%(title)s” ends soon. On %(date)s, its %(num)d answer will be deleted completely.', 'The retention period of “%(title)s” ends soon. On %(date)s, its %(num)d answers will be deleted completely.', responses, title=form.title, date=date) }} +{% else %} +{{ ngettext('The retention period of “%(title)s” ends soon. On %(date)s, its %(num)d answer will be anonymized: the link to the person and the answers to personal questions will be deleted, the rest stays for the results.', 'The retention period of “%(title)s” ends soon. On %(date)s, its %(num)d answers will be anonymized: the link to the person and the answers to personal questions will be deleted, the rest stays for the results.', responses, title=form.title, date=date) }} +{% endif %} + +{{ _('The answers:') }} +{{ link }} + +{{ _('If you still need them, extend the retention period in the settings of the form:') }} +{{ settings_link }} diff --git a/surveybox/web/templates/mail/slot_full.txt b/surveybox/web/templates/mail/slot_full.txt new file mode 100644 index 0000000..b76fbd8 --- /dev/null +++ b/surveybox/web/templates/mail/slot_full.txt @@ -0,0 +1,6 @@ +{% set subject = _('Booked up: %(title)s', title=form.title) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('All places for “%(entry)s” in “%(title)s” are now taken.', entry=entry, title=form.title) }} + +{{ link }} diff --git a/surveybox/web/templates/mail/test.txt b/surveybox/web/templates/mail/test.txt new file mode 100644 index 0000000..a5882bf --- /dev/null +++ b/surveybox/web/templates/mail/test.txt @@ -0,0 +1,6 @@ +{% set subject = _('Test message from %(app)s', app=app_name) %} +{% if name %}{{ _('Hello %(name)s,', name=name) }}{% else %}{{ _('Hello,') }}{% endif %} + +{{ _('This is a test message. If you can read it, sending email via the SMTP relay works.') }} + +{{ origin }} diff --git a/surveybox/web/templates/personal.html b/surveybox/web/templates/personal.html new file mode 100644 index 0000000..dbbe305 --- /dev/null +++ b/surveybox/web/templates/personal.html @@ -0,0 +1,96 @@ +{% extends "base.html" %} +{% block title %}{% if form %}{{ form.title }} · {% endif %}{{ appearance.name }}{% endblock %} + +{% block content %} +
+ {% if invalid_document %} +

{{ _('Document') }}

+ + {% elif invalid %} +

{{ _('Personal link') }}

+ +

{{ _('Request my links again') }}

+ {% elif deleted %} +

{{ form.title }}

+

{{ _('Your answer has been deleted.') }}

+ {% else %} +

{{ form.title }}

+ {% if saved %}

{{ _('Your changes have been saved.') }}

{% endif %} + {% if notify_changed %}

{{ _('Your notification setting has been saved.') }}

{% endif %} +

{{ _('Your answer from %(date)s.', date=own.submitted_at | datetime) }}{% if own.updated_at %} {{ _('Last changed %(date)s.', date=own.updated_at | datetime) }}{% endif %}

+ {% for q in waiting %} +

{{ _('You are on the waiting list for “%(entry)s”. If a place becomes free, you move up automatically.', entry=q.label) }}

+ {% endfor %} +
+ {% for q, text, files in rows %} +
{{ q.label }}
+
{% if files %}{% for f in files %}{{ f.name }} ({{ f.size | filesize }}){% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ text or '—' }}{% endif %}
+ {% endfor %} +
+ {% if documents %} +

{{ _('Documents') }}

+
    + {% for doc, media in documents %} +
  • {{ doc.title }} ({{ media.size | filesize }})
  • + {% endfor %} +
+ {% endif %} + {% if results_url %} +

{{ _('Show results') }}

+ {% endif %} + {% if can_edit %} +

{{ _('Change my answer') }}

+ {% elif open %} +

{{ _('This form does not allow changing answers.') }}

+ {% else %} +

{{ _('The form is closed; the answer can no longer be changed.') }}

+ {% endif %} + {% endif %} +
+ +{% if not invalid and not deleted and not invalid_document %} + {% if contact %} +
+

{{ _('Notifications') }}

+ {% if contact.confirmed_at %} +
+ {{ csrf_field(request) }} + + +
+ {% else %} +

{{ _('Your email address is not confirmed yet. Use the link in the confirmation email to receive notifications.') }}

+ {% endif %} +
+ {% endif %} + + {% if can_register %} +
+

{{ _('Create an account') }}

+

{{ _('With an account you see all your participations in one place and no longer need individual links. Your earlier answers with this address move to the account.') }}

+

{{ _('Create an account') }}

+
+ {% endif %} + +
+

{{ _('Download my answer') }}

+

{{ _('This answer with places as a JSON file, for your records or for another program.') }}

+
+ {{ csrf_field(request) }} + +
+
+ + {% if can_edit %} +
+

{{ _('Delete my answer') }}

+ {% if delete_error %}{% endif %} +
+ {{ csrf_field(request) }} + + +
+
+ {% endif %} +{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/question_edit.html b/surveybox/web/templates/question_edit.html new file mode 100644 index 0000000..8c152cc --- /dev/null +++ b/surveybox/web/templates/question_edit.html @@ -0,0 +1,389 @@ +{% extends "base.html" %} +{% block title %}{{ _(qtype.label) }} · {{ appearance.name }}{% endblock %} +{% block scripts %}{% endblock %} + +{% macro check(name, label) %} + +{% endmacro %} + +{% block content %} +

← {{ form.title }}

+
+

{{ _(qtype.label) }}

+ {% if error %}{% endif %} + {% if target_group %} +

{{ _('The question is added to the group “%(title)s”.', title=target_group.label) }}

+ {% endif %} + {% if answers %} +

{{ ngettext('This question already has %(num)d answer. Changes apply to it as well.', 'This question already has %(num)d answers. Changes apply to them as well.', answers) }}

+ {% endif %} +
+ {{ csrf_field(request) }} + + {% if qtype.key == 'info' %} + + + {% elif qtype.key == 'heading' %} + + + {% elif qtype.key == 'question_group' %} + + + + + {% elif qtype.key == 'page_break' %} + + + {% else %} + + + + + {% if required_by_group %} +

{{ _('This question is in a participation group: the group decides how many entries must be chosen (“Choose at least”). A single entry cannot be required here.') }}

+ {% elif qtype.key == 'participant_name' %} +

{{ _('First and last name are always required. Logged-in participants find them filled in from their account.') }}

+ {% else %} + {{ check('required', _('Answer required')) }} + {% endif %} + {{ check('personal', _('Contains personal data (e.g. name, contact details)')) }} + {% endif %} + + {% if qtype.key == 'participant_name' %} + {% set email_mode = values.get('email') or values.get('email_mode') or 'optional' %} + + +

{{ _('If the email address of guests is taken from the answers (form settings), guests receive their confirmation at this address.') }}

+ {% elif qtype.key in ('short_text', 'long_text') %} + + + {% elif qtype.key == 'number' %} + + + + + + + + + {% elif qtype.key == 'date' %} + + + + + {% elif qtype.key == 'yes_no' %} + + + + + {% elif qtype.key == 'file_upload' %} +
+ {{ _('Allowed file types') }} + {% for key, label in file_groups.items() %} + + {% endfor %} +
+ + + + +

{{ _('The administrator allows at most %(n)s MB per file.', n=media_cfg.upload_max_mb) }} {{ _('Uploaded images are re-encoded without metadata such as location.') }}

+ {% elif qtype.key == 'question_group' %} + + +
+ + + + +

{{ _('For participation: how many entries a person must and may sign up for in this group; this replaces “Answer required” on the single entries. For yes/no: how many “Yes” are needed and allowed; “Answer required” on a row then means that the row must be answered with yes or no.') }}

+
+

{{ _('All questions of this type directly below the group belong to it; another kind of question, a heading or a page break ends the group. Participants see the group as a compact table with one row per question. A condition on the group applies to all its questions.') }}

+ {% elif qtype.key == 'slots' and slot_mode == 'single' %} + + + + {{ check('waitlist', _('Waiting list when all places are taken')) }} + {{ check('hide_full', _('Hide when booked up')) }} +

{{ _('Participants tick a box to sign up. For several shifts or dates, add a question group and one question per entry; the group can limit how many entries a person may choose. A limit per person across all participation fields is in the form settings.') }}

+ {% elif qtype.key == 'slots' %} + + {{ check('multiple', _('A person may book several options')) }} + {{ check('waitlist', _('Waiting list when an option is full')) }} + {{ check('hide_full', _('Hide full options (instead of showing them as booked up)')) }} +

{{ _('Enter the number of places next to each option; empty means unlimited. A limit per person across all participation fields is in the form settings.') }}

+ {% elif qtype.key == 'poll' %} + + + + + {{ check('allow_proposals', _('Participants may propose further options')) }} +
+ {{ _('Dates') }} +

{{ _('Only used when the options are dates. Time and duration are optional; without a time the date counts as a whole day.') }}

+ {% set date_rows = (options if values.get('mode') == 'dates' else []) %} + {% for o in date_rows + [{}, {}, {}] %} +
+ + + + + +
+ {% endfor %} + +
+ {% elif qtype.key == 'rating' %} + + + + + + + {% endif %} + + {% if qtype.key == 'single_choice' %} + + + {% elif qtype.key == 'multiple_choice' %} + + + + + + + {% endif %} + + {% if qtype.has_options and not (qtype.key == 'slots' and slot_mode == 'single') %} +
+ {{ _('Options') }} +

{{ _('One option per line. Empty lines are ignored; to remove an option, delete its text. Renaming keeps existing answers.') }}

+ {% set with_images = qtype.key in ('single_choice', 'multiple_choice') %} + {% if with_images %}

{{ _('Images per option are shown with the display “Image tiles”.') }}

{% endif %} + {% for o in options %} +
+ + + {% if qtype.key == 'slots' %}{% endif %} + {% if o.proposed %}{{ _('proposed') }}{% endif %} + {% if with_images %} + {% if o.image %} + + + {% endif %} + + {% endif %} +
+ {% endfor %} + {% set offset = options | length %} + {% for _i in range(3 if options else 4) %} +
+ + + {% if qtype.key == 'slots' %}{% endif %} + {% if with_images %} + + {% endif %} +
+ {% endfor %} + +
+ {% if qtype.key in ('single_choice', 'multiple_choice') %} + {{ check('allow_other', _('Offer “Other” with a text field')) }} + {% endif %} + {% endif %} + +
+ {{ _('Condition (optional)') }} + {% if not cond_candidates %} +

{{ _('A condition refers to earlier questions with an answer. There are none before this one yet.') }}

+ {% else %} +

+ {% if qtype.key == 'page_break' %}{{ _('Applies to the whole page.') }} + {% elif qtype.key == 'heading' %}{{ _('Applies to the whole section up to the next heading or page.') }} + {% elif qtype.key == 'question_group' %}{{ _('Applies to all questions of the group.') }} + {% endif %} + {{ _('Hidden questions are not required; their answers are discarded when submitting.') }} +

+
+ + +
+ {% for row in cond_rows + [{}, {}] %} +
+ + +
+ + +
+
+ {% endfor %} +

{{ _('For choice and yes/no questions pick the option, otherwise enter the value. Dates as 2026-07-01, times as 18:30. Rows without a question are ignored.') }}

+ {% endif %} +
+ + +
+
+ +{% if question and question.id and not is_new and qtype.key != 'page_break' %} +{% set m = question.config.get('media') or {} %} +{% set base = '/forms/' ~ form.public_id ~ '/questions/' ~ question.id ~ '/media' %} +
+

{{ _('Images and video') }}

+

{{ _('Shown above the question: one or more images or one video. Adding a video replaces the images and vice versa.') }}

+ {% if media_error %}{% endif %} + + {% if m.kind == 'images' %} +
    + {% for item in m['items'] %} +
  • + {{ item.alt }} +
    + {{ csrf_field(request) }} + + +
    + + {% if not loop.first %}{% endif %} + {% if not loop.last %}{% endif %} + +
    +
    +
  • + {% endfor %} +
+ {% elif m.kind == 'video' %} + + {% for part, label in (('poster', _('Remove preview image')), ('captions', _('Remove subtitles'))) %} + {% if m.get(part) %} +
+ {{ csrf_field(request) }} + + +
+ {% endif %} + {% endfor %} + {% elif m.kind == 'embed' %} +

{{ _('External video') }}: {{ embed_watch_url(m) }}

+ {% endif %} + + {% if m.kind in (None, 'images') and (m.get('items') or []) | length < 12 %} +
+ {{ csrf_field(request) }} +

{{ _('Add image') }}

+ + + +

{{ _('JPEG, PNG or WebP, at most %(n)s MB. Surveybox removes metadata such as location and shrinks large images.', n=media_cfg.image_max_mb) }}

+ +
+ {% endif %} + +
+ {{ csrf_field(request) }} +

{% if m.kind == 'video' %}{{ _('Change video') }}{% else %}{{ _('Upload video') }}{% endif %}

+ + + + + + + + + + + +
+ + {% if media_cfg.policy.any %} +
+ {{ csrf_field(request) }} +

{{ _('External video') }}

+ + + + +

{{ _('Participants load the video only after a click and a notice that data is sent to the provider.') }}

+ +
+ {% endif %} + + {% if m.kind %} +
+ {{ csrf_field(request) }} + +
+ {% endif %} +
+{% endif %} + +{% if question and question.id and not is_new %} +
+

{{ _('Delete question') }}

+ {% if delete_error %}{% endif %} +
+ {{ csrf_field(request) }} + {% if answers %} + + {% endif %} + +
+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/recovery_codes.html b/surveybox/web/templates/recovery_codes.html new file mode 100644 index 0000000..770cbf7 --- /dev/null +++ b/surveybox/web/templates/recovery_codes.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} +{% block title %}{{ _('Recovery codes') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Recovery codes') }}

+ {% if first_setup %} +

{{ _('Two-factor authentication is now turned on.') }}

+ {% endif %} +

{{ _('If you lose your phone, you can sign in with one of these codes instead. Each code works once.') }}

+

{{ _('Store them now in a safe place, for example in your password manager. They will not be shown again.') }}

+
    + {% for code in codes %}
  • {{ code }}
  • {% endfor %} +
+ {% if not first_setup %} +

{{ _('Your previous recovery codes are no longer valid.') }}

+ {% endif %} +

{{ _('Done') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/register.html b/surveybox/web/templates/register.html new file mode 100644 index 0000000..dfe50c0 --- /dev/null +++ b/surveybox/web/templates/register.html @@ -0,0 +1,26 @@ +{% extends "base.html" %} +{% block title %}{{ _('Create an account') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Create an account') }}

+ {% if sent %} +

{{ _('If an account can be created for this address, we have sent you a link. Please also check your spam folder. The link is valid for 24 hours.') }}

+ {% else %} + {% if level == 'guests' %} +

{{ _('Accounts are available for people who took part in a form as a guest and confirmed their email address.') }}

+ {% endif %} + {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + + +
+

{{ _('You will receive an email with a link to set your password. The account is created only then. You can add a passkey later in your account.') }}

+ {% endif %} +

{{ _('Back to sign-in') }}

+
+{% endblock %} diff --git a/surveybox/web/templates/register_finish.html b/surveybox/web/templates/register_finish.html new file mode 100644 index 0000000..4164caa --- /dev/null +++ b/surveybox/web/templates/register_finish.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block title %}{{ _('Create an account') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Create an account') }}

+ {% if invalid %} + + {% else %} + {% if error %}{% endif %} + {% if taken %} +

{{ _('Sign in') }} · {{ _('Forgot your password?') }}

+ {% else %} +

{{ _('Account for %(name)s (%(email)s).', name=pending.name, email=pending.email) }}

+
+ {{ csrf_field(request) }} + + + + + +

{{ _('At least %(n)s characters. A sentence or several words are easier to remember than cryptic characters.', n=min_length) }}

+ +
+ {% endif %} + {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/response_view.html b/surveybox/web/templates/response_view.html new file mode 100644 index 0000000..4ea8688 --- /dev/null +++ b/surveybox/web/templates/response_view.html @@ -0,0 +1,69 @@ +{% extends "base.html" %} +{% block title %}{{ _('Answer') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('All answers') }}

+
+

{{ form.title }}

+ +
+
+
+
{{ _('Submitted') }}
{{ response.submitted_at | datetime }}
+ {% if response.updated_at %}
{{ _('Changed') }}
{{ response.updated_at | datetime }}
{% endif %} +
{{ _('Participant') }}
+
{% if form.anonymous %}{{ _('anonymous') }}{% elif participant %}{{ participant }}{% else %}{{ _('Guest') }}{% endif %}
+ {% if response.consent_at %}
{{ _('Consent given') }}
{{ response.consent_at | datetime }}
{% endif %} +
+
+
+
+ {% for q, text, files in rows %} +
{{ q.label }}
+
+ {% if files %} +
    + {% for f in files %}
  • {{ f.name }} ({{ f.size | filesize }})
  • {% endfor %} +
+ {% elif text %}{{ text }}{% else %}{{ _('no answer') }}{% endif %} +
+ {% endfor %} +
+
+{% set can_change = request.state.form_level is defined and request.state.form_level >= 2 %} +{% if notes or can_change %} +
+

{{ _('Changes by managers') }}

+ {% if notes %} +
    + {% for n in notes %} +
  1. +

    {{ n.created_at | datetime }} · {{ n.author or _('Deleted user') }}{% if n.changed %} · {{ _('Changed') }}: {{ n.changed | join(', ') }}{% else %} · {{ _('no answer changed') }}{% endif %}

    +

    {{ n.body }}

    +
  2. + {% endfor %} +
+ {% else %} +

{{ _('No manager has changed this answer so far.') }}

+ {% endif %} + {% if can_change %} +

{{ _('Change answer') }}

+

{{ _('For example, when someone asks you by phone to change their entry. A note on the change is required; it stays with the answer.') }}

+ {% endif %} +
+{% endif %} +{% if can_change %} +
+

{{ _('Delete answer') }}

+
+ {{ csrf_field(request) }} + {% if delete_error %}

{{ _('Please confirm the deletion.') }}

{% endif %} + + +
+
+{% endif %} +{% endblock %} diff --git a/surveybox/web/templates/results_public.html b/surveybox/web/templates/results_public.html new file mode 100644 index 0000000..8f68516 --- /dev/null +++ b/surveybox/web/templates/results_public.html @@ -0,0 +1,67 @@ +{% extends "base.html" %} +{% block title %}{{ _('Results') }} · {{ form.title }} · {{ appearance.name }}{% endblock %} + +{% block content %} +

← {{ _('Back') }}

+
+

{{ form.title }}

+ {% if not shown %} + {% if form.results_visibility == 'after_close' %} +

{{ _('The results are shown here once the form has closed.') }}

+ {% else %} +

{{ _('The results are shown here after you have taken part.') }}

+ {% endif %} + {% else %} +

{{ ngettext('Results from %(num)d answer.', 'Results from %(num)d answers.', total) }} {{ _('Free-text answers and personal details are not shown.') }}

+ {% for s in results %} +
+

{{ s.question.label }} · {{ ngettext('%(num)d answer', '%(num)d answers', s.answered) }}

+ {% if s.poll_rows %} + + {% if s.question.config.answers == 'ynm' %}{% endif %} + + {% for row in s.poll_rows %} + {% if s.question.config.answers == 'ynm' %}{% endif %} + {% endfor %} + +
{{ _('Option') }}{{ _('Yes') }}{{ _('Maybe') }}{{ _('No') }}
{{ row.text }}{% if row.confirmed %} {{ _('confirmed') }}{% endif %}{{ row.yes }}{{ row.maybe }}{{ row.no }}
+

{{ _('★ marks the option with the most “yes”.') }}

+ {% endif %} + {% if s.slot_rows %} + {% set by_option = slot_names.get(s.question.id) or {} %} + + + {% for row in s.slot_rows %} + {% set who = by_option.get(row.id) %} + + + + + + {% endfor %} + +
{{ row.text }}{% if who and (who.confirmed or who.waiting) %}{% if who.confirmed %}{{ who.confirmed | join(', ') }}{% endif %}{% if who.waiting %}{% if who.confirmed %} · {% endif %}{{ _('Waiting list:') }} {{ who.waiting | join(', ') }}{% endif %}{% endif %}{% if row.capacity %}{{ row.confirmed }}{% endif %}{{ row.confirmed }}{% if row.capacity %} / {{ row.capacity }}{% endif %}{% if row.waiting %} · {{ ngettext('%(num)d waiting', '%(num)d waiting', row.waiting) }}{% endif %}
+ {% endif %} + {% if s.bars %} + + + {% for bar in s.bars %} + + + + + + {% endfor %} + +
{{ bar.label }}{{ bar.count }}{{ bar.count }}
+ {% endif %} + {% if s.total is not none %}

{{ _('Sum') }}: {{ s.total }}

{% endif %} + {% if s.average is not none %}

{{ _('Average') }}: {{ s.average }}

{% endif %} + {% if s.note %}

{{ _('Order by average place') }}: {{ s.note }}

{% endif %} +
+ {% else %} +

{{ _('This form has no questions with results that can be shown.') }}

+ {% endfor %} + {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/setup.html b/surveybox/web/templates/setup.html new file mode 100644 index 0000000..2c93282 --- /dev/null +++ b/surveybox/web/templates/setup.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block title %}{{ _('Set password') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Set password') }}

+ {% if error %}{% endif %} + {% if not invalid %} +

+ {% if purpose == 'invite' %} + {{ _('Welcome, %(name)s. Choose a password for your account %(email)s.', name=invited.display_name, email=invited.email) }} + {% else %} + {{ _('Choose a new password for your account %(email)s. All existing sessions will be signed out.', email=invited.email) }} + {% endif %} +

+
+ {{ csrf_field(request) }} + + + +

{{ _('At least %(n)s characters. A sentence or several words are easier to remember than cryptic characters.', n=min_length) }}

+ + + +
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templates/totp_setup.html b/surveybox/web/templates/totp_setup.html new file mode 100644 index 0000000..e77f204 --- /dev/null +++ b/surveybox/web/templates/totp_setup.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block title %}{{ _('Set up authenticator app') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Set up authenticator app') }}

+
    +
  1. {{ _('Open an authenticator app on your phone, for example Aegis, 2FAS, FreeOTP or the one built into your password manager.') }}
  2. +
  3. {{ _('Scan this QR code. If that does not work, enter the key below by hand.') }}
  4. +
  5. {{ _('Enter the 6-digit code the app shows.') }}
  6. +
+
{{ qr_svg | safe }}
+

{{ secret_display }}

+ {% if error %}{% endif %} +
+ {{ csrf_field(request) }} + + + + {% if user.password_hash %} + + + + {% endif %} + +
+
+{% endblock %} diff --git a/surveybox/web/templates/unsubscribe.html b/surveybox/web/templates/unsubscribe.html new file mode 100644 index 0000000..ee1d471 --- /dev/null +++ b/surveybox/web/templates/unsubscribe.html @@ -0,0 +1,34 @@ +{% extends "base.html" %} +{% block title %}{{ _('Unsubscribe') }} · {{ appearance.name }}{% endblock %} + +{% block content %} +
+

{{ _('Unsubscribe') }}

+ {% if invalid %} + + {% elif done %} +

+ {% if guest %}{{ _('You will no longer receive notifications at this address.') }} + {% elif form %}{{ _('You will no longer receive notifications about “%(title)s”.', title=form.title) }} + {% else %}{{ _('You will no longer receive this kind of notification: %(event)s.', event=_(event.label)) }}{% endif %} +

+ {% if guest %} +

{{ _('You can switch notifications on again on the page of your personal link.') }}

+ {% else %} +

{{ _('You can change this at any time in your account under notification settings.') }} {{ _('Notification settings') }}

+ {% endif %} + {% else %} +

{{ _('Notification: %(event)s', event=_(event.label)) }}

+
+ {% if form %} + + {% endif %} + {% if guest %} + + {% else %} + + {% endif %} +
+ {% endif %} +
+{% endblock %} diff --git a/surveybox/web/templating.py b/surveybox/web/templating.py new file mode 100644 index 0000000..427df8d --- /dev/null +++ b/surveybox/web/templating.py @@ -0,0 +1,177 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Jinja2-Vorlagen mit Übersetzung, CSRF-Feld und automatischem Escaping.""" + +from __future__ import annotations + +from datetime import datetime +from pathlib import Path +from typing import Any + +from jinja2 import Environment, FileSystemLoader, select_autoescape +from markupsafe import Markup +from starlette.requests import Request +from starlette.responses import HTMLResponse +from starlette.templating import Jinja2Templates + +from surveybox import __version__, i18n +from surveybox.forms.types import format_size, option_text +from surveybox.i18n import N_ +from surveybox.security import csrf + +TEMPLATE_DIR = Path(__file__).parent / "templates" +STATIC_DIR = Path(__file__).parent / "static" + +# Hinweise nach einer Aktion (?notice=...). Nur diese Schlüssel werden angezeigt. +NOTICES: dict[str, str] = { + "logged_out": N_("You have been signed out."), + "setup_done": N_("Your password has been set. You can now sign in."), + "profile_saved": N_("Your profile has been saved."), + "password_changed": N_("Your password has been changed. Other sessions were signed out."), + "totp_disabled": N_("Two-factor authentication has been turned off."), + "sessions_revoked": N_("All other sessions have been signed out."), + "mfa_required_admin": N_( + "Administrators must set up a second factor before they can continue." + ), + "user_saved": N_("The user has been saved."), + "user_deleted": N_("The user has been deleted."), + "guest_unknown": N_("No data is stored for this guest address."), + "response_deleted": N_("The answer has been deleted."), + "response_edited": N_("The answer has been changed and the note saved."), + "user_sessions_revoked": N_("All sessions of this user have been signed out."), + "passkey_added": N_("The passkey has been added."), + "passkey_removed": N_("The passkey has been removed."), + "group_saved": N_("The group has been saved."), + "group_deleted": N_("The group has been deleted."), + "form_saved": N_("The form has been saved."), + "form_deleted": N_("The form has been deleted."), + "form_copied": N_("The copy has been created. It is a draft."), + "template_saved": N_( + "The template has been saved. New forms can be created from it in the form list." + ), + "settings_saved": N_("The settings have been saved."), + "mail_flushed": N_("Waiting messages are sent within the next minute."), + "notifications_saved": N_("Your notification settings have been saved."), + "invite_sent": N_("The invitation has been sent by email."), + "reset_link_sent": N_("A link to set a new password has been sent by email."), + "registered": N_("Your account has been created. You can now sign in."), + "condition_rules_removed": N_( + "The question has been deleted. Rules of other questions that referred to it were removed." + ), +} + + +def csrf_token(request: Request) -> str: + cookie_value = getattr(request.state, "csrf_cookie", None) or "" + secret: str = request.app.state.settings.secret_key.get_secret_value() + return csrf.form_token(secret, cookie_value) + + +def csrf_field(request: Request) -> Markup: + return Markup('').format( + csrf.FIELD_NAME, csrf_token(request) + ) + + +def format_day(value: datetime | None) -> str: + """Nur das Datum, lang ausgeschrieben, in der Zeitzone der Instanz.""" + if value is None: + return "" + from babel.dates import format_date as babel_format + + from surveybox.settings import get_settings + + local = value.astimezone(get_settings().tz) + text: str = babel_format(local.date(), format="long", locale=i18n.get_language()) + return text + + +def format_datetime(value: datetime | None) -> str: + if value is None: + return "" + from babel.dates import format_datetime as babel_format + + from surveybox.settings import get_settings + + local = value.astimezone(get_settings().tz) + text: str = babel_format(local, format="medium", locale=i18n.get_language()) + return text + + +def embed_info(config: dict[str, Any], policy: Any = None) -> dict[str, Any] | None: + """Für Vorlagen: Player- und Video-Adresse eines externen Videos.""" + from surveybox.media import embeds + + embed = embeds.from_config(config) + if embed is None or (policy is not None and not embeds.allowed(embed, policy)): + return None + return { + "player": embeds.player_url(embed), + "watch": embeds.watch_url(embed), + "provider": embeds.provider_label(embed), + "consent": policy is None or embeds.needs_consent(embed, policy), + "file": embed.provider == "file", + } + + +def embed_watch_url(config: dict[str, Any]) -> str: + info = embed_info(config) + return info["watch"] if info else "" + + +def _environment() -> Environment: + env = Environment( + loader=FileSystemLoader(TEMPLATE_DIR), + autoescape=select_autoescape(["html", "xml"]), + extensions=["jinja2.ext.i18n"], + trim_blocks=True, + lstrip_blocks=True, + ) + env.install_gettext_callables( # type: ignore[attr-defined] + gettext=i18n.gettext, ngettext=i18n.ngettext, newstyle=True + ) + env.globals["current_language"] = i18n.get_language + env.globals["language_names"] = i18n.LANGUAGE_NAMES + env.globals["languages"] = i18n.SUPPORTED_LANGUAGES + env.globals["surveybox_version"] = __version__ + env.globals["csrf_field"] = csrf_field + env.globals["csrf_token"] = csrf_token + env.globals["notices"] = NOTICES + env.filters["datetime"] = format_datetime + env.filters["date"] = format_day + env.filters["filesize"] = format_size + env.globals["embed_info"] = embed_info + env.globals["option_text"] = option_text + env.globals["embed_watch_url"] = embed_watch_url + from surveybox import appearance + + env.globals["appearance"] = appearance.DEFAULT # render() setzt die aktuelle + return env + + +templates = Jinja2Templates(env=_environment()) + + +def render( + request: Request, + name: str, + context: dict[str, Any] | None = None, + status_code: int = 200, +) -> HTMLResponse: + from surveybox import appearance, branding + + settings = request.app.state.settings + ctx: dict[str, Any] = { + "user": getattr(request.state, "user", None), + "brand": branding.current(settings.data_dir), + "appearance": appearance.current(settings.data_dir), + "source_url": settings.source_url, + "compact": bool(getattr(request.state, "compact", False)), + } + notice = request.query_params.get("notice") + if notice in NOTICES: + ctx["notice"] = NOTICES[notice] + ctx.update(context or {}) + response: HTMLResponse = templates.TemplateResponse( + request, name, ctx, status_code=status_code + ) + return response diff --git a/surveybox/worker.py b/surveybox/worker.py new file mode 100644 index 0000000..f1e2cd8 --- /dev/null +++ b/surveybox/worker.py @@ -0,0 +1,309 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Hintergrund-Worker. + +Aufgaben: tägliche Sicherung mit Aufbewahrungsfrist, Aufräumen, Versand der +E-Mail-Warteschlange (bei jedem Durchlauf), alle fünf Minuten: Enddatum +erreicht, Folge-Mails nach Zeitplan, Erinnerungen; täglich: Zusammenfassung +für Verwalter. +Später: Löschfristen, Erinnerungen. + +Der Worker startet erst, wenn die Datenbank auf dem Stand dieser Version ist +(das erledigt der Web-Dienst beim Start). Er migriert nie selbst. +""" + +from __future__ import annotations + +import logging +import signal +import threading +from datetime import UTC, datetime, timedelta +from pathlib import Path +from types import FrameType + +from sqlalchemy import Engine +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.orm import Session + +from surveybox import backup +from surveybox.db import get_engine +from surveybox.models import JobState +from surveybox.settings import Settings +from surveybox.upgrade import head_revision, schema_is_current + +log = logging.getLogger(__name__) + +HEARTBEAT_FILE = Path("/tmp/surveybox-worker-heartbeat") # noqa: S108 - tmpfs im Container +TICK_SECONDS = 30 +DAILY_BACKUP_JOB = "daily_backup" +CLEANUP_JOB = "cleanup" +CLEANUP_INTERVAL = timedelta(hours=1) +# Ohne eigene Sicherungen: so lange bleiben Einträge im Löschjournal +JOURNAL_WITHOUT_BACKUPS = timedelta(days=400) +RETRY_AFTER_ERROR = timedelta(hours=1) +DEADLINE_JOB = "deadlines" +DEADLINE_INTERVAL = timedelta(minutes=5) +# Nur Enddaten der letzten Tage melden (z. B. nach einer Pause des Workers) +DEADLINE_LOOKBACK = timedelta(days=3) +DIGEST_JOB = "digest" +DIGEST_HOUR = 7 + + +class Worker: + def __init__(self, settings: Settings, engine: Engine | None = None) -> None: + self.settings = settings + self.engine = engine or get_engine() + self._stop = threading.Event() + + # -- Steuerung --------------------------------------------------------- + + def request_stop(self, signum: int, _frame: FrameType | None) -> None: + log.info("Signal %s erhalten, Worker beendet sich.", signum) + self._stop.set() + + def run(self) -> None: + signal.signal(signal.SIGTERM, self.request_stop) + signal.signal(signal.SIGINT, self.request_stop) + self._wait_for_schema() + log.info("Worker läuft.") + while not self._stop.is_set(): + self._heartbeat() + try: + self.tick(datetime.now(UTC)) + except Exception: + log.exception("Fehler im Worker-Durchlauf") + self._stop.wait(TICK_SECONDS) + log.info("Worker beendet.") + + def _wait_for_schema(self) -> None: + head = head_revision() + waited = 0 + while not self._stop.is_set(): + try: + if schema_is_current(self.engine, head): + return + except Exception: + log.debug("Datenbank noch nicht erreichbar", exc_info=True) + if waited % 60 == 0: + log.info("Warte, bis die Datenbank auf Stand %s ist …", head) + self._heartbeat() + self._stop.wait(5) + waited += 5 + + def _heartbeat(self) -> None: + HEARTBEAT_FILE.touch() + + # -- Aufgaben ---------------------------------------------------------- + + def tick(self, now: datetime) -> None: + self.replay_erasures() + if self.daily_backup_due(now): + self.run_daily_backup(now) + if self.cleanup_due(now): + self.run_cleanup(now) + if self._due(DEADLINE_JOB, DEADLINE_INTERVAL, now): + self.run_deadlines(now) + if self.digest_due(now): + self.run_digest(now) + self.run_mail(now) + + def replay_erasures(self) -> int: + """Nach dem Zurückspielen einer Sicherung: Löschungen seither erneut anwenden.""" + from surveybox import erasure_journal + + since = erasure_journal.pending_since(self.settings) + if since is None: + return 0 + with Session(self.engine) as db, db.begin(): + applied = erasure_journal.replay(db, self.settings, since) + erasure_journal.clear_marker(self.settings) + log.info("Löschjournal nach Wiederherstellung angewendet: %d Einträge", applied) + return applied + + def digest_due(self, now: datetime) -> bool: + local = now.astimezone(self.settings.tz) + if local.hour < DIGEST_HOUR: + return False + with Session(self.engine) as session: + state = session.get(JobState, DIGEST_JOB) + last = state.last_success_at if state else None + return last is None or last.astimezone(self.settings.tz).date() < local.date() + + def run_digest(self, now: datetime) -> None: + """Tägliche Zusammenfassung neuer und geänderter Antworten.""" + from surveybox.forms import digest + + with Session(self.engine) as session: + state = session.get(JobState, DIGEST_JOB) + since = state.last_success_at if state and state.last_success_at else None + since = since or now - timedelta(days=1) + day = now.astimezone(self.settings.tz).date().isoformat() + with Session(self.engine) as db, db.begin(): + sent = digest.run(db, self.settings, since, day) + self._record(DIGEST_JOB, started=now, finished=now, status="ok", + message=f"mails={sent}", success=True) + + def _due(self, name: str, interval: timedelta, now: datetime) -> bool: + with Session(self.engine) as session: + state = session.get(JobState, name) + last = state.last_finished_at if state else None + return last is None or now - last >= interval + + def run_mail(self, now: datetime) -> int: + from surveybox.mail import outbox + + sent = outbox.process_due( + self.engine, self.settings.secret_key.get_secret_value(), + self.settings.public_host, now, + ) + if sent: + log.info("%d Mail(s) versendet", sent) + return sent + + def run_deadlines(self, now: datetime) -> None: + """Eigentümer benachrichtigen, wenn ein Formular sein Enddatum erreicht hat.""" + from sqlalchemy import func, select + + from surveybox.forms import followups, reminders + from surveybox.mail import notify + from surveybox.models import Form, FormStatus, Response + + with Session(self.engine) as db, db.begin(): + forms = db.scalars( + select(Form).where( + Form.is_template.is_(False), + Form.status != FormStatus.DRAFT, + Form.closes_at <= now, + Form.closes_at > now - DEADLINE_LOOKBACK, + ) + ).all() + for form in forms: + count = db.scalar( + select(func.count()).select_from(Response).where(Response.form_id == form.id) + ) or 0 + notify.safely(db, notify.deadline_reached, self.settings, form, int(count)) + n_followups = followups.run_due(db, self.settings, now) + n_reminders = notify.safely(db, reminders.run_due, self.settings, now) or 0 + self._record(DEADLINE_JOB, started=now, finished=datetime.now(UTC), status="ok", + message=f"forms={len(forms)} followups={n_followups} " + f"reminders={n_reminders}", success=True) + + def cleanup_due(self, now: datetime) -> bool: + with Session(self.engine) as session: + state = session.get(JobState, CLEANUP_JOB) + last = state.last_finished_at if state else None + return last is None or now - last >= CLEANUP_INTERVAL + + def run_cleanup(self, now: datetime) -> None: + """Abgelaufene Sitzungen, Zähler, Einmal-Links und alte Protokolleinträge löschen.""" + from sqlalchemy import delete + + from surveybox import erasure_journal + from surveybox.accounts import audit, passkeys, ratelimit, sessions + from surveybox.forms import guests, retention + from surveybox.mail import outbox + from surveybox.media import service as media_service + from surveybox.media import storage + from surveybox.models import ActionToken, MediaFile + + with Session(self.engine) as db, db.begin(): + n_sessions = sessions.purge_expired(db, self.settings) + n_limits = ratelimit.purge_stale(db) + n_links = db.execute( + delete(ActionToken).where(ActionToken.expires_at < now - timedelta(days=30)) + ).rowcount # type: ignore[attr-defined] + n_audit = audit.purge_older_than(db, self.settings.audit_retention_days) + passkeys.purge_expired_challenges(db) + n_mail = outbox.purge_old(db, now) + applied: list[str] = [] + n_retention_notices, n_retention = retention.run_due( + db, self.settings, now, applied) + n_guests = guests.purge_unconfirmed(db, now) + guests.purge_orphans(db, now) + # Nie abgeschickte Uploads + n_pending = db.execute( + delete(MediaFile).where( + MediaFile.pending_until < now, MediaFile.response_id.is_(None) + ) + ).rowcount # type: ignore[attr-defined] + for form_id in applied: + erasure_journal.record(self.settings, "retention", form_id) + # Journal-Einträge vor der ältesten Sicherung braucht keine Wiederherstellung + oldest = erasure_journal.oldest_backup_time(self.settings) + erasure_journal.prune(self.settings, oldest or now - JOURNAL_WITHOUT_BACKUPS) + with Session(self.engine) as db: + referenced = media_service.referenced_keys(db) + n_files = storage.sweep(self.settings.media_dir, referenced) + storage.clean_tmp(self.settings.tmp_dir) + message = ( + f"sessions={n_sessions} limits={n_limits} links={n_links or 0} audit={n_audit} " + f"uploads={n_pending or 0} files={n_files} mail={n_mail} guests={n_guests} " + f"retention={n_retention} retention_notices={n_retention_notices}" + ) + log.debug("Aufgeräumt: %s", message) + self._record(CLEANUP_JOB, started=now, finished=datetime.now(UTC), status="ok", + message=message, success=True) + + def daily_backup_due(self, now: datetime) -> bool: + local = now.astimezone(self.settings.tz) + if local.hour < self.settings.backup_hour: + return False + with Session(self.engine) as session: + state = session.get(JobState, DAILY_BACKUP_JOB) + last_success = state.last_success_at if state else None + failed_at = ( + state.last_finished_at if state and state.last_status == "error" else None + ) + today = local.date() + if last_success is not None and last_success.astimezone(self.settings.tz).date() >= today: + return False + # Nach einem Fehler höchstens einmal pro Stunde neu versuchen. + return not (failed_at is not None and now - failed_at < RETRY_AFTER_ERROR) + + def run_daily_backup(self, now: datetime) -> None: + self._record(DAILY_BACKUP_JOB, started=now) + try: + path = backup.create_backup(self.settings, "daily") + except Exception as exc: + log.exception("Tägliche Sicherung fehlgeschlagen") + self._record(DAILY_BACKUP_JOB, finished=datetime.now(UTC), status="error", + message=str(exc)[:2000]) + return + self._record(DAILY_BACKUP_JOB, finished=datetime.now(UTC), status="ok", + message=path.name, success=True) + + def _record( + self, + name: str, + *, + started: datetime | None = None, + finished: datetime | None = None, + status: str | None = None, + message: str | None = None, + success: bool = False, + ) -> None: + values: dict[str, object] = {"name": name} + if started is not None: + values["last_started_at"] = started + values["last_status"] = "running" + if finished is not None: + values["last_finished_at"] = finished + if status is not None: + values["last_status"] = status + if message is not None: + values["last_message"] = message + if success and finished is not None: + values["last_success_at"] = finished + stmt = insert(JobState).values(**values) + updates = {k: stmt.excluded[k] for k in values if k != "name"} + stmt = stmt.on_conflict_do_update(index_elements=[JobState.name], set_=updates) + with Session(self.engine) as session, session.begin(): + session.execute(stmt) + + +def heartbeat_age_seconds(now: float | None = None) -> float | None: + import time + + try: + mtime = HEARTBEAT_FILE.stat().st_mtime + except FileNotFoundError: + return None + return (now if now is not None else time.time()) - mtime diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5663a01 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,62 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Gemeinsame Test-Hilfen. + +Tests mit dem Marker `db` laufen nur, wenn SURVEYBOX_TEST_DB=1 gesetzt ist +und die SURVEYBOX_DB_*-Variablen auf eine Wegwerf-Datenbank zeigen (CI). +Die Datenbank wird dabei geleert! +""" + +from __future__ import annotations + +import os + +import pytest + + +def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: + if os.environ.get("SURVEYBOX_TEST_DB") == "1": + return + skip = pytest.mark.skip(reason="SURVEYBOX_TEST_DB=1 nicht gesetzt") + for item in items: + if "db" in item.keywords: + item.add_marker(skip) + + +@pytest.fixture +def db_settings(tmp_path, monkeypatch: pytest.MonkeyPatch): # type: ignore[no-untyped-def] + """Einstellungen mit leerem Datenverzeichnis und frischem Schema.""" + pytest.importorskip("sqlalchemy") + from sqlalchemy import text + + from surveybox import db + from surveybox import settings as settings_mod + + monkeypatch.setenv("SURVEYBOX_DATA_DIR", str(tmp_path / "data")) + settings_mod.get_settings.cache_clear() + db.get_engine.cache_clear() + engine = db.get_engine() + with engine.begin() as conn: + conn.execute(text(f"DROP SCHEMA IF EXISTS {db.DB_SCHEMA} CASCADE")) + yield settings_mod.get_settings() + engine.dispose() + settings_mod.get_settings.cache_clear() + db.get_engine.cache_clear() + + +@pytest.fixture +def app(db_settings): # type: ignore[no-untyped-def] + """Web-Anwendung auf frisch migrierter Datenbank.""" + from surveybox import db + from surveybox.upgrade import run_upgrade + from surveybox.web.app import create_app + + run_upgrade(db_settings, db.get_engine()) + return create_app() + + +@pytest.fixture +def client(app): # type: ignore[no-untyped-def] + from helpers import new_client + + with new_client(app) as c: + yield c diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..80fa19c --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,175 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Gemeinsame Hilfen für die Web-Tests gegen PostgreSQL.""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +import struct +import time +from typing import Any + +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session + +from surveybox import db +from surveybox.accounts import service +from surveybox.models import Role, UserAccount +from surveybox.security import totp +from surveybox.settings import get_settings + +PASSWORD = "ein langer und sicherer satz" +ORIGIN = "http://localhost" +RP_ID = "localhost" + + +def new_client(app: Any) -> TestClient: + return TestClient( + app, + base_url=ORIGIN, + headers={"Origin": ORIGIN, "Accept-Language": "en"}, + follow_redirects=False, + ) + + +def csrf_from(html: str) -> str: + match = re.search(r'name="csrf_token" value="([0-9a-f]+)"', html) + assert match, "kein CSRF-Feld auf der Seite" + return match.group(1) + + +def token_for(client: TestClient, path: str) -> str: + resp = client.get(path) + assert resp.status_code == 200, resp.text + return csrf_from(resp.text) + + +def make_user( + role: Role = Role.PARTICIPANT, email: str = "anna@example.de", with_totp: bool = False +) -> tuple[UserAccount, str | None]: + settings = get_settings() + with Session(db.get_engine()) as s: + user = service.create_user(s, email, "Anna", role, None) + service.set_password(s, user, PASSWORD) + secret = None + if with_totp: + secret = totp.generate_secret() + code = totp.code_at_step(secret, totp.current_step(time.time())) + service.enable_totp(s, settings, user, secret, code) + s.commit() + s.refresh(user) + s.expunge(user) + return user, secret + + +def next_totp(secret: str) -> str: + return totp.code_at_step(secret, totp.current_step(time.time()) + 1) + + +def login(client: TestClient, email: str, password: str = PASSWORD) -> Any: + token = token_for(client, "/login") + return client.post( + "/login", data={"email": email, "password": password, "csrf_token": token, "next": "/"} + ) + + +def post_json(client: TestClient, path: str, body: dict[str, Any], csrf: str) -> Any: + return client.post(path, json=body, headers={"X-CSRF-Token": csrf}) + + +# --------------------------------------------------------------------------- +# Software-Authenticator: erzeugt Passkey-Antworten wie ein Browser +# --------------------------------------------------------------------------- + + +def b64u(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def unb64u(value: str) -> bytes: + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + + +class SoftAuthenticator: + """ES256-Passkey mit Benutzerprüfung, Attestation "none".""" + + def __init__(self, rp_id: str = RP_ID, origin: str = ORIGIN) -> None: + from cryptography.hazmat.primitives.asymmetric import ec + + self.rp_id = rp_id + self.origin = origin + self.key = ec.generate_private_key(ec.SECP256R1()) + self.credential_id = os.urandom(32) + self.user_handle: bytes | None = None + self.counter = 0 + + def _rp_hash(self) -> bytes: + return hashlib.sha256(self.rp_id.encode()).digest() + + def _cose_key(self) -> bytes: + import cbor2 + + numbers = self.key.public_key().public_numbers() + return cbor2.dumps( + {1: 2, 3: -7, -1: 1, -2: numbers.x.to_bytes(32, "big"), + -3: numbers.y.to_bytes(32, "big")} + ) + + def _client_data(self, kind: str, challenge: str) -> bytes: + return json.dumps( + {"type": kind, "challenge": challenge, "origin": self.origin, "crossOrigin": False} + ).encode() + + def create(self, options: dict[str, Any]) -> dict[str, Any]: + import cbor2 + + self.user_handle = unb64u(options["user"]["id"]) + client_data = self._client_data("webauthn.create", options["challenge"]) + flags = 0x01 | 0x04 | 0x40 # Anwesenheit, Benutzerprüfung, Schlüsseldaten + auth_data = ( + self._rp_hash() + + bytes([flags]) + + struct.pack(">I", 0) + + b"\x00" * 16 + + struct.pack(">H", len(self.credential_id)) + + self.credential_id + + self._cose_key() + ) + attestation = cbor2.dumps({"fmt": "none", "attStmt": {}, "authData": auth_data}) + return { + "id": b64u(self.credential_id), + "rawId": b64u(self.credential_id), + "type": "public-key", + "response": { + "clientDataJSON": b64u(client_data), + "attestationObject": b64u(attestation), + "transports": ["internal"], + }, + "clientExtensionResults": {}, + } + + def get(self, options: dict[str, Any]) -> dict[str, Any]: + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import ec + + client_data = self._client_data("webauthn.get", options["challenge"]) + self.counter += 1 + auth_data = self._rp_hash() + bytes([0x01 | 0x04]) + struct.pack(">I", self.counter) + signature = self.key.sign( + auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256()) + ) + return { + "id": b64u(self.credential_id), + "rawId": b64u(self.credential_id), + "type": "public-key", + "response": { + "clientDataJSON": b64u(client_data), + "authenticatorData": b64u(auth_data), + "signature": b64u(signature), + "userHandle": b64u(self.user_handle) if self.user_handle else None, + }, + "clientExtensionResults": {}, + } diff --git a/tests/test_accounts.py b/tests/test_accounts.py new file mode 100644 index 0000000..16a7351 --- /dev/null +++ b/tests/test_accounts.py @@ -0,0 +1,224 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Anmeldung, zweiter Faktor, Verwaltung - durchgespielt gegen PostgreSQL (CI).""" + +from __future__ import annotations + +import re +import time + +import pytest + +pytest.importorskip("fastapi") +pytest.importorskip("httpx") +pytest.importorskip("argon2") + +from fastapi.testclient import TestClient +from helpers import ( + PASSWORD, + csrf_from, + login, + make_user, + new_client, + next_totp, + token_for, +) +from sqlalchemy import select +from sqlalchemy.orm import Session + +from surveybox import db +from surveybox.accounts import service +from surveybox.models import AuditEvent, Role, UserAccount +from surveybox.security import totp +from surveybox.settings import Settings, get_settings + +pytestmark = pytest.mark.db + + + +# --------------------------------------------------------------------------- + + +def test_login_logout(client: TestClient) -> None: + make_user() + resp = login(client, "Anna@Example.de") + assert resp.status_code == 303 and resp.headers["location"] == "/" + assert "surveybox_session" in client.cookies + page = client.get("/account") + assert page.status_code == 200 and "anna@example.de" in page.text + + out = client.post("/logout", data={"csrf_token": csrf_from(page.text)}) + assert out.status_code == 303 + after = client.get("/account") + assert after.status_code == 303 + assert after.headers["location"].startswith("/login?next=%2Faccount") + + +def test_wrong_password_and_lockout(client: TestClient) -> None: + make_user() + for _ in range(5): + resp = login(client, "anna@example.de", "falsches passwort!!") + assert resp.status_code == 400 + assert "Email or password is wrong" in resp.text + # Jetzt gesperrt: auch das richtige Passwort scheitert mit derselben Meldung + resp = login(client, "anna@example.de") + assert resp.status_code == 400 + with Session(db.get_engine()) as s: + user = s.scalar(select(UserAccount).where(UserAccount.email == "anna@example.de")) + assert user is not None and user.locked_until is not None + + +def test_unknown_user_gets_same_answer(client: TestClient) -> None: + resp = login(client, "niemand@example.de") + assert resp.status_code == 400 + assert "Email or password is wrong" in resp.text + + +def test_csrf_protection(client: TestClient, app) -> None: # type: ignore[no-untyped-def] + make_user() + data = {"email": "anna@example.de", "password": PASSWORD, "next": "/"} + client.get("/login") + assert client.post("/login", data=data).status_code == 403 # ohne Token + token = token_for(client, "/login") + evil = client.post("/login", data={**data, "csrf_token": token}, + headers={"Origin": "https://evil.example"}) + assert evil.status_code == 403 + # Token eines anderen Besuchers passt nicht + with new_client(app) as other: + foreign = token_for(other, "/login") + assert client.post("/login", data={**data, "csrf_token": foreign}).status_code == 403 + + +def test_admin_must_set_up_totp_then_login_with_second_factor(client: TestClient) -> None: + make_user(Role.ADMIN, "admin@example.de") + resp = login(client, "admin@example.de") + assert resp.headers["location"] == "/account?notice=mfa_required_admin" + assert client.get("/admin/users").headers["location"].startswith("/account") + + setup = client.get("/account/totp") + assert setup.status_code == 200 + sealed = re.search(r'name="sealed" value="([0-9a-f]+)"', setup.text) + secret_text = re.search(r'class="secret">([A-Z2-7 ]+)', setup.text) + assert sealed and secret_text + secret = secret_text.group(1).replace(" ", "") + code = totp.code_at_step(secret, totp.current_step(time.time())) + done = client.post( + "/account/totp", + data={ + "sealed": sealed.group(1), + "code": code, + "current_password": PASSWORD, + "csrf_token": csrf_from(setup.text), + }, + ) + assert done.status_code == 200 + codes = re.findall(r"([A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4})", done.text) + assert len(codes) == 10 + assert client.get("/admin/users").status_code == 200 + + # Abmelden, neu anmelden: jetzt mit zweitem Faktor + client.post("/logout", data={"csrf_token": csrf_from(done.text)}) + resp = login(client, "admin@example.de") + assert resp.headers["location"].startswith("/login/mfa") + mfa_page = client.get("/login/mfa") + token = csrf_from(mfa_page.text) + wrong = client.post("/login/mfa", data={"code": "000000", "csrf_token": token, "next": "/"}) + assert wrong.status_code == 400 + # Derselbe TOTP-Code wie bei der Einrichtung zählt nicht ein zweites Mal + replay = client.post("/login/mfa", data={"code": code, "csrf_token": token, "next": "/"}) + assert replay.status_code == 400 + ok = client.post("/login/mfa", data={"code": codes[0], "csrf_token": token, "next": "/"}) + assert ok.status_code == 303 and ok.headers["location"] == "/" + assert client.get("/admin/users").status_code == 200 + + # Ein Wiederherstellungscode funktioniert nur einmal + with Session(db.get_engine()) as s: + user = service.find_by_email(s, "admin@example.de") + assert user is not None + settings: Settings = get_settings() + assert service.verify_second_factor(s, settings, user, codes[0]) is None + assert service.verify_second_factor(s, settings, user, codes[1]) == "recovery" + + +def test_admin_invites_user_who_sets_password( # type: ignore[no-untyped-def] + client: TestClient, app +) -> None: + _, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True) + assert secret + login(client, "admin@example.de") + mfa = client.get("/login/mfa") + client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text), + "next": "/"}) + form = client.get("/admin/users/new") + assert form.status_code == 200 + created = client.post( + "/admin/users/new", + data={"email": "Bob@Example.de", "display_name": "Bob", "role": "creator", + "csrf_token": csrf_from(form.text)}, + ) + assert created.status_code == 200 + link = re.search(r"http://localhost/setup/([A-Za-z0-9_-]+)", created.text) + assert link + + with new_client(app) as bob: + page = bob.get(f"/setup/{link.group(1)}") + assert page.status_code == 200 + mismatch = bob.post( + f"/setup/{link.group(1)}", + data={"password": PASSWORD, "password2": PASSWORD + "x", + "csrf_token": csrf_from(page.text)}, + ) + assert mismatch.status_code == 400 + done = bob.post( + f"/setup/{link.group(1)}", + data={"password": PASSWORD, "password2": PASSWORD, + "csrf_token": csrf_from(page.text)}, + ) + assert done.headers["location"] == "/login?notice=setup_done" + # Link ist verbraucht + assert bob.get(f"/setup/{link.group(1)}").status_code == 410 + assert login(bob, "bob@example.de").status_code == 303 + + +def test_participant_cannot_open_admin(client: TestClient) -> None: + make_user() + login(client, "anna@example.de") + assert client.get("/admin/users").status_code == 403 + assert client.get("/admin/audit").status_code == 403 + + +def test_last_admin_cannot_remove_own_rights(client: TestClient) -> None: + admin, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True) + assert secret + login(client, "admin@example.de") + mfa = client.get("/login/mfa") + client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text), + "next": "/"}) + page = client.get(f"/admin/users/{admin.public_id}") + resp = client.post( + f"/admin/users/{admin.public_id}", + data={"display_name": "Admin", "role": "participant", "is_active": "on", + "csrf_token": csrf_from(page.text)}, + ) + assert resp.status_code == 400 + with Session(db.get_engine()) as s: + assert service.count_active_admins(s) == 1 + + +def test_audit_log_contains_no_personal_data(client: TestClient) -> None: + make_user() + login(client, "anna@example.de", "falsches passwort!!") + login(client, "anna@example.de") + with Session(db.get_engine()) as s: + events = list(s.scalars(select(AuditEvent))) + assert {e.action for e in events} >= {"auth.login_failed", "auth.login"} + for e in events: + blob = f"{e.target_id} {e.details}" + assert "@" not in blob and "anna" not in blob.lower() + + +def test_security_headers_on_pages(client: TestClient) -> None: + resp = client.get("/login") + assert "default-src 'self'" in resp.headers["content-security-policy"] + assert resp.headers["x-frame-options"] == "DENY" + assert resp.headers["cache-control"] == "no-store" + assert "surveybox_csrf" in client.cookies diff --git a/tests/test_appearance.py b/tests/test_appearance.py new file mode 100644 index 0000000..feafa5a --- /dev/null +++ b/tests/test_appearance.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Einstellungen > Gestaltung über die Oberfläche (CI).""" + +from __future__ import annotations + +import io +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from helpers import new_client, token_for +from PIL import Image +from test_forms import participant +from test_mail import admin + +pytestmark = pytest.mark.db + + +def png(color: tuple[int, int, int, int] = (31, 95, 174, 255)) -> bytes: + buf = io.BytesIO() + Image.new("RGBA", (300, 100), color).save(buf, "PNG") + return buf.getvalue() + + +def save(client: Any, **fields: str) -> Any: + data = {"name": "Feuerwehr Test", "mode": "auto", "primary": "#c00000", + "accent": "#ffcc00", "background": "#f6f7f9", "text": "#1c1e21", + "background_default": "on", "text_default": "on", **fields} + return client.post("/admin/appearance", + data={"csrf_token": token_for(client, "/admin/appearance"), **data}) + + +def test_name_colours_and_footer(app: Any) -> None: + root = admin(app) + guest = new_client(app) + assert "/branding/theme.css" not in guest.get("/login").text + resp = save(root, imprint_url="https://fw.example/impressum", + privacy_url="https://fw.example/datenschutz", footer_text="Freiwillige ", + welcome="Hallo Welt") + assert resp.status_code == 303 and "settings_saved" in resp.headers["location"] + page = guest.get("/login").text + assert "Sign in · Feuerwehr Test" in page and "/branding/theme.css?v=" in page + assert 'href="https://fw.example/impressum"' in page and "Legal notice" in page + assert "Freiwillige <b>" in page + assert "Hallo <i>Welt</i>" in guest.get("/").text + css = guest.get("/branding/theme.css") + assert css.status_code == 200 and css.headers["content-type"].startswith("text/css") + assert "--sb-primary:#c00000" in css.text and "--sb-accent:#ffcc00" in css.text + assert "--sb-bg:#f6f7f9" in css.text # Standard angehakt: unverändert + # Gelbe Akzentfarbe: zu wenig Kontrast, Warnung ohne Speicherverbot + assert "accent colour has too little contrast" in root.get("/admin/appearance").text + + +def test_invalid_input_is_not_saved(app: Any) -> None: + root = admin(app) + resp = save(root, name="", imprint_url="javascript:alert(1)") + assert resp.status_code == 400 + assert "Please enter a name" in resp.text and "must start with https://" in resp.text + assert "/branding/theme.css" not in new_client(app).get("/login").text + + +def test_font_export_import_and_reset(app: Any) -> None: + root = admin(app) + save(root, mode="dark", css=".brand-name { letter-spacing: 1px }") + csrf = token_for(root, "/admin/appearance") + resp = root.post("/admin/appearance/font", data={"csrf_token": csrf}, + files={"font": ("x.svg", b"", "image/svg+xml")}) + assert "error=font" in resp.headers["location"] + csrf = token_for(root, "/admin/appearance") + root.post("/admin/appearance/font", data={"csrf_token": csrf}, + files={"font": ("a.woff2", b"wOF2" + b"\0" * 64, "font/woff2")}) + guest = new_client(app) + css = guest.get("/branding/theme.css").text + assert "@font-face" in css and "color-scheme:dark" in css and "letter-spacing" in css + assert guest.get("/branding/font").headers["content-type"] == "font/woff2" + csrf = token_for(root, "/admin/settings") + root.post("/admin/settings/logo", data={"csrf_token": csrf}, + files={"logo": ("logo.png", png(), "image/png")}) + csrf = token_for(root, "/admin/appearance") + root.post("/admin/settings/logo", data={"csrf_token": csrf, "variant": "dark"}, + files={"logo": ("dark.png", png((255, 255, 255, 255)), "image/png")}) + assert "/branding/logo-dark.png?v=" in guest.get("/login").text + exported = root.get("/admin/appearance/export") + assert exported.status_code == 200 and "surveybox-appearance" in exported.text + # Zurücksetzen, dann Import stellt alles wieder her + csrf = token_for(root, "/admin/appearance") + root.post("/admin/appearance/reset", data={"csrf_token": csrf}) + assert "color-scheme:dark" not in guest.get("/branding/theme.css").text + csrf = token_for(root, "/admin/appearance") + resp = root.post("/admin/appearance/import", data={"csrf_token": csrf}, + files={"design": ("d.json", exported.content, "application/json")}) + assert resp.status_code == 303 and "settings_saved" in resp.headers["location"] + assert "color-scheme:dark" in guest.get("/branding/theme.css").text + csrf = token_for(root, "/admin/appearance") + resp = root.post("/admin/appearance/import", data={"csrf_token": csrf}, + files={"design": ("d.json", b'{"format": "x"}', "application/json")}) + assert "error=import" in resp.headers["location"] + + +def test_only_admins(app: Any) -> None: + paul = participant(app) + assert paul.get("/admin/appearance").status_code in (303, 403) + assert new_client(app).get("/admin/appearance/export").status_code in (303, 401, 403) diff --git a/tests/test_appearance_units.py b/tests/test_appearance_units.py new file mode 100644 index 0000000..53f914e --- /dev/null +++ b/tests/test_appearance_units.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Gestaltung ohne Datenbank: Eingaben prüfen, Kontrast, theme.css, Export und Import.""" + +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path + +import pytest + +from surveybox import appearance as app + + +def test_parse_accepts_and_rejects() -> None: + look, errors = app.parse({ + "name": " Feuerwehr\nTitisee ", "mode": "dark", "primary": "#C00000", + "imprint_url": "https://fw.example/impressum", "welcome": "Zeile 1\r\nZeile 2\x07", + "css": ".x { color: red }", + }) + assert errors == [] + assert look.name == "Feuerwehr Titisee" and look.mode == "dark" + assert look.primary == "#c00000" and look.welcome == "Zeile 1\nZeile 2" + bad, errors = app.parse({"name": "", "primary": "red", "privacy_url": "javascript:x", + "imprint_url": "https://x\" onmouseover=1", "mode": "neon", + "footer_text": "x" * 400}) + assert errors == ["color", "name", "too_long", "url"] + assert bad.primary == "" and bad.privacy_url == "" and bad.imprint_url == "" + assert bad.mode == "auto" and len(bad.footer_text) == app.MAX_FOOTER + + +def test_contrast_and_palette() -> None: + assert round(app.contrast("#000000", "#ffffff"), 1) == 21.0 + assert app.warnings(app.DEFAULT) == [] + keys = [key for key, _ in app.warnings(app.Appearance(primary="#ffee00"))] + assert "button" in keys and "link" in keys + keys = [key for key, _ in app.warnings(app.Appearance(text="#cccccc"))] + assert keys == ["text"] + # Die dunkle Darstellung hellt eine dunkle Primärfarbe auf, bis sie lesbar ist + colors = app.palette(app.Appearance(primary="#202060")) + assert app.contrast(colors.dark["primary"], app.DARK["surface"]) >= 4.5 + # Dunkler Hintergrund: Karten nicht weiß, Hinweise lesbar + colors = app.palette(app.Appearance(background="#101820", text="#f0f0f0")) + assert colors.light["surface"] != "#ffffff" + assert app.contrast(colors.light["muted"], colors.light["surface"]) >= 4.5 + + +def test_theme_css_by_mode() -> None: + auto = app.theme_css(app.Appearance(primary="#c00000", css=".x{}"), None) + assert "--sb-primary:#c00000" in auto and "@media (prefers-color-scheme: dark)" in auto + assert auto.rstrip().endswith(".x{}") + light = app.theme_css(app.Appearance(mode="light"), None) + assert "color-scheme:light;" in light and "@media" not in light + dark = app.theme_css(app.Appearance(mode="dark", font_format="woff2"), "/branding/font?v=1") + assert "--sb-bg:#121417" in dark and 'format("woff2")' in dark and "SurveyboxCustom" in dark + + +def test_save_current_and_font(tmp_path: Path) -> None: + assert app.current(tmp_path) == app.DEFAULT + saved = app.save(tmp_path, app.Appearance(name="Test", primary="#123456")) + assert saved.name == "Test" and saved.version and saved.themed + assert app.font_format(b"wOF2" + b"\0" * 20) == "woff2" + assert app.font_format(b" None: + look = replace(app.Appearance(name="X", footer_text="F"), version="v9") + data = app.export(look, {"logo": b"\x89PNG", "font": b"wOF2"}) + assert "version" not in data["appearance"] + values, files = app.read_export(json.dumps(data).encode()) + assert app.parse(values)[0].name == "X" and files == {"logo": b"\x89PNG", "font": b"wOF2"} + for raw in (b"kein json", b"{}", json.dumps({"format": "x"}).encode(), + json.dumps({**data, "files": {"logo": "%%%"}}).encode()): + with pytest.raises(ValueError): + app.read_export(raw) diff --git a/tests/test_audit_actions.py b/tests/test_audit_actions.py new file mode 100644 index 0000000..1e3de10 --- /dev/null +++ b/tests/test_audit_actions.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Jede Protokollaktion im Code ist erlaubt (audit.ACTIONS) und hat einen Namen +für die Protokollseite (routes/admin.py: ACTION_NAMES). + +Eine nicht erlaubte Aktion löst zur Laufzeit einen Fehler aus (HTTP 500). Der +Test liest nur den Quelltext und braucht keine Datenbank. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent / "surveybox" + + +def _literal_set(path: Path, name: str) -> set[str]: + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + targets: list[ast.expr] = [] + value: ast.expr | None = None + if isinstance(node, ast.Assign): + targets, value = node.targets, node.value + elif isinstance(node, ast.AnnAssign) and node.value is not None: + targets, value = [node.target], node.value + if any(isinstance(t, ast.Name) and t.id == name for t in targets) and value is not None: + if isinstance(value, ast.Set): + return {e.value for e in value.elts if isinstance(e, ast.Constant)} + if isinstance(value, ast.Dict): + return {k.value for k in value.keys if isinstance(k, ast.Constant)} + raise AssertionError(f"{name} nicht gefunden in {path}") + + +def _used_actions() -> dict[str, str]: + """Aktion -> Fundstelle für audit.record(db, "…") und action="…".""" + found: dict[str, str] = {} + for path in ROOT.rglob("*.py"): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + is_record = isinstance(func, ast.Attribute) and func.attr == "record" and ( + isinstance(func.value, ast.Name) and func.value.id == "audit" + ) + if is_record and len(node.args) >= 2 and isinstance(node.args[1], ast.Constant): + found[str(node.args[1].value)] = f"{path.name}:{node.lineno}" + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name not in ("record", "create_link"): + continue + for keyword in node.keywords: + if keyword.arg == "action" and isinstance(keyword.value, ast.Constant): + found[str(keyword.value.value)] = f"{path.name}:{node.lineno}" + # Standardwerte von Parametern namens "action" + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef): + args = node.args + defaults = dict(zip( + [a.arg for a in args.args][-len(args.defaults):] if args.defaults else [], + args.defaults, strict=False, + )) + value = defaults.get("action") + if isinstance(value, ast.Constant): + found[str(value.value)] = f"{path.name}:{node.lineno}" + return found + + +def test_every_used_action_is_allowed_and_named() -> None: + allowed = _literal_set(ROOT / "accounts" / "audit.py", "ACTIONS") + named = _literal_set(ROOT / "web" / "routes" / "admin.py", "ACTION_NAMES") + used = _used_actions() + assert used, "keine Protokollaktionen gefunden - Test prüft nichts" + missing = {a: where for a, where in used.items() if a not in allowed} + assert not missing, f"nicht in audit.ACTIONS: {missing}" + unnamed = {a: where for a, where in used.items() if a not in named} + assert not unnamed, f"nicht in ACTION_NAMES: {unnamed}" + + +def test_found_the_new_actions() -> None: + used = _used_actions() + for action in ("admin.mail_settings_changed", "admin.mail_test", + "account.reset_requested", "account.notifications_changed"): + assert action in used diff --git a/tests/test_backup.py b/tests/test_backup.py new file mode 100644 index 0000000..dc3a70d --- /dev/null +++ b/tests/test_backup.py @@ -0,0 +1,237 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +from __future__ import annotations + +import os +import socket +import subprocess +from collections.abc import Iterator +from datetime import UTC, datetime +from pathlib import Path + +import pytest + +from surveybox import backup + +# --------------------------------------------------------------------------- +# Reine Hilfsfunktionen +# --------------------------------------------------------------------------- + + +def _fake_pg_lib(root: Path, versions: list[int]) -> Path: + for v in versions: + bindir = root / str(v) / "bin" + bindir.mkdir(parents=True) + for tool in ("pg_dump", "pg_restore"): + (bindir / tool).write_text("#!/bin/sh\n") + (root / "notaversion").mkdir() + return root + + +@pytest.mark.parametrize( + ("server", "expected"), + [(17, 17), (18, 18), (16, 17), (19, 19)], +) +def test_find_pg_tool_prefers_same_then_next_higher( + tmp_path: Path, server: int, expected: int +) -> None: + root = _fake_pg_lib(tmp_path, [17, 18, 19]) + assert backup.find_pg_tool("pg_dump", server, root) == root / str(expected) / "bin/pg_dump" + + +def test_find_pg_tool_refuses_newer_server(tmp_path: Path) -> None: + root = _fake_pg_lib(tmp_path, [17, 18]) + with pytest.raises(backup.BackupError, match="PostgreSQL 19"): + backup.find_pg_tool("pg_dump", 19, root) + + +def test_backup_filename_sorts_chronologically() -> None: + a = backup.backup_filename("daily", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)) + b = backup.backup_filename("daily", datetime(2026, 11, 2, 3, 4, 5, tzinfo=UTC)) + assert a == "surveybox-daily-20260102T030405Z.dump" + assert a < b + + +def test_backup_filename_with_revisions_is_safe() -> None: + name = backup.backup_filename( + "pre-upgrade", datetime(2026, 1, 1, tzinfo=UTC), "0001_initial", "../../evil rev" + ) + assert "/" not in name and " " not in name + assert name.startswith("surveybox-pre-upgrade-20260101T000000Z-from-0001_initial-to-") + + +def test_apply_retention_keeps_newest(tmp_path: Path) -> None: + names = [ + backup.backup_filename("daily", datetime(2026, 1, day, tzinfo=UTC)) for day in range(1, 6) + ] + for n in names: + (tmp_path / n).write_bytes(b"x") + (tmp_path / "surveybox-daily-20260106T000000Z.dump.partial").write_bytes(b"x") + deleted = backup.apply_retention(tmp_path, keep=2) + assert [p.name for p in deleted] == names[:3] + remaining = sorted(p.name for p in tmp_path.iterdir()) + assert names[3] in remaining and names[4] in remaining + assert any(n.endswith(".partial") for n in remaining) # unfertige bleiben unangetastet + + +def test_subprocess_env_does_not_leak_app_secrets(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("SURVEYBOX_SECRET_KEY", "geheim") + env = backup._subprocess_env({"PGHOST": "db"}) + assert "SURVEYBOX_SECRET_KEY" not in env + assert env["PGHOST"] == "db" + + +# --------------------------------------------------------------------------- +# Gegen ein echtes PostgreSQL (temporärer Cluster oder Test-Datenbank) +# --------------------------------------------------------------------------- + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return int(s.getsockname()[1]) + + +@pytest.fixture(scope="module") +def pg_cluster(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[dict[str, str], int]]: + """Startet einen Wegwerf-Cluster mit den lokal installierten Werkzeugen.""" + versions = backup.available_pg_versions() + initdb = [backup.PG_LIB_ROOT / str(v) / "bin/initdb" for v in versions] + initdb = [p for p in initdb if p.is_file()] + if not initdb: + pytest.skip("kein initdb vorhanden") + if os.geteuid() == 0: + pytest.skip("PostgreSQL startet nicht als root") + bindir = initdb[-1].parent + major = int(bindir.parent.name) + base = tmp_path_factory.mktemp("pg") + data, sock = base / "data", base / "sock" + sock.mkdir() + subprocess.run( + [str(bindir / "initdb"), "-D", str(data), "-U", "test", "--auth=trust", "-E", "UTF8"], + check=True, capture_output=True, + ) + port = _free_port() + subprocess.run( + [str(bindir / "pg_ctl"), "-D", str(data), "-w", "-l", str(base / "log"), + "-o", f"-p {port} -k {sock} -c listen_addresses=''", "start"], + check=True, capture_output=True, + ) + env = {"PGHOST": str(sock), "PGPORT": str(port), "PGUSER": "test", "PGDATABASE": "postgres"} + try: + yield env, major + finally: + subprocess.run([str(bindir / "pg_ctl"), "-D", str(data), "-m", "fast", "stop"], + check=False, capture_output=True) + + +def _psql(bindir: Path, env: dict[str, str], sql: str) -> str: + out = subprocess.run( + [str(bindir / "psql"), "-XAtq", "-v", "ON_ERROR_STOP=1", "-c", sql], + env={**os.environ, **env}, check=True, capture_output=True, text=True, + ) + return out.stdout.strip() + + +def _tools(major: int) -> tuple[Path, Path, Path]: + return ( + backup.find_pg_tool("pg_dump", major), + backup.find_pg_tool("pg_restore", major), + backup.find_pg_tool("psql", major), + ) + + +def test_dump_verify_and_restore_roundtrip( + pg_cluster: tuple[dict[str, str], int], tmp_path: Path +) -> None: + env, major = pg_cluster + pg_dump, pg_restore, psql = _tools(major) + bindir = pg_dump.parent + + _psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox") + _psql(bindir, env, "CREATE TABLE surveybox.t (id int primary key, note text)") + _psql(bindir, env, "INSERT INTO surveybox.t VALUES (1, 'vorher')") + _psql(bindir, env, "CREATE TABLE public.fremd (x int); INSERT INTO public.fremd VALUES (7)") + + target = tmp_path / "out" / "surveybox-manual-test.dump" + backup.dump_to_file(pg_dump, pg_restore, env, target) + assert target.is_file() + assert oct(target.stat().st_mode & 0o777) == "0o600" + assert not list(target.parent.glob("*.partial")) + + # Ein "Update" nach der Sicherung: Daten geändert, neue Tabelle mit + # Fremdschlüssel auf eine alte Tabelle. Genau das ließe ein einfaches + # pg_restore --clean scheitern. + _psql(bindir, env, "UPDATE surveybox.t SET note = 'nachher'") + _psql( + bindir, + env, + "CREATE TABLE surveybox.neu (id int primary key, t_id int references surveybox.t(id))", + ) + _psql(bindir, env, "INSERT INTO surveybox.neu VALUES (1, 1)") + _psql(bindir, env, "UPDATE public.fremd SET x = 8") + + backup.restore_from_file(pg_restore, psql, env, target, tmp_path / "work") + assert _psql(bindir, env, "SELECT note FROM surveybox.t WHERE id = 1") == "vorher" + assert _psql(bindir, env, "SELECT to_regclass('surveybox.neu') IS NULL") == "t" + # Andere Schemata bleiben unberührt + assert _psql(bindir, env, "SELECT x FROM public.fremd") == "8" + assert not list((tmp_path / "work").glob(".restore-*")) + + +def test_failed_restore_keeps_current_state( + pg_cluster: tuple[dict[str, str], int], tmp_path: Path +) -> None: + """Bricht das Einspielen ab, bleibt der bisherige Stand vollständig erhalten.""" + env, major = pg_cluster + pg_dump, pg_restore, psql = _tools(major) + bindir = pg_dump.parent + _psql(bindir, env, "DROP SCHEMA IF EXISTS surveybox CASCADE; CREATE SCHEMA surveybox") + _psql(bindir, env, "CREATE TABLE surveybox.t (v text); INSERT INTO surveybox.t VALUES ('a')") + target = tmp_path / "surveybox-manual-t.dump" + backup.dump_to_file(pg_dump, pg_restore, env, target) + + _psql(bindir, env, "UPDATE surveybox.t SET v = 'b'") + # Eine Rolle, die es beim Einspielen nicht gibt, lässt einen Befehl der + # Sicherung scheitern: Wir hängen ihn an das erzeugte Skript an, indem + # wir pg_restore durch einen Wrapper ersetzen. + wrapper = tmp_path / "pg_restore_wrapper.sh" + wrapper.write_text( + "#!/bin/sh\n" + f'"{pg_restore}" "$@" || exit $?\n' + 'for a in "$@"; do case "$a" in --file=*) ' + 'echo "SELECT kaputt_absichtlich();" >> "${a#--file=}";; esac; done\n' + ) + wrapper.chmod(0o755) + with pytest.raises(backup.BackupError, match="Einspielen"): + backup.restore_from_file(wrapper, psql, env, target, tmp_path / "work") + assert _psql(bindir, env, "SELECT v FROM surveybox.t") == "b" + + +def test_failed_dump_leaves_no_file( + pg_cluster: tuple[dict[str, str], int], tmp_path: Path +) -> None: + env, major = pg_cluster + pg_dump, pg_restore, _ = _tools(major) + target = tmp_path / "surveybox-manual-broken.dump" + with pytest.raises(backup.BackupError, match="pg_dump"): + backup.dump_to_file(pg_dump, pg_restore, {**env, "PGDATABASE": "gibtsnicht"}, target) + assert not target.exists() + assert not list(tmp_path.glob("*.partial")) + + +def test_restore_rejects_corrupt_file( + pg_cluster: tuple[dict[str, str], int], tmp_path: Path +) -> None: + env, major = pg_cluster + _, pg_restore, psql = _tools(major) + bad = tmp_path / "kaputt.dump" + bad.write_bytes(b"keine Sicherung") + with pytest.raises(backup.BackupError, match="Prüfung"): + backup.restore_from_file(pg_restore, psql, env, bad, tmp_path / "work") + + +def test_restore_rejects_bad_schema_name(tmp_path: Path) -> None: + f = tmp_path / "x.dump" + f.write_bytes(b"x") + with pytest.raises(backup.BackupError, match="Schemaname"): + backup.restore_from_file(f, f, {}, f, tmp_path, schema="x; DROP") diff --git a/tests/test_branding.py b/tests/test_branding.py new file mode 100644 index 0000000..d127eea --- /dev/null +++ b/tests/test_branding.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Eigenes Logo über die Admin-Einstellungen (CI).""" + +from __future__ import annotations + +import io +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from helpers import new_client, token_for +from PIL import Image +from test_mail import admin + +pytestmark = pytest.mark.db + + +def png() -> bytes: + buf = io.BytesIO() + Image.new("RGBA", (300, 100), (31, 95, 174, 255)).save(buf, "PNG") + return buf.getvalue() + + +def test_upload_show_and_remove_logo(app: Any) -> None: + root = admin(app) + guest = new_client(app) + assert "img/logo.svg" in guest.get("/login").text + assert guest.get("/favicon.ico", follow_redirects=False).headers["location"].startswith( + "/static/img/") + csrf = token_for(root, "/admin/settings") + resp = root.post("/admin/settings/logo", data={"csrf_token": csrf}, + files={"logo": ("logo.png", png(), "image/png")}) + assert resp.status_code == 303 and "notice=settings_saved" in resp.headers["location"] + page = guest.get("/login").text + assert "/branding/logo.png?v=" in page and "/branding/favicon.png?v=" in page + logo = guest.get("/branding/logo.png") + assert logo.status_code == 200 and logo.headers["content-type"] == "image/png" + assert "immutable" in logo.headers["cache-control"] + assert guest.get("/favicon.ico", follow_redirects=False).headers["location"].startswith( + "/branding/favicon.png?v=") + assert guest.get("/branding/branding.json").status_code == 404 + # SVG wird abgelehnt, das bisherige Logo bleibt + csrf = token_for(root, "/admin/settings") + resp = root.post("/admin/settings/logo", data={"csrf_token": csrf}, + files={"logo": ("x.svg", b"", + "image/svg+xml")}) + assert "error=logo_invalid" in resp.headers["location"] + assert "/branding/logo.png?v=" in guest.get("/login").text + csrf = token_for(root, "/admin/settings") + root.post("/admin/settings/logo/remove", data={"csrf_token": csrf}) + assert "img/logo.svg" in guest.get("/login").text + assert guest.get("/branding/logo.png").status_code == 404 diff --git a/tests/test_branding_units.py b/tests/test_branding_units.py new file mode 100644 index 0000000..521c40c --- /dev/null +++ b/tests/test_branding_units.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Eigenes Logo: neu berechnet, drei Fassungen, nur bekannte Dateien (ohne Datenbank).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +pytest.importorskip("PIL") + +from PIL import Image, ImageDraw + +from surveybox import branding +from surveybox.media import images + + +def logo_file(tmp_path: Path, size: tuple[int, int] = (1200, 300)) -> Path: + img = Image.new("RGBA", size, (0, 0, 0, 0)) + ImageDraw.Draw(img).rectangle((100, 50, size[0] - 100, size[1] - 50), fill=(200, 30, 30, 255)) + path = tmp_path / "in.png" + img.save(path) + return path + + +def test_default_until_a_logo_is_saved(tmp_path: Path) -> None: + assert branding.current(tmp_path) == branding.DEFAULT + assert branding.DEFAULT.url("logo") is None + brand = branding.save_logo(tmp_path, logo_file(tmp_path)) + assert brand.custom and brand.url("favicon") == f"/branding/favicon.png?v={brand.version}" + sizes = {name: Image.open(tmp_path / "branding" / name).size + for name in branding.FILES.values() if name != "logo-dark.png"} + assert not brand.dark and brand.url("logo_dark") is None + assert sizes["favicon.png"] == (64, 64) and sizes["touch.png"] == (180, 180) + assert sizes["logo.png"][0] <= 800 and sizes["logo.png"][1] <= 240 + # Leere Ränder sind abgeschnitten + width, height = sizes["logo.png"] + assert width == 800 and 158 <= height <= 162 + branding.remove_logo(tmp_path) + assert branding.current(tmp_path) == branding.DEFAULT + + +def test_only_known_files_are_served(tmp_path: Path) -> None: + branding.save_logo(tmp_path, logo_file(tmp_path)) + assert branding.file_path(tmp_path, "logo.png") is not None + assert branding.file_path(tmp_path, "branding.json") is None + assert branding.file_path(tmp_path, "../secret") is None + + +def test_svg_and_garbage_are_refused(tmp_path: Path) -> None: + svg = tmp_path / "x.svg" + svg.write_text('') + with pytest.raises(images.ImageError): + branding.save_logo(tmp_path, svg) + assert branding.current(tmp_path) == branding.DEFAULT + + +def test_dark_logo(tmp_path: Path) -> None: + branding.save_logo(tmp_path, logo_file(tmp_path)) + brand = branding.save_logo(tmp_path, logo_file(tmp_path), dark=True) + assert brand.dark and brand.url("logo_dark") == f"/branding/logo-dark.png?v={brand.version}" + branding.remove_dark_logo(tmp_path) + brand = branding.current(tmp_path) + assert brand.custom and not brand.dark diff --git a/tests/test_calendar.py b/tests/test_calendar.py new file mode 100644 index 0000000..6dddb15 --- /dev/null +++ b/tests/test_calendar.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""iCalendar-Ausgabe der bestätigten Termine (ohne Datenbank).""" + +from __future__ import annotations + +from datetime import UTC, datetime +from types import SimpleNamespace +from zoneinfo import ZoneInfo + +from surveybox.forms import calendar + + +def poll(confirmed: list[str]) -> SimpleNamespace: + return SimpleNamespace( + id=7, + type="poll", + config={ + "mode": "dates", + "confirmed": confirmed, + "options": [ + {"id": "aaaa0001", "label": "", "date": "2026-07-01", "time": "18:30", + "duration": 90}, + {"id": "aaaa0002", "label": "Ausweichtermin; mit Grill, bitte", + "date": "2026-07-08", "time": None, "duration": None}, + {"id": "aaaa0003", "label": "", "date": "2026-07-15", "time": None, + "duration": None}, + ], + }, + ) + + +def test_only_confirmed_dates_with_utc_and_all_day() -> None: + events = calendar.confirmed_events([poll(["aaaa0001", "aaaa0002"])]) + text = calendar.build( + title="Sommerfest", url="https://x/f/t", host="x", events=events, + tz=ZoneInfo("Europe/Berlin"), now=datetime(2026, 6, 1, tzinfo=UTC), + ) + assert text.count("BEGIN:VEVENT") == 2 + assert "DTSTART:20260701T163000Z" in text and "DTEND:20260701T180000Z" in text + assert "DTSTART;VALUE=DATE:20260708" in text and "DTEND;VALUE=DATE:20260709" in text + assert "SUMMARY:Sommerfest: Ausweichtermin\\; mit Grill\\, bitte" in text + assert "20260715" not in text + assert all(len(line.encode()) <= 75 for line in text.split("\r\n")) + + +def test_folding_keeps_utf8() -> None: + long = "Ä" * 60 + folded = calendar._fold(f"SUMMARY:{long}") + assert "\r\n " in folded + assert folded.replace("\r\n ", "") == f"SUMMARY:{long}" diff --git a/tests/test_conditions.py b/tests/test_conditions.py new file mode 100644 index 0000000..c3adfc1 --- /dev/null +++ b/tests/test_conditions.py @@ -0,0 +1,176 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Bedingungen: Auswertung, Designer-Eingaben, Pflege (ohne Datenbank).""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +import pytest + +from surveybox.forms import conditions as c + + +@dataclass +class Q: + id: int + type: str + label: str = "" + config: dict[str, Any] = field(default_factory=dict) + position: int = 0 + required: bool = False + + +def form() -> list[Q]: + qs = [ + Q(1, "yes_no", "Kommen Sie?"), + Q(2, "number", "Wie viele?", {"decimals": 0}), + Q(3, "single_choice", "Essen", {"options": [{"id": "veg01", "label": "Vegetarisch"}, + {"id": "mea01", "label": "Fleisch"}]}), + Q(4, "multiple_choice", "Extras", {"options": [{"id": "dri01", "label": "Getränke"}, + {"id": "des01", "label": "Nachtisch"}]}), + Q(5, "short_text", "Unverträglichkeiten"), + Q(6, "page_break", "Seite 2"), + Q(7, "heading", "Übernachtung"), + Q(8, "date", "Anreise"), + Q(9, "file_upload", "Nachweis"), + ] + for index, q in enumerate(qs): + q.position = index + return qs + + +def rule(q: int, op: str, value: str = "") -> dict[str, Any]: + return {"q": q, "op": op, "value": value} + + +def cond(*rules: dict[str, Any], action: str = "show", match: str = "all") -> dict[str, Any]: + return {"action": action, "match": match, "rules": list(rules)} + + +def test_show_when_yes_and_hidden_answers_count_as_empty() -> None: + qs = form() + qs[1].config["condition"] = cond(rule(1, "eq", "yes")) + qs[2].config["condition"] = cond(rule(2, "gt", "2")) + # Nein: Frage 2 aus, also gilt ihr Wert als leer, also auch Frage 3 aus + hidden = c.hidden_ids(qs, {"q1": ["no"], "q2": ["5"]}) + assert {2, 3} <= hidden + hidden = c.hidden_ids(qs, {"q1": ["yes"], "q2": ["5"]}) + assert not {2, 3} & hidden + hidden = c.hidden_ids(qs, {"q1": ["yes"], "q2": ["2"]}) + assert 3 in hidden and 2 not in hidden + + +def test_page_and_section_conditions() -> None: + qs = form() + qs[5].config["condition"] = cond(rule(1, "eq", "yes")) # ganze Seite 2 + qs[6].config["condition"] = cond(rule(4, "contains", "des01"), action="hide") + hidden = c.hidden_ids(qs, {"q1": ["no"]}) + assert {6, 7, 8, 9} <= hidden + hidden = c.hidden_ids(qs, {"q1": ["yes"], "q4": ["dri01", "des01"]}) + assert 6 not in hidden and {7, 8, 9} <= hidden + hidden = c.hidden_ids(qs, {"q1": ["yes"], "q4": ["dri01"]}) + assert not {6, 7, 8, 9} & hidden + + +@pytest.mark.parametrize( + ("question", "rule_", "fields", "expected"), + [ + (5, rule(5, "contains", "NUSS"), {"q5": ["Haselnuss, Gluten"]}, True), + (5, rule(5, "eq", "gluten"), {"q5": [" Gluten "]}, True), + (5, rule(5, "not_contains", "nuss"), {"q5": [""]}, True), + (5, rule(5, "empty"), {"q5": [" "]}, True), + (2, rule(2, "lt", "3"), {"q2": ["2,0"]}, True), + (2, rule(2, "eq", "3"), {"q2": ["abc"]}, False), + (2, rule(2, "ne", "3"), {}, True), + (3, rule(3, "ne", "veg01"), {"q3": ["mea01"]}, True), + (4, rule(4, "not_contains", "des01"), {"q4": ["dri01"]}, True), + (8, rule(8, "gt", "2026-07-01"), {"q8": ["2026-07-02"]}, True), + (8, rule(8, "lt", "2026-07-01"), {"q8": [""]}, False), + ], +) +def test_operators(question: int, rule_: dict[str, Any], fields: dict[str, list[str]], + expected: bool) -> None: + qs = form() + target = Q(99, "info", "Ziel", {"condition": cond(rule_)}, position=100) + assert (99 not in c.hidden_ids([*qs, target], fields)) is expected + + +def test_files_and_any_match() -> None: + qs = form() + target = Q(99, "info", "Ziel", {"condition": cond(rule(9, "not_empty"), rule(1, "eq", "no"), + match="any")}, position=100) + assert 99 in c.hidden_ids([*qs, target], {"q1": ["yes"]}) + assert 99 not in c.hidden_ids([*qs, target], {"q1": ["yes"]}, with_files={9}) + + +def test_parse_from_designer() -> None: + qs = form() + question = qs[7] # Anreise, Position 7 + fields = { + "cond_action": ["show"], + "cond_match": ["any"], + "rule_q": ["1", "3", "2", ""], + "rule_op": ["eq", "ne", "gt", "eq"], + "rule_text": ["", "", "1,50", ""], + "rule_option": ["yes", "veg01", "", ""], + } + parsed = c.parse(question, fields, qs) + assert parsed == { + "action": "show", + "match": "any", + "rules": [rule(1, "eq", "yes"), rule(3, "ne", "veg01"), rule(2, "gt", "1.5")], + } + assert c.parse(question, {"rule_q": [""]}, qs) is None + + +@pytest.mark.parametrize( + ("fields", "code"), + [ + ({"rule_q": ["9"], "rule_op": ["empty"]}, "condition_ref_invalid"), # spätere Frage + ({"rule_q": ["7"], "rule_op": ["empty"]}, "condition_ref_invalid"), # keine Eingabe + ({"rule_q": ["1"], "rule_op": ["gt"], "rule_option": ["yes"]}, "condition_op_invalid"), + ({"rule_q": ["3"], "rule_op": ["eq"], "rule_option": ["xxx"]}, + "condition_value_invalid"), + ({"rule_q": ["2"], "rule_op": ["eq"], "rule_text": ["viele"]}, + "condition_value_invalid"), + ], +) +def test_parse_rejects(fields: dict[str, list[str]], code: str) -> None: + qs = form() + with pytest.raises(c.ConditionError) as exc: + c.parse(qs[7], fields, qs) + assert exc.value.code == code + + +def test_order_delete_and_copy_helpers() -> None: + qs = form() + qs[4].config["condition"] = cond(rule(1, "eq", "yes"), rule(3, "eq", "veg01")) + assert c.order_violations(qs) == [] + reordered = [qs[4], *qs[:4], *qs[5:]] + assert c.order_violations(reordered) == [5] + + cleaned = c.without_reference(qs[4].config, 3) + assert cleaned is not None and cleaned["condition"]["rules"] == [rule(1, "eq", "yes")] + assert c.without_reference(qs[4].config, 8) is None + assert "condition" not in c.remap(qs[4].config, {}) + assert c.remap(qs[4].config, {1: 11, 3: 13})["condition"]["rules"][1]["q"] == 13 + + +def test_layout() -> None: + pages = c.layout(form()) + assert len(pages) == 2 + assert [q.id for q in pages[0]["sections"][0]["items"]] == [1, 2, 3, 4, 5] + assert pages[1]["break"].id == 6 + assert pages[1]["sections"][1]["heading"].id == 7 + starts_with_break = [Q(1, "page_break"), Q(2, "short_text")] + assert len(c.layout(starts_with_break)) == 1 + + +def test_poll_and_slots_in_conditions() -> None: + qs = [Q(1, "poll", config={"options": [{"id": "t1", "label": "A"}]}), + Q(2, "slots", config={"options": [{"id": "s1", "label": "Früh"}]}, position=1), + Q(3, "info", config={"condition": cond(rule(1, "not_empty"))}, position=2), + Q(4, "info", config={"condition": cond(rule(2, "contains", "s1"))}, position=3)] + assert c.hidden_ids(qs, {"q1_propose_text": ["x"]}) == {3, 4} + assert c.hidden_ids(qs, {"q1_t1": ["no"], "q2": ["s1"]}) == set() diff --git a/tests/test_embed.py b/tests/test_embed.py new file mode 100644 index 0000000..7945013 --- /dev/null +++ b/tests/test_embed.py @@ -0,0 +1,70 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Einbetten im Rahmen (Nextcloud "External sites") und kompakte Darstellung (CI).""" + +from __future__ import annotations + +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from helpers import new_client + +pytestmark = pytest.mark.db + + +def test_embedding_forbidden_by_default(app: Any) -> None: + resp = new_client(app).get("/login") + assert resp.headers["X-Frame-Options"] == "DENY" + assert "frame-ancestors 'none'" in resp.headers["Content-Security-Policy"] + assert 'class="brand"' in resp.text + + +@pytest.fixture +def embed_app(db_settings: Any, monkeypatch: pytest.MonkeyPatch) -> Any: + from surveybox import db + from surveybox import settings as settings_mod + from surveybox.upgrade import run_upgrade + from surveybox.web.app import create_app + + monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", "https://cloud.example.de") + settings_mod.get_settings.cache_clear() + settings = settings_mod.get_settings() + run_upgrade(settings, db.get_engine()) + return create_app() + + +def test_allowed_ancestors_and_compact_mode(embed_app: Any) -> None: + client = new_client(embed_app) + resp = client.get("/login") + assert "X-Frame-Options" not in resp.headers + assert ("frame-ancestors 'self' https://cloud.example.de" + in resp.headers["Content-Security-Policy"]) + assert 'class="brand"' in resp.text # außerhalb des Rahmens wie immer + # Im Rahmen: ohne Logo und Fußzeile, mit "Neuer Tab" + framed = client.get("/login", headers={"Sec-Fetch-Dest": "iframe"}).text + assert 'class="brand"' not in framed and "topbar compact" in framed and "?embed=0" in framed + # ?embed=1 merkt sich die Darstellung, ?embed=0 schaltet sie ab + client.get("/login?embed=1") + assert "topbar compact" in client.get("/login").text + client.get("/login?embed=0") + assert "topbar compact" not in client.get("/login").text + + +def test_invalid_ancestors_are_refused(monkeypatch: pytest.MonkeyPatch) -> None: + pytest.importorskip("pydantic_settings") + from pydantic import ValidationError + + from surveybox.settings import Settings + + monkeypatch.setenv("SURVEYBOX_PUBLIC_URL", "https://umfrage.example.de") + monkeypatch.setenv("SURVEYBOX_SECRET_KEY", "x" * 40) + monkeypatch.setenv("SURVEYBOX_DB_PASSWORD", "x") + for value in ("http://cloud.example.de", "*", "https://a.de/pfad", "'unsafe-inline'"): + monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", value) + with pytest.raises(ValidationError): + Settings() + monkeypatch.setenv("SURVEYBOX_FRAME_ANCESTORS", "https://Cloud.example.de/, https://b.de:8443") + settings = Settings() + assert settings.frame_ancestors_csp == "'self' https://cloud.example.de https://b.de:8443" diff --git a/tests/test_erasure.py b/tests/test_erasure.py new file mode 100644 index 0000000..37c3b01 --- /dev/null +++ b/tests/test_erasure.py @@ -0,0 +1,196 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Phase 7b gegen PostgreSQL: Konten und Gast-Adressen löschen, Löschjournal (CI).""" + +from __future__ import annotations + +import re +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import new_client, token_for +from sqlalchemy import select, update +from sqlalchemy.orm import Session +from test_forms import creator, fill, form_row, participant +from test_mail import admin, content, messages +from test_phase5 import bookings, slot_form + +from surveybox import db, erasure_journal +from surveybox.models import ( + AuditEvent, + Comment, + Form, + FormMember, + GuestContact, + MailMessage, + Response, + UserAccount, + UserSession, +) +from surveybox.settings import get_settings + +pytestmark = pytest.mark.db + + +def user_by_email(email: str) -> UserAccount | None: + with Session(db.get_engine()) as s: + found = s.scalar(select(UserAccount).where(UserAccount.email == email)) + if found is not None: + s.expunge(found) + return found + + +def post_delete(client: TestClient, path: str, **data: Any) -> Any: + csrf = token_for(client, path) + return client.post(path, data={"csrf_token": csrf, **data}) + + +def audit_actions() -> list[str]: + with Session(db.get_engine()) as s: + return list(s.scalars(select(AuditEvent.action))) + + +def test_self_deletion_releases_place_and_is_journaled(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla, waitlist=True) + paul = participant(app) + assert fill(paul, token, {f"q{qid}": early}).status_code == 303 + assert fill(participant(app, "olga@example.de"), token, {f"q{qid}": early}).status_code == 303 + assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"] + page = paul.get("/account/delete").text + assert "1 answer is anonymized" in page and "waiting list move up" in page + # Ohne Bestätigung passiert nichts + assert post_delete(paul, "/account/delete").status_code == 400 + assert user_by_email("paul@example.de") is not None + resp = post_delete(paul, "/account/delete", confirm="on") + assert resp.status_code == 200 and "has been deleted" in resp.text + assert user_by_email("paul@example.de") is None + # Olga rückt nach; Pauls Antwort bleibt anonym ohne Platz (Formular läuft noch) + assert [b[1:] for b in bookings(qid)] == [("confirmed", True)] + with Session(db.get_engine()) as s: + rows = list(s.scalars(select(Response).where(Response.form_id == form_row(pid).id))) + assert sum(1 for r in rows if r.user_id is None and r.anonymized_at is not None) == 1 + assert "account.deleted" in audit_actions() + entries = erasure_journal.entries(get_settings()) + assert [e.kind for e in entries] == ["user"] + # Sitzung ist weg + assert paul.get("/account").status_code in (303, 401, 403) + + +def test_deletion_needs_recent_sign_in(app: Any) -> None: + paul = participant(app) + with Session(db.get_engine()) as s: + s.execute(update(UserSession).values(reauth_at=datetime.now(UTC) - timedelta(hours=1))) + s.commit() + page = paul.get("/account/delete").text + assert "sign in again" in page + assert post_delete(paul, "/account/delete", confirm="on").status_code == 403 + assert user_by_email("paul@example.de") is not None + resp = post_delete(paul, "/logout", next="/account/delete") + assert resp.headers["location"] == "/login?next=/account/delete" + + +def test_forms_are_handed_over_or_deleted(app: Any) -> None: + carla = creator(app) + kept, _, _, _ = slot_form(carla) + dropped, _, _, _ = slot_form(carla) + creator(app, "bea@example.de") + bea = user_by_email("bea@example.de") + assert bea is not None + with Session(db.get_engine()) as s: + s.add(FormMember(form_id=form_row(kept).id, user_id=bea.id, role="editor")) + s.add(Comment(form_id=form_row(kept).id, user_id=user_by_email("carla@example.de").id, # type: ignore[union-attr] + body="Hallo", status="published")) + s.commit() + page = carla.get("/account/delete").text + assert "Hand over to" in page + resp = post_delete(carla, "/account/delete", confirm="on", + **{f"form_{kept}": str(bea.public_id), f"form_{dropped}": "delete"}) + assert resp.status_code == 200 + with Session(db.get_engine()) as s: + forms = {str(f.public_id): f.owner_id for f in s.scalars(select(Form))} + comment = s.scalar(select(Comment)) + assert comment is not None and comment.author_deleted and comment.user_id is None + assert forms == {kept: bea.id} + (entry,) = erasure_journal.entries(get_settings()) + assert entry.extra["forms"] == {kept: str(bea.public_id), dropped: ""} + + +def test_admin_deletes_user_and_last_admin_is_protected(app: Any) -> None: + root = admin(app) + carla = creator(app) + pid, _, _, _ = slot_form(carla) + target = user_by_email("carla@example.de") + me = user_by_email("admin@example.de") + assert target is not None and me is not None + path = f"/admin/users/{target.public_id}/delete" + assert "Forms of this user" in root.get(path).text + resp = post_delete(root, path, confirm="on", forms_to=str(me.public_id)) + assert resp.headers["location"] == "/admin/users?notice=user_deleted" + assert user_by_email("carla@example.de") is None + assert form_row(pid).owner_id == me.id + # Der einzige Administrator kann sich nicht selbst löschen + assert root.get(f"/admin/users/{me.public_id}/delete").headers["location"] == "/account/delete" + resp = post_delete(root, "/account/delete", confirm="on") + assert resp.status_code == 400 and "last administrator" in resp.text + + +def test_guest_deletes_all_data_by_mail(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") + fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + guest = new_client(app) + csrf = token_for(guest, "/links") + resp = guest.post("/links/erase", data={"csrf_token": csrf, "email": "gast@example.de"}) + assert "sent a link to delete it" in resp.text + (mail,) = messages("guest_erase") + link = re.search(r"https?://\S+/g/erase/\S+", content(mail)["text"]).group(0) # type: ignore[union-attr] + path = link.replace(get_settings().public_origin, "") + page = guest.get(path) + assert page.status_code == 200 and "1 answer is anonymized" in page.text + csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr] + done = guest.post(path, data={"csrf_token": csrf, "confirm": "on"}) + assert done.status_code == 200 and "has been deleted" in done.text + with Session(db.get_engine()) as s: + assert s.scalar(select(GuestContact)) is None + assert list(s.scalars(select(MailMessage).where( + MailMessage.recipient == "gast@example.de"))) == [] + (response,) = s.scalars(select(Response)) + assert response.guest_contact_id is None and response.anonymized_at is not None + assert guest.get(path).status_code == 404 # Link ist verbraucht + assert "guest.deleted" in audit_actions() + + +def test_unknown_address_gets_same_answer(app: Any) -> None: + guest = new_client(app) + csrf = token_for(guest, "/links") + resp = guest.post("/links/erase", data={"csrf_token": csrf, "email": "niemand@example.de"}) + assert "sent a link to delete it" in resp.text + assert messages("guest_erase") == [] + + +def test_journal_is_replayed_after_restore(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") + fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + settings = get_settings() + with Session(db.get_engine()) as s: + contact = s.scalar(select(GuestContact)) + assert contact is not None + pid = contact.public_id + # Als wäre die Adresse nach der Sicherung gelöscht und die Sicherung dann zurückgespielt + erasure_journal.record(settings, "guest", pid) + erasure_journal.mark_restore(settings, datetime.now(UTC) - timedelta(minutes=5)) + from surveybox.worker import Worker + + assert Worker(settings).replay_erasures() == 1 + assert erasure_journal.pending_since(settings) is None + with Session(db.get_engine()) as s: + assert s.scalar(select(GuestContact)) is None + # Ältere Einträge fallen beim Aufräumen weg + assert erasure_journal.prune(settings, datetime.now(UTC) + timedelta(seconds=1)) == 1 + assert erasure_journal.entries(settings) == [] diff --git a/tests/test_erasure_journal_units.py b/tests/test_erasure_journal_units.py new file mode 100644 index 0000000..863c794 --- /dev/null +++ b/tests/test_erasure_journal_units.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Löschjournal ohne Datenbank: Einträge, Marke nach Wiederherstellung, Aufräumen.""" + +from __future__ import annotations + +import uuid +from datetime import UTC, datetime, timedelta +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +pytest.importorskip("pydantic_settings") + +from surveybox import erasure_journal +from surveybox.backup import backup_time + + +def settings(tmp_path: Path) -> Any: + return SimpleNamespace(data_dir=tmp_path, backup_dir=tmp_path / "backups") + + +def test_record_read_and_prune(tmp_path: Path) -> None: + s = settings(tmp_path) + first = uuid.uuid4() + erasure_journal.record(s, "user", first, forms={"a": ""}) + erasure_journal.record(s, "guest", uuid.uuid4()) + with erasure_journal.journal_path(s).open("a", encoding="utf-8") as handle: + handle.write('{"at": "kaputt"') # angefangene Zeile nach einem Absturz + found = erasure_journal.entries(s) + assert [e.kind for e in found] == ["user", "guest"] + assert found[0].id == str(first) and found[0].extra == {"forms": {"a": ""}} + later = datetime.now(UTC) + timedelta(seconds=1) + assert erasure_journal.entries(s, later) == [] + assert erasure_journal.prune(s, later) == 3 + assert erasure_journal.entries(s) == [] + with pytest.raises(ValueError): + erasure_journal.record(s, "unknown", first) + + +def test_restore_marker(tmp_path: Path) -> None: + s = settings(tmp_path) + assert erasure_journal.pending_since(s) is None + taken = datetime(2026, 11, 1, 3, 0, tzinfo=UTC) + erasure_journal.mark_restore(s, taken) + assert erasure_journal.pending_since(s) == taken + erasure_journal.clear_marker(s) + assert erasure_journal.pending_since(s) is None + + +def test_backup_time_from_name() -> None: + assert backup_time(Path("surveybox-daily-20261101T030000Z.dump")) == datetime( + 2026, 11, 1, 3, 0, tzinfo=UTC) + assert backup_time(Path( + "surveybox-pre-upgrade-20261101T030000Z-from-0012-to-0013.dump" + )) == datetime(2026, 11, 1, 3, 0, tzinfo=UTC) + assert backup_time(Path("eigene.dump")) is None diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py new file mode 100644 index 0000000..909f066 --- /dev/null +++ b/tests/test_evaluation.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Phase 8b gegen PostgreSQL: Filter, Teilnehmerlisten, Export, Löschen von Antworten (CI).""" + +from __future__ import annotations + +import csv +import io +import zipfile +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import new_client, token_for +from sqlalchemy import select, update +from sqlalchemy.orm import Session +from test_forms import add_question, creator, fill, form_row, participant, question_ids +from test_phase5 import slot_form + +from surveybox import db +from surveybox.models import AuditEvent, Response + +pytestmark = pytest.mark.db + + +def prepare(app: Any) -> tuple[TestClient, str, str, int, int, list[str]]: + carla = creator(app) + pid, token, slot_q, options = slot_form(carla, capacity="1", waitlist=True) + add_question(carla, pid, "participant_name", label="Name", email_mode="optional", + personal="on") + name_q = question_ids(pid)[-1] + fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Bernd", + f"q{name_q}_last": "Krause", f"q{name_q}_email": "=b@x.de"}) + fill(new_client(app), token, {f"q{slot_q}": options[0], f"q{name_q}_first": "Carla", + f"q{name_q}_last": "Kurz"}) + fill(participant(app), token, {f"q{slot_q}": options[1], f"q{name_q}_first": "Paul", + f"q{name_q}_last": "Peters"}) + return carla, pid, token, slot_q, name_q, options + + +def export(client: TestClient, pid: str, **data: str) -> Any: + csrf = token_for(client, f"/forms/{pid}/responses") + return client.post(f"/forms/{pid}/responses/export", data={"csrf_token": csrf, **data}) + + +def test_lists_filters_and_summary(app: Any) -> None: + carla, pid, _, slot_q, _, options = prepare(app) + page = carla.get(f"/forms/{pid}/responses").text + # Teilnehmerliste: Früh mit Bernd, Carla auf der Warteliste; Spät mit Paul + assert "Bernd Krause" in page and "Carla Kurz" in page and "Paul Peters" in page + filtered = carla.get(f"/forms/{pid}/responses?answer={slot_q}:{options[1]}").text + assert "1 of 3 answers match the filter" in filtered + assert "Paul Peters" in filtered and "Bernd Krause" not in filtered + tomorrow = (datetime.now(UTC) + timedelta(days=1)).date().isoformat() + assert "0 of 3 answers" in carla.get(f"/forms/{pid}/responses?from={tomorrow}").text + # Unbekannter Filter wird ignoriert + assert "3 answers so far" in carla.get(f"/forms/{pid}/responses?answer=999:x").text + + +def test_csv_and_xlsx_export(app: Any) -> None: + carla, pid, _, _, _, _ = prepare(app) + resp = export(carla, pid, format="csv") + assert resp.status_code == 200 and "attachment" in resp.headers["content-disposition"] + text = resp.content.decode("utf-8-sig") + rows = list(csv.reader(io.StringIO(text), delimiter=";")) + assert rows[0][:4] == ["No.", "Submitted", "Changed", "Participant"] + assert "Name: First name" in rows[0] and "Name: Email address" in rows[0] + assert len(rows) == 4 + assert any("'=b@x.de" in cell for cell in rows[1]) # Formel entschärft + assert any("(waiting list)" in cell for row in rows for cell in row) + # Ohne personenbezogene Daten: keine Namensspalten, kein Kontoname + lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig") + assert "Krause" not in lean and "Participant" not in lean.splitlines()[0] + # Gefiltert und als XLSX mit Info-Blatt und Logo + resp = export(carla, pid, format="xlsx", answer="") + with zipfile.ZipFile(io.BytesIO(resp.content)) as z: + assert "xl/worksheets/sheet2.xml" not in z.namelist() + assert any(n.startswith("xl/media/") for n in z.namelist()) + assert "Krause" in z.read("xl/worksheets/sheet1.xml").decode() + with Session(db.get_engine()) as s: + details = [e.details for e in s.scalars( + select(AuditEvent).where(AuditEvent.action == "form.exported"))] + assert [d["format"] for d in details] == ["csv", "csv", "xlsx"] # type: ignore[index] + assert details[1]["personal"] is False # type: ignore[index] + + +def test_browse_and_delete_answer(app: Any) -> None: + carla, pid, _, _, _, _ = prepare(app) + with Session(db.get_engine()) as s: + first = s.scalar(select(Response).where(Response.form_id == form_row(pid).id) + .order_by(Response.submitted_at, Response.id)) + assert first is not None + rid = first.public_id + s.execute(update(Response).where(Response.id == first.id).values( + submitted_at=datetime.now(UTC) - timedelta(hours=1))) + s.commit() + page = carla.get(f"/forms/{pid}/responses/{rid}").text + assert "Next" in page and "Delete answer" in page + csrf = token_for(carla, f"/forms/{pid}/responses/{rid}") + resp = carla.post(f"/forms/{pid}/responses/{rid}/delete", + data={"csrf_token": csrf, "confirm": "on"}) + assert resp.status_code == 303 and "response_deleted" in resp.headers["location"] + page = carla.get(f"/forms/{pid}/responses").text + assert "Bernd Krause" not in page + # Carla rückt von der Warteliste nach + assert "2 answers so far" in page + + +def test_invited_people_without_response_are_listed(app: Any) -> None: + from helpers import login + + from surveybox.models import Form, FormAccess, FormAccessEntry, UserAccount + + carla = creator(app) + pid, token, slot_q, options = slot_form(carla, capacity="") + participant(app) # paul + participant(app, "olga@example.de") + with Session(db.get_engine()) as s: + form = s.get(Form, form_row(pid).id) + assert form is not None + users = {u.email: u.id for u in s.scalars(select(UserAccount))} + for email in ("paul@example.de", "olga@example.de"): + s.add(FormAccessEntry(form_id=form.id, user_id=users[email])) + form.access = FormAccess.RESTRICTED + s.commit() + paul = new_client(app) + login(paul, "paul@example.de") + assert fill(paul, token, {f"q{slot_q}": options[0]}).status_code == 303 + page = carla.get(f"/forms/{pid}/responses").text + assert "1 invited person has not responded yet" in page + assert "no response yet" in page and "received" in page + missing = carla.get(f"/forms/{pid}/responses?missing=1").text + assert "no response yet" in missing and "received" not in missing + # Im Export ebenfalls, aber nicht ohne personenbezogene Daten + full = export(carla, pid, format="csv").content.decode("utf-8-sig") + assert "no response yet" in full + lean = export(carla, pid, format="csv", personal="off").content.decode("utf-8-sig") + assert "no response yet" not in lean diff --git a/tests/test_followups.py b/tests/test_followups.py new file mode 100644 index 0000000..4c7672a --- /dev/null +++ b/tests/test_followups.py @@ -0,0 +1,343 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Phase 6c gegen PostgreSQL: Folge-Mails mit Dokumenten, gestrichene Einträge, +Erinnerungen, tägliche Zusammenfassung (CI).""" + +from __future__ import annotations + +import re +import uuid +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import new_client, token_for +from sqlalchemy import select, update +from sqlalchemy.orm import Session +from test_forms import creator, fill, form_row, participant +from test_mail import content, messages +from test_phase5 import bookings, options_of, slot_form + +from surveybox import db +from surveybox.forms import digest, followups, reminders +from surveybox.models import ( + Followup, + FollowupDocument, + Form, + FormAccess, + FormAccessEntry, + UserAccount, +) +from surveybox.settings import get_settings + +pytestmark = pytest.mark.db + +PDF = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n" + + +def path_of(url: str) -> str: + return url.replace(get_settings().public_origin, "") + + +def create_followup(client: TestClient, pid: str, **fields: Any) -> str: + data = {"subject": "Unterlagen zu {form}", "body": "Hallo {name},\nanbei das Programm.", + "trigger": "manual", "link_days": "90", "catch_up": "no", **fields} + csrf = token_for(client, f"/forms/{pid}/followups/new") + resp = client.post(f"/forms/{pid}/followups/new", data={"csrf_token": csrf, **data}) + assert resp.status_code == 303, resp.text + match = re.search(r"/followups/([0-9a-f-]{36})", resp.headers["location"]) + assert match + return match.group(1) + + +def upload_pdf(client: TestClient, pid: str, fid: str) -> None: + url = f"/forms/{pid}/followups/{fid}" + csrf = token_for(client, url) + resp = client.post(f"{url}/documents", data={"csrf_token": csrf, "title": "Programm"}, + files={"document": ("programm.pdf", PDF, "application/pdf")}) + assert resp.status_code == 303, resp.text + + +def send_now(client: TestClient, pid: str, fid: str) -> Any: + url = f"/forms/{pid}/followups/{fid}" + csrf = token_for(client, url) + return client.post(f"{url}/send", data={"csrf_token": csrf, "confirm": "on"}) + + +def downloads() -> list[int]: + with Session(db.get_engine()) as s: + return [d.downloads for d in s.scalars(select(FollowupDocument))] + + +def test_followup_on_submit_with_personal_document_link(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla) + fid = create_followup(carla, pid, trigger="submit") + upload_pdf(carla, pid, fid) + paul = participant(app) + assert fill(paul, token, {f"q{qid}": early}).status_code == 303 + (mail,) = messages("followup") + assert mail.recipient == "paul@example.de" + data = content(mail) + assert data["subject"] == "Unterlagen zu Sommerfest" + assert data["text"].startswith("Hallo Anna,") # Testkonten heißen "Anna" + (link,) = [w for w in data["text"].split() if "/d/" in w] + # Persönlicher Link funktioniert ohne Anmeldung, zählt nur anonym + resp = new_client(app).get(path_of(link)) + assert resp.status_code == 200 and resp.content == PDF + assert "attachment" in resp.headers["content-disposition"] + assert downloads() == [1] + # Die Bestätigungsseite zeigt das Dokument; nur der Empfänger kommt dran + page = paul.get(f"/f/{token}").text + assert "Programm" in page + doc_url = re.search(rf"/f/{token}/documents/[0-9a-f-]{{36}}", page).group(0) # type: ignore[union-attr] + assert paul.get(doc_url).status_code == 200 + other = participant(app, "olga@example.de") + assert other.get(doc_url).status_code == 404 + # Geänderte Antwort: keine zweite Mail + fill(paul, token, {f"q{qid}": early}, path="/edit") + assert len(messages("followup")) == 1 + + +def test_manual_send_reaches_everyone_once(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, late) = slot_form(carla, capacity="") + fid = create_followup(carla, pid) + fill(participant(app), token, {f"q{qid}": early}) + fill(participant(app, "olga@example.de"), token, {f"q{qid}": late}) + page = carla.get(f"/forms/{pid}/followups/{fid}").text + assert "2 people who have not received it yet" in page + assert "Unterlagen zu Sommerfest" in page # Vorschau + resp = send_now(carla, pid, fid) + assert resp.status_code == 303 and "sent=2" in resp.headers["location"] + assert send_now(carla, pid, fid).headers["location"].count("sent=0") == 1 + assert sorted(m.recipient for m in messages("followup")) == [ + "olga@example.de", "paul@example.de"] + + +def test_only_confirmed_places(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla, waitlist=True) + fid = create_followup(carla, pid, only_confirmed="on") + fill(participant(app), token, {f"q{qid}": early}) + fill(participant(app, "olga@example.de"), token, {f"q{qid}": early}) + assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"] + send_now(carla, pid, fid) + assert [m.recipient for m in messages("followup")] == ["paul@example.de"] + + +def test_followup_when_form_closes(app: Any) -> None: + from test_forms import set_status + + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla) + create_followup(carla, pid, trigger="close") + fill(participant(app), token, {f"q{qid}": early}) + settings = get_settings() + with Session(db.get_engine()) as s: + assert followups.run_due(s, settings, datetime.now(UTC)) == 0 + s.commit() + assert set_status(carla, pid, "closed").status_code == 303 + with Session(db.get_engine()) as s: + assert followups.run_due(s, settings, datetime.now(UTC)) == 1 + s.commit() + (item,) = s.scalars(select(Followup)).all() + assert item.sent_at is not None + assert followups.run_due(s, settings, datetime.now(UTC)) == 0 + + +def test_removed_entry_notifies_and_frees_bookings(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, late) = slot_form(carla, capacity="") + fill(participant(app), token, {f"q{qid}": early}) + labels = {o["id"]: o["label"] for o in options_of(qid)} + assert labels[early] == "Früh" + # "Früh" streichen + csrf = token_for(carla, f"/forms/{pid}/questions/{qid}") + resp = carla.post(f"/forms/{pid}/questions/{qid}", data={ + "csrf_token": csrf, "label": "Schicht", "slot_mode": "list", + "option_id": [late], "option_label": ["Spät"], "option_capacity": [""]}) + assert resp.status_code == 303 + assert bookings(qid) == [] + (mail,) = messages("changed") + assert mail.recipient == "paul@example.de" and "Früh" in content(mail)["text"] + + +def test_reminder_for_invited_people(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, _) = slot_form(carla) + participant(app) # paul + participant(app, "olga@example.de") + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.share_token == token)) + assert form is not None + users = {u.email: u.id for u in s.scalars(select(UserAccount))} + for email in ("paul@example.de", "olga@example.de"): + s.add(FormAccessEntry(form_id=form.id, user_id=users[email])) + s.execute(update(Form).where(Form.id == form.id).values( + access=FormAccess.RESTRICTED, closes_at=datetime.now(UTC) + timedelta(days=2), + reminder_days=3)) + s.commit() + olga = new_client(app) + from helpers import login + + login(olga, "olga@example.de") + assert fill(olga, token, {f"q{qid}": early}).status_code == 303 + settings = get_settings() + with Session(db.get_engine()) as s: + assert reminders.run_due(s, settings, datetime.now(UTC)) == 1 + s.commit() + assert reminders.run_due(s, settings, datetime.now(UTC)) == 0 # nur einmal + s.commit() + assert [m.recipient for m in messages("reminder")] == ["paul@example.de"] + + +def test_daily_digest_for_managers(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, _) = slot_form(carla) + since = datetime.now(UTC) - timedelta(minutes=1) + fill(participant(app), token, {f"q{qid}": early}) + with Session(db.get_engine()) as s: + assert digest.run(s, get_settings(), since, "2026-11-25") == 1 + s.commit() + assert digest.run(s, get_settings(), since, "2026-11-25") == 0 # einmal je Tag + (mail,) = messages("digest") + assert mail.recipient == "carla@example.de" + assert "1 new answer" in content(mail)["text"] + + +def test_copy_keeps_followups_and_documents(app: Any) -> None: + carla = creator(app) + pid, _, _, _ = slot_form(carla) + fid = create_followup(carla, pid, trigger="submit") + upload_pdf(carla, pid, fid) + csrf = token_for(carla, f"/forms/{pid}") + resp = carla.post(f"/forms/{pid}/copy", data={"csrf_token": csrf}) + assert resp.status_code == 303 + with Session(db.get_engine()) as s: + assert len(s.scalars(select(Followup)).all()) == 2 + assert len(s.scalars(select(FollowupDocument)).all()) == 2 + assert form_row(pid) is not None + + +# -------------------------------------------------------------------------- +# Empfängerübersicht und Hinweise an Gäste +# -------------------------------------------------------------------------- + + +def recipients_page(client: TestClient, pid: str, fid: str) -> str: + resp = client.get(f"/forms/{pid}/followups/{fid}/recipients") + assert resp.status_code == 200 + return str(resp.text) + + +def send_to(client: TestClient, pid: str, fid: str, key: str) -> Any: + url = f"/forms/{pid}/followups/{fid}/recipients" + csrf = token_for(client, url) + return client.post(f"{url}/send", data={"csrf_token": csrf, "recipient": key}) + + +def test_guest_without_address_is_told_once(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") + guest = new_client(app) + # Ohne Folge-Mail: kein Hinweis + assert fill(guest, token, {f"q{qid}": early}).status_code == 303 + create_followup(carla, pid) + guest = new_client(app) + form_page = guest.get(f"/f/{token}").text + assert "You only receive it if you enter your email address" in form_page + first = fill(guest, token, {f"q{qid}": early}) + assert first.status_code == 200 + assert "You have not entered an email address" in first.text + assert 'name="followup_ack" value="1"' in first.text + second = fill(guest, token, {f"q{qid}": early, "followup_ack": "1"}) + assert second.status_code == 303 and second.headers["location"].endswith("?mail=none") + assert "without an email address" in guest.get(second.headers["location"]).text + # Mit Adresse: Hinweis in der Eingangsbestätigung und auf der Dankeseite + other = new_client(app) + resp = fill(other, token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + assert resp.headers["location"].endswith("?mail=confirm") + (mail,) = messages("guest_receipt") + assert "You only receive it if you confirm your email address" in content(mail)["text"] + + +def test_recipient_overview_and_sending_again(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") + fid = create_followup(carla, pid) + fill(participant(app), token, {f"q{qid}": early}) + fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + fill(new_client(app), token, {f"q{qid}": early, "followup_ack": "1"}) + page = recipients_page(carla, pid, fid) + assert "Not sent yet" in page and "Address not confirmed" in page + assert "No email address" in page + assert "gast@example.de" not in page # Zusage an Gäste: Adresse bleibt verborgen + keys = re.findall(r'name="recipient" value="([^"]+)"', page) + assert len(keys) == 1 and keys[0].startswith("u:") # nur Paul kann eine Mail bekommen + resp = send_to(carla, pid, fid, keys[0]) + assert resp.status_code == 303 and resp.headers["location"].endswith("result=sent") + page = recipients_page(carla, pid, fid) + assert "Received" in page and "Send again" in page and "waiting to be sent" in page + # Erneut senden: zweite Mail trotz Sperre gegen doppelte Einträge + assert send_to(carla, pid, fid, keys[0]).headers["location"].endswith("result=sent") + assert [m.recipient for m in messages("followup")] == ["paul@example.de"] * 2 + # Kein Teilnehmer dieses Formulars, kein Versand + bad = send_to(carla, pid, fid, "u:00000000-0000-0000-0000-000000000000") + assert bad.headers["location"].endswith("result=failed") + # Der Gesamtversand bleibt bei "noch nicht erhalten": Paul ist erledigt + assert "sent=0" in send_now(carla, pid, fid).headers["location"] + + +def test_planned_ignores_finished_one_time_mails(app: Any) -> None: + carla = creator(app) + pid, _, _, _ = slot_form(carla) + with Session(db.get_engine()) as s: + form = s.get(Form, form_row(pid).id) + assert form is not None and not followups.planned(s, form) + fid = create_followup(carla, pid, trigger="close") + with Session(db.get_engine()) as s: + form = s.get(Form, form_row(pid).id) + assert form is not None and followups.planned(s, form) + s.execute(update(Followup).where(Followup.public_id == uuid.UUID(fid)) + .values(sent_at=datetime.now(UTC))) + s.expire_all() + assert not followups.planned(s, form) + + +def test_catch_up_for_people_who_join_later(app: Any) -> None: + carla = creator(app) + pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional") + # Die Frage nach dem Nachholen muss beantwortet werden + csrf = token_for(carla, f"/forms/{pid}/followups/new") + resp = carla.post(f"/forms/{pid}/followups/new", data={ + "csrf_token": csrf, "subject": "S", "body": "B", "trigger": "manual", "link_days": "90"}) + assert resp.status_code == 400 and "join later" in resp.text + auto = create_followup(carla, pid, subject="Automatisch", catch_up="yes") + by_hand = create_followup(carla, pid, subject="Von Hand", catch_up="no") + fill(participant(app), token, {f"q{qid}": early}) + # Vor dem ersten Versand wird nichts nachgeholt + assert messages("followup") == [] + send_now(carla, pid, auto) + send_now(carla, pid, by_hand) + assert len(messages("followup")) == 2 + # Spätere Teilnahme: nur die Mail mit Nachholen kommt automatisch + fill(participant(app, "olga@example.de"), token, {f"q{qid}": early}) + later = [content(m)["subject"] for m in messages("followup") + if m.recipient == "olga@example.de"] + assert later == ["Automatisch"] + # Gast bestätigt seine Adresse erst später + guest = new_client(app) + fill(guest, token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + (receipt,) = messages("guest_receipt") + (confirm,) = [w for w in content(receipt)["text"].split() if "/g/confirm/" in w] + other = new_client(app) + page = other.get(path_of(confirm)) + csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr] + assert other.post(path_of(confirm), data={"csrf_token": csrf}).status_code == 200 + guest_mails = [content(m)["subject"] for m in messages("followup") + if m.recipient == "gast@example.de"] + assert guest_mails == ["Automatisch"] diff --git a/tests/test_form_files.py b/tests/test_form_files.py new file mode 100644 index 0000000..ac17464 --- /dev/null +++ b/tests/test_form_files.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""form_files muss die Dateien liefern, die request.form() erzeugt.""" + +from __future__ import annotations + +import asyncio + +import pytest + +pytest.importorskip("sqlalchemy") +pytest.importorskip("multipart") + +from starlette.requests import Request + +from surveybox.web.deps import form_files + +BOUNDARY = "sbtestboundary" + + +def _request(parts: list[tuple[str, str | None, bytes]]) -> Request: + body = b"" + for name, filename, data in parts: + disposition = f'form-data; name="{name}"' + if filename is not None: + disposition += f'; filename="{filename}"' + body += f"--{BOUNDARY}\r\nContent-Disposition: {disposition}\r\n".encode() + if filename is not None: + body += b"Content-Type: application/pdf\r\n" + body += b"\r\n" + data + b"\r\n" + body += f"--{BOUNDARY}--\r\n".encode() + sent = False + + async def receive() -> dict[str, object]: + nonlocal sent + if sent: + return {"type": "http.disconnect"} + sent = True + return {"type": "http.request", "body": body, "more_body": False} + + scope = { + "type": "http", + "method": "POST", + "path": "/", + "headers": [(b"content-type", f"multipart/form-data; boundary={BOUNDARY}".encode())], + } + return Request(scope, receive) + + +def test_uploaded_file_is_found_and_empty_field_skipped() -> None: + request = _request([ + ("csrf_token", None, b"x"), + ("document", "programm.pdf", b"%PDF-1.4 test"), + ("other", "", b""), + ]) + files = asyncio.run(form_files(request)) + assert list(files) == ["document"] + assert files["document"][0].filename == "programm.pdf" diff --git a/tests/test_forms.py b/tests/test_forms.py new file mode 100644 index 0000000..e8db1ce --- /dev/null +++ b/tests/test_forms.py @@ -0,0 +1,423 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Formulare: Anlegen, Ausfüllen, Zugriffsarten, Anonymität, Rechte (CI, PostgreSQL).""" + +from __future__ import annotations + +import uuid +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import login, make_user, new_client, token_for +from sqlalchemy import func, select +from sqlalchemy.orm import Session + +from surveybox import db +from surveybox.accounts import groups +from surveybox.models import ( + Answer, + Form, + FormParticipation, + Response, + Role, + UserAccount, +) + +pytestmark = pytest.mark.db + + +# --------------------------------------------------------------------------- +# Hilfen +# --------------------------------------------------------------------------- + + +def creator(app: Any, email: str = "carla@example.de") -> TestClient: + make_user(Role.CREATOR, email) + client = new_client(app) + assert login(client, email).status_code == 303 + return client + + +def participant(app: Any, email: str = "paul@example.de") -> TestClient: + make_user(Role.PARTICIPANT, email) + client = new_client(app) + assert login(client, email).status_code == 303 + return client + + +def create_form(client: TestClient, title: str = "Sommerfest") -> str: + csrf = token_for(client, "/forms") + resp = client.post("/forms", data={"title": title, "csrf_token": csrf}) + assert resp.status_code == 303, resp.text + return resp.headers["location"].rsplit("/", 1)[-1] + + +def add_question(client: TestClient, pid: str, type_key: str, **fields: Any) -> None: + csrf = token_for(client, f"/forms/{pid}/questions/new?type={type_key}") + data = {"csrf_token": csrf, **fields} + resp = client.post(f"/forms/{pid}/questions/new?type={type_key}", data=data) + assert resp.status_code == 303, resp.text + + +def save_settings(client: TestClient, pid: str, **overrides: Any) -> Any: + csrf = token_for(client, f"/forms/{pid}/settings") + data: dict[str, Any] = { + "csrf_token": csrf, + "title": "Sommerfest", + "access": "users", + "allow_edit": "until_close", + "deletion_mode": "anonymize", + "guest_email": "none", + "results_visibility": "never", + } + data.update(overrides) + return client.post(f"/forms/{pid}/settings", data=data) + + +def set_status(client: TestClient, pid: str, status: str) -> Any: + csrf = token_for(client, f"/forms/{pid}") + return client.post(f"/forms/{pid}/status", data={"status": status, "csrf_token": csrf}) + + +def form_row(pid: str) -> Form: + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid))) + assert form is not None + s.expunge(form) + return form + + +def question_ids(pid: str) -> list[int]: + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid))) + assert form is not None + return [q.id for q in form.questions] + + +def response_count(pid: str) -> int: + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid))) + assert form is not None + return s.scalar(select(func.count()).where(Response.form_id == form.id)) or 0 + + +def simple_form(client: TestClient, **settings: Any) -> tuple[str, str, list[int]]: + """Formular mit Pflicht-Textfrage und Einfachauswahl, veröffentlicht.""" + pid = create_form(client) + add_question(client, pid, "short_text", label="Ihr Name", required="on", max_length="50") + add_question( + client, pid, "single_choice", label="Lieblingsessen", + option_id=["", "", ""], option_label=["Pizza", "Salat", ""], display="radio", + ) + if settings: + assert save_settings(client, pid, **settings).status_code == 303 + assert set_status(client, pid, "open").status_code == 303 + return pid, form_row(pid).share_token, question_ids(pid) + + +def option_ids(pid: str, qid: int) -> list[str]: + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid))) + assert form is not None + question = next(q for q in form.questions if q.id == qid) + return [o["id"] for o in question.config["options"]] + + +def fill(client: TestClient, token: str, data: dict[str, Any], path: str = "") -> Any: + csrf = token_for(client, f"/f/{token}{path}") + return client.post(f"/f/{token}{path}", data={"csrf_token": csrf, **data}) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +def test_create_form_and_questions(app: Any) -> None: + client = creator(app) + pid = create_form(client, " Umfrage Herbst ") + assert form_row(pid).title == "Umfrage Herbst" + add_question(client, pid, "heading", label="Teil 1") + add_question(client, pid, "rating", label="Wie war es?", scale_max="7") + add_question( + client, pid, "multiple_choice", label="Was?", + option_id=["", ""], option_label=["A", "B"], min_select="0", max_select="2", + ) + page = client.get(f"/forms/{pid}") + assert page.status_code == 200 + assert "Wie war es?" in page.text + ids = question_ids(pid) + assert len(ids) == 3 + + # Zu wenige Optionen werden abgelehnt + csrf = token_for(client, f"/forms/{pid}/questions/new?type=ranking") + resp = client.post( + f"/forms/{pid}/questions/new?type=ranking", + data={"csrf_token": csrf, "label": "Rang", "option_id": [""], "option_label": ["nur eine"]}, + ) + assert resp.status_code == 400 + assert "at least two options" in resp.text + + # Verschieben: die letzte Frage nach oben + csrf = token_for(client, f"/forms/{pid}") + resp = client.post( + f"/forms/{pid}/questions/{ids[2]}/move", data={"direction": "up", "csrf_token": csrf} + ) + assert resp.status_code == 303 + assert question_ids(pid) == [ids[0], ids[2], ids[1]] + + # Vorschau rendert das Formular ohne Absende-Knopf + preview = client.get(f"/forms/{pid}/preview") + assert preview.status_code == 200 + assert 'type="submit">Submit' not in preview.text + + +def test_publish_needs_input_question(app: Any) -> None: + client = creator(app) + pid = create_form(client) + add_question(client, pid, "info", label="Nur Text") + resp = set_status(client, pid, "open") + assert resp.status_code == 400 + assert form_row(pid).status == "draft" + + +def test_draft_is_not_reachable(app: Any) -> None: + client = creator(app) + pid = create_form(client) + token = form_row(pid).share_token + guest = new_client(app) + assert guest.get(f"/f/{token}").status_code == 404 + assert guest.get("/f/doesnotexist").status_code == 404 + + +def test_fill_as_user_once_and_edit(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, q_food) = simple_form(owner) + pizza = option_ids(pid, q_food)[0] + + user = participant(app) + # Startseite zeigt das offene Formular + assert "Sommerfest" in user.get("/").text + + resp = fill(user, token, {f"q{q_name}": "Paul", f"q{q_food}": pizza}) + assert resp.status_code == 303 + assert resp.headers["location"] == f"/f/{token}/thanks" + assert response_count(pid) == 1 + + # Zweiter Aufruf: bereits teilgenommen, Ändern möglich + again = user.get(f"/f/{token}") + assert "already filled in" in again.text + assert f"/f/{token}/edit" in again.text + + # Doppeltes Absenden (z. B. altes Formular im Browser) legt nichts an + csrf = token_for(user, "/") + user.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Paul"}) + assert response_count(pid) == 1 + + # Ändern + edit = user.get(f"/f/{token}/edit") + assert edit.status_code == 200 + assert 'value="Paul"' in edit.text + resp = fill(user, token, {f"q{q_name}": "Paul Neu"}, path="/edit") + assert resp.status_code == 303 + with Session(db.get_engine()) as s: + texts = set(s.scalars(select(Answer.value_text).where(Answer.question_id == q_name))) + assert texts == {"Paul Neu"} + # Auswahl wurde entfernt, weil im neuen Absenden leer + assert s.scalar(select(func.count()).where(Answer.question_id == q_food)) == 0 + + +def test_users_access_requires_login(app: Any) -> None: + owner = creator(app) + _, token, _ = simple_form(owner) + guest = new_client(app) + resp = guest.get(f"/f/{token}") + assert resp.status_code == 303 + assert resp.headers["location"].startswith("/login") + + +def test_validation_errors_keep_input(app: Any) -> None: + owner = creator(app) + pid = create_form(owner) + add_question(owner, pid, "short_text", label="Name", required="on", max_length="50") + add_question(owner, pid, "number", label="Anzahl", min="1", max="10", decimals="0") + add_question(owner, pid, "email", label="Mail") + assert save_settings(owner, pid, access="link").status_code == 303 + assert set_status(owner, pid, "open").status_code == 303 + token = form_row(pid).share_token + q_name, q_num, q_mail = question_ids(pid) + + guest = new_client(app) + resp = fill(guest, token, {f"q{q_name}": "", f"q{q_num}": "12", f"q{q_mail}": "kein@"}) + assert resp.status_code == 400 + assert "Please answer this question." in resp.text + assert "The number is too large." in resp.text + assert "Please enter a valid email address." in resp.text + assert 'value="12"' in resp.text + assert response_count(pid) == 0 + + resp = fill(guest, token, {f"q{q_name}": "Gast", f"q{q_num}": "3", f"q{q_mail}": ""}) + assert resp.status_code == 303 + with Session(db.get_engine()) as s: + response = s.scalar(select(Response)) + assert response is not None + assert response.user_id is None + numbers = list(s.scalars(select(Answer.value_number).where(Answer.question_id == q_num))) + assert [float(n) for n in numbers] == [3.0] + + +def test_link_password(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner, access="link_password", link_password="geheim1") + guest = new_client(app) + + page = guest.get(f"/f/{token}") + assert page.status_code == 200 + assert 'name="password"' in page.text + + csrf = token_for(guest, f"/f/{token}") + wrong = guest.post(f"/f/{token}/password", data={"password": "falsch", "csrf_token": csrf}) + assert wrong.status_code == 400 + + right = guest.post(f"/f/{token}/password", data={"password": "geheim1", "csrf_token": csrf}) + assert right.status_code == 303 + page = guest.get(f"/f/{token}") + assert f'name="q{q_name}"' in page.text + assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303 + assert response_count(pid) == 1 + + # Neues Passwort macht alte Freischaltungen ungültig + changed = save_settings(owner, pid, access="link_password", link_password="anderes2") + assert changed.status_code == 303 + assert 'name="password"' in guest.get(f"/f/{token}").text + + +def test_link_password_needs_password(app: Any) -> None: + owner = creator(app) + pid = create_form(owner) + resp = save_settings(owner, pid, access="link_password") + assert resp.status_code == 400 + assert form_row(pid).access == "users" + + +def test_restricted_access_via_group(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner) + member_client = participant(app, "mia@example.de") + outsider = participant(app, "otto@example.de") + + with Session(db.get_engine()) as s: + member = s.scalar(select(UserAccount).where(UserAccount.email == "mia@example.de")) + assert member is not None + group = groups.create(s, "Festausschuss", "", actor_id=member.id) + groups.add_member(s, group, member, actor_id=member.id) + s.commit() + group_pid = str(group.public_id) + + resp = save_settings(owner, pid, access="restricted") + assert resp.status_code == 303 + assert resp.headers["location"] == f"/forms/{pid}/access" + csrf = token_for(owner, f"/forms/{pid}/access") + resp = owner.post(f"/forms/{pid}/access", data={"groups": [group_pid], "csrf_token": csrf}) + assert resp.status_code == 303 + + assert outsider.get(f"/f/{token}").status_code == 403 + assert "Sommerfest" not in outsider.get("/").text + assert member_client.get(f"/f/{token}").status_code == 200 + assert fill(member_client, token, {f"q{q_name}": "Mia"}).status_code == 303 + + +def test_anonymous_participation(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner, anonymous="on") + user = participant(app) + assert fill(user, token, {f"q{q_name}": "geheim"}).status_code == 303 + + with Session(db.get_engine()) as s: + response = s.scalar(select(Response)) + assert response is not None + assert response.user_id is None + assert s.scalar(select(func.count()).select_from(FormParticipation)) == 1 + + again = user.get(f"/f/{token}") + assert "already filled in" in again.text + assert "/edit" not in again.text + assert user.get(f"/f/{token}/edit").status_code == 303 + + # Anonymität lässt sich nach der ersten Antwort nicht mehr abschalten + resp = save_settings(owner, pid) + assert resp.status_code == 400 + assert form_row(pid).anonymous is True + + +def test_consent_required(app: Any) -> None: + owner = creator(app) + _, token, (q_name, _) = simple_form( + owner, access="link", require_consent="on", consent_text="Ich willige ein." + ) + guest = new_client(app) + resp = fill(guest, token, {f"q{q_name}": "Gast"}) + assert resp.status_code == 400 + assert "Please confirm the consent." in resp.text + assert fill(guest, token, {f"q{q_name}": "Gast", "consent": "on"}).status_code == 303 + with Session(db.get_engine()) as s: + response = s.scalar(select(Response)) + assert response is not None + assert response.consent_at is not None + + +def test_closed_form(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner, access="link") + assert set_status(owner, pid, "closed").status_code == 303 + guest = new_client(app) + page = guest.get(f"/f/{token}") + assert "This form is closed" in page.text + csrf = token_for(guest, f"/f/{token}") + guest.post(f"/f/{token}", data={"csrf_token": csrf, f"q{q_name}": "Zu spät"}) + assert response_count(pid) == 0 + + +def test_responses_view_and_permissions(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner) + user = participant(app) + assert fill(user, token, {f"q{q_name}": "Antwort von Paul"}).status_code == 303 + + listing = owner.get(f"/forms/{pid}/responses") + assert listing.status_code == 200 + with Session(db.get_engine()) as s: + response = s.scalar(select(Response)) + assert response is not None + rid = str(response.public_id) + assert rid in listing.text + detail = owner.get(f"/forms/{pid}/responses/{rid}") + assert "Antwort von Paul" in detail.text + + # Teilnehmende und fremde Ersteller sehen nichts + assert pid not in user.get("/forms").text + assert user.get(f"/forms/{pid}/responses").status_code == 403 + other = creator(app, "olga@example.de") + assert other.get(f"/forms/{pid}").status_code == 403 + assert other.get(f"/forms/{pid}/responses/{rid}").status_code == 403 + assert pid not in other.get("/forms").text + + +def test_delete_form(app: Any) -> None: + owner = creator(app) + pid, token, (q_name, _) = simple_form(owner, access="link") + guest = new_client(app) + assert fill(guest, token, {f"q{q_name}": "Gast"}).status_code == 303 + + csrf = token_for(owner, f"/forms/{pid}/settings") + assert owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf}).status_code == 400 + resp = owner.post(f"/forms/{pid}/delete", data={"csrf_token": csrf, "confirm": "on"}) + assert resp.status_code == 303 + with Session(db.get_engine()) as s: + assert s.scalar(select(func.count()).select_from(Form)) == 0 + assert s.scalar(select(func.count()).select_from(Response)) == 0 + assert s.scalar(select(func.count()).select_from(Answer)) == 0 + assert guest.get(f"/f/{token}").status_code == 404 diff --git a/tests/test_group_scope.py b/tests/test_group_scope.py new file mode 100644 index 0000000..704f88c --- /dev/null +++ b/tests/test_group_scope.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Gruppenadministratoren, Gruppenersteller, Hierarchie (CI, PostgreSQL).""" + +from __future__ import annotations + +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import csrf_from, login, make_user, new_client, next_totp, token_for +from sqlalchemy import select +from sqlalchemy.orm import Session +from test_forms import add_question, fill, form_row, set_status + +from surveybox import db +from surveybox.models import ( + Form, + FormAccessEntry, + GroupMember, + GroupRole, + Role, + UserAccount, + UserGroup, +) + +pytestmark = pytest.mark.db + + +def build_tree() -> dict[str, int]: + """Gesamtwehr > Nord > Jugend; Gesamtwehr > Süd.""" + with Session(db.get_engine()) as s: + top = UserGroup(name="Gesamtwehr") + s.add(top) + s.flush() + north = UserGroup(name="Nord", parent_id=top.id) + south = UserGroup(name="Süd", parent_id=top.id) + s.add_all([north, south]) + s.flush() + youth = UserGroup(name="Jugend", parent_id=north.id) + s.add(youth) + s.commit() + return {"top": top.id, "north": north.id, "south": south.id, "youth": youth.id} + + +def user_id(email: str) -> int: + with Session(db.get_engine()) as s: + uid = s.scalar(select(UserAccount.id).where(UserAccount.email == email)) + assert uid is not None + return uid + + +def give(email: str, group: int, *, member: bool = True, role: str | None = None) -> None: + uid = user_id(email) + with Session(db.get_engine()) as s: + if member: + s.add(GroupMember(group_id=group, user_id=uid)) + if role: + s.add(GroupRole(group_id=group, user_id=uid, role=role)) + s.commit() + + +def public_id(group: int) -> str: + with Session(db.get_engine()) as s: + return str(s.get(UserGroup, group).public_id) # type: ignore[union-attr] + + +def signed_in(app: Any, email: str, secret: str | None = None) -> TestClient: + client = new_client(app) + login(client, email) + if secret: + mfa = client.get("/login/mfa") + client.post("/login/mfa", data={"code": next_totp(secret), + "csrf_token": csrf_from(mfa.text), "next": "/"}) + return client + + +def test_group_admin_needs_second_factor(app: Any) -> None: + ids = build_tree() + make_user(Role.PARTICIPANT, "gina@example.de") + give("gina@example.de", ids["north"], role="admin") + client = signed_in(app, "gina@example.de") + resp = client.get("/admin/groups") + assert resp.status_code == 303 + assert "mfa_required_admin" in resp.headers["location"] + + +def test_group_admin_scope(app: Any) -> None: + ids = build_tree() + _, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True) + give("gina@example.de", ids["north"], role="admin") + make_user(Role.PARTICIPANT, "sven@example.de") + give("sven@example.de", ids["south"]) + client = signed_in(app, "gina@example.de", secret) + + listing = client.get("/admin/groups").text + assert "Nord" in listing and "Jugend" in listing + assert "Süd" not in listing and "Gesamtwehr" not in listing + assert client.get(f"/admin/groups/{public_id(ids['south'])}").status_code == 403 + assert client.get("/admin/users").status_code == 403 + + # Neue Gruppe nur unterhalb der eigenen + csrf = token_for(client, "/admin/groups") + resp = client.post("/admin/groups", data={"name": "Oben", "csrf_token": csrf}) + assert resp.status_code == 400 + resp = client.post("/admin/groups", data={"name": "Kinder", "csrf_token": csrf, + "parent": public_id(ids["youth"])}) + assert resp.status_code == 303 + + # Neues Konto direkt in der Jugend, als Teilnehmer + youth_page = f"/admin/groups/{public_id(ids['youth'])}" + csrf = token_for(client, youth_page) + resp = client.post(f"{youth_page}/new-member", data={ + "csrf_token": csrf, "display_name": "Jana", "email": "jana@example.de"}) + assert resp.status_code == 200 and "/setup/" in resp.text + with Session(db.get_engine()) as s: + jana = s.scalar(select(UserAccount).where(UserAccount.email == "jana@example.de")) + assert jana is not None and jana.role == Role.PARTICIPANT + assert s.get(GroupMember, (ids["youth"], jana.id)) is not None + sven_pid = str(s.scalar(select(UserAccount.public_id).where( + UserAccount.email == "sven@example.de"))) + jana_pid = str(jana.public_id) + + # Jana wird Gruppenerstellerin; Sven (Süd) kann nicht geholt werden + resp = client.post(f"{youth_page}/roles", data={"csrf_token": csrf, "user": jana_pid, + "role": "creator"}) + assert resp.status_code == 303 + resp = client.post(f"{youth_page}/members", data={"csrf_token": csrf, "user": sven_pid}) + assert resp.status_code == 403 + + # Die eigene oberste Gruppe lässt sich nicht löschen, Untergruppen schon + north_page = f"/admin/groups/{public_id(ids['north'])}" + csrf = token_for(client, north_page) + assert client.post(f"{north_page}/delete", + data={"csrf_token": csrf, "confirm": "on"}).status_code == 403 + + +def test_group_creator_forms_and_inheritance(app: Any) -> None: + ids = build_tree() + make_user(Role.PARTICIPANT, "carl@example.de") + give("carl@example.de", ids["north"], member=False, role="creator") + make_user(Role.PARTICIPANT, "jule@example.de") + give("jule@example.de", ids["youth"]) + make_user(Role.PARTICIPANT, "sven@example.de") + give("sven@example.de", ids["south"]) + carl = signed_in(app, "carl@example.de") + + # Nur in eigenen Gruppen + csrf = token_for(carl, "/forms") + resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug", + "group": public_id(ids["south"])}) + assert resp.status_code == 400 + resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug"}) + assert resp.status_code == 400 + resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug", + "group": public_id(ids["north"])}) + assert resp.status_code == 303 + pid = resp.headers["location"].rsplit("/", 1)[-1] + form = form_row(pid) + assert form.access == "restricted" and form.group_id == ids["north"] + with Session(db.get_engine()) as s: + entries = list(s.scalars(select(FormAccessEntry.group_id).where( + FormAccessEntry.form_id == form.id))) + assert entries == [ids["north"]] + + # "Alle angemeldeten Benutzer" ist gesperrt + csrf = token_for(carl, f"/forms/{pid}/settings") + resp = carl.post(f"/forms/{pid}/settings", data={ + "csrf_token": csrf, "title": "Ausflug", "access": "users", "allow_edit": "until_close", + "deletion_mode": "anonymize", "guest_email": "none", "results_visibility": "never", + "group": public_id(ids["north"])}) + assert resp.status_code == 400 + access_page = carl.get(f"/forms/{pid}/access").text + assert "Jugend" in access_page and "Süd" not in access_page + + add_question(carl, pid, "short_text", label="Name") + assert set_status(carl, pid, "open").status_code == 303 + token = form_row(pid).share_token + qid = _question_id(pid) + + # Mitglied der Untergruppe Jugend darf, Süd nicht + jule = signed_in(app, "jule@example.de") + assert jule.get(f"/f/{token}").status_code == 200 + assert "Ausflug" in jule.get("/").text + assert fill(jule, token, {f"q{qid}": "Jule"}).status_code == 303 + sven = signed_in(app, "sven@example.de") + assert sven.get(f"/f/{token}").status_code == 403 + + +def test_group_admin_manages_forms_below(app: Any) -> None: + ids = build_tree() + make_user(Role.PARTICIPANT, "carl@example.de") + give("carl@example.de", ids["youth"], member=False, role="creator") + _, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True) + give("gina@example.de", ids["north"], member=False, role="admin") + _, secret_s = make_user(Role.PARTICIPANT, "sina@example.de", with_totp=True) + give("sina@example.de", ids["south"], member=False, role="admin") + + carl = signed_in(app, "carl@example.de") + csrf = token_for(carl, "/forms") + resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Zeltlager", + "group": public_id(ids["youth"])}) + pid = resp.headers["location"].rsplit("/", 1)[-1] + + gina = signed_in(app, "gina@example.de", secret) + assert gina.get(f"/forms/{pid}").status_code == 200 + assert "Zeltlager" in gina.get("/forms").text + assert gina.get(f"/forms/{pid}/team").status_code == 200 # Verwaltung wie Eigentümer + sina = signed_in(app, "sina@example.de", secret_s) + assert sina.get(f"/forms/{pid}").status_code == 403 + assert "Zeltlager" not in sina.get("/forms").text + + +def _question_id(pid: str) -> int: + import uuid + + with Session(db.get_engine()) as s: + form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid))) + assert form is not None + return form.questions[0].id diff --git a/tests/test_groups.py b/tests/test_groups.py new file mode 100644 index 0000000..27206ab --- /dev/null +++ b/tests/test_groups.py @@ -0,0 +1,264 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Fragengruppen und Teilnahme mit einem Eintrag (ohne Datenbank).""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Any +from zoneinfo import ZoneInfo + +import pytest + +from surveybox.forms import conditions, groups, types + +TZ = ZoneInfo("Europe/Berlin") + + +@dataclass +class Q: + id: int + type: str + label: str = "" + config: dict[str, Any] = field(default_factory=dict) + position: int = 0 + required: bool = False + + +def slot(qid: int, label: str, capacity: int | None = None, **extra: Any) -> Q: + option: dict[str, Any] = {"id": types.SINGLE_SLOT, "label": label} + if capacity: + option["capacity"] = capacity + return Q(qid, "slots", label, {"single": True, "options": [option], **extra}) + + +def numbered(qs: list[Q]) -> list[Q]: + for index, q in enumerate(qs): + q.position = index + return qs + + +def shifts() -> list[Q]: + return numbered([ + Q(1, "yes_no", "Helfen Sie mit?"), + Q(2, groups.GROUP, "Schichten", {"member_type": "slots", "max_select": 2}), + slot(3, "Fr früh", 3), + slot(4, "Fr spät", 3), + slot(5, "Sa früh"), + Q(6, "short_text", "Bemerkung"), + slot(7, "Einzeln"), # nach einer anderen Frage: nicht mehr in der Gruppe + ]) + + +# -------------------------------------------------------------------------- +# Zugehörigkeit +# -------------------------------------------------------------------------- + + +def test_members_are_following_questions_of_the_type() -> None: + qs = shifts() + assert [m.id for m in groups.resolve(qs)[2]] == [3, 4, 5] + assert groups.member_of(qs) == {3: 2, 4: 2, 5: 2} + + +def test_heading_or_other_group_ends_a_group() -> None: + qs = numbered([ + Q(1, groups.GROUP, "A", {"member_type": "yes_no"}), + Q(2, "yes_no", "a"), + Q(3, "heading", "H"), + Q(4, "yes_no", "b"), + Q(5, groups.GROUP, "B", {"member_type": "yes_no"}), + Q(6, groups.GROUP, "C", {"member_type": "yes_no"}), + Q(7, "yes_no", "c"), + ]) + found = groups.resolve(qs) + assert [m.id for m in found[1]] == [2] + assert found[5] == [] + assert [m.id for m in found[6]] == [7] + + +def test_legacy_slot_lists_do_not_join_a_group() -> None: + legacy = Q(3, "slots", "Alt", {"options": [{"id": "aaaaaa", "label": "x"}, + {"id": "bbbbbb", "label": "y"}]}) + qs = numbered([Q(1, groups.GROUP, "G", {"member_type": "slots"}), slot(2, "neu"), legacy]) + assert [m.id for m in groups.resolve(qs)[1]] == [2] + + +def test_members_must_match_the_first_one() -> None: + a = {"options": [{"id": "aaaaaa", "label": "Rot"}, {"id": "bbbbbb", "label": "Grün"}]} + b = {"options": [{"id": "cccccc", "label": "Rot"}, {"id": "dddddd", "label": "Grün"}]} + c = {"options": [{"id": "eeeeee", "label": "Blau"}, {"id": "ffffff", "label": "Grün"}]} + qs = numbered([ + Q(1, groups.GROUP, "M", {"member_type": "single_choice"}), + Q(2, "single_choice", "x", a), Q(3, "single_choice", "y", b), Q(4, "single_choice", "z", c), + Q(5, groups.GROUP, "R", {"member_type": "rating"}), + Q(6, "rating", "r1", {"scale_max": 5}), Q(7, "rating", "r2", {"scale_max": 7}), + Q(8, groups.GROUP, "J", {"member_type": "yes_no"}), + Q(9, "yes_no", "j1"), Q(10, "yes_no", "j2", {"label_yes": "Gern"}), + ]) + found = groups.resolve(qs) + assert [m.id for m in found[1]] == [2, 3] + assert [m.id for m in found[5]] == [6] + assert [m.id for m in found[8]] == [9] + + +def test_choice_with_other_cannot_be_grouped() -> None: + cfg = {"allow_other": True, "options": [{"id": "aaaaaa", "label": "x"}]} + qs = numbered([Q(1, groups.GROUP, "M", {"member_type": "single_choice"}), + Q(2, "single_choice", "x", cfg)]) + assert groups.resolve(qs)[1] == [] + + +def test_max_select_only_for_counting_types() -> None: + def group(**cfg: Any) -> Q: + return Q(1, groups.GROUP, config=cfg) + + assert groups.max_select(group(member_type="slots", max_select=2)) == 2 + assert groups.max_select(group(member_type="rating", max_select=2)) == 0 + assert groups.max_select(group(member_type="slots")) == 0 + assert groups.min_select(group(member_type="yes_no", min_select=1)) == 1 + assert groups.min_select(group(member_type="rating", min_select=1)) == 0 + + +# -------------------------------------------------------------------------- +# Höchstzahl +# -------------------------------------------------------------------------- + + +def booked() -> dict[str, Any]: + return {"value_json": {"selected": [types.SINGLE_SLOT]}} + + +def test_too_many_counts_bookings() -> None: + qs = shifts() + check = groups.count_errors + assert check(qs, {3: booked(), 4: booked()}, set()) == {} + assert check(qs, {3: booked(), 4: booked(), 5: booked()}, set()) == {2: "group_too_many"} + # Ausgeblendete Fragen und Gruppen zählen nicht + assert check(qs, {3: booked(), 4: booked(), 5: booked()}, {5}) == {} + assert check(qs, {3: booked(), 4: booked(), 5: booked()}, {2}) == {} + # Fragen außerhalb der Gruppe zählen nicht + assert check(qs, {3: booked(), 4: booked(), 7: booked()}, set()) == {} + + +def test_too_many_counts_yes_only() -> None: + qs = numbered([Q(1, groups.GROUP, "J", {"member_type": "yes_no", "max_select": 1}), + Q(2, "yes_no", "a"), Q(3, "yes_no", "b")]) + yes, no = {"value_bool": True}, {"value_bool": False} + assert groups.count_errors(qs, {2: yes, 3: no}, set()) == {} + assert groups.count_errors(qs, {2: yes, 3: yes}, set()) == {1: "group_too_many"} + + +def test_min_select() -> None: + qs = shifts() + qs[1].config.update(min_select=1, max_select=1) + assert groups.count_errors(qs, {}, set()) == {2: "group_too_few"} + assert groups.count_errors(qs, {4: booked()}, set()) == {} + # Weniger sichtbare Zeilen als die Mindestzahl: dann zählen alle sichtbaren + qs[1].config.update(min_select=3, max_select=0) + assert groups.count_errors(qs, {3: booked(), 4: booked()}, {5}) == {} + assert groups.count_errors(qs, {3: booked()}, {5}) == {2: "group_too_few"} + # Ausgeblendete Gruppe verlangt nichts + assert groups.count_errors(qs, {}, {2, 3, 4, 5}) == {} + + +def test_required_rows_in_slot_group_are_ruled_by_the_group() -> None: + qs = shifts() + for q in qs[2:5]: + q.required = True # drei Pflicht-Schichten, höchstens eine wählbar + ruled = groups.required_by_group(qs) + assert ruled == {3, 4, 5} + # Die einzelne Schicht ist dann keine Pflicht mehr + assert types.parse_answer(qs[2], {}, TZ, required=False).error is None + assert types.parse_answer(qs[2], {}, TZ).error == "required" + # Ja/Nein-Zeilen behalten ihre Pflicht + yn = numbered([Q(1, groups.GROUP, "J", {"member_type": "yes_no"}), Q(2, "yes_no", "a")]) + assert groups.required_by_group(yn) == set() + + +# -------------------------------------------------------------------------- +# Bedingungen und Aufbau der Seite +# -------------------------------------------------------------------------- + + +def test_condition_on_group_hides_all_members() -> None: + qs = shifts() + qs[1].config["condition"] = {"action": "show", "match": "all", + "rules": [{"q": 1, "op": "eq", "value": "yes"}]} + assert conditions.hidden_ids(qs, {"q1": ["no"]}) == {2, 3, 4, 5} + assert conditions.hidden_ids(qs, {"q1": ["yes"]}) == set() + + +def test_member_keeps_its_own_condition() -> None: + qs = shifts() + qs[3].config["condition"] = {"action": "show", "match": "all", + "rules": [{"q": 3, "op": "contains", "value": "single"}]} + assert conditions.hidden_ids(qs, {}) == {4} + assert conditions.hidden_ids(qs, {"q3": ["single"]}) == set() + + +def test_layout_shows_group_instead_of_members() -> None: + qs = shifts() + items = conditions.layout(qs)[0]["sections"][0]["items"] + assert [q.id for q in items] == [1, 2, 6, 7] + + +def test_single_slot_rule_option_is_signed_up() -> None: + assert conditions.options_for_rules(slot(1, "x")) == [(types.SINGLE_SLOT, "signed up")] + + +# -------------------------------------------------------------------------- +# Einstellungen und Antworten +# -------------------------------------------------------------------------- + + +def test_group_config() -> None: + cfg = types.parse_config(groups.GROUP, {"member_type": ["slots"], "max_select": ["3"], + "min_select": ["1"]}) + assert cfg == {"member_type": "slots", "min_select": 1, "max_select": 3} + cfg = types.parse_config(groups.GROUP, {"member_type": ["rating"], "max_select": ["3"]}) + assert cfg == {"member_type": "rating", "min_select": 0, "max_select": 0} + with pytest.raises(types.ConfigError): + types.parse_config(groups.GROUP, {"member_type": ["slots"], "min_select": ["2"], + "max_select": ["1"]}) + with pytest.raises(types.ConfigError): + types.parse_config(groups.GROUP, {"member_type": ["poll"]}) + with pytest.raises(types.ConfigError): + types.parse_config(groups.GROUP, {"member_type": ["slots"], "max_select": ["-1"]}) + + +def test_single_slot_config_keeps_option_id() -> None: + cfg = types.parse_config("slots", {"label": ["Fr früh"], "capacity": ["4"], + "waitlist": ["on"]}) + assert cfg["single"] is True + assert cfg["options"] == [{"id": types.SINGLE_SLOT, "label": "Fr früh", "capacity": 4}] + assert cfg["waitlist"] is True + unlimited = types.parse_config("slots", {"label": ["x"], "capacity": [""]}) + assert "capacity" not in unlimited["options"][0] + with pytest.raises(types.ConfigError): + types.parse_config("slots", {"label": ["x"], "capacity": ["0"]}) + + +def test_slot_list_mode_still_works() -> None: + cfg = types.parse_config("slots", {"slot_mode": ["list"], "option_label": ["A", "B"], + "option_id": ["", ""], "option_capacity": ["2", ""]}) + assert "single" not in cfg + assert [o["label"] for o in cfg["options"]] == ["A", "B"] + + +def test_single_slot_answer() -> None: + q = slot(5, "Fr früh", 2) + result = types.parse_answer(q, {"q5": ["single"]}, TZ) + assert result.stored == {"value_json": {"selected": ["single"]}} + assert types.parse_answer(q, {}, TZ).stored is None + assert types.parse_answer(q, {"q5": ["other"]}, TZ).error == "choice" + assert types.display_answer(q, result.stored or {}, TZ) == "signed up" + assert types.display_answer(q, {}, TZ) == "" + assert types.raw_from_answer(q, result.stored or {}, TZ) == {"q5": ["single"]} + + +def test_group_has_no_answer() -> None: + assert not types.TYPES[groups.GROUP].is_input + assert types.parse_answer(Q(1, groups.GROUP), {"q1": ["x"]}, TZ).stored is None + assert types.parse_answer(Q(2, "rating", config={"scale_max": 5}), {"q2": ["3"]}, + TZ).stored == {"value_number": Decimal(3)} diff --git a/tests/test_guests.py b/tests/test_guests.py new file mode 100644 index 0000000..aa46f1d --- /dev/null +++ b/tests/test_guests.py @@ -0,0 +1,279 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Phase 6b gegen PostgreSQL: Gäste, persönliche Links, Double-Opt-in, +Meine Links anfordern, Selbstregistrierung (CI).""" + +from __future__ import annotations + +import re +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import new_client, token_for +from sqlalchemy import select, update +from sqlalchemy.orm import Session +from test_forms import ( + add_question, + create_form, + creator, + fill, + form_row, + question_ids, + save_settings, + set_status, +) +from test_mail import admin, content, messages +from test_phase5 import bookings, slot_form + +from surveybox import db +from surveybox.forms import guests +from surveybox.models import GuestContact, Response, UserAccount +from surveybox.settings import get_settings + +pytestmark = pytest.mark.db + + +def path_of(url: str) -> str: + return url.replace(get_settings().public_origin, "") + + +def links_in(text: str, part: str) -> list[str]: + return [path_of(u) for u in re.findall(r"https?://\S+", text) if part in u] + + +def guest_form(app: Any, **settings: Any) -> tuple[str, int, list[str]]: + carla = creator(app) + _, token, qid, options = slot_form(carla, **{"guest_email": "optional", **settings}) + return token, qid, options + + +def responses() -> list[Response]: + with Session(db.get_engine()) as s: + rows = list(s.scalars(select(Response).order_by(Response.id))) + for row in rows: + s.expunge(row) + return rows + + +def contact(email: str) -> GuestContact | None: + with Session(db.get_engine()) as s: + found = s.scalar(select(GuestContact).where(GuestContact.email == email)) + if found is not None: + s.expunge(found) + return found + + +# -------------------------------------------------------------------------- +# Persönlicher Link +# -------------------------------------------------------------------------- + + +def test_guest_without_email_sees_link_once(app: Any) -> None: + token, qid, (early, _) = guest_form(app) + guest = new_client(app) + assert fill(guest, token, {f"q{qid}": early}).status_code == 303 + (response,) = responses() + assert response.user_id is None and response.access_hash is not None + assert response.guest_contact_id is None + page = guest.get(f"/f/{token}/thanks").text + (link,) = links_in(page, "/r/") + assert "/r/" in link + # Nur einmal angezeigt + assert "/r/" not in guest.get(f"/f/{token}/thanks").text + view = new_client(app).get(link) + assert view.status_code == 200 and "Früh" in view.text + assert messages("guest_receipt") == [] # ohne Adresse keine Mail + + +def test_guest_with_email_gets_receipt_and_confirms(app: Any) -> None: + token, qid, (early, _) = guest_form(app) + guest = new_client(app) + resp = fill(guest, token, {f"q{qid}": early, "guest_email": "Gast@Example.de"}) + assert resp.status_code == 303 + (mail,) = messages("guest_receipt") + assert mail.recipient == "gast@example.de" and mail.user_id is None + text = content(mail)["text"] + (link,) = links_in(text, "/r/") + (confirm,) = links_in(text, "/g/confirm/") + found = contact("gast@example.de") + assert found is not None and found.confirmed_at is None + # Bestätigen: GET ändert nichts, erst der Knopf + other = new_client(app) + page = other.get(confirm) + assert page.status_code == 200 + assert contact("gast@example.de").confirmed_at is None # type: ignore[union-attr] + csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr] + assert other.post(confirm, data={"csrf_token": csrf}).status_code == 200 + assert contact("gast@example.de").confirmed_at is not None # type: ignore[union-attr] + assert new_client(app).get(confirm).status_code == 404 # nur einmal + assert new_client(app).get(link).status_code == 200 + + +def test_address_from_email_question(app: Any) -> None: + carla = creator(app) + pid = create_form(carla) + add_question(carla, pid, "email", label="Ihre E-Mail-Adresse") + assert save_settings(carla, pid, access="link", guest_email="question").status_code == 303 + assert set_status(carla, pid, "open").status_code == 303 + (qid,) = question_ids(pid) + token = form_row(pid).share_token + page = new_client(app).get(f"/f/{token}").text + assert 'name="guest_email"' not in page and "personal link" in page + guest = new_client(app) + assert fill(guest, token, {f"q{qid}": "Gast@Example.de"}).status_code == 303 + (mail,) = messages("guest_receipt") + assert mail.recipient == "gast@example.de" + link = links_in(content(mail)["text"], "/r/")[0] + # Neue Adresse über den persönlichen Link: neue Bestätigung an die neue Adresse + csrf = token_for(guest, f"{link}/edit") + guest.post(f"{link}/edit", data={"csrf_token": csrf, f"q{qid}": "neu@example.de"}) + assert [m.recipient for m in messages("guest_receipt")] == ["gast@example.de", + "neu@example.de"] + assert "/g/confirm/" in content(messages("guest_receipt")[1])["text"] + + +def test_invalid_email_keeps_form(app: Any) -> None: + token, qid, (early, _) = guest_form(app, guest_email="required") + resp = fill(new_client(app), token, {f"q{qid}": early, "guest_email": "kaputt@"}) + assert resp.status_code == 400 + assert responses() == [] + + +def test_edit_and_delete_with_personal_link(app: Any) -> None: + token, qid, (early, late) = guest_form(app, waitlist=True) + first, second = new_client(app), new_client(app) + fill(first, token, {f"q{qid}": early}) + link = links_in(first.get(f"/f/{token}/thanks").text, "/r/")[0] + fill(second, token, {f"q{qid}": early}) + assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"] + # Ändern über den Link: Platz wechseln, der Wartende rückt nach + csrf = token_for(first, f"{link}/edit") + resp = first.post(f"{link}/edit", data={"csrf_token": csrf, f"q{qid}": late}) + assert resp.status_code == 303 and resp.headers["location"].endswith("?done=saved") + assert sorted(b[:2] for b in bookings(qid)) == [(early, "confirmed"), (late, "confirmed")] + # Löschen braucht die Bestätigung + csrf = token_for(first, link) + assert first.post(f"{link}/delete", data={"csrf_token": csrf}).status_code == 400 + resp = first.post(f"{link}/delete", data={"csrf_token": csrf, "confirm": "on"}) + assert resp.status_code == 200 + assert len(responses()) == 1 and [b[0] for b in bookings(qid)] == [early] + assert new_client(app).get(link).status_code == 404 + + +def test_guessing_links_is_limited(app: Any) -> None: + client = new_client(app) + codes = {client.get(f"/r/{'x' * 43}{i}").status_code for i in range(guests.LINK_GUESSES_PER_IP)} + assert codes == {404} + + +def test_confirmed_guest_is_notified_when_promoted(app: Any) -> None: + token, qid, (early, late) = guest_form(app, waitlist=True) + anna = new_client(app) + fill(anna, token, {f"q{qid}": early, "guest_email": "anna@gast.de"}) + anna_link = links_in(anna.get(f"/f/{token}/thanks").text, "/r/")[0] + bert = new_client(app) + fill(bert, token, {f"q{qid}": early, "guest_email": "bert@gast.de"}) + # Bert ist noch nicht bestätigt: keine Benachrichtigung + with Session(db.get_engine()) as s: + s.execute(update(GuestContact).where(GuestContact.email == "bert@gast.de") + .values(confirmed_at=datetime.now(UTC))) + s.commit() + csrf = token_for(anna, f"{anna_link}/edit") + anna.post(f"{anna_link}/edit", data={"csrf_token": csrf, f"q{qid}": late}) + (mail,) = messages("promoted") + assert mail.recipient == "bert@gast.de" + data = content(mail) + assert "/links" in data["text"] + unsubscribe = path_of(data["headers"]["List-Unsubscribe"].strip("<>")) + one_click = TestClient(app).post(unsubscribe, data={"List-Unsubscribe": "One-Click"}) + assert one_click.status_code == 200 + assert contact("bert@gast.de").notify is False # type: ignore[union-attr] + + +def test_request_links_replaces_old_ones(app: Any) -> None: + token, qid, (early, _) = guest_form(app) + guest = new_client(app) + fill(guest, token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + old = links_in(guest.get(f"/f/{token}/thanks").text, "/r/")[0] + client = new_client(app) + for address in ("gast@example.de", "nobody@example.de"): + csrf = token_for(client, "/links") + page = client.post("/links", data={"csrf_token": csrf, "email": address}) + assert page.status_code == 200 and "If we have answers for this address" in page.text + (mail,) = messages("guest_links") + (new,) = links_in(content(mail)["text"], "/r/") + assert new != old + assert new_client(app).get(old).status_code == 404 + assert new_client(app).get(new).status_code == 200 + + +def test_unconfirmed_addresses_are_purged(app: Any) -> None: + token, qid, (early, _) = guest_form(app) + fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"}) + with Session(db.get_engine()) as s: + assert guests.purge_unconfirmed(s, datetime.now(UTC)) == 0 + assert guests.purge_unconfirmed(s, datetime.now(UTC) + timedelta(days=8)) == 1 + s.commit() + (response,) = responses() + assert response.guest_contact_id is None and response.access_hash is not None + + +# -------------------------------------------------------------------------- +# Selbstregistrierung +# -------------------------------------------------------------------------- + + +def register(client: TestClient, email: str, name: str = "Gast Anna") -> Any: + csrf = token_for(client, "/register") + return client.post("/register", data={"csrf_token": csrf, "email": email, "name": name}) + + +def test_registration_for_confirmed_guests(app: Any) -> None: + token, qid, (early, _) = guest_form(app) + guest = new_client(app) + fill(guest, token, {f"q{qid}": early, "guest_email": "anna@gast.de"}) + client = new_client(app) + # Unbestätigt: gleiche Antwort, aber keine Mail + assert register(client, "anna@gast.de").status_code == 200 + assert messages("register") == [] + with Session(db.get_engine()) as s: + s.execute(update(GuestContact).values(confirmed_at=datetime.now(UTC))) + s.commit() + assert register(client, "anna@gast.de").status_code == 200 + (mail,) = messages("register") + (link,) = links_in(content(mail)["text"], "/register/") + csrf = token_for(client, link) + resp = client.post(link, data={"csrf_token": csrf, "password": "ein langer und sicherer satz", + "password2": "ein langer und sicherer satz"}) + assert resp.status_code == 303 and "registered" in resp.headers["location"] + with Session(db.get_engine()) as s: + user = s.scalar(select(UserAccount).where(UserAccount.email == "anna@gast.de")) + assert user is not None and user.role == "participant" + assert user.email_verified_at is not None + (response,) = s.scalars(select(Response)).all() + assert response.user_id == user.id and response.access_hash is None + assert contact("anna@gast.de") is None + # Zweites Mal: Konto existiert, also kein neuer Link + csrf = token_for(client, link) + again = client.post(link, data={"csrf_token": csrf, "password": "noch ein langer satz hier", + "password2": "noch ein langer satz hier"}) + assert again.status_code == 400 + register(new_client(app), "anna@gast.de") + assert len(messages("register_exists")) == 1 + + +def test_registration_levels(app: Any) -> None: + client = admin(app) + for level, status in (("off", 404), ("open", 200)): + csrf = token_for(client, "/admin/settings") + client.post("/admin/settings/registration", + data={"csrf_token": csrf, "self_registration": level}) + assert new_client(app).get("/register").status_code == status + # Offen: jede Adresse bekommt einen Link + register(new_client(app), "neu@example.de") + assert [m.recipient for m in messages("register")] == ["neu@example.de"] + assert "/register" in new_client(app).get("/login").text diff --git a/tests/test_guests_units.py b/tests/test_guests_units.py new file mode 100644 index 0000000..6e01760 --- /dev/null +++ b/tests/test_guests_units.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Gäste und Selbstregistrierung ohne Datenbank (braucht die Modelle).""" + +from __future__ import annotations + +import time +import uuid +from types import SimpleNamespace + +import pytest + +pytest.importorskip("sqlalchemy") + +from surveybox.accounts import registration +from surveybox.forms import guests +from surveybox.mail import notify + +SECRET = "s" * 48 + + +def form(**kw: object) -> SimpleNamespace: + return SimpleNamespace(**{"anonymous": False, "guest_email": "optional", **kw}) + + +def test_registration_token_roundtrip_and_expiry() -> None: + now = time.time() + token = registration.make_token(SECRET, "anna@example.de", "Anna Ä", "de", now) + pending = registration.parse_token(SECRET, token, now + 60) + assert pending == registration.Pending("anna@example.de", "Anna Ä", "de") + assert registration.parse_token(SECRET, token, now + 25 * 3600) is None + assert registration.parse_token("x" * 48, token, now) is None + raw, _, mac = token.partition(".") + other = registration.make_token(SECRET, "eve@example.de", "Eve", "de", now) + assert registration.parse_token(SECRET, other.partition(".")[0] + "." + mac, now) is None + assert registration.parse_token(SECRET, raw, now) is None + assert registration.parse_token(SECRET, "", now) is None + + +def test_parse_guest_email() -> None: + user = SimpleNamespace(id=1) + assert guests.parse_email(form(), user, "a@b.de").email is None # angemeldet + assert guests.parse_email(form(anonymous=True), None, "a@b.de").email is None + assert guests.parse_email(form(guest_email="none"), None, "a@b.de").email is None + assert guests.parse_email(form(), None, " Anna@Example.DE ").email == "anna@example.de" + assert guests.parse_email(form(), None, "").error is None + assert guests.parse_email(form(guest_email="required"), None, "").error == "required" + assert guests.parse_email(form(), None, "kein@").error == "email" + + +def test_wants_link() -> None: + assert guests.wants_link(form(), None) + assert not guests.wants_link(form(anonymous=True), None) + assert not guests.wants_link(form(), SimpleNamespace(id=1)) + + +def test_guest_unsubscribe_token() -> None: + contact = SimpleNamespace(public_id=uuid.uuid4(), email="g@example.de", language="de", + confirmed_at=None, notify=True) + recipient = notify.for_guest(contact, SimpleNamespace(default_language="de")) # type: ignore[arg-type] + token = notify.unsubscribe_token(SECRET, recipient, "promoted") + found = notify.parse_unsubscribe(SECRET, token) + assert found is not None and found.kind == "guest" and found.public_id == contact.public_id + + +def test_guest_needs_confirmation_for_notifications() -> None: + contact = SimpleNamespace(public_id=uuid.uuid4(), email="g@example.de", language=None, + confirmed_at=None, notify=True) + settings = SimpleNamespace(default_language="fr") + recipient = notify.for_guest(contact, settings) # type: ignore[arg-type] + assert recipient.language == "fr" + assert not notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type] + contact.confirmed_at = 1 + assert notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type] + assert not notify.allowed(None, recipient, "comment_new", None) # type: ignore[arg-type] + contact.notify = False + assert not notify.allowed(None, recipient, "promoted", None) # type: ignore[arg-type] + + +def test_email_from_answers() -> None: + questions = [SimpleNamespace(id=1, type="short_text"), SimpleNamespace(id=2, type="email"), + SimpleNamespace(id=3, type="email")] + stored = {2: {"value_text": " Anna@Example.DE "}, 3: {"value_text": "b@example.de"}} + assert guests.email_from_answers( + form(guest_email="question", questions=questions), stored, set()) == "anna@example.de" + # Ausgeblendete Frage zählt nicht, die nächste E-Mail-Frage schon + assert guests.email_from_answers( + form(guest_email="question", questions=questions), stored, {2}) == "b@example.de" + assert guests.email_from_answers(form(guest_email="optional", questions=questions), + stored, set()) is None + assert guests.email_from_answers( + form(guest_email="question", anonymous=True, questions=questions), stored, set()) is None + # Das eigene Feld gibt es dann nicht + assert guests.parse_email(form(guest_email="question"), None, "a@b.de").email is None + + +def test_followup_document_token() -> None: + from surveybox.forms import followups + + doc = SimpleNamespace(public_id=uuid.uuid4()) + now = time.time() + token = followups.document_token(SECRET, doc, "u:x", int(now + 60)) # type: ignore[arg-type] + assert followups.parse_document_token(SECRET, token, now) == doc.public_id + assert followups.parse_document_token(SECRET, token, now + 120) is None # abgelaufen + assert followups.parse_document_token("x" * 48, token, now) is None + raw, _, mac = token.partition(".") + assert followups.parse_document_token(SECRET, raw + "." + mac[::-1], now) is None + + +def test_followup_placeholders() -> None: + from surveybox.forms import followups + + f = SimpleNamespace(title="Fest") + assert followups.personalize("Hallo {name}, zu {form}: {x} %s {}", "Anna", f) == ( # type: ignore[arg-type] + "Hallo Anna, zu Fest: {x} %s {}") + + +def test_removed_options() -> None: + from surveybox.forms import changes + + before = [{"id": "a", "label": "A"}, {"id": "b", "label": "B"}] + after = [{"id": "b", "label": "B2"}] + assert changes.removed_options(before, after) == [{"id": "a", "label": "A"}] + assert changes.removed_options(before, before) == [] diff --git a/tests/test_i18n.py b/tests/test_i18n.py new file mode 100644 index 0000000..c70e4f5 --- /dev/null +++ b/tests/test_i18n.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +from __future__ import annotations + +from pathlib import Path + +import pytest +from babel.messages.mofile import write_mo +from babel.messages.pofile import read_po + +from surveybox import i18n + +SOURCE_LOCALE = Path(i18n.__file__).parent / "locale" + + +@pytest.fixture +def compiled_locale(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + for lang in i18n.SUPPORTED_LANGUAGES: + po = SOURCE_LOCALE / lang / "LC_MESSAGES" / "messages.po" + target = tmp_path / lang / "LC_MESSAGES" + target.mkdir(parents=True) + with po.open("rb") as fh: + catalog = read_po(fh, locale=lang) + with (target / "messages.mo").open("wb") as fh: + write_mo(fh, catalog) + monkeypatch.setattr(i18n, "LOCALE_DIR", tmp_path) + i18n.translations.cache_clear() + yield tmp_path + i18n.translations.cache_clear() + + +@pytest.mark.parametrize( + ("cookie", "header", "expected"), + [ + ("fr", "de-DE,de;q=0.9", "fr"), + (None, "de-DE,de;q=0.9,en;q=0.8", "de"), + (None, "en-US,en;q=0.9", "en"), + (None, "it-IT,fr;q=0.5,en;q=0.7", "en"), + (None, "fr-CH, fr;q=0.9, en;q=0.8", "fr"), + (None, "es, *;q=0.5", "de"), + (None, None, "de"), + ("xx", "en", "en"), + (None, "en;q=0, fr", "fr"), + (None, "de;q=abc, en", "en"), + ], +) +def test_negotiate_language(cookie: str | None, header: str | None, expected: str) -> None: + assert i18n.negotiate_language(cookie, header, "de") == expected + + +def test_unknown_default_falls_back_to_german() -> None: + assert i18n.negotiate_language(None, None, "xx") == "de" + + +def test_catalogs_cover_the_same_messages() -> None: + ids: dict[str, set[str]] = {} + for lang in i18n.SUPPORTED_LANGUAGES: + with (SOURCE_LOCALE / lang / "LC_MESSAGES" / "messages.po").open("rb") as fh: + catalog = read_po(fh, locale=lang) + ids[lang] = {m.id for m in catalog if m.id} + missing = [m.id for m in catalog if m.id and not m.string] + assert not missing, f"{lang}: unübersetzt: {missing}" + assert ids["de"] == ids["en"] == ids["fr"] + + +def test_template_messages_are_in_catalog() -> None: + from babel.messages.extract import extract_from_dir + + method_map = [("**/templates/**.html", "jinja2"), ("**.py", "python")] + options = {"**/templates/**.html": {"extensions": "jinja2.ext.i18n"}} + extracted = { + msg[2] + for msg in extract_from_dir( + str(SOURCE_LOCALE.parent), method_map=method_map, options_map=options + ) + if isinstance(msg[2], str) + } + with (SOURCE_LOCALE / "de" / "LC_MESSAGES" / "messages.po").open("rb") as fh: + catalog_ids = {m.id for m in read_po(fh) if m.id} + assert extracted <= catalog_ids, f"Fehlen im Katalog: {extracted - catalog_ids}" + + +def test_gettext_follows_context_language(compiled_locale: Path) -> None: + token = i18n.set_language("de") + try: + assert i18n.gettext("Database") == "Datenbank" + finally: + i18n.reset_language(token) + token = i18n.set_language("fr") + try: + assert i18n.gettext("Database") == "Base de données" + finally: + i18n.reset_language(token) + token = i18n.set_language("en") + try: + assert i18n.gettext("Database") == "Database" + finally: + i18n.reset_language(token) + + +def test_unsupported_language_is_not_set() -> None: + token = i18n.set_language("xx") + try: + assert i18n.get_language() == "de" + finally: + i18n.reset_language(token) diff --git a/tests/test_mail.py b/tests/test_mail.py new file mode 100644 index 0000000..19e1f20 --- /dev/null +++ b/tests/test_mail.py @@ -0,0 +1,313 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Phase 6a gegen PostgreSQL: Mail-Einstellungen, Warteschlange, Versand, +Passwort vergessen, Einladungen, Benachrichtigungen, Abmelden (CI).""" + +from __future__ import annotations + +import smtplib +from datetime import UTC, datetime, timedelta +from email.message import EmailMessage +from typing import Any, ClassVar + +import pytest + +pytest.importorskip("fastapi") + +from fastapi.testclient import TestClient +from helpers import csrf_from, login, make_user, new_client, next_totp, token_for +from sqlalchemy import select +from sqlalchemy.orm import Session +from test_forms import creator, fill, participant +from test_phase5 import slot_form + +from surveybox import db +from surveybox.mail import config as mail_config +from surveybox.mail import outbox, smtp +from surveybox.models import AppSetting, AuditEvent, MailMessage, Role, UserAccount +from surveybox.settings import get_settings + +pytestmark = pytest.mark.db + +RELAY = { + "host": "smtp.example.org", "port": "587", "security": "starttls", "username": "relay", + "password": "relay-geheim", "from_address": "surveybox@example.org", + "from_name": "Surveybox Test", "reply_to": "team@example.org", +} + + +def admin(app: Any) -> TestClient: + _, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True) + assert secret + client = new_client(app) + login(client, "admin@example.de") + mfa = client.get("/login/mfa") + client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text), + "next": "/"}) + return client + + +def configure(client: TestClient) -> None: + csrf = token_for(client, "/admin/mail") + resp = client.post("/admin/mail", data={"csrf_token": csrf, **RELAY}) + assert resp.status_code == 303, resp.text + + +def messages(kind: str | None = None) -> list[MailMessage]: + with Session(db.get_engine()) as s: + stmt = select(MailMessage).order_by(MailMessage.id) + if kind: + stmt = stmt.where(MailMessage.kind == kind) + rows = list(s.scalars(stmt)) + for row in rows: + s.expunge(row) + return rows + + +def content(row: MailMessage) -> dict[str, Any]: + found = outbox.content_of(get_settings().secret_key.get_secret_value(), row) + assert found is not None + return dict(found) + + +class FakeRelay: + """Ersetzt smtp.Connection; merkt sich, was gesendet wurde.""" + + sent: ClassVar[list[EmailMessage]] = [] + fail_connect: ClassVar[Exception | None] = None + fail_send: ClassVar[Exception | None] = None + + def __init__(self, cfg: Any, password: str) -> None: + self.password = password + + def __enter__(self) -> FakeRelay: + if FakeRelay.fail_connect is not None: + raise FakeRelay.fail_connect + return self + + def send(self, msg: EmailMessage) -> None: + if FakeRelay.fail_send is not None: + raise FakeRelay.fail_send + FakeRelay.sent.append(msg) + + def __exit__(self, *args: object) -> None: + return None + + +@pytest.fixture +def relay(monkeypatch: pytest.MonkeyPatch) -> type[FakeRelay]: + FakeRelay.sent = [] + FakeRelay.fail_connect = None + FakeRelay.fail_send = None + monkeypatch.setattr(smtp, "Connection", FakeRelay) + return FakeRelay + + +def run_queue(at: datetime | None = None) -> int: + settings = get_settings() + return outbox.process_due(db.get_engine(), settings.secret_key.get_secret_value(), + settings.public_host, at or datetime.now(UTC) + timedelta(seconds=1)) + + +# -------------------------------------------------------------------------- +# Einstellungen +# -------------------------------------------------------------------------- + + +def test_settings_store_password_encrypted(app: Any) -> None: + client = admin(app) + page = client.get("/admin/mail").text + assert "No SMTP relay is set up yet" in page + configure(client) + with Session(db.get_engine()) as s: + row = s.get(AppSetting, "mail") + assert row is not None + assert "relay-geheim" not in str(row.value) + cfg = mail_config.load(s) + assert cfg.password(get_settings().secret_key.get_secret_value()) == "relay-geheim" + events = list(s.scalars(select(AuditEvent).where( + AuditEvent.action == "admin.mail_settings_changed"))) + assert events and "relay-geheim" not in str(events[0].details) + assert "@" not in str(events[0].details) # keine Adressen im Protokoll + page = client.get("/admin/mail").text + assert "relay-geheim" not in page and "No SMTP relay" not in page + # Ohne neues Passwort bleibt das alte + csrf = token_for(client, "/admin/mail") + client.post("/admin/mail", data={"csrf_token": csrf, **RELAY, "password": ""}) + with Session(db.get_engine()) as s: + assert mail_config.load(s).has_password + + +def test_invalid_settings_are_refused(app: Any) -> None: + client = admin(app) + csrf = token_for(client, "/admin/mail") + resp = client.post("/admin/mail", data={"csrf_token": csrf, **RELAY, + "from_address": "x@y\r\nBcc: z@example.org"}) + assert resp.status_code == 400 + + +def test_test_mail_reports_errors(app: Any, relay: type[FakeRelay]) -> None: + client = admin(app) + configure(client) + csrf = token_for(client, "/admin/mail") + # send_now baut seine eigene Verbindung über smtp.Connection (hier: FakeRelay) + resp = client.post("/admin/mail/test", data={"csrf_token": csrf, "to": ""}) + assert resp.status_code == 200 + assert "has been sent to admin@example.de" in resp.text + assert relay.sent and relay.sent[0]["To"] == "admin@example.de" + assert relay.sent[0]["Reply-To"] == "team@example.org" + relay.fail_connect = smtplib.SMTPAuthenticationError(535, b"auth failed") + csrf = token_for(client, "/admin/mail") + resp = client.post("/admin/mail/test", data={"csrf_token": csrf, "to": ""}) + assert "535 auth failed" in resp.text + with Session(db.get_engine()) as s: + tests = list(s.scalars(select(AuditEvent).where(AuditEvent.action == "admin.mail_test"))) + assert [e.details for e in tests] == [{"ok": True}, {"ok": False}] + + +# -------------------------------------------------------------------------- +# Warteschlange und Versand +# -------------------------------------------------------------------------- + + +def forgot(client: TestClient, email: str) -> Any: + csrf = token_for(client, "/forgot") + return client.post("/forgot", data={"csrf_token": csrf, "email": email}) + + +def test_forgot_password_answers_the_same(app: Any) -> None: + make_user(Role.PARTICIPANT, "anna@example.de") + known = forgot(new_client(app), "anna@example.de") + unknown = forgot(new_client(app), "nobody@example.de") + assert known.status_code == unknown.status_code == 200 + assert known.text.replace(csrf_from(known.text), "") == unknown.text.replace( + csrf_from(unknown.text), "") + (mail,) = messages("password_reset") + assert mail.recipient == "anna@example.de" and mail.status == "queued" + text = content(mail)["text"] + link = next(w for w in text.split() if "/setup/" in w) + assert new_client(app).get(link.replace(get_settings().public_origin, "")).status_code == 200 + # Inhalt liegt nur verschlüsselt in der Datenbank + assert mail.content_enc is not None and b"/setup/" not in mail.content_enc + + +def test_forgot_password_is_rate_limited(app: Any) -> None: + make_user(Role.PARTICIPANT, "anna@example.de") + for _ in range(5): + forgot(new_client(app), "anna@example.de") + assert len(messages("password_reset")) == 3 + + +def test_queue_waits_without_relay_and_sends_later(app: Any, relay: type[FakeRelay]) -> None: + make_user(Role.PARTICIPANT, "anna@example.de") + forgot(new_client(app), "anna@example.de") + assert run_queue() == 0 and messages()[0].status == "queued" + configure(admin(app)) + assert run_queue() == 1 + (mail,) = messages("password_reset") + assert mail.status == "sent" and mail.content_enc is None and mail.sent_at is not None + sent = relay.sent[0] + assert sent["To"] == "anna@example.de" + assert sent["From"] == "Surveybox Test " + assert "/setup/" in sent.get_body(("plain",)).get_content() + + +def test_retry_and_permanent_failure(app: Any, relay: type[FakeRelay]) -> None: + configure(admin(app)) + make_user(Role.PARTICIPANT, "anna@example.de") + forgot(new_client(app), "anna@example.de") + relay.fail_connect = smtplib.SMTPServerDisconnected("gone") + now = datetime.now(UTC) + timedelta(seconds=1) + assert run_queue(now) == 0 + (mail,) = messages("password_reset") + assert mail.status == "queued" and mail.attempts == 1 and "gone" in (mail.last_error or "") + assert mail.next_attempt_at > now + # Vor der nächsten Fälligkeit passiert nichts + relay.fail_connect = None + assert run_queue(now) == 0 + relay.fail_send = smtp.PermanentError("550 no such user") + assert run_queue(now + timedelta(minutes=2)) == 0 + (mail,) = messages("password_reset") + assert mail.status == "failed" and mail.content_enc is None + + +def test_invite_by_mail(app: Any) -> None: + client = admin(app) + csrf = token_for(client, "/admin/users/new") + resp = client.post("/admin/users/new", data={ + "csrf_token": csrf, "email": "neu@example.de", "display_name": "Neu", + "role": "participant", "send_mail": "on"}) + assert resp.status_code == 303 and "invite_sent" in resp.headers["location"] + (mail,) = messages("invite") + assert mail.recipient == "neu@example.de" + assert "/setup/" in content(mail)["text"] + + +# -------------------------------------------------------------------------- +# Benachrichtigungen +# -------------------------------------------------------------------------- + + +def comment(client: TestClient, token: str, body: str) -> Any: + csrf = token_for(client, f"/f/{token}") + return client.post(f"/f/{token}/comments", data={"csrf_token": csrf, "body": body}) + + +def test_comment_notifies_owner_and_one_click_unsubscribe(app: Any) -> None: + carla = creator(app) + _, token, _, _ = slot_form(carla, comments_notify="on") + paul = participant(app) + assert comment(paul, token, "Gibt es Parkplätze?").status_code == 303 + (mail,) = messages("comment_new") + assert mail.recipient == "carla@example.de" + data = content(mail) + assert "Parkplätze" not in data["text"] # nur Links, keine Inhalte + unsubscribe = data["headers"]["List-Unsubscribe"].strip("<>") + assert data["headers"]["List-Unsubscribe-Post"] == "List-Unsubscribe=One-Click" + # Ein-Klick-Abmeldung des Mailprogramms: ohne Cookies und ohne CSRF-Feld + path = unsubscribe.replace(get_settings().public_origin, "") + assert new_client(app).get(path).status_code == 200 # GET ändert nichts + resp = TestClient(app).post(path, data={"List-Unsubscribe": "One-Click"}) + assert resp.status_code == 200 + with Session(db.get_engine()) as s: + user = s.scalar(select(UserAccount).where(UserAccount.email == "carla@example.de")) + assert user is not None and user.notify_prefs.get("comment_new") is False + comment(paul, token, "Und Getränke?") + assert len(messages("comment_new")) == 1 + + +def test_waitlist_promotion_and_booked_up_mails(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, late) = slot_form(carla, waitlist=True) + anna = participant(app, "anna2@example.de") + bert = participant(app, "bert@example.de") + assert fill(anna, token, {f"q{qid}": early}).status_code == 303 + assert [m.recipient for m in messages("slot_full")] == ["carla@example.de"] + assert [m.recipient for m in messages("participation")] == ["anna2@example.de"] + assert fill(bert, token, {f"q{qid}": early}).status_code == 303 + assert messages("promoted") == [] + # Anna wechselt: Bert rückt nach und bekommt genau eine Mail + assert fill(anna, token, {f"q{qid}": late}, path="/edit").status_code == 303 + (mail,) = messages("promoted") + assert mail.recipient == "bert@example.de" + assert "Früh" in content(mail)["text"] + + +def test_no_participant_mails_for_anonymous_forms(app: Any) -> None: + carla = creator(app) + _, token, qid, (early, _) = slot_form(carla, anonymous="on") + paul = participant(app) + assert fill(paul, token, {f"q{qid}": early}).status_code == 303 + assert messages("participation") == [] + + +def test_notification_settings_page(app: Any) -> None: + paul = participant(app) + csrf = token_for(paul, "/account/notifications") + resp = paul.post("/account/notifications", data={"csrf_token": csrf, + "event_promoted": "on"}) + assert resp.status_code == 303 + with Session(db.get_engine()) as s: + user = s.scalar(select(UserAccount).where(UserAccount.email == "paul@example.de")) + assert user is not None + assert user.notify_prefs["promoted"] is True + assert user.notify_prefs["participation"] is False diff --git a/tests/test_mail_custom_units.py b/tests/test_mail_custom_units.py new file mode 100644 index 0000000..3045868 --- /dev/null +++ b/tests/test_mail_custom_units.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Eigene Mail-Vorlagen ohne Datenbank: Platzhalter, Prüfung, Anwenden.""" + +from __future__ import annotations + +from types import SimpleNamespace + +from surveybox.mail import custom, render + + +def context(**extra: object) -> dict[str, object]: + return {"app_name": "Feuerwehr", "origin": "https://x", "name": "Erika", + "form": SimpleNamespace(title="Sommerfest"), "link": "https://x/f/abc", + "guest": False, "links_url": "https://x/links", "unsubscribe_url": None, + "settings_url": "https://x/s", **extra} + + +def test_placeholders_follow_the_template() -> None: + assert {"greeting", "details", "app", "title", "name", "link", "entry"} <= set( + custom.placeholders("promoted")) + assert "title" not in custom.placeholders("invite") + assert custom.required("invite") == ["link"] + assert custom.required("register_exists") == ["forgot_url", "login_url"] + + +def test_validate() -> None: + ok = custom.clean(" Platz für {name}\n ", "{greeting}\r\n\r\nSchön!\n\n{details}") + assert ok.subject == "Platz für {name}" and "\r" not in ok.body + assert custom.validate("promoted", ok) == [] + errors = dict(custom.validate("promoted", custom.Custom("", "Hallo {nope} ohne Link"))) + assert set(errors) == {"subject", "unknown", "missing"} + assert errors["unknown"] == "{nope}" and errors["missing"] == "{link}" + assert custom.validate("promoted", custom.Custom("x", "Hier: {link}")) == [] + + +def test_render_with_custom_text() -> None: + own = custom.Custom("Platz frei bei {app}: {title}", + "{greeting}\n\nWir freuen uns!\n\n{details}\n\nEure Feuerwehr") + mail = render.render("promoted", "en", context(entry="Früh"), own) + assert mail.subject == "Platz frei bei Feuerwehr: Sommerfest" + assert mail.text.startswith("Hello Erika,\n\nWir freuen uns!\n\nA place") + assert "https://x/f/abc" in mail.text and "Eure Feuerwehr" in mail.text + assert mail.text.count("Hello Erika") == 1 # Anrede nicht doppelt + assert '' in mail.html and "-- \n" in mail.text + # Ohne Namen: allgemeine Anrede + plain = render.render("promoted", "en", context(name="", entry="Früh"), own) + assert plain.text.startswith("Hello,\n\nWir") + + +def test_preview_with_missing_values() -> None: + mail = render.render("confirmed", "en", {"name": "A"}, strict=False) + assert mail.subject and mail.text diff --git a/tests/test_mail_templates.py b/tests/test_mail_templates.py new file mode 100644 index 0000000..9d90aa0 --- /dev/null +++ b/tests/test_mail_templates.py @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""E-Mail-Vorlagen über die Oberfläche und beim Versand (CI).""" + +from __future__ import annotations + +from typing import Any + +import pytest + +pytest.importorskip("fastapi") + +from helpers import make_user, new_client, token_for +from test_mail import admin, content, forgot, messages + +from surveybox.models import Role + +pytestmark = pytest.mark.db + + +def save(client: Any, kind: str, language: str, subject: str, body: str) -> Any: + url = f"/admin/mail/templates/{kind}?lang={language}" + return client.post(f"/admin/mail/templates/{kind}", data={ + "csrf_token": token_for(client, url), "language": language, "subject": subject, + "body": body}) + + +def test_edit_preview_and_use_template(app: Any) -> None: + root = admin(app) + page = root.get("/admin/mail/templates").text + assert "Reset password" in page and "standard" in page + edit = root.get("/admin/mail/templates/password_reset?lang=en").text + assert "{greeting}" in edit and "Standard text" in edit + # Ohne {details} und ohne {link} kommt die Mail ohne Link an: abgelehnt + resp = save(root, "password_reset", "en", "Neues Passwort", "Hallo {wer}") + assert resp.status_code == 400 + assert "Unknown placeholders: {wer}" in resp.text and "{link}" in resp.text + for language in ("de", "en", "fr"): + resp = save(root, "password_reset", language, "Neues Passwort für {app}", + "{greeting}\n\nDein Zugang bei der Feuerwehr:\n{link}\n\nGruß ") + assert resp.status_code == 303 + page = root.get("/admin/mail/templates/password_reset?lang=en").text + assert "Preview with sample data" in page and "Gruß <b>" in page + make_user(Role.PARTICIPANT, "anna@example.de") + forgot(new_client(app), "anna@example.de") + (mail,) = messages("password_reset") + found = content(mail) + assert found["subject"].startswith("Neues Passwort für ") + assert "Dein Zugang bei der Feuerwehr:" in found["text"] and "/setup/" in found["text"] + assert "Gruß <b>" in found["html"] + # Zurück zum Standard + for language in ("de", "en", "fr"): + url = f"/admin/mail/templates/password_reset?lang={language}" + root.post("/admin/mail/templates/password_reset/reset", + data={"csrf_token": token_for(root, url), "language": language}) + assert "own text" not in root.get("/admin/mail/templates").text + + +def test_unknown_kind_and_rights(app: Any) -> None: + root = admin(app) + assert root.get("/admin/mail/templates/followup").status_code == 404 + assert new_client(app).get("/admin/mail/templates").status_code in (303, 401, 403) diff --git a/tests/test_mail_units.py b/tests/test_mail_units.py new file mode 100644 index 0000000..f553560 --- /dev/null +++ b/tests/test_mail_units.py @@ -0,0 +1,261 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Mail ohne Datenbank: Einstellungen, Vorlagen, Aufbau der Nachricht, Abmeldelinks.""" + +from __future__ import annotations + +import uuid +from email import message_from_bytes +from email.policy import default +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from surveybox.mail import config, render, smtp +from surveybox.mail.config import MailConfig, MailConfigError + +SECRET = "s" * 48 +TEMPLATES = Path(render.TEMPLATE_DIR) + + +def fields(**values: str) -> dict[str, list[str]]: + return {k: [v] for k, v in values.items()} + + +# -------------------------------------------------------------------------- +# Einstellungen +# -------------------------------------------------------------------------- + + +def test_parse_form_encrypts_password_and_keeps_it() -> None: + cfg = config.parse_form( + MailConfig(), + fields(host="SMTP.Example.org", port="587", security="starttls", username="relay", + password="geheim 123", from_address="sb@example.org", from_name="Sommerfest\nX", + reply_to="team@example.org"), + SECRET, + ) + assert cfg.host == "smtp.example.org" + assert cfg.from_name == "Sommerfest X" + assert "geheim" not in cfg.password_enc + assert cfg.password(SECRET) == "geheim 123" + # Leeres Passwortfeld behält das gespeicherte + again = config.parse_form(cfg, fields(host="smtp.example.org", port="465", security="tls", + username="relay", from_address="sb@example.org"), + SECRET) + assert again.password(SECRET) == "geheim 123" + assert again.security == "tls" + removed = config.parse_form(cfg, fields(host="smtp.example.org", port="587", + security="starttls", username="relay", + from_address="sb@example.org", password_remove="on"), + SECRET) + assert not removed.has_password + assert "password_enc" not in config.summary(cfg) + + +@pytest.mark.parametrize( + ("values", "code"), + [ + ({"host": "https://smtp.example.org"}, "mail_host_invalid"), + ({"host": "smtp.example.org:587"}, "mail_host_invalid"), + ({"port": "0"}, "mail_port_invalid"), + ({"security": "none"}, "mail_security_invalid"), + ({"from_address": "Anna "}, "mail_address_invalid"), + ({"reply_to": "a@example.org\r\nBcc: x@example.org"}, "mail_address_invalid"), + ({"from_address": ""}, "mail_address_invalid"), + ({"password": "a\nb"}, "mail_password_invalid"), + ], +) +def test_parse_form_rejects(values: dict[str, str], code: str) -> None: + base = {"host": "smtp.example.org", "port": "587", "security": "starttls", + "username": "relay", "from_address": "sb@example.org"} + with pytest.raises(MailConfigError) as exc: + config.parse_form(MailConfig(), fields(**{**base, **values}), SECRET) + assert exc.value.code == code + + +def test_not_configured_without_host() -> None: + assert not MailConfig().configured + assert MailConfig(host="x.de", from_address="a@x.de").configured + assert config.from_dict({"port": "abc", "security": "plain"}) == MailConfig() + + +# -------------------------------------------------------------------------- +# Vorlagen +# -------------------------------------------------------------------------- + + +BASE: dict[str, Any] = { + "app_name": "Surveybox", "origin": "https://umfrage.example", "name": "Anna ", + "form": SimpleNamespace(title="Fest ") + assert sniff.detect_file(html, "x.png").key == "txt" # type: ignore[union-attr] + + +def _zip(tmp_path: Path, name: str, files: dict[str, bytes]) -> Path: + path = tmp_path / name + with zipfile.ZipFile(path, "w") as archive: + for inner, content in files.items(): + archive.writestr(inner, content) + return path + + +def test_office_formats_from_archive(tmp_path: Path) -> None: + docx = _zip(tmp_path, "a.docx", {"[Content_Types].xml": b"", "word/document.xml": b""}) + assert sniff.detect_file(docx).key == "docx" # type: ignore[union-attr] + ods = _zip(tmp_path, "a.ods", {"mimetype": b"application/vnd.oasis.opendocument.spreadsheet"}) + assert sniff.detect_file(ods).key == "ods" # type: ignore[union-attr] + plain = _zip(tmp_path, "a.zip", {"readme.txt": b"hi"}) + assert sniff.detect_file(plain).key == "zip" # type: ignore[union-attr] + + +def test_safe_filename() -> None: + assert sniff.safe_filename("C:\\Users\\x\\Bericht 2026.PDF", "pdf") == "Bericht 2026.pdf" + assert sniff.safe_filename('../../etc/pa"ss\x00wd', "txt") == "passwd.txt" + assert sniff.safe_filename("", "png") == "datei.png" + + +# --------------------------------------------------------------------------- +# Bilder +# --------------------------------------------------------------------------- + +PIL = pytest.importorskip("PIL") + + +def _jpeg_with_gps(path: Path, size: tuple[int, int] = (3000, 2000)) -> None: + from PIL import Image + + img = Image.new("RGB", size, (200, 30, 30)) + exif = Image.Exif() + exif[0x010F] = "Kamerahersteller" + exif[0x0112] = 6 # um 90° gedreht + exif[0x8825] = {1: "N", 2: (47.0, 54.0, 0.0)} + img.save(path, "JPEG", exif=exif) + + +def test_image_is_rotated_resized_and_stripped(tmp_path: Path) -> None: + from PIL import Image + + from surveybox.media import images + + source = tmp_path / "foto.jpg" + _jpeg_with_gps(source) + full, thumb = tmp_path / "full", tmp_path / "thumb" + result = images.process(source, full, thumb) + # Ausrichtung angewandt (hochkant), auf 2560 begrenzt + assert (result.width, result.height) == (1707, 2560) + with Image.open(full) as out: + assert out.format == "WEBP" + assert not out.getexif() + assert "exif" not in out.info + with Image.open(thumb) as small: + assert max(small.size) == 640 + + +def test_image_rejects_garbage_and_bombs(tmp_path: Path) -> None: + from PIL import Image + + from surveybox.media import images + + junk = _write(tmp_path, "x.png", b"\x89PNG\r\n\x1a\n" + os.urandom(200)) + with pytest.raises(images.ImageError): + images.process(junk, tmp_path / "f", tmp_path / "t") + gif = tmp_path / "a.gif" + Image.new("RGB", (10, 10)).save(gif, "GIF") + with pytest.raises(images.ImageError): + images.process(gif, tmp_path / "f", tmp_path / "t") + bomb = tmp_path / "bomb.png" + Image.new("1", (9000, 9000)).save(bomb, "PNG") + with pytest.raises(images.ImageError): + images.process(bomb, tmp_path / "f", tmp_path / "t") + + +def test_transparent_png_keeps_alpha(tmp_path: Path) -> None: + from PIL import Image + + from surveybox.media import images + + source = tmp_path / "logo.png" + Image.new("RGBA", (100, 50), (0, 0, 0, 0)).save(source, "PNG") + images.process(source, tmp_path / "f", tmp_path / "t") + with Image.open(tmp_path / "f") as out: + assert out.mode == "RGBA" + + +# --------------------------------------------------------------------------- +# Externe Videos +# --------------------------------------------------------------------------- + +ALL = embeds.EmbedPolicy(youtube=True, vimeo=True, peertube_hosts=("video.example.org",)) + + +@pytest.mark.parametrize( + ("url", "provider", "video"), + [ + ("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10", "youtube", "dQw4w9WgXcQ"), + ("https://youtu.be/dQw4w9WgXcQ?si=abc", "youtube", "dQw4w9WgXcQ"), + ("https://www.youtube.com/shorts/dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"), + ("https://vimeo.com/76979871", "vimeo", "76979871"), + ("https://player.vimeo.com/video/76979871?h=abc123def", "vimeo", "76979871"), + ("https://video.example.org/w/9c9de5e8-0a1e-484a-b099-e80766180a6d", "peertube", + "9c9de5e8-0a1e-484a-b099-e80766180a6d"), + ("https://video.example.org/videos/watch/kkGMgK9ZtnKfYAgnEtQxbv", "peertube", + "kkGMgK9ZtnKfYAgnEtQxbv"), + ], +) +def test_parse_video_urls(url: str, provider: str, video: str) -> None: + embed = embeds.parse_url(url, ALL) + assert (embed.provider, embed.video) == (provider, video) + assert embeds.from_config(embed.to_config()) == embed + + +@pytest.mark.parametrize( + "url", + [ + "javascript:alert(1)", + "https://www.youtube.com/watch?v=short", + "https://www.youtube.com/watch?v=dQw4w9WgXcQ\">