Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adf723419d | ||
|
|
f3f4ca2c9f | ||
|
|
c9c40af382 | ||
|
|
ae4f153482 | ||
|
|
1bfcc7a079 | ||
|
|
43c7dccc9f | ||
|
|
c4661d1dc0 | ||
|
|
81397ba61f | ||
|
|
314bdc6296 | ||
|
|
bfb8f2ff9c | ||
|
|
a574e93359 | ||
|
|
bc865813cb | ||
|
|
e8f971b54e | ||
|
|
d522f35663 | ||
|
|
e7d76f40de | ||
|
|
5b3e10be94 | ||
|
|
c53d38a0e9 | ||
|
|
3fc6894070 | ||
|
|
69c1e4926c | ||
|
|
a49b939fdc | ||
|
|
aa95ab2745 | ||
|
|
13a0c07d1b | ||
|
|
3c892d02ed | ||
|
|
bf7be65b03 | ||
|
|
ce9b173c71 | ||
|
|
10c459db0f |
No files matched your search
@@ -52,6 +52,12 @@ ADMIN_BOOTSTRAP_EMAIL=
|
|||||||
# request shares ONE rate-limit bucket (/sign-in/* allows 3 per 10 seconds, so
|
# request shares ONE rate-limit bucket (/sign-in/* allows 3 per 10 seconds, so
|
||||||
# one noisy client locks everyone out). Check with:
|
# one noisy client locks everyone out). Check with:
|
||||||
# SELECT `key` FROM rateLimit; -- a "no-trusted-ip" row means it is happening.
|
# SELECT `key` FROM rateLimit; -- a "no-trusted-ip" row means it is happening.
|
||||||
|
# The header the reverse proxy puts the real client IP in. Must be one the proxy
|
||||||
|
# actually overwrites - trusting a header it does not set lets any client send its
|
||||||
|
# own value and bypass the sign-in rate limit entirely.
|
||||||
|
# Set to "none" to trust no header at all: every request then shares one rate-limit
|
||||||
|
# bucket, which is the safe fallback if the check below fails. Verify after deploy
|
||||||
|
# with: SELECT ipAddress FROM session ORDER BY createdAt DESC LIMIT 3;
|
||||||
CLIENT_IP_HEADERS=x-real-ip
|
CLIENT_IP_HEADERS=x-real-ip
|
||||||
TRUSTED_PROXY_IPS=
|
TRUSTED_PROXY_IPS=
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Tests every push and pull request; deploys pushes to master to the Plesk server.
|
||||||
|
# Setup and what the deploy may touch: docs/deployment.md.
|
||||||
|
#
|
||||||
|
# Same pattern as the calendar frontend (Calendar_Frontend/.gitea/workflows/deploy.yml): build here,
|
||||||
|
# deliver over SSH as the Plesk subscription user, restart Passenger. Unlike there, the app folder
|
||||||
|
# also holds things the deploy must never touch (.env with the secrets, logs/, tmp/), so only the
|
||||||
|
# app's own folders are synced with --delete and nothing is deleted at the top level.
|
||||||
|
name: Test and deploy
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# One job, not test + deploy: every job starts in a fresh container, so two jobs meant checking out,
|
||||||
|
# setting up Node and running `npm ci` twice (~2 min each, 2026-11-08). The deploy steps only run
|
||||||
|
# for pushes to master; on pull requests the job ends after the tests. The condition is spelled out
|
||||||
|
# on every deploy step rather than stored in an env flag: a flag compared as a string ('true') would
|
||||||
|
# skip the deploy silently - and green - if the runner ever rendered the boolean differently.
|
||||||
|
test-and-deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
|
||||||
|
DEPLOY_PORT: ${{ vars.DEPLOY_PORT }}
|
||||||
|
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
|
||||||
|
DEPLOY_PATH: ${{ vars.DEPLOY_PATH }}
|
||||||
|
# Absolute on purpose: rsync passes its -e string to ssh without a shell, and ssh expands "~"
|
||||||
|
# from the passwd entry, not $HOME (see the calendar frontend's docs/gotchas.md).
|
||||||
|
SSH_DIR: /tmp/deploy-ssh
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: .nvmrc
|
||||||
|
- run: npm ci
|
||||||
|
- run: npx tsc --noEmit
|
||||||
|
# Unit tests only. The integration tests (npm run test:integration) start their own MariaDB
|
||||||
|
# container and aren't run here.
|
||||||
|
# FEEDBACK_IP_SALT (which the Jenkins job exported) isn't needed: vitest.config.ts sets one.
|
||||||
|
- run: npm test
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
run: npm run build
|
||||||
|
# Only runtime dependencies go to the server (no typescript, vitest, ...).
|
||||||
|
- name: Prune dev dependencies
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
run: npm prune --omit=dev
|
||||||
|
|
||||||
|
- name: SSH setup
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
env:
|
||||||
|
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||||
|
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||||
|
run: |
|
||||||
|
test -n "$DEPLOY_HOST" && test -n "$DEPLOY_USER" && test -n "$DEPLOY_PATH"
|
||||||
|
if ! command -v rsync >/dev/null 2>&1 || ! command -v ssh >/dev/null 2>&1; then
|
||||||
|
apt-get update && apt-get install -y --no-install-recommends rsync openssh-client
|
||||||
|
fi
|
||||||
|
install -m 700 -d "$SSH_DIR"
|
||||||
|
printf '%s\n' "$DEPLOY_SSH_KEY" > "$SSH_DIR/key"
|
||||||
|
chmod 600 "$SSH_DIR/key"
|
||||||
|
# Pinned host key, never trust-on-first-use.
|
||||||
|
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$SSH_DIR/known_hosts"
|
||||||
|
|
||||||
|
- name: Upload
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
run: |
|
||||||
|
rsh="ssh -p ${DEPLOY_PORT:-22} -i $SSH_DIR/key -o UserKnownHostsFile=$SSH_DIR/known_hosts -o IdentitiesOnly=yes -o BatchMode=yes"
|
||||||
|
target="$DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH"
|
||||||
|
# The app's own folders, each mirrored exactly (--delete within the folder only).
|
||||||
|
# src/ is needed at runtime: swagger-jsdoc reads the route docs from src/models/**/*.ts.
|
||||||
|
for dir in dist src public node_modules; do
|
||||||
|
rsync -az --delete -e "$rsh" "$dir/" "$target/$dir/"
|
||||||
|
done
|
||||||
|
# Single files at the top level, without --delete: .env, logs/ and tmp/ live there too.
|
||||||
|
# package.json is what makes Node treat dist/ as ES modules ("type": "module").
|
||||||
|
rsync -az -e "$rsh" package.json package-lock.json "$target/"
|
||||||
|
|
||||||
|
- name: Restart
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
run: |
|
||||||
|
# Passenger restarts the app on its next request when tmp/restart.txt is touched.
|
||||||
|
ssh -p "${DEPLOY_PORT:-22}" -i "$SSH_DIR/key" -o "UserKnownHostsFile=$SSH_DIR/known_hosts" \
|
||||||
|
-o IdentitiesOnly=yes -o BatchMode=yes "$DEPLOY_USER@$DEPLOY_HOST" \
|
||||||
|
"mkdir -p '$DEPLOY_PATH/tmp' && touch '$DEPLOY_PATH/tmp/restart.txt'"
|
||||||
|
|
||||||
|
# Set DEPLOY_SMOKE_URL to an endpoint that must answer 200 without a session, e.g.
|
||||||
|
# https://api.nachklang.art/calendar/events/public/json (what nachklang.art itself reads).
|
||||||
|
- name: Smoke test
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master' && vars.DEPLOY_SMOKE_URL != ''
|
||||||
|
env:
|
||||||
|
DEPLOY_SMOKE_URL: ${{ vars.DEPLOY_SMOKE_URL }}
|
||||||
|
run: |
|
||||||
|
# Passenger starts the app on the first request after the restart; give it a moment.
|
||||||
|
for _ in 1 2 3 4 5 6; do
|
||||||
|
if curl -fsS -o /dev/null "$DEPLOY_SMOKE_URL"; then echo "OK: $DEPLOY_SMOKE_URL"; exit 0; fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "Smoke test failed: $DEPLOY_SMOKE_URL"
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Remove key
|
||||||
|
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
|
run: rm -f "$SSH_DIR/key"
|
||||||
@@ -8,7 +8,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
npm run build # Compile TypeScript → dist/
|
npm run build # Compile TypeScript → dist/
|
||||||
npm run start # Build and start (tsc && node ./dist/app.js)
|
npm run start # Build and start (tsc && node ./dist/app.js)
|
||||||
npm run debug # Start with DEBUG=* environment variable
|
npm run debug # Start with DEBUG=* environment variable
|
||||||
npm run test # Run the vitest suite once with coverage (lcov + testResults/sonar-report.xml)
|
npm run test # Run the vitest suite once with coverage (text summary + lcov in coverage/)
|
||||||
npm run test:watch # vitest in watch mode
|
npm run test:watch # vitest in watch mode
|
||||||
npm run test:integration # Admin-module tests against a throwaway MariaDB (needs docker or podman)
|
npm run test:integration # Admin-module tests against a throwaway MariaDB (needs docker or podman)
|
||||||
```
|
```
|
||||||
@@ -18,6 +18,12 @@ Run a single test file:
|
|||||||
npx vitest run test/some.test.ts
|
npx vitest run test/some.test.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Deploys** run in Gitea Actions (`.gitea/workflows/deploy.yml`, since 2026-11-08; Jenkins is
|
||||||
|
retired): every push/PR runs `tsc` and the unit tests, pushes to master build, prune dev
|
||||||
|
dependencies and rsync `dist/`, `src/`, `public/`, `node_modules/` and `package.json` to Plesk over
|
||||||
|
SSH. `.env`, `logs/` and `tmp/` on the server are never touched; SQL migrations stay manual.
|
||||||
|
Details: `docs/deployment.md`.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Express.js REST API in TypeScript with a service-oriented layering. Domains: `Calendar` (events, users), `Feedback` (concert feedback forms, mounted at `/feedback`, backed by its own `FEEDBACK_DB` — see `src/models/feedback/`: public submission flow, admin CRUD, reporting, and a Salesforce newsletter-sync integration), `Tickets` (mounted at `/tickets`), and `Admin` (identity and permissions, mounted at `/admin`, backed by `ADMIN_DB` — see below).
|
Express.js REST API in TypeScript with a service-oriented layering. Domains: `Calendar` (events, users), `Feedback` (concert feedback forms, mounted at `/feedback`, backed by its own `FEEDBACK_DB` — see `src/models/feedback/`: public submission flow, admin CRUD, reporting, and a Salesforce newsletter-sync integration), `Tickets` (mounted at `/tickets`), and `Admin` (identity and permissions, mounted at `/admin`, backed by `ADMIN_DB` — see below).
|
||||||
@@ -33,29 +39,51 @@ Express.js REST API in TypeScript with a service-oriented layering. Domains: `Ca
|
|||||||
|
|
||||||
| Layer | Location |
|
| Layer | Location |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Router | `src/models/calendar/Calendar.router.ts`, `…/events/events.router.ts`, `…/users/users.router.ts` |
|
| Router | `src/models/calendar/Calendar.router.ts`, `…/events/events.router.ts` |
|
||||||
| Services | `…/events/events.service.ts`, `…/users/users.service.ts`, `…/events/credentials.service.ts`, `…/events/icalgenerator.service.ts` |
|
| Services | `…/events/events.service.ts`, `…/events/credentials.service.ts`, `…/events/icalgenerator.service.ts` |
|
||||||
| DB pool | `src/models/calendar/Calendar.db.ts` (MariaDB, pool size 5) |
|
| DB pool | `src/models/calendar/Calendar.db.ts` (MariaDB, pool size 5) |
|
||||||
| Shared | `src/common/` (base route class, nodemailer wrapper), `src/middleware/logger.ts` (Winston) |
|
| Shared | `src/common/` (base route class, nodemailer wrapper), `src/middleware/logger.ts` (Winston) |
|
||||||
|
|
||||||
**Auth model:** Two of them, on purpose.
|
**Auth model:** One, since the calendar migration completed.
|
||||||
|
|
||||||
*Admin module (`src/models/admin/`)* — the current one, used by feedback, tickets and the
|
*Admin module (`src/models/admin/`)* — used by every app: calendar, feedback, tickets and the
|
||||||
admin app. better-auth 1.7 on its own `nachklang_admin` database (Kysely + mysql2; every
|
admin app itself. better-auth 1.7 on its own `nachklang_admin` database (Kysely + mysql2; every
|
||||||
other domain keeps the `mariadb` driver), mounted at `/admin/auth/*` for the auth handler
|
other domain keeps the `mariadb` driver), mounted at `/admin/auth/*` for the auth handler
|
||||||
and `/admin` for the JSON routes. Sessions are httpOnly cookies scoped to
|
and `/admin` for the JSON routes. Sessions are httpOnly cookies scoped to
|
||||||
`.nachklang.art`, so one sign-in covers every app. Accounts are **invite-only** — public
|
`.nachklang.art`, so one sign-in covers every app. Accounts are **invite-only** — public
|
||||||
sign-up is disabled, and `invitations.plugin.ts` is the only code that creates users.
|
sign-up is disabled, and `invitations.plugin.ts` is the only code that creates users.
|
||||||
Permissions are per app in `user_app_permissions`; `requireAppAccess(app)` in
|
A permission is **(app, role)** in `user_app_permissions`, keyed on
|
||||||
`admin.middleware.ts` is the single authenticator, and it queries the database on every
|
`(user_id, app, role)` so one user can hold several roles per app. Two roles exist: `access`
|
||||||
request (no cookie cache) so disabling a user takes effect at once. `ADMIN_BOOTSTRAP_EMAIL`
|
(full access) and `read` (read-only, not for `admin`) - see `docs/admin-roles.md`, including
|
||||||
|
how `requireAppAccess` enforces `read` by HTTP method; `APP_ROLES` in `admin.schema.ts` is the contract,
|
||||||
|
and a role not listed there is rejected rather than written. `requireAppAccess(app)` in
|
||||||
|
`admin.middleware.ts` is the single authenticator - it takes an optional second argument to
|
||||||
|
narrow to one role, and queries the database on every request (no cookie cache) so disabling
|
||||||
|
a user takes effect at once. Two things to know before touching this: any count of admins
|
||||||
|
must count **distinct users**, not permission rows, or a single admin with two roles reads as
|
||||||
|
two and the last-admin guard stops guarding; and both write endpoints accept
|
||||||
|
`{permissions: [{app, role}]}` as well as the older `{apps: ['tickets']}`, which means the
|
||||||
|
same at the `access` role. `ADMIN_BOOTSTRAP_EMAIL`
|
||||||
makes sure someone can always get in on a fresh database.
|
makes sure someone can always get in on a fresh database.
|
||||||
|
|
||||||
*Legacy calendar* — unchanged: users need a `@nachklang.art` email, and after activation
|
*The calendar* used to be the exception - its own `users`/`sessions` tables, and a session
|
||||||
get a session token (30-day window, hash + IP stored in the DB), passed as query
|
token passed in **query parameters**. That is gone: `docs/calendar-auth-migration.md` records
|
||||||
parameters. Migration is planned but not started: `docs/calendar-auth-migration.md`.
|
the migration, finished 2026-09-06. Writes sit behind `requireAppAccess('calendar')`; reads
|
||||||
Credentials for non-user calendar access (`MEMBER_CREDENTIAL`, `CHOIR_CREDENTIAL`,
|
resolve the same cookie optionally, because one URL serves an anonymous visitor, an iCal
|
||||||
`MANAGEMENT_CREDENTIAL`) come from `.env`.
|
subscription and a signed-in editor.
|
||||||
|
|
||||||
|
Two calendar-specific things survive that migration and are easy to break:
|
||||||
|
|
||||||
|
- **The `public` calendar answers with no credential of any kind.** nachklang.art reads it to
|
||||||
|
show the next upcoming event. Pinned by `test/calendar/credentials.service.test.ts` and
|
||||||
|
`test/calendar/events.router.test.ts`.
|
||||||
|
- **The shared passwords (`MEMBER_CREDENTIAL`, `CHOIR_CREDENTIAL`, `MANAGEMENT_CREDENTIAL`,
|
||||||
|
from `.env`) still open the restricted calendars for reading**, because an iCal client
|
||||||
|
cannot send a cookie. They can never write.
|
||||||
|
|
||||||
|
An event's creator is a display name and nothing else - nothing authorises on it. It resolves
|
||||||
|
from the admin module's `user.name` when the row carries an admin id, and otherwise from
|
||||||
|
`created_by_name`, a snapshot taken before the legacy `users` table was renamed aside.
|
||||||
|
|
||||||
**Admin database driver:** the admin pool is the **callback-style** `mysql2`, never
|
**Admin database driver:** the admin pool is the **callback-style** `mysql2`, never
|
||||||
`mysql2/promise`. Kysely's `MysqlDialect` calls `pool.getConnection((err, conn) => ...)`;
|
`mysql2/promise`. Kysely's `MysqlDialect` calls `pool.getConnection((err, conn) => ...)`;
|
||||||
@@ -68,6 +96,19 @@ error. Only the integration tests catch this.
|
|||||||
`better-auth/db`, called with `auth.options`), diff, and add a numbered migration. Do not
|
`better-auth/db`, called with `auth.options`), diff, and add a numbered migration. Do not
|
||||||
use the published `@better-auth/cli`; it lags the library.
|
use the published `@better-auth/cli`; it lags the library.
|
||||||
|
|
||||||
|
**`docker-compose.dev.yml` builds a fresh local dev database from `docker/init/`, not
|
||||||
|
from `sql/<domain>/` directly** - the two domains use different mechanisms and both need
|
||||||
|
to be kept in sync by hand whenever a migration is added: `docker/init/03-tickets-schema.sql`
|
||||||
|
and `02-feedback-schema.sql` are thin files that `SOURCE` every `sql/<domain>/NNN_*.sql`
|
||||||
|
in order (add the new migration's `SOURCE` line there too); `01-calendar-schema-dev.sql`
|
||||||
|
and `04-admin-schema.sql` instead fold each migration's effect directly into one
|
||||||
|
reconstructed CREATE-TABLE schema (own header comment: "keep the two in step") - no
|
||||||
|
`SOURCE` list to extend, edit the reconstructed schema itself. Found
|
||||||
|
`03-tickets-schema.sql` missing the `SOURCE` line for `003_add_confirmation_email_status.sql`
|
||||||
|
while adding `004` - every tickets dev DB spun up since that migration was added has been
|
||||||
|
silently missing the column (mail sends still succeed, `recordConfirmationEmailResult`'s
|
||||||
|
`UPDATE` just fails and logs). Fixed.
|
||||||
|
|
||||||
**Event versioning:** Events have a companion `event_versions` table. `events.service.ts` manages writes to both.
|
**Event versioning:** Events have a companion `event_versions` table. `events.service.ts` manages writes to both.
|
||||||
|
|
||||||
**Calendar types and IDs:** `public` (1), `members` (2), `management` (3), `choir` (4), `birthdays` (5). `credentials.service.ts` enforces which session/credential can read each calendar.
|
**Calendar types and IDs:** `public` (1), `members` (2), `management` (3), `choir` (4), `birthdays` (5). `credentials.service.ts` enforces which session/credential can read each calendar.
|
||||||
|
|||||||
+31
-32
@@ -5,15 +5,28 @@ These items were identified during a security review on 2026-05-02 and conscious
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Session credentials in URL query parameters (logged-in users)
|
## 1. Session credentials in URL query parameters (logged-in users) — CLOSED 2026-09-06
|
||||||
|
|
||||||
**Files:** `src/models/calendar/events/events.router.ts` — all GET/PUT/DELETE handlers
|
**Files:** `src/models/calendar/events/events.router.ts` — all GET/PUT/DELETE handlers
|
||||||
|
|
||||||
`sessionId` and `sessionKey` are currently read from query parameters, which means they appear in server access logs, browser history, proxy logs, and `Referer` headers.
|
`sessionId` and `sessionKey` were read from query parameters, which meant they appeared in
|
||||||
|
server access logs, browser history, proxy logs, and `Referer` headers.
|
||||||
|
|
||||||
**Fix:** Move to request headers (`X-Session-Id` / `X-Session-Key`) or the request body. Requires a corresponding frontend update.
|
**Fixed** by step 4 of `docs/calendar-auth-migration.md`: the calendar's write routes now sit
|
||||||
|
behind `requireAppAccess('calendar')` against the better-auth session cookie, and the read
|
||||||
|
routes resolve the same cookie optionally. No route reads `sessionId`/`sessionKey` any more,
|
||||||
|
and the Angular frontend sends `withCredentials` instead of appending them to every URL. That
|
||||||
|
closed the item outright rather than moving the credential somewhere safer.
|
||||||
|
|
||||||
> Note: the shared calendar `password` parameter in query params is intentional (iCal clients don't support headers) and is acceptable for the current setup.
|
Two things this did *not* change, both deliberate:
|
||||||
|
|
||||||
|
- The shared calendar `password` parameter stays. An iCal client cannot send a cookie, so
|
||||||
|
this is the one caller that genuinely needs a credential in the URL. It grants read access
|
||||||
|
to one calendar and nothing else - `test/calendar/events.router.test.ts` pins that it can
|
||||||
|
never be used to write.
|
||||||
|
- ~~The legacy `/calendar/users/*` routes still exist.~~ Removed by step 5 on 2026-09-06,
|
||||||
|
along with the `users` and `sessions` tables they used - renamed aside rather than dropped,
|
||||||
|
so nothing was destroyed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,43 +37,29 @@ These items were identified during a security review on 2026-05-02 and conscious
|
|||||||
- `PUT /move/:eventId` (move)
|
- `PUT /move/:eventId` (move)
|
||||||
- `DELETE /:eventId` (delete)
|
- `DELETE /:eventId` (delete)
|
||||||
|
|
||||||
Currently any active user can edit, move, or delete any event regardless of who created it. This is acceptable while all users are trusted admins.
|
Currently any account holding the `calendar` permission can edit, move, or delete any event regardless of who created it. This is acceptable while everyone holding it is a trusted admin.
|
||||||
|
|
||||||
**Fix:** When non-admin users are introduced, fetch the event first and verify `event.createdById === user.userId` before allowing the mutation. Add an `isAdmin` flag to the user model to let admins bypass the check.
|
**Fix (updated 2026-09-06):** fetch the event first and verify `event.createdByUserId === res.locals.admin.id` before allowing the mutation — `createdById`, the legacy INT, is no longer written and is gone at step 5. Rather than an `isAdmin` flag, the bypass belongs in the permission model that already exists: `requireAppAccess('calendar', 'manage')` alongside the current `access` role, which needs a row in `APP_ROLES` on both sides and nothing else.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Activation token has no expiry
|
## 3. Activation token has no expiry — CLOSED 2026-09-06
|
||||||
|
|
||||||
> **Superseded for new accounts (2026-09-05).** The admin module
|
**File:** ~~`src/models/calendar/users/users.service.ts`~~ — deleted.
|
||||||
> (`src/models/admin/`) replaced account creation for the feedback, tickets and admin
|
|
||||||
> apps: accounts now come from `invitations`, whose tokens expire after 7 days and are
|
|
||||||
> stored only as a SHA-256 hash. The item below still stands for the legacy calendar
|
|
||||||
> `users` table, which the admin module deliberately left alone - see
|
|
||||||
> `docs/calendar-auth-migration.md`.
|
|
||||||
|
|
||||||
**File:** `src/models/calendar/users/users.service.ts` — `createUser` / `activateUser`
|
The e-mail activation link was valid indefinitely. Closed not by adding an expiry but by
|
||||||
|
removing the thing that issued it: step 5 of `docs/calendar-auth-migration.md` deleted the
|
||||||
|
calendar's own account system. Accounts now come only from the admin module's `invitations`,
|
||||||
|
whose tokens expire after 7 days and are stored as a SHA-256 hash.
|
||||||
|
|
||||||
The email activation link is valid indefinitely. Acceptable for a small, trusted userbase.
|
Any activation link still sitting in an inbox now 404s. It only ever activated a legacy
|
||||||
|
account, which no longer opens anything.
|
||||||
**Fix:**
|
|
||||||
1. Add an `activation_expires` column to the `users` table (e.g. `DATETIME`).
|
|
||||||
2. Set it to `NOW() + INTERVAL 24 HOUR` in `createUser`.
|
|
||||||
3. Check `activation_expires > NOW()` in `activateUser` before accepting the token.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Password reset token has no expiry
|
## 4. Password reset token has no expiry — CLOSED 2026-09-06
|
||||||
|
|
||||||
> **Superseded for new accounts (2026-09-05).** Password resets for admin-module accounts
|
**File:** ~~`src/models/calendar/users/users.service.ts`~~ — deleted.
|
||||||
> go through better-auth, whose reset tokens expire after one hour. As with item 3, the
|
|
||||||
> text below still applies to the legacy calendar `users` table.
|
|
||||||
|
|
||||||
**File:** `src/models/calendar/users/users.service.ts` — `initiatePasswordReset` / `finalizePasswordReset`
|
Same as item 3: `pw_reset_token_hash` never expired, and the code that set it no longer
|
||||||
|
exists. Password resets go through better-auth, whose reset tokens expire after one hour.
|
||||||
The reset token stored in `pw_reset_token_hash` never expires. Acceptable for a small, trusted userbase.
|
|
||||||
|
|
||||||
**Fix:**
|
|
||||||
1. Add a `pw_reset_expires` column to the `users` table (e.g. `DATETIME`).
|
|
||||||
2. Set it to `NOW() + INTERVAL 15 MINUTE` in `initiatePasswordReset`.
|
|
||||||
3. Check `pw_reset_expires > NOW()` in `finalizePasswordReset` before accepting the token.
|
|
||||||
@@ -1,5 +1,13 @@
|
|||||||
-- Local dev only. Real schema, provided directly by the repo owner
|
-- Local dev only. Derived from the real schema, which was provided directly by
|
||||||
-- (calendars, events, event_versions, sessions, users) - not a guess.
|
-- the repo owner (calendars, events, event_versions, and the sessions/users
|
||||||
|
-- tables that step 5 of docs/calendar-auth-migration.md renamed aside).
|
||||||
|
--
|
||||||
|
-- There is no users or sessions table here: a fresh dev database has no legacy
|
||||||
|
-- accounts to archive, so it starts where production ends up.
|
||||||
|
--
|
||||||
|
-- Changes made by this repo's own migrations under sql/calendar/ are folded in
|
||||||
|
-- here rather than appended, so a fresh dev container matches production once
|
||||||
|
-- every migration has been applied. Keep the two in step.
|
||||||
USE nachklang_calendar;
|
USE nachklang_calendar;
|
||||||
|
|
||||||
CREATE TABLE `calendars` (
|
CREATE TABLE `calendars` (
|
||||||
@@ -9,41 +17,20 @@ CREATE TABLE `calendars` (
|
|||||||
PRIMARY KEY (`calendar_id`)
|
PRIMARY KEY (`calendar_id`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
CREATE TABLE `users` (
|
|
||||||
`user_id` int(11) NOT NULL AUTO_INCREMENT,
|
|
||||||
`full_name` text NOT NULL,
|
|
||||||
`password_hash` text DEFAULT NULL,
|
|
||||||
`email` text NOT NULL,
|
|
||||||
`is_active` tinyint(1) DEFAULT 0,
|
|
||||||
`pw_reset_token_hash` text DEFAULT NULL,
|
|
||||||
`activation_token` text DEFAULT NULL,
|
|
||||||
PRIMARY KEY (`user_id`),
|
|
||||||
UNIQUE KEY `email` (`email`) USING HASH
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
|
||||||
|
|
||||||
CREATE TABLE `sessions` (
|
|
||||||
`session_id` int(11) NOT NULL AUTO_INCREMENT,
|
|
||||||
`user_id` int(11) NOT NULL,
|
|
||||||
`session_key_hash` text DEFAULT NULL,
|
|
||||||
`created_date` datetime DEFAULT current_timestamp(),
|
|
||||||
`valid_until` datetime DEFAULT (current_timestamp() + interval 30 day),
|
|
||||||
`last_ip` text DEFAULT NULL,
|
|
||||||
PRIMARY KEY (`session_id`),
|
|
||||||
KEY `sessions_users_user_id_fk` (`user_id`),
|
|
||||||
CONSTRAINT `sessions_users_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
|
||||||
|
|
||||||
CREATE TABLE `events` (
|
CREATE TABLE `events` (
|
||||||
`event_id` int(11) NOT NULL AUTO_INCREMENT,
|
`event_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
`calendar_id` int(11) NOT NULL,
|
`calendar_id` int(11) NOT NULL,
|
||||||
`uuid` text NOT NULL,
|
`uuid` text NOT NULL,
|
||||||
`created_date` datetime DEFAULT current_timestamp(),
|
`created_date` datetime DEFAULT current_timestamp(),
|
||||||
`created_by_id` int(11) NOT NULL,
|
-- Bridge to the admin module's user ids; see sql/calendar/001_add_admin_user_bridge.sql.
|
||||||
|
`created_by_user_id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
||||||
|
-- Creator name, archived before the legacy users table went away;
|
||||||
|
-- see sql/calendar/002_snapshot_legacy_creator_names.sql.
|
||||||
|
`created_by_name` varchar(255) DEFAULT NULL,
|
||||||
PRIMARY KEY (`event_id`),
|
PRIMARY KEY (`event_id`),
|
||||||
KEY `events_calendars_calendar_id_fk` (`calendar_id`),
|
KEY `events_calendars_calendar_id_fk` (`calendar_id`),
|
||||||
KEY `events_users_user_id_fk` (`created_by_id`),
|
KEY `events_created_by_user_idx` (`created_by_user_id`),
|
||||||
CONSTRAINT `events_calendars_calendar_id_fk` FOREIGN KEY (`calendar_id`) REFERENCES `calendars` (`calendar_id`),
|
CONSTRAINT `events_calendars_calendar_id_fk` FOREIGN KEY (`calendar_id`) REFERENCES `calendars` (`calendar_id`)
|
||||||
CONSTRAINT `events_users_user_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `users` (`user_id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
CREATE TABLE `event_versions` (
|
CREATE TABLE `event_versions` (
|
||||||
@@ -57,14 +44,16 @@ CREATE TABLE `event_versions` (
|
|||||||
`repeat_frequency` text DEFAULT NULL,
|
`repeat_frequency` text DEFAULT NULL,
|
||||||
`location` text DEFAULT NULL,
|
`location` text DEFAULT NULL,
|
||||||
`url` text DEFAULT NULL,
|
`url` text DEFAULT NULL,
|
||||||
`version_created_by_id` int(11) DEFAULT NULL,
|
-- Bridge to the admin module's user ids; see sql/calendar/001_add_admin_user_bridge.sql.
|
||||||
|
`version_created_by_user_id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
||||||
|
-- Archived editor name; see sql/calendar/002_snapshot_legacy_creator_names.sql.
|
||||||
|
`version_created_by_name` varchar(255) DEFAULT NULL,
|
||||||
`status` text DEFAULT NULL,
|
`status` text DEFAULT NULL,
|
||||||
`version_created_at` datetime DEFAULT current_timestamp(),
|
`version_created_at` datetime DEFAULT current_timestamp(),
|
||||||
PRIMARY KEY (`event_version_id`),
|
PRIMARY KEY (`event_version_id`),
|
||||||
KEY `event_versions_events_event_id_fk` (`event_id`),
|
KEY `event_versions_events_event_id_fk` (`event_id`),
|
||||||
KEY `event_versions_users_user_id_fk` (`version_created_by_id`),
|
KEY `event_versions_created_by_user_idx` (`version_created_by_user_id`),
|
||||||
CONSTRAINT `event_versions_events_event_id_fk` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
CONSTRAINT `event_versions_events_event_id_fk` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
CONSTRAINT `event_versions_users_user_id_fk` FOREIGN KEY (`version_created_by_id`) REFERENCES `users` (`user_id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
INSERT INTO calendars (calendar_id, name, includes_calendars) VALUES
|
INSERT INTO calendars (calendar_id, name, includes_calendars) VALUES
|
||||||
@@ -74,16 +63,17 @@ INSERT INTO calendars (calendar_id, name, includes_calendars) VALUES
|
|||||||
(4, 'choir', '[]'),
|
(4, 'choir', '[]'),
|
||||||
(5, 'birthdays', '[]');
|
(5, 'birthdays', '[]');
|
||||||
|
|
||||||
-- Dev admin, password: devpassword
|
-- Two events carry only an archived creator name, as every pre-cutover event
|
||||||
INSERT INTO users (email, password_hash, full_name, is_active) VALUES
|
-- does, and one carries an admin user id whose name is resolved live. Dev
|
||||||
('dev@nachklang.art', '$2b$10$vmj7POS/68SGE.eI7pGjMegrw0vNNZ2HVSUTra5NRsl8iOLwiMgZK', 'Dev Admin', 1);
|
-- therefore exercises both name sources rather than only one. The one with an
|
||||||
|
-- id is deliberately a PUBLIC event, so the anonymous listing the website uses
|
||||||
|
-- covers both. The id is the dev admin from 04-admin-schema.sql.
|
||||||
|
INSERT INTO events (calendar_id, uuid, created_by_user_id, created_by_name) VALUES
|
||||||
|
(1, UUID(), NULL, 'Dev Admin'),
|
||||||
|
(1, UUID(), 'dev-user-0000-0000-0000-000000000001', NULL),
|
||||||
|
(1, UUID(), NULL, 'Dev Admin');
|
||||||
|
|
||||||
INSERT INTO events (calendar_id, uuid, created_by_id) VALUES
|
INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, location, url, status, version_created_by_user_id, version_created_by_name) VALUES
|
||||||
(1, UUID(), 1),
|
(1, 'Frühlingskonzert 2026', 'Erstes Konzert der Reihe', '2026-04-18 19:00:00', '2026-04-18 21:00:00', 0, 'Musikhochschule, Karlsruhe', 'https://www.nachklang.art/events/fruehlingskonzert-2026', 'PUBLIC', NULL, 'Dev Admin'),
|
||||||
(1, UUID(), 1),
|
(2, 'Sommerkonzert 2026', 'Zweites Konzert der Reihe', '2026-07-11 19:00:00', '2026-07-11 21:00:00', 0, 'Christuskirche, Karlsruhe', 'https://www.nachklang.art/events/sommerkonzert-2026', 'PUBLIC', 'dev-user-0000-0000-0000-000000000001', NULL),
|
||||||
(1, UUID(), 1);
|
(3, 'Adventskonzert 2026', 'Drittes Konzert der Reihe', '2026-12-05 19:00:00', '2026-12-05 21:00:00', 0, 'Stadtkirche, Karlsruhe', 'https://www.nachklang.art/events/adventskonzert-2026', 'DRAFT', NULL, 'Dev Admin');
|
||||||
|
|
||||||
INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, location, url, status, version_created_by_id) VALUES
|
|
||||||
(1, 'Frühlingskonzert 2026', 'Erstes Konzert der Reihe', '2026-04-18 19:00:00', '2026-04-18 21:00:00', 0, 'Musikhochschule, Karlsruhe', 'https://www.nachklang.art/events/fruehlingskonzert-2026', 'PUBLIC', 1),
|
|
||||||
(2, 'Sommerkonzert 2026', 'Zweites Konzert der Reihe', '2026-07-11 19:00:00', '2026-07-11 21:00:00', 0, 'Christuskirche, Karlsruhe', 'https://www.nachklang.art/events/sommerkonzert-2026', 'PUBLIC', 1),
|
|
||||||
(3, 'Adventskonzert 2026', 'Drittes Konzert der Reihe', '2026-12-05 19:00:00', '2026-12-05 21:00:00', 0, 'Stadtkirche, Karlsruhe', 'https://www.nachklang.art/events/adventskonzert-2026', 'DRAFT', 1);
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
USE nachklang_feedback;
|
USE nachklang_feedback;
|
||||||
SOURCE /migrations/feedback/001_init.sql;
|
SOURCE /migrations/feedback/001_init.sql;
|
||||||
SOURCE /migrations/feedback/002_add_poster_image_url.sql;
|
SOURCE /migrations/feedback/002_add_poster_image_url.sql;
|
||||||
|
SOURCE /migrations/feedback/003_add_submission_client_token.sql;
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
USE nachklang_tickets;
|
USE nachklang_tickets;
|
||||||
SOURCE /migrations/tickets/001_init.sql;
|
SOURCE /migrations/tickets/001_init.sql;
|
||||||
SOURCE /migrations/tickets/002_add_require_address.sql;
|
SOURCE /migrations/tickets/002_add_require_address.sql;
|
||||||
|
SOURCE /migrations/tickets/003_add_confirmation_email_status.sql;
|
||||||
|
SOURCE /migrations/tickets/004_add_tickets_mailed.sql;
|
||||||
@@ -103,15 +103,21 @@ CREATE TABLE IF NOT EXISTS `rateLimit` (
|
|||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Which apps a user may administer. `admin` is just another app: holding it is
|
-- Which apps a user may administer. `admin` is just another app: holding it is
|
||||||
-- what lets someone manage users and invitations. `role` is reserved for
|
-- what lets someone manage users and invitations. A permission is (app, role);
|
||||||
-- per-app roles later and is 'admin' for every row today.
|
-- `access` is the only role today, and the key admits several per app so finer
|
||||||
|
-- ones can be added by inserting rows rather than by migrating this table.
|
||||||
CREATE TABLE IF NOT EXISTS `user_app_permissions` (
|
CREATE TABLE IF NOT EXISTS `user_app_permissions` (
|
||||||
`user_id` VARCHAR(36) NOT NULL,
|
`user_id` VARCHAR(36) NOT NULL,
|
||||||
`app` ENUM('calendar','feedback','tickets','admin') NOT NULL,
|
`app` ENUM('calendar','feedback','tickets','admin') NOT NULL,
|
||||||
`role` VARCHAR(32) NOT NULL DEFAULT 'admin',
|
-- One row per (user, app, role). `access` means "may use this app at all"
|
||||||
|
-- and is the only role today; the key allows several per app so a finer
|
||||||
|
-- permission can be added later by inserting rows, not by migrating.
|
||||||
|
`role` VARCHAR(32) NOT NULL DEFAULT 'access',
|
||||||
`granted_by` VARCHAR(36) DEFAULT NULL,
|
`granted_by` VARCHAR(36) DEFAULT NULL,
|
||||||
`granted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`granted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`user_id`, `app`),
|
-- (user_id, app) is the leftmost prefix of this key, so the per-request
|
||||||
|
-- permission lookup needs no separate index.
|
||||||
|
PRIMARY KEY (`user_id`, `app`, `role`),
|
||||||
CONSTRAINT `uap_user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
CONSTRAINT `uap_user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
@@ -122,7 +128,7 @@ CREATE TABLE IF NOT EXISTS `invitations` (
|
|||||||
`email` VARCHAR(255) NOT NULL,
|
`email` VARCHAR(255) NOT NULL,
|
||||||
`name` VARCHAR(255) NOT NULL,
|
`name` VARCHAR(255) NOT NULL,
|
||||||
`token_hash` CHAR(64) NOT NULL,
|
`token_hash` CHAR(64) NOT NULL,
|
||||||
`apps` JSON NOT NULL,
|
`permissions` JSON NOT NULL,
|
||||||
`invited_by` VARCHAR(36) DEFAULT NULL,
|
`invited_by` VARCHAR(36) DEFAULT NULL,
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`expires_at` DATETIME NOT NULL,
|
`expires_at` DATETIME NOT NULL,
|
||||||
@@ -158,7 +164,7 @@ VALUES (
|
|||||||
);
|
);
|
||||||
|
|
||||||
INSERT INTO `user_app_permissions` (`user_id`, `app`, `role`) VALUES
|
INSERT INTO `user_app_permissions` (`user_id`, `app`, `role`) VALUES
|
||||||
('dev-user-0000-0000-0000-000000000001', 'calendar', 'admin'),
|
('dev-user-0000-0000-0000-000000000001', 'calendar', 'access'),
|
||||||
('dev-user-0000-0000-0000-000000000001', 'feedback', 'admin'),
|
('dev-user-0000-0000-0000-000000000001', 'feedback', 'access'),
|
||||||
('dev-user-0000-0000-0000-000000000001', 'tickets', 'admin'),
|
('dev-user-0000-0000-0000-000000000001', 'tickets', 'access'),
|
||||||
('dev-user-0000-0000-0000-000000000001', 'admin', 'admin');
|
('dev-user-0000-0000-0000-000000000001', 'admin', 'access');
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Admin roles: full access and read-only
|
||||||
|
|
||||||
|
Added 2026-10-29. A user's permission is a list of **(app, role)** grants in
|
||||||
|
`user_app_permissions` (see `src/models/admin/admin.schema.ts`). Each app can now be granted at
|
||||||
|
one of two levels:
|
||||||
|
|
||||||
|
| Role | UI label (admin app) | Apps | Meaning |
|
||||||
|
|----------|----------------------|-------------------------------|--------------------------------------------|
|
||||||
|
| `access` | Vollzugriff | calendar, feedback, tickets, admin | Everything in that app, as before. |
|
||||||
|
| `read` | Nur lesen | calendar, feedback, tickets | See everything, change nothing. |
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **`access` and `read` on the same app are mutually exclusive.** `toPermissions` returns `null`
|
||||||
|
for a list holding both, so `PUT /admin/users/:id/permissions` and `POST /admin/invitations`
|
||||||
|
answer 400. There is no "higher one wins".
|
||||||
|
- **`admin` (user management) has no `read` role.** Viewing it means viewing other people's
|
||||||
|
email addresses, IPs and sessions; that is a different trust level from viewing concerts.
|
||||||
|
- Existing grants were not migrated: every pre-existing row is `access` and still means full
|
||||||
|
access.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
`requireAppAccess(app)` (no role argument - which is how every app router uses it) does, after
|
||||||
|
the existing session/disabled/has-any-grant checks:
|
||||||
|
|
||||||
|
- `GET`, `HEAD`, `OPTIONS` - allowed for any grant on the app.
|
||||||
|
- anything else - allowed only with `access` (`canWrite`). A `read`-only user gets
|
||||||
|
`403 {status: 'FORBIDDEN', message: 'Du hast für diesen Bereich nur Lesezugriff.'}`.
|
||||||
|
|
||||||
|
This is by method on purpose: a write route added later is covered without being marked. It
|
||||||
|
relies on one convention that **must stay true**: admin routes read with GET and change with
|
||||||
|
POST/PUT/PATCH/DELETE. When this was built, every GET handler in tickets, feedback and calendar
|
||||||
|
was checked to call only read functions (no SQL writes, no mail). A GET with a side effect, or a
|
||||||
|
POST that only reads, breaks the read-only role in one direction or the other.
|
||||||
|
|
||||||
|
Consequences worth knowing:
|
||||||
|
|
||||||
|
- "Resend confirmation email" (tickets) is a POST and therefore not available read-only - by
|
||||||
|
decision: it has an effect outside the system.
|
||||||
|
- CSV exports and reports are GETs and therefore available read-only - also by decision.
|
||||||
|
Read-only means all data, including personal data. A restricted variant would be a new role.
|
||||||
|
- `requireAppAccess(app, role)` with an explicit role does **not** apply the method rule: the
|
||||||
|
caller has already named exactly the grant it needs.
|
||||||
|
|
||||||
|
## Telling the frontend
|
||||||
|
|
||||||
|
- `GET /tickets/admin/me` and `GET /feedback/admin/me` return `readOnly: boolean` alongside
|
||||||
|
`email` and `fullName`. Frontends hide write controls when it is `true`; the API refuses the
|
||||||
|
writes regardless.
|
||||||
|
- `GET /admin/me` returns the full `permissions` list; `isReadOnly(permissions, app)` in
|
||||||
|
`admin.schema.ts` is the same rule.
|
||||||
|
|
||||||
|
## Calendar
|
||||||
|
|
||||||
|
The API side is done: calendar writes sit behind `requireAppAccess('calendar')` and so refuse a
|
||||||
|
`read`-only user, and the optional-cookie reads (`/:calendar/json`, `/ical`) check
|
||||||
|
`access.apps.includes('calendar')`, which a `read` grant satisfies - read-only users see the
|
||||||
|
restricted calendars.
|
||||||
|
|
||||||
|
The current Angular frontend (`Calendar_Frontend`) was deliberately **not** changed, because it
|
||||||
|
is being rewritten in Next.js. Until then a read-only calendar user sees the edit buttons and
|
||||||
|
gets the 403 above when using them. Contract for the rewrite: there is no `/calendar/.../me`
|
||||||
|
with `readOnly`; read `GET /admin/me` and compute `isReadOnly(permissions, 'calendar')` - or add
|
||||||
|
a calendar `/me` mirroring tickets/feedback.
|
||||||
|
|
||||||
|
## Adding a finer role later
|
||||||
|
|
||||||
|
`canWrite` checks for `access` specifically, so a new role (e.g. `tickets:redeem`) grants no
|
||||||
|
writes through the method rule. Watch out: tickets and feedback apply the role-less
|
||||||
|
`requireAdminAuth` once at the top of their admin router, so that gate would already refuse the
|
||||||
|
new role's POST before any route-level `requireAppAccess(app, 'redeem')` runs. A finer role
|
||||||
|
therefore needs `canWrite` (or the top-level gate) taught about it, not just a route-level check.
|
||||||
+238
-34
@@ -1,8 +1,27 @@
|
|||||||
# Migrating the Calendar domain onto the admin identity module
|
# Migrating the Calendar domain onto the admin identity module
|
||||||
|
|
||||||
Status: **not started.** Written 2026-09-05 alongside the admin module (step 2 of
|
Status: **complete and deployed, 2026-09-06.** Every step is live. Step 2 was dropped by
|
||||||
`docs/plan-admin-auth.md` in the nachklang-admin repo), which deliberately left the
|
decision and part of step 5 brought forward; the rest went out as written.
|
||||||
calendar alone.
|
|
||||||
|
The calendar now shares one identity with the tickets, feedback and admin apps: writes sit
|
||||||
|
behind `requireAppAccess('calendar')` against the shared session cookie, reads resolve that
|
||||||
|
cookie optionally, and the calendar's own `users`/`sessions` tables are renamed aside and
|
||||||
|
referenced by nothing. `DEFERRED_SECURITY.md` items 1, 3 and 4 closed with it.
|
||||||
|
|
||||||
|
Verified in production after the final deploy: the public calendar answers anonymously on all
|
||||||
|
three endpoints (23 events, 23 VEVENTs in the iCal feed, the next-event teaser intact),
|
||||||
|
restricted calendars still refuse without a credential, unauthenticated writes answer 401,
|
||||||
|
all six `/calendar/users/*` routes answer 404, CORS grants only `Content-Type`, sign-out from
|
||||||
|
`calendar.nachklang.art` succeeds, and **every event kept its author** - rendered from the
|
||||||
|
`created_by_name` snapshot, since the table it was copied from no longer exists under that
|
||||||
|
name. That last one is the whole reason part of step 5 was brought forward.
|
||||||
|
|
||||||
|
Remaining, at your leisure: `DROP TABLE sessions_legacy_archive, users_legacy_archive;`
|
||||||
|
|
||||||
|
Written 2026-09-05 alongside the admin module (step 2 of `docs/plan-admin-auth.md` in the
|
||||||
|
nachklang-admin repo), which deliberately left the calendar alone. Steps 1-4 of that plan
|
||||||
|
are now live, so the calendar is the last module still on the legacy query-parameter
|
||||||
|
sessions.
|
||||||
|
|
||||||
## Why the calendar was left out
|
## Why the calendar was left out
|
||||||
|
|
||||||
@@ -38,37 +57,222 @@ permissions can be granted before anything else moves.
|
|||||||
|
|
||||||
Each step is meant to leave production working on its own.
|
Each step is meant to leave production working on its own.
|
||||||
|
|
||||||
1. **Add a bridging column.** `ALTER TABLE events ADD COLUMN created_by_user_id
|
1. **Add a bridging column.** ~~`ALTER TABLE events ADD COLUMN created_by_user_id
|
||||||
VARCHAR(36) NULL`, indexed. Nothing reads it yet.
|
VARCHAR(36) NULL`, indexed. Nothing reads it yet.~~ **Done 2026-09-06**, as
|
||||||
2. **Map the accounts.** For every legacy `users` row that should survive, invite the
|
`sql/calendar/001_add_admin_user_bridge.sql` - the first migration this repo owns for the
|
||||||
person through the admin UI. On acceptance, backfill `events.created_by_user_id` from
|
calendar schema, mirrored into `docker/init/01-calendar-schema-dev.sql`. It covers both
|
||||||
`events.created_by_id` via an email-to-new-id mapping. Everyone not re-invited keeps
|
`events.created_by_user_id` and `event_versions.version_created_by_user_id`, and carries
|
||||||
working on the legacy path until step 4.
|
no foreign key (see "What the code actually looks like" below). The dev seed leaves two
|
||||||
3. **Dual-read.** Change `events.service.ts` to prefer `created_by_user_id` and fall back
|
events on the legacy path and gives one an admin id, so step 3's dual-read has both cases
|
||||||
to `created_by_id`. Writes fill both. This is the only step that is temporary code, and
|
to exercise. Verified by applying the pre-migration schema and then the migration to a
|
||||||
it should carry a removal note pointing at step 5.
|
throwaway MariaDB 11 container, and diffing `SHOW CREATE TABLE` against a fresh dev
|
||||||
4. **Switch the routes.** Replace the query-parameter session checks in
|
schema: identical. Applied to the running dev database on the same day; a dev container
|
||||||
`events.router.ts` and `users.router.ts` with `requireAppAccess('calendar')`, and change
|
created before then needs it applied, or recreating.
|
||||||
the Angular frontend to `withCredentials: true` against the same origin list. Deploy the
|
2. ~~**Map the accounts.**~~ **Dropped 2026-09-06.** There is no backfill: since the
|
||||||
API first; the calendar frontend is broken between the two deploys, so pick a quiet
|
creator is only ever a display name (see below), old events keep resolving through the
|
||||||
time. This closes `DEFERRED_SECURITY.md` item 1.
|
legacy join until step 5 and then simply lose the name. Re-inviting the people who
|
||||||
5. **Drop the legacy path.** Remove `users.service.ts`'s session handling, the `sessions`
|
actually still need calendar access remains an operational task, but it is no longer a
|
||||||
table, `created_by_id`, and the dual-read from step 3. Legacy `/calendar/users/*` stays
|
migration step and nothing is blocked on it.
|
||||||
only if something still calls it - otherwise delete it too. `X-Session-Id` /
|
3. **Dual-read.** ~~Change `events.service.ts` to prefer `created_by_user_id` and fall back
|
||||||
`X-Session-Key` can then come out of the CORS `allowedHeaders` list in
|
to `created_by_id`. Writes fill both.~~ **Done 2026-09-06.** `events.service.ts` now reads
|
||||||
`src/app.factory.ts`.
|
both columns and prefers the admin one, resolving the name through a single
|
||||||
|
`findDisplayNames` lookup against the admin database per result set (added to
|
||||||
|
`users.admin.service.ts` for this). Four copies of the same SELECT and four copies of the
|
||||||
|
row mapper were collapsed into one of each first - the dual read would otherwise have had
|
||||||
|
to be written four times.
|
||||||
|
|
||||||
|
A name now has three possible sources, tried weakest first: the legacy join, then the
|
||||||
|
`created_by_name` snapshot from migration 002, then the live admin lookup - which wins
|
||||||
|
because it is the only one that follows an account being renamed. An admin id that no
|
||||||
|
longer resolves falls back rather than blanking, and a failure to reach the admin database
|
||||||
|
is caught and logged rather than propagated, so an anonymous read of the public calendar
|
||||||
|
never depends on the admin database being up. Covered by
|
||||||
|
`test/calendar/events.service.test.ts`.
|
||||||
|
|
||||||
|
**Writes are not dual-written**, contrary to the original plan: before the cutover the
|
||||||
|
request only ever carries a legacy session, so there is no admin id available to write.
|
||||||
|
Writes start filling `created_by_user_id` (and stop filling `created_by_id`) in step 4.
|
||||||
|
4. **Switch the routes.** ~~Replace the query-parameter session checks in `events.router.ts`
|
||||||
|
and `users.router.ts` with `requireAppAccess('calendar')`, and change the Angular frontend
|
||||||
|
to `withCredentials: true`.~~ **Done 2026-09-06.** `DEFERRED_SECURITY.md` item 1 is closed:
|
||||||
|
no route reads `sessionId`/`sessionKey` any more.
|
||||||
|
|
||||||
|
How it came out, route by route:
|
||||||
|
|
||||||
|
- The four write routes sit behind `requireAppAccess('calendar')` as middleware. They
|
||||||
|
answer 401 when signed out and 403 without the permission, where they used to answer 403
|
||||||
|
for both.
|
||||||
|
- The three read routes cannot use middleware - the same URL serves an anonymous visitor,
|
||||||
|
an iCal subscription holding a shared password, and a signed-in editor who should see
|
||||||
|
drafts. They call `resolveAccess` optionally instead (`signedInEditor` in the router),
|
||||||
|
and a signed-in user *without* the calendar permission is treated as anonymous rather
|
||||||
|
than refused, so they keep their access to the public calendar.
|
||||||
|
- `credentials.service.ts` lost its session half entirely and is now just the password
|
||||||
|
table. `hasAccess(calendar, password)`.
|
||||||
|
- `/calendar/users/*` was left alone. Nothing calls it and a session it mints opens
|
||||||
|
nothing, but they are live password-accepting endpoints - step 5 removes them.
|
||||||
|
|
||||||
|
Also: `calendar.nachklang.art` joined `DEFAULT_APP_ORIGINS` (better-auth `trustedOrigins`,
|
||||||
|
without which sign-out from the calendar fails while everything else works), and
|
||||||
|
`localhost:4200` joined the dev origins for the same reason.
|
||||||
|
|
||||||
|
Two things this step had to carry that the original sequence put in step 5:
|
||||||
|
|
||||||
|
- **`sql/calendar/003_allow_null_legacy_creator.sql` makes `events.created_by_id` nullable**
|
||||||
|
(`MODIFY created_by_id INT NULL`). It is `NOT NULL` today, so the first event created after the
|
||||||
|
cutover would otherwise fail to insert - there is no legacy int id to write any more.
|
||||||
|
`event_versions.version_created_by_id` is already nullable. The foreign key can stay
|
||||||
|
until step 5; it permits NULL. It also re-runs 002's idempotent name backfill, to catch
|
||||||
|
anything created between the two migrations. Applying it early is safe - widening a
|
||||||
|
column to accept NULL cannot break the running pre-cutover build.
|
||||||
|
- **The public calendar stays anonymous.** `hasAccess('public')` returns true before any
|
||||||
|
credential check, and nachklang.art reads `/calendar/events/public/json` and
|
||||||
|
`/public/json/next` with no session at all. Pinned at both levels - the password table in
|
||||||
|
`test/calendar/credentials.service.test.ts`, the routes themselves in
|
||||||
|
`test/calendar/events.router.test.ts` - so this cannot regress quietly.
|
||||||
|
|
||||||
|
### Deploy checklist
|
||||||
|
|
||||||
|
Production has **none** of the three migrations: 001 and 002 were only ever applied to the
|
||||||
|
dev database. The API build below selects `created_by_user_id` and `created_by_name` on
|
||||||
|
every read, so deploying it against a database missing them fails every calendar request
|
||||||
|
including the anonymous public feed the website uses. In order:
|
||||||
|
|
||||||
|
1. **Apply `sql/calendar/001`, `002`, `003`, in that order**, against `CALENDAR_DB`. All
|
||||||
|
three are re-runnable, so applying one that is already applied is a no-op. Verify
|
||||||
|
before continuing:
|
||||||
|
`SHOW COLUMNS FROM events LIKE '%by_user%'; SHOW COLUMNS FROM events LIKE '%by_name%';`
|
||||||
|
- four rows across the two tables, and `created_by_id` nullable.
|
||||||
|
2. **Check `APP_ORIGINS` on the API vhost.** `calendar.nachklang.art` is in the code's
|
||||||
|
default list, but the environment variable *replaces* that list rather than adding to
|
||||||
|
it - so if it is set at all (the tickets/feedback cutover may have set it), append
|
||||||
|
`https://calendar.nachklang.art` or the calendar's sign-out will 403 while everything
|
||||||
|
else works. That is the failure mode the comment in `admin.config.ts` warns about.
|
||||||
|
3. **Deploy the API.**
|
||||||
|
4. **Deploy the calendar frontend immediately after.** Do not leave a gap - see below.
|
||||||
|
5. **Re-run 002's two `UPDATE` statements.** Between step 1 and step 3 the old API was
|
||||||
|
still writing `created_by_id` with no snapshot; those few rows would otherwise lose
|
||||||
|
their author at step 5.
|
||||||
|
6. **Rebuild the admin app** if `NEXT_PUBLIC_ALLOWED_REDIRECT_ORIGINS` does not already
|
||||||
|
contain `https://calendar.nachklang.art`. It is a **build-time** value, so a restart
|
||||||
|
does nothing.
|
||||||
|
|
||||||
|
**The window between steps 3 and 4 does not look broken, which is the danger.** The old
|
||||||
|
Angular bundle starts by calling `POST /calendar/users/checkSessionValid`, and those
|
||||||
|
legacy routes are untouched - so it still succeeds and the page renders as signed in. What
|
||||||
|
the user then sees is an empty event table and saves that silently do nothing. It looks
|
||||||
|
like the calendar lost its data, not like a deploy in progress. Keep the gap to minutes,
|
||||||
|
or take the frontend offline for it.
|
||||||
|
|
||||||
|
**One-way door:** any iCal subscription whose URL carries `?sessionId=&sessionKey=` rather
|
||||||
|
than `?password=` stops working permanently. The shared-password URLs are unaffected.
|
||||||
|
5. **Drop the legacy path.** **Deployed 2026-09-06.** Gated on step 4 being live, which it
|
||||||
|
was.
|
||||||
|
|
||||||
|
What went:
|
||||||
|
|
||||||
|
- `src/models/calendar/users/` in its entirety - registration, login, activation, both
|
||||||
|
password-reset routes, and the session checking the feedback and tickets admin areas
|
||||||
|
used to authenticate against - plus its mount in `Calendar.router.ts`. That was the
|
||||||
|
API's last unauthenticated account-creation and mail-sending endpoint.
|
||||||
|
- The two `LEFT OUTER JOIN users` clauses in `events.service.ts` and the `legacy_*`
|
||||||
|
aliases they fed, along with `created_by_id` / `version_created_by_id` in the SELECT, the
|
||||||
|
row mapper and the `Event` interface. One name source remains besides the live admin
|
||||||
|
lookup: the snapshot, which is what made this safe.
|
||||||
|
- `X-Session-Id` / `X-Session-Key` from the CORS `allowedHeaders`. Nothing had read them
|
||||||
|
since the tickets and feedback cutover, or sent them since this one.
|
||||||
|
- The tripwire in `test/admin/auth-binding.ts` asserting neither module fell back to a
|
||||||
|
calendar header session. There is nothing left to fall back to.
|
||||||
|
|
||||||
|
`DEFERRED_SECURITY.md` items **3** and **4** (activation and reset tokens never expiring)
|
||||||
|
close with it - not by adding expiries but by deleting the code that issued them.
|
||||||
|
|
||||||
|
### Deploy checklist — kept for the record; the order was REVERSED from step 4
|
||||||
|
|
||||||
|
Step 4's migration only added columns, so it went first. `004` *removes* columns and a
|
||||||
|
table that the currently running build still selects and joins, so running it first fails
|
||||||
|
every calendar read including the public feed. The step 5 build references none of them and
|
||||||
|
runs happily against the old schema. Therefore:
|
||||||
|
|
||||||
|
1. **Confirm the snapshot is complete.** Both must return 0:
|
||||||
|
```sql
|
||||||
|
SELECT SUM(created_by_id IS NOT NULL AND created_by_name IS NULL) FROM events;
|
||||||
|
SELECT SUM(version_created_by_id IS NOT NULL AND version_created_by_name IS NULL) FROM event_versions;
|
||||||
|
```
|
||||||
|
A non-zero count is an event whose author `004` would erase. Re-run 002's backfill first.
|
||||||
|
2. **Deploy the API.** No frontend deploy is needed: the calendar frontend never read
|
||||||
|
`createdById` (its `Event` model has only the name), and nothing else is known to.
|
||||||
|
3. **Confirm the calendar still works** - the public feed, a signed-in read, and one save.
|
||||||
|
At this point the old columns and tables still exist, unused, so this step is fully
|
||||||
|
reversible by redeploying the previous build.
|
||||||
|
|
||||||
|
Note that `tsc` does not remove output for deleted sources, so a build over an existing
|
||||||
|
`dist/` leaves `dist/src/models/calendar/users/*.js` behind. Nothing imports it and the
|
||||||
|
routes 404, but the deployed artifact still contains the code - clear `dist/` in the
|
||||||
|
pipeline if you want the artifact to match the source.
|
||||||
|
4. **Apply `sql/calendar/004_drop_legacy_auth.sql`.** This is the point of no return for
|
||||||
|
the columns; the accounts themselves are only renamed aside.
|
||||||
|
5. Optionally, later and at a quiet moment:
|
||||||
|
`DROP TABLE sessions_legacy_archive, users_legacy_archive;`
|
||||||
|
|
||||||
|
**One-way door:** `Event.createdById` and `lastModifiedById` leave the API response. Check
|
||||||
|
anything reading `/calendar/events/*/json` that is not the calendar frontend.
|
||||||
|
|
||||||
|
**Observed during the deploy, worth keeping.** A browser holding a *cached pre-cutover*
|
||||||
|
Angular bundle looked signed in and showed every event's status as "Error". The old bundle
|
||||||
|
called `/calendar/users/checkSessionValid`, which still existed between step 4 and step 5,
|
||||||
|
so it rendered as authenticated - then fetched events with no cookie, got the anonymous
|
||||||
|
listing, which omits `status`, and the UI's status switch fell through to its error label.
|
||||||
|
Signing out and back in fixed it. After this step that route 404s, so a stale bundle now
|
||||||
|
fails honestly instead of faking a session. This is the same "does not look broken" window
|
||||||
|
the step 4 checklist warns about, seen from the other side.
|
||||||
|
|
||||||
|
## What the code actually looks like (surveyed 2026-09-06)
|
||||||
|
|
||||||
|
Four things found while doing step 1 that change how the later steps should be built:
|
||||||
|
|
||||||
|
- **`created_by_id` is display-only.** Nothing authorises on it. `events.router.ts` gates
|
||||||
|
PUT, POST, DELETE and `/move` on `user?.isActive` alone - there is no "only the creator may
|
||||||
|
edit" rule anywhere - and the column is read back solely to render `created_by_name` and
|
||||||
|
`last_modified_by_name`. That de-risks steps 2, 3 and 5 considerably: an event whose
|
||||||
|
creator never gets re-invited loses a name in the UI, it does not become uneditable or
|
||||||
|
invisible. It also means the step 2 backfill is best-effort, not a precondition.
|
||||||
|
- **The two schemas are separate databases.** `nachklang_calendar` and `nachklang_admin`
|
||||||
|
have their own connection pools (`Calendar.db.ts` vs the admin module's Kysely instance).
|
||||||
|
So the bridging columns get no foreign key, and - the part the original sequence missed -
|
||||||
|
**the `LEFT OUTER JOIN users` that produces the creator's name cannot simply be repointed**.
|
||||||
|
It would have to become a cross-schema join, which hardcodes the admin database name into
|
||||||
|
calendar SQL and ties the two schemas together exactly as an FK would. Recommendation for
|
||||||
|
step 3: drop the join for the new path and resolve names in the service layer instead -
|
||||||
|
collect the distinct ids from the result set and do one lookup against the admin users
|
||||||
|
service. One extra query per listing, no coupling, and it keeps working if the admin
|
||||||
|
database ever moves.
|
||||||
|
- **`events.created_by_id` is `NOT NULL`.** Step 5 cannot simply stop writing it; that step
|
||||||
|
has to drop the column (and its FK to `users`) in the same migration that stops the writes,
|
||||||
|
or make it nullable first.
|
||||||
|
- **Every calendar read already hits the session table.** `/:calendar/json` calls
|
||||||
|
`UserService.checkSession` before falling back to `credentials.service.ts`, so the shared
|
||||||
|
credentials are the *fallback*, not the primary path. Step 4 replaces the first half of
|
||||||
|
that with `requireAppAccess('calendar')` and has to decide what happens to the second half
|
||||||
|
- which is the first open question below.
|
||||||
|
|
||||||
## Open questions to settle before starting
|
## Open questions to settle before starting
|
||||||
|
|
||||||
- **The shared calendar credentials.** Do `MEMBER_CREDENTIAL` and friends stay as a
|
**Settled 2026-09-06:**
|
||||||
separate mechanism (they serve people with no account at all, and iCal clients that
|
|
||||||
cannot send headers), or do read-only accounts replace them? This is a product decision,
|
- **The shared calendar credentials keep working, but only for iCal.** The web app goes
|
||||||
not a technical one, and it decides how much of `credentials.service.ts` survives.
|
cookie-only at step 4; `MEMBER_CREDENTIAL` and friends survive on
|
||||||
- **The iCal export.** `GET /calendar/events/{calendar}/ical` takes a password in the query
|
`GET /calendar/events/{calendar}/ical`, which is the one case where the client genuinely
|
||||||
string on purpose, because iCal clients cannot send headers. Cookie sessions do not help
|
cannot send a cookie. Everything else in `credentials.service.ts` goes with step 5.
|
||||||
here; this endpoint likely keeps its own scheme.
|
`public` stays anonymous everywhere - see the note under step 4.
|
||||||
- **Which legacy accounts to keep.** Step 2 is the moment to not re-invite people who no
|
- **The iCal export keeps its own scheme.** Same reasoning; it is the reason the shared
|
||||||
longer need access.
|
credentials survive at all rather than an exception to their removal.
|
||||||
- **`event_versions.version_created_by_id`.** The same INT reference again, joined in
|
- **No account backfill.** See step 2 above.
|
||||||
`events.service.ts` for the "last modified by" name. It has to move with `events`, and it
|
- **Pre-cutover authorship is archived, not discarded.** `events.created_by_name` and
|
||||||
is the reason step 1's bridging column needs a sibling on `event_versions`.
|
`event_versions.version_created_by_name`, backfilled once by migration 002 and never
|
||||||
|
written again. This was originally listed as a step 5 question; it was brought forward so
|
||||||
|
the data is safe well before the table that holds it is dropped.
|
||||||
|
|
||||||
|
**Nothing is open.** The last one - ~~`event_versions.version_created_by_id`~~, the same INT
|
||||||
|
reference on the version rows - was handled in passing: step 1 gave it a sibling bridging
|
||||||
|
column, step 2 a sibling snapshot, and step 3 reads it exactly like `events`.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Calendar iCal export and subscriptions
|
||||||
|
|
||||||
|
How `GET /calendar/events/{calendar}/ical` builds its file, what changed on 2026-09-28, and the
|
||||||
|
endpoint the calendar app uses to hand editors ready-made subscription URLs.
|
||||||
|
|
||||||
|
## The export
|
||||||
|
|
||||||
|
`icalgenerator.service.ts` turns a calendar's `PUBLIC` events into one `VCALENDAR`:
|
||||||
|
|
||||||
|
- Timed events: `DTSTART;TZID=Europe/Berlin:` / `DTEND;TZID=Europe/Berlin:` formatted with the
|
||||||
|
**API process's local** `getHours()` etc. The times are therefore only right if the process runs
|
||||||
|
in Berlin time (`TZ=Europe/Berlin`, or a server in that zone). Nothing enforces this. Inferred
|
||||||
|
from the code; not checked against the production server.
|
||||||
|
- Whole-day events: `VALUE=DATE`, and the stored end date is treated as the *inclusive* last day -
|
||||||
|
the generator adds one day for `DTEND`. The calendar app stores whole-day events as 00:00 to
|
||||||
|
23:59 Berlin time for this reason.
|
||||||
|
- `repeatFrequency` is written verbatim as `RRULE:FREQ=<value>` (no interval, count or end).
|
||||||
|
- `public` needs no credential; the other calendars take `?password=` because a calendar client
|
||||||
|
cannot send the session cookie (see `calendar-auth-migration.md`).
|
||||||
|
|
||||||
|
## RFC 5545 conformance (2026-09-28)
|
||||||
|
|
||||||
|
Before this date the generator wrote text values raw. A line break in a description ended the
|
||||||
|
`DESCRIPTION` property early and the rest was read as a garbage property; unescaped `,` and `;`
|
||||||
|
are invalid in text values. The new calendar frontend has a multi-line description field, so this
|
||||||
|
went from theoretical to certain. Now:
|
||||||
|
|
||||||
|
- `SUMMARY`, `DESCRIPTION` and `LOCATION` go through `escapeText` (`\` `;` `,` and line breaks,
|
||||||
|
backslash first).
|
||||||
|
- `URL` is a URI value and is not escaped; line breaks are stripped from it.
|
||||||
|
- Every content line is folded at 75 octets (UTF-8 aware - a multi-byte character is never split)
|
||||||
|
and the file uses CRLF line endings throughout (`toContentLines`).
|
||||||
|
- `formatDate` no longer shifts the caller's `Date` when it adds the whole-day end's extra day.
|
||||||
|
- The response is `Content-Type: text/calendar; charset=utf-8`. Before, Express inferred
|
||||||
|
`text/html` from the string body; calendar apps coped, but it was wrong.
|
||||||
|
|
||||||
|
Pinned by `test/calendar/icalgenerator.service.test.ts`.
|
||||||
|
|
||||||
|
Not changed, worth knowing: `ORGANIZER` is written as a bare display name (`ORGANIZER:Anna`),
|
||||||
|
while RFC 5545 expects a cal-address (`ORGANIZER;CN=Anna:mailto:…`). Calendar apps have tolerated
|
||||||
|
it so far.
|
||||||
|
|
||||||
|
## `GET /calendar/events/subscriptions`
|
||||||
|
|
||||||
|
For the calendar app's "Abonnieren" dialog. Behind `requireAppAccess('calendar')`; the shared
|
||||||
|
password is **not** accepted here (one calendar's password must not reveal the others).
|
||||||
|
|
||||||
|
Returns `[{calendar, icalUrl}]` in `calendarNames` order, built from `API_BASE_URL`:
|
||||||
|
|
||||||
|
- `public` without a password;
|
||||||
|
- every other calendar with `?password=<its shared password>`, URL-encoded;
|
||||||
|
- a calendar whose credential env var is unset is left out rather than listed with a URL that
|
||||||
|
cannot work.
|
||||||
|
|
||||||
|
`choir` and `birthdays` share `CHOIR_CREDENTIAL`, so rotating it changes both URLs - and breaks
|
||||||
|
every existing subscription to either. The response is sent with `Cache-Control: no-store`
|
||||||
|
because it carries the passwords.
|
||||||
|
|
||||||
|
Signed-in editors can read every event of every calendar anyway, so handing them the passwords
|
||||||
|
exposes nothing they could not already see.
|
||||||
|
|
||||||
|
## Found while doing this
|
||||||
|
|
||||||
|
- Only the admin pool reads `DB_PORT`; `Calendar.db.ts` (and the feedback/tickets pools) always
|
||||||
|
connect to 3306. A local test database for the calendar has to listen there.
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# Deployment
|
||||||
|
|
||||||
|
The API runs on the Plesk server as a Node.js app (Phusion Passenger) and is deployed by **Gitea
|
||||||
|
Actions** (`.gitea/workflows/deploy.yml`), which replaced the Jenkins job on 2026-11-08. Same
|
||||||
|
pattern as the calendar frontend; the reusable how-to (server facts, one-time setup, gotchas) is in
|
||||||
|
`Calendar_Frontend/docs/deployment.md` and in Patrick's PKM ("Jenkins to Gitea Actions for a Plesk
|
||||||
|
Node.js App").
|
||||||
|
|
||||||
|
```
|
||||||
|
push to master ──▶ Gitea ──▶ runner (container on the server)
|
||||||
|
└─ one job: npm ci, tsc --noEmit, npm test (unit tests)
|
||||||
|
└─ (master only) build, prune dev deps ─ rsync over SSH ─▶
|
||||||
|
plesk-nachklang@nachklang.art:<app root> + tmp/restart.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Pull requests run the same job up to the tests; the deploy steps only run for pushes to master. It
|
||||||
|
used to be two jobs, which ran `npm ci` twice (~2 min each); merged into one on 2026-11-08.
|
||||||
|
|
||||||
|
## Plesk (as configured, 2026-11-08)
|
||||||
|
|
||||||
|
*Websites & Domains → api.nachklang.art → Node.js*:
|
||||||
|
|
||||||
|
| Setting | Value |
|
||||||
|
|---|---|
|
||||||
|
| Node.js version | 26.13.0 |
|
||||||
|
| Application root | `/api.nachklang.art` (= `/var/www/vhosts/nachklang.art/api.nachklang.art`) |
|
||||||
|
| Document root | `/api.nachklang.art/public` |
|
||||||
|
| Application startup file | `dist/app.js` |
|
||||||
|
| Application mode | production |
|
||||||
|
| Environment variable | `PORT=443` (Passenger takes over the port; `app.ts` exits without `PORT`) |
|
||||||
|
|
||||||
|
## What the deploy touches - and what it must not
|
||||||
|
|
||||||
|
The app root holds more than the build, so the workflow syncs **only the app's own parts**:
|
||||||
|
|
||||||
|
| Path | How | Why it's needed at runtime |
|
||||||
|
|---|---|---|
|
||||||
|
| `dist/` | mirrored (`--delete` inside) | the compiled app |
|
||||||
|
| `src/` | mirrored | swagger-jsdoc reads the route docs from `src/models/**/*.router.ts` / `*.interface.ts` for `/docs` |
|
||||||
|
| `public/` | mirrored | Passenger's document root |
|
||||||
|
| `node_modules/` | mirrored, production dependencies only (`npm prune --omit=dev`) | runtime dependencies |
|
||||||
|
| `package.json`, `package-lock.json` | copied, no delete | `"type": "module"` makes Node load `dist/` as ES modules |
|
||||||
|
|
||||||
|
**Never touched** (nothing is deleted at the top level): `.env` (the secrets; `dotenv` reads it from
|
||||||
|
the app root), `logs/` (Winston writes there, relative to the app root), `tmp/` (Passenger's
|
||||||
|
`restart.txt`), and anything else in that folder.
|
||||||
|
|
||||||
|
The Jenkins job copied `dist/`, `src/` and `node_modules/` with `cp` (never deleting, so stale files
|
||||||
|
piled up) and never `package.json` or `public/`; the first rsync deploy cleans that up.
|
||||||
|
|
||||||
|
**SQL migrations are not part of the deploy.** Files under `sql/` are still applied by hand, before
|
||||||
|
the deploy that needs them.
|
||||||
|
|
||||||
|
## Gitea settings
|
||||||
|
|
||||||
|
Shared by all Nachklang repos, on the organisation (*Nachklang → Settings → Actions*): secrets
|
||||||
|
`DEPLOY_SSH_KEY`, `DEPLOY_KNOWN_HOSTS`; variables `DEPLOY_HOST=nachklang.art`, `DEPLOY_PORT=42069`,
|
||||||
|
`DEPLOY_USER=plesk-nachklang`.
|
||||||
|
|
||||||
|
On this repository (*API → Settings → Actions → Variables*):
|
||||||
|
|
||||||
|
| Variable | Value |
|
||||||
|
|---|---|
|
||||||
|
| `DEPLOY_PATH` | `/var/www/vhosts/nachklang.art/api.nachklang.art` |
|
||||||
|
| `DEPLOY_SMOKE_URL` | `https://api.nachklang.art/calendar/events/public/json` |
|
||||||
|
|
||||||
|
The smoke test only needs an endpoint that answers 200 without a session; the public calendar feed
|
||||||
|
is the one nachklang.art itself depends on.
|
||||||
|
|
||||||
|
## Switchover (done once)
|
||||||
|
|
||||||
|
1. Pause the Jenkins API job (done 2026-11-08).
|
||||||
|
1a. **Fix file ownership** (as root): Jenkins deployed as **root**, so `dist/`, `src/` and
|
||||||
|
`node_modules/` were `root:root`, and the first Gitea deploy failed with rsync "Operation not
|
||||||
|
permitted" / "Permission denied" - the subscription user can't change root's files. Fixed with
|
||||||
|
`chown -R plesk-nachklang:psacln dist src node_modules` in the app root (the group of the files
|
||||||
|
the app creates itself, e.g. `.env`, `logs/`); then re-run the failed job.
|
||||||
|
Check: `find . ! -user plesk-nachklang` prints nothing.
|
||||||
|
2. Set `DEPLOY_PATH` and `DEPLOY_SMOKE_URL`.
|
||||||
|
3. Open a PR → green run → merge → watch the deploy steps. Unlike the calendar there is no gap:
|
||||||
|
the folder keeps working while files are replaced, and Passenger restarts on the next request.
|
||||||
|
4. Check `https://api.nachklang.art/docs` and the calendar/feedback/tickets apps.
|
||||||
|
|
||||||
|
Rollback: revert the commit on master; the workflow deploys the previous state.
|
||||||
|
|
||||||
|
## Checked locally (2026-11-08)
|
||||||
|
|
||||||
|
- `actionlint`: no findings.
|
||||||
|
- In a clean `node:26` container (26.13.0, no `.env`): `npm ci`, `tsc --noEmit`, all 233 unit tests,
|
||||||
|
build, `npm prune --omit=dev`.
|
||||||
|
- The pruned bundle, laid out like the server folder with a test `.env`, started with
|
||||||
|
`node dist/app.js` against a throwaway MariaDB: public JSON 200, iCal `text/calendar`, `/docs` 200
|
||||||
|
including the subscriptions route (so `src/` is read), `/admin/me` 401, `logs/` created in the app
|
||||||
|
root.
|
||||||
|
- The workflow's upload step against a throwaway SSH server with a folder like the real one: `.env`,
|
||||||
|
`logs/`, `tmp/` and an unrelated top-level file kept; a stale package in `node_modules/` and a stale
|
||||||
|
file in `dist/` removed; `package.json` updated.
|
||||||
|
|
||||||
|
Not checked: the workflow on the real runner.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- There was **no `package.json` on the server** before the first rsync deploy (Jenkins never copied
|
||||||
|
it); `dist/app.js` still ran as ES modules, probably because Node ≥ 22 detects ES module syntax on
|
||||||
|
its own [inference, not checked]. The deploy now ships `package.json`, so it doesn't depend on that.
|
||||||
|
- A failed upload leaves new and old files mixed in `dist/`, but the running app is unaffected:
|
||||||
|
the restart step is skipped, so Passenger keeps the old code in memory until the next deploy (or an
|
||||||
|
unplanned restart - fix and re-run soon).
|
||||||
|
|
||||||
|
- `bcrypt` was removed on 2026-11-08: nothing imported it any more (passwords moved to better-auth,
|
||||||
|
which hashes with its own scrypt). It was the only production dependency with a native build step.
|
||||||
|
- `FEEDBACK_IP_SALT`, which the Jenkins test step exported, isn't needed in CI: `vitest.config.ts`
|
||||||
|
sets one for the test run.
|
||||||
|
- SonarQube isn't used any more; `sonar-project.properties`, the `vitest-sonar-reporter` and its
|
||||||
|
`testResults/sonar-report.xml` were removed on 2026-11-08 (the Jenkins job ran the tests only to
|
||||||
|
feed Sonar's coverage).
|
||||||
Generated
+6
-757
File diff suppressed because it is too large.
Load diff
+1
-4
@@ -23,7 +23,6 @@
|
|||||||
"@better-auth/passkey": "^1.7.2",
|
"@better-auth/passkey": "^1.7.2",
|
||||||
"app-root-path": "^3.0.0",
|
"app-root-path": "^3.0.0",
|
||||||
"axios": "^1.20.0",
|
"axios": "^1.20.0",
|
||||||
"bcrypt": "^5.0.1",
|
|
||||||
"better-auth": "^1.7.2",
|
"better-auth": "^1.7.2",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"debug": "^4.3.1",
|
"debug": "^4.3.1",
|
||||||
@@ -41,7 +40,6 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/app-root-path": "^1.2.4",
|
"@types/app-root-path": "^1.2.4",
|
||||||
"@types/bcrypt": "^3.0.1",
|
|
||||||
"@types/cors": "^2.8.19",
|
"@types/cors": "^2.8.19",
|
||||||
"@types/debug": "^4.1.5",
|
"@types/debug": "^4.1.5",
|
||||||
"@types/express": "^4.17.15",
|
"@types/express": "^4.17.15",
|
||||||
@@ -56,8 +54,7 @@
|
|||||||
"source-map-support": "^0.5.19",
|
"source-map-support": "^0.5.19",
|
||||||
"supertest": "^7.2.2",
|
"supertest": "^7.2.2",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vitest": "^5.0.0",
|
"vitest": "^5.0.0"
|
||||||
"vitest-sonar-reporter": "^3.0.0"
|
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"better-auth": {
|
"better-auth": {
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
sonar.projectKey=nk-api
|
|
||||||
sonar.sources=src
|
|
||||||
sonar.tests=test
|
|
||||||
sonar.language=ts
|
|
||||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
|
||||||
sonar.testExecutionReportPaths=testResults/sonar-report.xml
|
|
||||||
+11
-5
@@ -114,15 +114,21 @@ CREATE TABLE IF NOT EXISTS `rateLimit` (
|
|||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Which apps a user may administer. `admin` is just another app: holding it is
|
-- Which apps a user may administer. `admin` is just another app: holding it is
|
||||||
-- what lets someone manage users and invitations. `role` is reserved for
|
-- what lets someone manage users and invitations. A permission is (app, role);
|
||||||
-- per-app roles later and is 'admin' for every row today.
|
-- `access` is the only role today, and the key admits several per app so finer
|
||||||
|
-- ones can be added by inserting rows rather than by migrating this table.
|
||||||
CREATE TABLE IF NOT EXISTS `user_app_permissions` (
|
CREATE TABLE IF NOT EXISTS `user_app_permissions` (
|
||||||
`user_id` VARCHAR(36) NOT NULL,
|
`user_id` VARCHAR(36) NOT NULL,
|
||||||
`app` ENUM('calendar','feedback','tickets','admin') NOT NULL,
|
`app` ENUM('calendar','feedback','tickets','admin') NOT NULL,
|
||||||
`role` VARCHAR(32) NOT NULL DEFAULT 'admin',
|
-- One row per (user, app, role). `access` means "may use this app at all"
|
||||||
|
-- and is the only role today; the key allows several per app so a finer
|
||||||
|
-- permission can be added later by inserting rows, not by migrating.
|
||||||
|
`role` VARCHAR(32) NOT NULL DEFAULT 'access',
|
||||||
`granted_by` VARCHAR(36) DEFAULT NULL,
|
`granted_by` VARCHAR(36) DEFAULT NULL,
|
||||||
`granted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`granted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`user_id`, `app`),
|
-- (user_id, app) is the leftmost prefix of this key, so the per-request
|
||||||
|
-- permission lookup needs no separate index.
|
||||||
|
PRIMARY KEY (`user_id`, `app`, `role`),
|
||||||
CONSTRAINT `uap_user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
CONSTRAINT `uap_user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
@@ -133,7 +139,7 @@ CREATE TABLE IF NOT EXISTS `invitations` (
|
|||||||
`email` VARCHAR(255) NOT NULL,
|
`email` VARCHAR(255) NOT NULL,
|
||||||
`name` VARCHAR(255) NOT NULL,
|
`name` VARCHAR(255) NOT NULL,
|
||||||
`token_hash` CHAR(64) NOT NULL,
|
`token_hash` CHAR(64) NOT NULL,
|
||||||
`apps` JSON NOT NULL,
|
`permissions` JSON NOT NULL,
|
||||||
`invited_by` VARCHAR(36) DEFAULT NULL,
|
`invited_by` VARCHAR(36) DEFAULT NULL,
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`expires_at` DATETIME NOT NULL,
|
`expires_at` DATETIME NOT NULL,
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
-- Nachklang e.V. Calendar module — step 1 of docs/calendar-auth-migration.md.
|
||||||
|
-- Adds the bridging columns that let an event record who created it as an
|
||||||
|
-- *admin* user id (VARCHAR(36)) alongside the legacy calendar users.user_id
|
||||||
|
-- (INT). Apply manually against the CALENDAR_DB database:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <CALENDAR_DB> < 001_add_admin_user_bridge.sql
|
||||||
|
--
|
||||||
|
-- Numbered 001 because this is the first migration this repo owns for the
|
||||||
|
-- calendar schema: the tables themselves predate it and were provided by the
|
||||||
|
-- repo owner (mirrored for dev in docker/init/01-calendar-schema-dev.sql).
|
||||||
|
--
|
||||||
|
-- Nothing reads these columns yet — step 3 introduces the dual-read. Adding
|
||||||
|
-- them first means the backfill in step 2 has somewhere to write, and this
|
||||||
|
-- migration can be applied to production on its own without any code change.
|
||||||
|
--
|
||||||
|
-- No foreign key, on purpose. The admin `user` table lives in a *different*
|
||||||
|
-- database (nachklang_admin) behind a different connection pool, and a
|
||||||
|
-- cross-schema FK would tie the two schemas' lifecycles together: you could no
|
||||||
|
-- longer dump, restore or move one without the other. The reference is
|
||||||
|
-- enforced in application code, which is also where the legacy/new fallback
|
||||||
|
-- lives.
|
||||||
|
--
|
||||||
|
-- The collation is pinned to the admin database's (utf8mb4_unicode_ci) rather
|
||||||
|
-- than inherited from the calendar tables' utf8mb4_general_ci. These columns
|
||||||
|
-- hold ids that only ever compare against nachklang_admin.user.id, and a
|
||||||
|
-- mismatched collation makes any such comparison fail at runtime with
|
||||||
|
-- "Illegal mix of collations" instead of at review time.
|
||||||
|
|
||||||
|
ALTER TABLE `events`
|
||||||
|
ADD COLUMN IF NOT EXISTS `created_by_user_id` VARCHAR(36)
|
||||||
|
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
|
||||||
|
NULL DEFAULT NULL AFTER `created_by_id`,
|
||||||
|
ADD KEY IF NOT EXISTS `events_created_by_user_idx` (`created_by_user_id`);
|
||||||
|
|
||||||
|
ALTER TABLE `event_versions`
|
||||||
|
ADD COLUMN IF NOT EXISTS `version_created_by_user_id` VARCHAR(36)
|
||||||
|
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
|
||||||
|
NULL DEFAULT NULL AFTER `version_created_by_id`,
|
||||||
|
ADD KEY IF NOT EXISTS `event_versions_created_by_user_idx` (`version_created_by_user_id`);
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
-- Nachklang e.V. Calendar module — step 5 preparation, brought forward.
|
||||||
|
-- Apply manually against the CALENDAR_DB database, after 001:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <CALENDAR_DB> < 002_snapshot_legacy_creator_names.sql
|
||||||
|
--
|
||||||
|
-- Snapshots the creator's and last editor's *name* onto the event itself.
|
||||||
|
--
|
||||||
|
-- Why: the creator is only ever rendered as a name (nothing authorises on it),
|
||||||
|
-- and today that name comes from joining the calendar's own `users` table.
|
||||||
|
-- Step 5 drops that table, which would silently erase the authorship of every
|
||||||
|
-- event created before the cutover. There is no account backfill to save them
|
||||||
|
-- either - that was dropped deliberately, see docs/calendar-auth-migration.md.
|
||||||
|
-- One text column per reference keeps the history at no ongoing cost.
|
||||||
|
--
|
||||||
|
-- These columns are an archive, not a source of truth. Nothing writes them
|
||||||
|
-- after this backfill: events created from the cutover onwards carry an admin
|
||||||
|
-- user id, whose name is resolved live so that renaming an account updates
|
||||||
|
-- everywhere. The read path prefers the live admin name, falls back to this
|
||||||
|
-- snapshot, and falls back again to the join until step 5 removes it.
|
||||||
|
--
|
||||||
|
-- The whole file is re-runnable: IF NOT EXISTS on the columns, and the backfill
|
||||||
|
-- only touches rows with no snapshot yet. Step 4's migration re-runs the
|
||||||
|
-- backfill, to catch anything created between this migration and the cutover.
|
||||||
|
--
|
||||||
|
-- No charset clause: unlike 001's id columns these hold display text that is
|
||||||
|
-- only ever compared against other calendar data, so they inherit the tables'
|
||||||
|
-- utf8mb4_general_ci like the columns they are copied from.
|
||||||
|
|
||||||
|
ALTER TABLE `events`
|
||||||
|
ADD COLUMN IF NOT EXISTS `created_by_name` VARCHAR(255) NULL DEFAULT NULL AFTER `created_by_user_id`;
|
||||||
|
|
||||||
|
ALTER TABLE `event_versions`
|
||||||
|
ADD COLUMN IF NOT EXISTS `version_created_by_name` VARCHAR(255) NULL DEFAULT NULL AFTER `version_created_by_user_id`;
|
||||||
|
|
||||||
|
UPDATE `events` e
|
||||||
|
JOIN `users` u ON u.user_id = e.created_by_id
|
||||||
|
SET e.created_by_name = u.full_name
|
||||||
|
WHERE e.created_by_name IS NULL;
|
||||||
|
|
||||||
|
UPDATE `event_versions` v
|
||||||
|
JOIN `users` u ON u.user_id = v.version_created_by_id
|
||||||
|
SET v.version_created_by_name = u.full_name
|
||||||
|
WHERE v.version_created_by_name IS NULL;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- Nachklang e.V. Calendar module — step 4 of docs/calendar-auth-migration.md,
|
||||||
|
-- the cutover. Apply manually against the CALENDAR_DB database, after 002,
|
||||||
|
-- and BEFORE deploying the API build that goes with it:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <CALENDAR_DB> < 003_allow_null_legacy_creator.sql
|
||||||
|
--
|
||||||
|
-- From the cutover on, an event's creator is an admin-module user id. There is
|
||||||
|
-- no legacy calendar user id to write any more, and `events.created_by_id` is
|
||||||
|
-- NOT NULL - so without this the very first event created after the deploy
|
||||||
|
-- fails to insert. `event_versions.version_created_by_id` is already nullable.
|
||||||
|
--
|
||||||
|
-- The foreign key to `users` is kept: it permits NULL, so it costs nothing
|
||||||
|
-- until step 5 drops the column and the table together.
|
||||||
|
--
|
||||||
|
-- Applying this early is harmless. Widening a column to accept NULL cannot
|
||||||
|
-- break the running pre-cutover build, which always supplies a value, so this
|
||||||
|
-- can go out ahead of the deploy rather than during it.
|
||||||
|
|
||||||
|
ALTER TABLE `events`
|
||||||
|
MODIFY COLUMN `created_by_id` INT(11) NULL DEFAULT NULL;
|
||||||
|
|
||||||
|
-- Re-run of 002's backfill, to catch anything created between the two
|
||||||
|
-- migrations while the legacy path was still writing events. Idempotent by
|
||||||
|
-- construction: it only touches rows that have no snapshot yet.
|
||||||
|
UPDATE `events` e
|
||||||
|
JOIN `users` u ON u.user_id = e.created_by_id
|
||||||
|
SET e.created_by_name = u.full_name
|
||||||
|
WHERE e.created_by_name IS NULL;
|
||||||
|
|
||||||
|
UPDATE `event_versions` v
|
||||||
|
JOIN `users` u ON u.user_id = v.version_created_by_id
|
||||||
|
SET v.version_created_by_name = u.full_name
|
||||||
|
WHERE v.version_created_by_name IS NULL;
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
-- Nachklang e.V. Calendar module — step 5 of docs/calendar-auth-migration.md.
|
||||||
|
-- Apply manually against the CALENDAR_DB database, after 003:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <CALENDAR_DB> < 004_drop_legacy_auth.sql
|
||||||
|
--
|
||||||
|
-- *** APPLY THIS AFTER DEPLOYING THE API, NOT BEFORE. ***
|
||||||
|
--
|
||||||
|
-- This is the opposite order from the step 4 cutover, and getting it wrong by
|
||||||
|
-- analogy is the obvious mistake. Step 4's migration only *added* things, so it
|
||||||
|
-- was safe ahead of the deploy. This one removes columns and a table that the
|
||||||
|
-- currently running build still selects and joins - applying it first fails
|
||||||
|
-- every calendar read, including the anonymous public feed the website uses.
|
||||||
|
-- The step 5 build touches none of them, so it runs happily against the old
|
||||||
|
-- schema; deploy it, confirm the calendar works, then run this.
|
||||||
|
--
|
||||||
|
-- Nothing here loses information that is still reachable: the creators' display
|
||||||
|
-- names were snapshotted into events.created_by_name and
|
||||||
|
-- event_versions.version_created_by_name by migration 002, and the step 4
|
||||||
|
-- runbook re-ran that backfill after the deploy. Verify before running:
|
||||||
|
--
|
||||||
|
-- SELECT SUM(created_by_id IS NOT NULL AND created_by_name IS NULL) FROM events;
|
||||||
|
-- SELECT SUM(version_created_by_id IS NOT NULL AND version_created_by_name IS NULL) FROM event_versions;
|
||||||
|
--
|
||||||
|
-- Both must be 0. A non-zero count is an event whose author this migration
|
||||||
|
-- would erase; re-run 002's backfill first.
|
||||||
|
|
||||||
|
-- The foreign keys have to go before the columns they are declared on.
|
||||||
|
-- IF EXISTS so that a re-run after a partial failure gets past them.
|
||||||
|
ALTER TABLE `events`
|
||||||
|
DROP FOREIGN KEY IF EXISTS `events_users_user_id_fk`;
|
||||||
|
|
||||||
|
ALTER TABLE `event_versions`
|
||||||
|
DROP FOREIGN KEY IF EXISTS `event_versions_users_user_id_fk`;
|
||||||
|
|
||||||
|
ALTER TABLE `events`
|
||||||
|
DROP INDEX IF EXISTS `events_users_user_id_fk`,
|
||||||
|
DROP COLUMN IF EXISTS `created_by_id`;
|
||||||
|
|
||||||
|
ALTER TABLE `event_versions`
|
||||||
|
DROP INDEX IF EXISTS `event_versions_users_user_id_fk`,
|
||||||
|
DROP COLUMN IF EXISTS `version_created_by_id`;
|
||||||
|
|
||||||
|
-- The accounts themselves are renamed aside rather than dropped.
|
||||||
|
--
|
||||||
|
-- Nothing visible depends on them any more - the names are snapshotted, and no
|
||||||
|
-- code has referenced these tables since the step 4 cutover. But they still
|
||||||
|
-- hold e-mail addresses and password hashes, and a rename makes them
|
||||||
|
-- unreachable without destroying anything.
|
||||||
|
--
|
||||||
|
-- `sessions` has a foreign key into `users`; InnoDB rewires it to the new name
|
||||||
|
-- on rename, so after this it reads REFERENCES `users_legacy_archive` and the
|
||||||
|
-- pair stays internally consistent whichever order they are renamed in.
|
||||||
|
-- Verified on MariaDB 11.
|
||||||
|
--
|
||||||
|
-- Unlike the statements above this is not re-runnable, and that is the safe
|
||||||
|
-- behaviour: a second run fails on a missing `sessions` rather than doing
|
||||||
|
-- anything. Drop them for real whenever you like, at a moment when nobody is
|
||||||
|
-- mid-deploy:
|
||||||
|
-- DROP TABLE `sessions_legacy_archive`, `users_legacy_archive`;
|
||||||
|
RENAME TABLE `sessions` TO `sessions_legacy_archive`;
|
||||||
|
RENAME TABLE `users` TO `users_legacy_archive`;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- Nachklang e.V. Feedback module — makes submitting idempotent per form visit.
|
||||||
|
-- Apply manually against the FEEDBACK_DB database, after 002_add_poster_image_url.sql:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <FEEDBACK_DB> < 003_add_submission_client_token.sql
|
||||||
|
--
|
||||||
|
-- The form generates one UUID per visit and resends it on every retry. When
|
||||||
|
-- a submission saved but its response never reached the phone, the visitor
|
||||||
|
-- sees an error and taps "absenden" again; the API now finds the stored token
|
||||||
|
-- and answers with the original submission instead of saving a copy.
|
||||||
|
--
|
||||||
|
-- Unique per event, not globally: one visit can switch to another concert's
|
||||||
|
-- form in the same tab, and that event's submission must still save.
|
||||||
|
--
|
||||||
|
-- NULL for every row written before this migration and for any client that
|
||||||
|
-- sends no token; a UNIQUE index allows any number of NULLs.
|
||||||
|
ALTER TABLE submissions
|
||||||
|
ADD COLUMN client_token CHAR(36) NULL AFTER ip_hash,
|
||||||
|
ADD UNIQUE KEY uq_sub_event_client_token (event_id, client_token);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Nachklang e.V. Tickets module — adds a per-event "tickets are mailed" flag.
|
||||||
|
-- Defaults to 0 (not mailed) because no event mails physical tickets today -
|
||||||
|
-- the redemption confirmation email uses this to decide whether to tell the
|
||||||
|
-- guest their tickets await pickup at the Abendkasse instead. Apply manually
|
||||||
|
-- against TICKETS_DB, after 003_add_confirmation_email_status.sql:
|
||||||
|
-- mysql -h <DB_HOST> -u <DB_USER> -p <TICKETS_DB> < 004_add_tickets_mailed.sql
|
||||||
|
ALTER TABLE event_ticket_settings
|
||||||
|
ADD COLUMN tickets_mailed TINYINT(1) NOT NULL DEFAULT 0 AFTER require_address;
|
||||||
+37
-6
@@ -4,6 +4,7 @@ import swaggerUi from 'swagger-ui-express';
|
|||||||
import swaggerJSDoc from 'swagger-jsdoc';
|
import swaggerJSDoc from 'swagger-jsdoc';
|
||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import {toNodeHandler} from 'better-auth/node';
|
import {toNodeHandler} from 'better-auth/node';
|
||||||
|
import logger from './middleware/logger.js';
|
||||||
|
|
||||||
// Router imports
|
// Router imports
|
||||||
import {calendarRouter} from './models/calendar/Calendar.router.js';
|
import {calendarRouter} from './models/calendar/Calendar.router.js';
|
||||||
@@ -11,7 +12,7 @@ import {feedbackRouter} from './models/feedback/Feedback.router.js';
|
|||||||
import {ticketsRouter} from './models/tickets/Tickets.router.js';
|
import {ticketsRouter} from './models/tickets/Tickets.router.js';
|
||||||
import {adminRouter} from './models/admin/Admin.router.js';
|
import {adminRouter} from './models/admin/Admin.router.js';
|
||||||
import {auth} from './models/admin/admin.auth.js';
|
import {auth} from './models/admin/admin.auth.js';
|
||||||
import {ADMIN_ALLOWED_ORIGINS} from './models/admin/admin.config.js';
|
import {ADMIN_ALLOWED_ORIGINS, isProd} from './models/admin/admin.config.js';
|
||||||
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
@@ -47,16 +48,27 @@ export const createApp = (): express.Application => {
|
|||||||
// staging host does not need a code change here.
|
// staging host does not need a code change here.
|
||||||
...ADMIN_ALLOWED_ORIGINS
|
...ADMIN_ALLOWED_ORIGINS
|
||||||
];
|
];
|
||||||
const isDev = process.env.NODE_ENV !== 'production';
|
// `isProd` from admin.config, NOT `NODE_ENV !== 'production'`. The two are not
|
||||||
|
// the same when NODE_ENV is unset, which is exactly what a fresh Plesk vhost
|
||||||
|
// gives you: the old test called that "dev" and opened the loopback and
|
||||||
|
// private-LAN exceptions below. With `credentials: true` on this CORS config
|
||||||
|
// and a session cookie scoped to .nachklang.art, that let any page served
|
||||||
|
// from localhost read a signed-in admin's data cross-origin. admin.config
|
||||||
|
// treats anything but an explicit 'development'/'test' as production, so an
|
||||||
|
// unset value now fails closed.
|
||||||
|
const isDev = !isProd;
|
||||||
const localhostRegex = /^http:\/\/localhost:\d+$/;
|
const localhostRegex = /^http:\/\/localhost:\d+$/;
|
||||||
// Matches http://<private-LAN-IPv4>:<port> - needed so the feedback form can
|
// Matches http://<private-LAN-IPv4>:<port> - needed so the feedback form can
|
||||||
// be reached from a real phone over WiFi during dev (the phone's Origin is
|
// be reached from a real phone over WiFi during dev (the phone's Origin is
|
||||||
// the dev machine's LAN IP, never "localhost"). Dev-only, same as above.
|
// the dev machine's LAN IP, never "localhost"). Dev-only, same as above.
|
||||||
const lanIpRegex = /^http:\/\/(192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}):\d+$/;
|
const lanIpRegex = /^http:\/\/(192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}):\d+$/;
|
||||||
app.use(cors({
|
app.use(cors({
|
||||||
// X-Session-* stay allowed until the calendar module is migrated off the
|
// Content-Type alone. X-Session-Id / X-Session-Key were allowed here
|
||||||
// legacy header sessions (see docs/calendar-auth-migration.md).
|
// through the two cutovers so that a browser still holding a pre-cutover
|
||||||
allowedHeaders: ['Content-Type', 'X-Session-Id', 'X-Session-Key'],
|
// bundle got a clean 401 rather than a confusing CORS preflight failure.
|
||||||
|
// Nothing has read them since the first cutover and nothing has sent them
|
||||||
|
// since the second, so they came out with the rest of the legacy path.
|
||||||
|
allowedHeaders: ['Content-Type'],
|
||||||
// The admin session lives in a cookie, so browsers must be allowed to send
|
// The admin session lives in a cookie, so browsers must be allowed to send
|
||||||
// it cross-origin - this is what makes credentials: 'include' work.
|
// it cross-origin - this is what makes credentials: 'include' work.
|
||||||
credentials: true,
|
credentials: true,
|
||||||
@@ -83,7 +95,26 @@ export const createApp = (): express.Application => {
|
|||||||
|
|
||||||
// better-auth's own handler, mounted before express.json(): it reads the raw
|
// better-auth's own handler, mounted before express.json(): it reads the raw
|
||||||
// request body stream itself and a parsed body would leave it hanging.
|
// request body stream itself and a parsed body would leave it hanging.
|
||||||
app.all('/admin/auth/*', toNodeHandler(auth));
|
//
|
||||||
|
// Wrapped, because Express 4 does not await an async handler: a rejected
|
||||||
|
// promise escapes as an unhandled rejection instead of becoming a response.
|
||||||
|
// Nearly every better-auth route touches the admin database, so a database
|
||||||
|
// blip would leave the request hanging with no answer at all while the
|
||||||
|
// process logged an uncaughtException - observed by pointing ADMIN_DB at a
|
||||||
|
// database the user cannot open. Answer 503 instead: the caller learns, and
|
||||||
|
// the other domains keep serving.
|
||||||
|
const authHandler = toNodeHandler(auth);
|
||||||
|
app.all('/admin/auth/*', (req, res) => {
|
||||||
|
Promise.resolve(authHandler(req, res)).catch((e: any) => {
|
||||||
|
logger.error('Admin auth handler failed', {path: req.path, detail: e?.message});
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.status(503).send({
|
||||||
|
status: 'SERVICE_UNAVAILABLE',
|
||||||
|
message: 'Die Anmeldung ist derzeit nicht verfügbar. Bitte versuche es später erneut.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// here we are adding middleware to parse all incoming requests as JSON
|
// here we are adding middleware to parse all incoming requests as JSON
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|||||||
@@ -35,6 +35,11 @@ adminRouter.get('/me', requireSignedIn, (req: Request, res: Response) => {
|
|||||||
id: res.locals.admin.id,
|
id: res.locals.admin.id,
|
||||||
email: res.locals.admin.email,
|
email: res.locals.admin.email,
|
||||||
fullName: res.locals.admin.displayName,
|
fullName: res.locals.admin.displayName,
|
||||||
|
// `permissions` is the full (app, role) truth; `apps` is the distinct
|
||||||
|
// apps within it. Both are sent because the three frontends only ever ask
|
||||||
|
// "may I show this app?", and keeping `apps` means a finer permission can
|
||||||
|
// land here without a coordinated deploy of all of them.
|
||||||
|
permissions: res.locals.admin.permissions,
|
||||||
apps: res.locals.admin.apps
|
apps: res.locals.admin.apps
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {betterAuth} from 'better-auth';
|
import {betterAuth} from 'better-auth';
|
||||||
import {APIError} from 'better-auth/api';
|
import {APIError} from 'better-auth/api';
|
||||||
import {passkey} from '@better-auth/passkey';
|
import {passkey, getAuthenticatorName} from '@better-auth/passkey';
|
||||||
import {NachklangAdminDB} from './Admin.db.js';
|
import {NachklangAdminDB} from './Admin.db.js';
|
||||||
import {invitationsPlugin} from './invitations/invitations.plugin.js';
|
import {invitationsPlugin} from './invitations/invitations.plugin.js';
|
||||||
import {sendPasswordResetMail} from './admin.mail.js';
|
import {sendPasswordResetMail} from './admin.mail.js';
|
||||||
@@ -33,7 +33,11 @@ const localhostOrigins = [
|
|||||||
'http://localhost:3000',
|
'http://localhost:3000',
|
||||||
'http://localhost:3001',
|
'http://localhost:3001',
|
||||||
'http://localhost:3002',
|
'http://localhost:3002',
|
||||||
'http://localhost:3003'
|
'http://localhost:3003',
|
||||||
|
// The Angular calendar frontend; `ng serve` defaults to 4200. Missing from
|
||||||
|
// this list, sign-out from the calendar answers 403 in dev only, which is a
|
||||||
|
// confusing thing to debug against a production config that is fine.
|
||||||
|
'http://localhost:4200'
|
||||||
];
|
];
|
||||||
|
|
||||||
const trustedOrigins = isProd
|
const trustedOrigins = isProd
|
||||||
@@ -116,7 +120,24 @@ export const auth = betterAuth({
|
|||||||
passkey({
|
passkey({
|
||||||
rpID: PASSKEY_RP_ID,
|
rpID: PASSKEY_RP_ID,
|
||||||
rpName: 'Nachklang',
|
rpName: 'Nachklang',
|
||||||
origin: ADMIN_ALLOWED_ORIGINS
|
origin: ADMIN_ALLOWED_ORIGINS,
|
||||||
|
|
||||||
|
registration: {
|
||||||
|
// Without this, every passkey is stored with name = NULL and the
|
||||||
|
// account page can only label them all "Passkey" - useless at the
|
||||||
|
// one moment that list matters, when someone has to remove the
|
||||||
|
// passkey on the device they just lost.
|
||||||
|
//
|
||||||
|
// The AAGUID identifies the authenticator *model* (not a device
|
||||||
|
// and not a person), and better-auth ships the lookup table, so
|
||||||
|
// this yields "1Password", "iCloud Keychain", "Windows Hello".
|
||||||
|
// It only fills a blank: a name the client sent always wins, and
|
||||||
|
// an unknown AAGUID leaves the column NULL as before.
|
||||||
|
afterVerification: async ({verification}) => {
|
||||||
|
const name = getAuthenticatorName(verification.registrationInfo?.aaguid);
|
||||||
|
return name ? {name} : undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
invitationsPlugin()
|
invitationsPlugin()
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as UsersService from './users/users.admin.service.js';
|
import * as UsersService from './users/users.admin.service.js';
|
||||||
import * as InvitationsService from './invitations/invitations.service.js';
|
import * as InvitationsService from './invitations/invitations.service.js';
|
||||||
import {sendInvitationMail} from './admin.mail.js';
|
import {sendInvitationMail} from './admin.mail.js';
|
||||||
|
import {ACCESS_ROLE} from './admin.schema.js';
|
||||||
import {ADMIN_APP_URL, ADMIN_BOOTSTRAP_EMAIL, LOG_INVITE_LINKS} from './admin.config.js';
|
import {ADMIN_APP_URL, ADMIN_BOOTSTRAP_EMAIL, LOG_INVITE_LINKS} from './admin.config.js';
|
||||||
import logger from '../../middleware/logger.js';
|
import logger from '../../middleware/logger.js';
|
||||||
|
|
||||||
@@ -48,7 +49,7 @@ export const bootstrapAdmin = async (): Promise<void> => {
|
|||||||
const invitation = await InvitationsService.createInvitation(
|
const invitation = await InvitationsService.createInvitation(
|
||||||
email,
|
email,
|
||||||
'Nachklang Admin',
|
'Nachklang Admin',
|
||||||
['admin'],
|
[{app: 'admin', role: ACCESS_ROLE}],
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -73,8 +73,29 @@ const parseList = (value: string | undefined, fallback: string[]): string[] => {
|
|||||||
return parsed.length > 0 ? parsed : fallback;
|
return parsed.length > 0 ? parsed : fallback;
|
||||||
};
|
};
|
||||||
|
|
||||||
// The apps whose frontends may talk to /admin/* with credentials.
|
/**
|
||||||
export const APP_ORIGINS = parseList(process.env.APP_ORIGINS, []).map(origin => origin.replace(/\/$/, ''));
|
* The apps whose frontends may talk to /admin/* with credentials.
|
||||||
|
*
|
||||||
|
* They feed better-auth's `trustedOrigins`, which is what lets the tickets and
|
||||||
|
* feedback admin areas call /admin/auth/sign-out from their own origin. That
|
||||||
|
* became load-bearing with the step 4 cutover: before it, the only browser
|
||||||
|
* origin that ever reached /admin/auth was the admin app itself. The calendar
|
||||||
|
* joined them with its own cutover (docs/calendar-auth-migration.md step 4).
|
||||||
|
*
|
||||||
|
* Hence the production default rather than an empty list. An origin missing
|
||||||
|
* here fails in a way that is easy to misread - sign-in works, the app works,
|
||||||
|
* and only sign-out returns an origin error - so the two frontends we know
|
||||||
|
* about are named here and APP_ORIGINS overrides them for a staging host.
|
||||||
|
* Dev adds the localhost ports separately (see admin.auth.ts).
|
||||||
|
*/
|
||||||
|
const DEFAULT_APP_ORIGINS = [
|
||||||
|
'https://tickets.nachklang.art',
|
||||||
|
'https://feedback.nachklang.art',
|
||||||
|
'https://calendar.nachklang.art'
|
||||||
|
];
|
||||||
|
|
||||||
|
export const APP_ORIGINS = parseList(process.env.APP_ORIGINS, DEFAULT_APP_ORIGINS)
|
||||||
|
.map(origin => origin.replace(/\/$/, ''));
|
||||||
|
|
||||||
// Kept in sync by construction rather than by three separate lists: the admin
|
// Kept in sync by construction rather than by three separate lists: the admin
|
||||||
// app itself always counts, and dev adds the local ports.
|
// app itself always counts, and dev adds the local ports.
|
||||||
@@ -101,16 +122,53 @@ export const ADMIN_ALLOWED_ORIGINS = Array.from(new Set([
|
|||||||
* brute-force budget - so the default is the single header nginx sets, not a
|
* brute-force budget - so the default is the single header nginx sets, not a
|
||||||
* permissive list.
|
* permissive list.
|
||||||
*/
|
*/
|
||||||
export const CLIENT_IP_HEADERS = parseList(process.env.CLIENT_IP_HEADERS, ['x-real-ip']);
|
|
||||||
|
/**
|
||||||
|
* `CLIENT_IP_HEADERS=none` trusts no header at all.
|
||||||
|
*
|
||||||
|
* This is the escape hatch for the one case where the wrong setting is worse
|
||||||
|
* than no setting: if the proxy turns out NOT to overwrite the header we are
|
||||||
|
* trusting, any client can send it and mint itself an unlimited brute-force
|
||||||
|
* budget against /sign-in. Falling back to the shared bucket is bad (one noisy
|
||||||
|
* client can lock the organisation out for ten seconds at a time) but it is
|
||||||
|
* bad in a way that fails closed, and it can be reverted from the environment
|
||||||
|
* without a deploy.
|
||||||
|
*
|
||||||
|
* Reach for it only after a check has actually failed - `SELECT ipAddress FROM
|
||||||
|
* session ORDER BY createdAt DESC` showing 127.0.0.1 or NULL for a real remote
|
||||||
|
* sign-in - and take it back out once the header is configured.
|
||||||
|
*
|
||||||
|
* An empty or unset value still means "use the default", not "trust nothing":
|
||||||
|
* a stray blank line in a .env must not silently change how requests are
|
||||||
|
* bucketed. Only the explicit word does that.
|
||||||
|
*/
|
||||||
|
const TRUST_NO_HEADER = 'none';
|
||||||
|
|
||||||
|
export const TRUST_NO_CLIENT_IP_HEADER =
|
||||||
|
(process.env.CLIENT_IP_HEADERS || '').trim().toLowerCase() === TRUST_NO_HEADER;
|
||||||
|
|
||||||
|
// An empty array is what better-auth reads as "no headers": it only falls back
|
||||||
|
// to its own default when the option is absent, and `[]` is truthy.
|
||||||
|
export const CLIENT_IP_HEADERS = TRUST_NO_CLIENT_IP_HEADER
|
||||||
|
? []
|
||||||
|
: parseList(process.env.CLIENT_IP_HEADERS, ['x-real-ip']);
|
||||||
|
|
||||||
export const TRUSTED_PROXY_IPS = parseList(process.env.TRUSTED_PROXY_IPS, []);
|
export const TRUSTED_PROXY_IPS = parseList(process.env.TRUSTED_PROXY_IPS, []);
|
||||||
|
|
||||||
if (isProd && TRUSTED_PROXY_IPS.length === 0) {
|
if (isProd && TRUST_NO_CLIENT_IP_HEADER) {
|
||||||
|
logger.warn(
|
||||||
|
'Admin module: CLIENT_IP_HEADERS=none - no client-IP header is trusted, so every ' +
|
||||||
|
'request shares one rate-limit bucket and /sign-in allows 3 attempts per 10 seconds ' +
|
||||||
|
'for everyone combined. This is the safe fallback, not a destination: configure the ' +
|
||||||
|
'header the proxy actually sets and remove it.'
|
||||||
|
);
|
||||||
|
} else if (isProd && TRUSTED_PROXY_IPS.length === 0) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'Admin module: TRUSTED_PROXY_IPS is not set. If the proxy sends a multi-value ' +
|
'Admin module: TRUSTED_PROXY_IPS is not set. If the proxy sends a multi-value ' +
|
||||||
`${CLIENT_IP_HEADERS.join('/')}, better-auth cannot resolve a client IP and every ` +
|
`${CLIENT_IP_HEADERS.join('/')}, better-auth cannot resolve a client IP and every ` +
|
||||||
'request shares one rate-limit bucket. Verify with: SELECT `key` FROM rateLimit - ' +
|
'request shares one rate-limit bucket. Verify with: SELECT `key` FROM rateLimit - ' +
|
||||||
'a "no-trusted-ip" row means this is happening.'
|
'a "no-trusted-ip" row means this is happening. A single-value header needs no ' +
|
||||||
|
'trusted proxies, so this warning is expected on a plain single-proxy setup.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,14 @@ import express from 'express';
|
|||||||
import {fromNodeHeaders} from 'better-auth/node';
|
import {fromNodeHeaders} from 'better-auth/node';
|
||||||
import {auth} from './admin.auth.js';
|
import {auth} from './admin.auth.js';
|
||||||
import * as UsersService from './users/users.admin.service.js';
|
import * as UsersService from './users/users.admin.service.js';
|
||||||
import {AppName} from './admin.schema.js';
|
import {AppName, AppPermission, AppRole, canWrite} from './admin.schema.js';
|
||||||
import {sendServerError} from './admin.errors.js';
|
import {sendServerError} from './admin.errors.js';
|
||||||
|
|
||||||
|
// What a read-only grant may do. Every admin route reads with GET and changes
|
||||||
|
// with POST/PUT/PATCH/DELETE - keep it that way, or a read-only user either
|
||||||
|
// loses a view or gains a write.
|
||||||
|
const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one authenticator for every admin area in this API. It replaces
|
* The one authenticator for every admin area in this API. It replaces
|
||||||
* feedback.auth.ts and tickets.auth.ts, which each re-implemented the same
|
* feedback.auth.ts and tickets.auth.ts, which each re-implemented the same
|
||||||
@@ -28,6 +33,9 @@ export interface AdminIdentity {
|
|||||||
|
|
||||||
export interface AdminAccess extends AdminIdentity {
|
export interface AdminAccess extends AdminIdentity {
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
|
/** Every (app, role) grant. */
|
||||||
|
permissions: AppPermission[];
|
||||||
|
/** The distinct apps those grants cover. */
|
||||||
apps: AppName[];
|
apps: AppName[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +67,7 @@ export const resolveAccess = async (req: express.Request): Promise<AdminAccess |
|
|||||||
email: access.email,
|
email: access.email,
|
||||||
displayName: access.displayName,
|
displayName: access.displayName,
|
||||||
disabled: access.disabled,
|
disabled: access.disabled,
|
||||||
|
permissions: access.permissions,
|
||||||
apps: access.apps
|
apps: access.apps
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -97,8 +106,12 @@ export const requireSignedIn: express.RequestHandler = async (req, res, next) =>
|
|||||||
* what feedback.auth.ts's requireAdminAuth used to be, except that it now
|
* what feedback.auth.ts's requireAdminAuth used to be, except that it now
|
||||||
* answers 403 for a signed-in user without that app's permission instead of
|
* answers 403 for a signed-in user without that app's permission instead of
|
||||||
* letting any activated @nachklang.art account in.
|
* letting any activated @nachklang.art account in.
|
||||||
|
*
|
||||||
|
* The optional second argument narrows it to one role within the app. Nothing
|
||||||
|
* passes it today - every app has exactly the `access` role - but it is the
|
||||||
|
* seam a finer permission arrives through.
|
||||||
*/
|
*/
|
||||||
export const requireAppAccess = (app: AppName): express.RequestHandler => {
|
export const requireAppAccess = (app: AppName, role?: AppRole): express.RequestHandler => {
|
||||||
return async (req, res, next) => {
|
return async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const access = await resolveAccess(req);
|
const access = await resolveAccess(req);
|
||||||
@@ -110,11 +123,28 @@ export const requireAppAccess = (app: AppName): express.RequestHandler => {
|
|||||||
forbidden(res, 'Dieses Konto ist deaktiviert.');
|
forbidden(res, 'Dieses Konto ist deaktiviert.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!access.apps.includes(app)) {
|
|
||||||
|
// Without a role this asks "may they open this app at all?", which is
|
||||||
|
// any grant on it. With one it asks for that specific grant - the hook
|
||||||
|
// a finer permission plugs into, without touching existing call sites.
|
||||||
|
const allowed = role === undefined
|
||||||
|
? access.apps.includes(app)
|
||||||
|
: access.permissions.some(permission => permission.app === app && permission.role === role);
|
||||||
|
|
||||||
|
if (!allowed) {
|
||||||
forbidden(res, 'Für diesen Bereich fehlt dir die Berechtigung.');
|
forbidden(res, 'Für diesen Bereich fehlt dir die Berechtigung.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The read-only level, enforced by method rather than per route so a
|
||||||
|
// write route added later is covered without being marked. Only the
|
||||||
|
// role-less form applies it: a caller asking for a specific role has
|
||||||
|
// already said exactly what is required.
|
||||||
|
if (role === undefined && !READ_METHODS.has(req.method) && !canWrite(access.permissions, app)) {
|
||||||
|
forbidden(res, 'Du hast für diesen Bereich nur Lesezugriff.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
res.locals.admin = access;
|
res.locals.admin = access;
|
||||||
next();
|
next();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|||||||
@@ -19,6 +19,119 @@ export const isAppName = (value: unknown): value is AppName => {
|
|||||||
return typeof value === 'string' && (APP_NAMES as string[]).includes(value);
|
return typeof value === 'string' && (APP_NAMES as string[]).includes(value);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A permission is (app, role), not just an app. Today every app has exactly one
|
||||||
|
* role - `access`, "may use this app at all" - so the model looks like a plain
|
||||||
|
* list of apps and the UI renders one checkbox each. It is written this way
|
||||||
|
* anyway because the alternative gets expensive fast: `user_app_permissions`
|
||||||
|
* has primary key (user_id, app, role), so a user can hold several roles for
|
||||||
|
* the same app, and adding one later is a string in APP_ROLES plus rows - never
|
||||||
|
* a schema migration and never a change to the shape on the wire.
|
||||||
|
*
|
||||||
|
* Note the role is deliberately NOT called `admin`, which is what the column
|
||||||
|
* defaulted to before: on a `tickets` row that reads as "tickets administrator"
|
||||||
|
* when it only ever meant "has access", and once real roles exist there would
|
||||||
|
* be no way to tell the two apart.
|
||||||
|
*/
|
||||||
|
export const ACCESS_ROLE = 'access';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-only access to an app: everything `access` may see, nothing it may
|
||||||
|
* change. requireAppAccess enforces it by HTTP method - a user holding only
|
||||||
|
* this role gets GET/HEAD/OPTIONS and a 403 for anything else - so a new write
|
||||||
|
* route is covered without anyone remembering to mark it.
|
||||||
|
*
|
||||||
|
* It and `access` are mutually exclusive on one app (toPermissions rejects a
|
||||||
|
* list holding both), because "full access and also read-only" has no sensible
|
||||||
|
* reading. The `admin` app deliberately has no read role: viewing user
|
||||||
|
* management means viewing other people's addresses, IPs and sessions.
|
||||||
|
*/
|
||||||
|
export const READ_ROLE = 'read';
|
||||||
|
|
||||||
|
export type AppRole = string;
|
||||||
|
|
||||||
|
/** Every role that exists, per app, in display order. Extend to add one. */
|
||||||
|
export const APP_ROLES: Record<AppName, readonly AppRole[]> = {
|
||||||
|
calendar: [ACCESS_ROLE, READ_ROLE],
|
||||||
|
feedback: [ACCESS_ROLE, READ_ROLE],
|
||||||
|
tickets: [ACCESS_ROLE, READ_ROLE],
|
||||||
|
admin: [ACCESS_ROLE]
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface AppPermission {
|
||||||
|
app: AppName;
|
||||||
|
role: AppRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isAppRole = (app: AppName, role: unknown): role is AppRole => {
|
||||||
|
return typeof role === 'string' && APP_ROLES[app].includes(role);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isAppPermission = (value: unknown): value is AppPermission => {
|
||||||
|
if (typeof value !== 'object' || value === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const candidate = value as {app?: unknown; role?: unknown};
|
||||||
|
return isAppName(candidate.app) && isAppRole(candidate.app, candidate.role);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalises whatever a caller sent into a valid, duplicate-free permission
|
||||||
|
* list. Accepts the richer `{app, role}` form and the plain `AppName` form,
|
||||||
|
* because `{apps: ['tickets']}` is still what the older callers send and it
|
||||||
|
* means exactly "tickets at the access role".
|
||||||
|
*/
|
||||||
|
export const toPermissions = (value: unknown): AppPermission[] | null => {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions: AppPermission[] = [];
|
||||||
|
for (const entry of value) {
|
||||||
|
if (isAppName(entry)) {
|
||||||
|
permissions.push({app: entry, role: ACCESS_ROLE});
|
||||||
|
} else if (isAppPermission(entry)) {
|
||||||
|
permissions.push({app: entry.app, role: entry.role});
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const unique = permissions.filter(permission => {
|
||||||
|
const key = `${permission.app}:${permission.role}`;
|
||||||
|
if (seen.has(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
seen.add(key);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Rejected rather than resolved to either level: whichever one we picked,
|
||||||
|
// the caller asked for something else.
|
||||||
|
const contradictory = APP_NAMES.some(app => seen.has(`${app}:${ACCESS_ROLE}`) && seen.has(`${app}:${READ_ROLE}`));
|
||||||
|
return contradictory ? null : unique;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The distinct apps a permission list grants any access to. */
|
||||||
|
export const appsOf = (permissions: AppPermission[]): AppName[] => {
|
||||||
|
return APP_NAMES.filter(app => permissions.some(permission => permission.app === app));
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether these grants allow changing anything in `app`. Only `access` does:
|
||||||
|
* `read` is the read-only level, and a finer role added later grants exactly
|
||||||
|
* what its own check says, not writes in general.
|
||||||
|
*/
|
||||||
|
export const canWrite = (permissions: AppPermission[], app: AppName): boolean => {
|
||||||
|
return permissions.some(permission => permission.app === app && permission.role === ACCESS_ROLE);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Holds some grant on `app`, but none that allows changes. */
|
||||||
|
export const isReadOnly = (permissions: AppPermission[], app: AppName): boolean => {
|
||||||
|
return appsOf(permissions).includes(app) && !canWrite(permissions, app);
|
||||||
|
};
|
||||||
|
|
||||||
export interface UserTable {
|
export interface UserTable {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -52,7 +165,7 @@ export interface PasskeyTable {
|
|||||||
export interface UserAppPermissionTable {
|
export interface UserAppPermissionTable {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
app: AppName;
|
app: AppName;
|
||||||
role: string;
|
role: AppRole;
|
||||||
granted_by: string | null;
|
granted_by: string | null;
|
||||||
granted_at: Generated<Date>;
|
granted_at: Generated<Date>;
|
||||||
}
|
}
|
||||||
@@ -63,8 +176,9 @@ export interface InvitationTable {
|
|||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
token_hash: string;
|
token_hash: string;
|
||||||
// JSON column holding an AppName[].
|
// JSON column holding an AppPermission[]. Older rows may hold a plain
|
||||||
apps: string;
|
// AppName[]; `parsePermissions` reads both.
|
||||||
|
permissions: string;
|
||||||
invited_by: string | null;
|
invited_by: string | null;
|
||||||
created_at: Generated<Date>;
|
created_at: Generated<Date>;
|
||||||
expires_at: Date;
|
expires_at: Date;
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ export const invitationsPlugin = () => {
|
|||||||
return created;
|
return created;
|
||||||
});
|
});
|
||||||
|
|
||||||
await UsersService.setPermissions(user.id, invitation.apps, null);
|
await UsersService.setPermissions(user.id, invitation.permissions, null);
|
||||||
|
|
||||||
const session = await ctx.context.internalAdapter.createSession(user.id);
|
const session = await ctx.context.internalAdapter.createSession(user.id);
|
||||||
await setSessionCookie(ctx, {session, user});
|
await setSessionCookie(ctx, {session, user});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as InvitationsService from './invitations.service.js';
|
import * as InvitationsService from './invitations.service.js';
|
||||||
import * as UsersService from '../users/users.admin.service.js';
|
import * as UsersService from '../users/users.admin.service.js';
|
||||||
import {isAppName, AppName} from '../admin.schema.js';
|
import {toPermissions} from '../admin.schema.js';
|
||||||
import {sendInvitationMail} from '../admin.mail.js';
|
import {sendInvitationMail} from '../admin.mail.js';
|
||||||
import {ADMIN_APP_URL, LOG_INVITE_LINKS} from '../admin.config.js';
|
import {ADMIN_APP_URL, LOG_INVITE_LINKS} from '../admin.config.js';
|
||||||
import {sendServerError} from '../admin.errors.js';
|
import {sendServerError} from '../admin.errors.js';
|
||||||
@@ -64,16 +64,24 @@ invitationsRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* application/json:
|
* application/json:
|
||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [email, name, apps]
|
* required: [email, name, permissions]
|
||||||
* properties:
|
* properties:
|
||||||
* email:
|
* email:
|
||||||
* type: string
|
* type: string
|
||||||
* name:
|
* name:
|
||||||
* type: string
|
* type: string
|
||||||
* apps:
|
* permissions:
|
||||||
* type: array
|
* type: array
|
||||||
|
* description: >
|
||||||
|
* One entry per (app, role). A plain array of app names is
|
||||||
|
* accepted too and means the same at the `access` role.
|
||||||
* items:
|
* items:
|
||||||
* type: string
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* app:
|
||||||
|
* type: string
|
||||||
|
* role:
|
||||||
|
* type: string
|
||||||
* responses:
|
* responses:
|
||||||
* 201:
|
* 201:
|
||||||
* description: Invitation created and mailed
|
* description: Invitation created and mailed
|
||||||
@@ -86,10 +94,15 @@ invitationsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
const email = String(req.body?.email || '').trim().toLowerCase();
|
const email = String(req.body?.email || '').trim().toLowerCase();
|
||||||
const name = String(req.body?.name || '').trim();
|
const name = String(req.body?.name || '').trim();
|
||||||
const apps: unknown = req.body?.apps;
|
|
||||||
|
|
||||||
if (!EMAIL_PATTERN.test(email) || name.length === 0 || !Array.isArray(apps) || !apps.every(isAppName)) {
|
// Same two accepted shapes as PUT /admin/users/:id/permissions.
|
||||||
res.status(400).send({status: 'BAD_REQUEST', message: 'E-Mail, Name und App-Liste sind erforderlich.'});
|
const permissions = toPermissions(req.body?.permissions ?? req.body?.apps);
|
||||||
|
|
||||||
|
if (!EMAIL_PATTERN.test(email) || name.length === 0 || !permissions) {
|
||||||
|
res.status(400).send({
|
||||||
|
status: 'BAD_REQUEST',
|
||||||
|
message: 'E-Mail, Name und Berechtigungen sind erforderlich.'
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,7 +120,7 @@ invitationsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
const invitation = await InvitationsService.createInvitation(
|
const invitation = await InvitationsService.createInvitation(
|
||||||
email,
|
email,
|
||||||
name,
|
name,
|
||||||
apps as AppName[],
|
permissions,
|
||||||
res.locals.admin.id
|
res.locals.admin.id
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as crypto from 'crypto';
|
import * as crypto from 'crypto';
|
||||||
import {NachklangAdminDB} from '../Admin.db.js';
|
import {NachklangAdminDB} from '../Admin.db.js';
|
||||||
import {AppName, APP_NAMES, isAppName} from '../admin.schema.js';
|
import {AppPermission, isAppName, isAppPermission, ACCESS_ROLE} from '../admin.schema.js';
|
||||||
|
|
||||||
const db = NachklangAdminDB.db;
|
const db = NachklangAdminDB.db;
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ export interface OpenInvitation {
|
|||||||
id: number;
|
id: number;
|
||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
apps: AppName[];
|
permissions: AppPermission[];
|
||||||
invitedBy: string | null;
|
invitedBy: string | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
expiresAt: Date;
|
expiresAt: Date;
|
||||||
@@ -29,7 +29,7 @@ export interface AcceptableInvitation {
|
|||||||
id: number;
|
id: number;
|
||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
apps: AppName[];
|
permissions: AppPermission[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const hashToken = (token: string): string => {
|
const hashToken = (token: string): string => {
|
||||||
@@ -41,11 +41,28 @@ const generateToken = (): string => {
|
|||||||
return crypto.randomBytes(32).toString('base64url');
|
return crypto.randomBytes(32).toString('base64url');
|
||||||
};
|
};
|
||||||
|
|
||||||
const parseApps = (value: unknown): AppName[] => {
|
/**
|
||||||
// mysql2 hands back a JSON column already parsed; a driver or column-type
|
* Reads the stored permission list. Two shapes are accepted: the current
|
||||||
// change that turns it into a string must not break the read path.
|
* `[{app, role}]`, and a bare `['tickets', ...]` from before roles existed,
|
||||||
|
* which means the same thing at the `access` role. Invitations live for seven
|
||||||
|
* days, so a deploy that changes the shape has in-flight rows in the old one -
|
||||||
|
* tolerating both is what stops those invitees from being stranded.
|
||||||
|
*
|
||||||
|
* mysql2 hands back a JSON column already parsed; a driver or column-type
|
||||||
|
* change that turns it into a string must not break the read path either.
|
||||||
|
*/
|
||||||
|
const parsePermissions = (value: unknown): AppPermission[] => {
|
||||||
const raw = typeof value === 'string' ? JSON.parse(value) : value;
|
const raw = typeof value === 'string' ? JSON.parse(value) : value;
|
||||||
return Array.isArray(raw) ? raw.filter(isAppName) : [];
|
if (!Array.isArray(raw)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return raw.flatMap((entry): AppPermission[] => {
|
||||||
|
if (isAppName(entry)) {
|
||||||
|
return [{app: entry, role: ACCESS_ROLE}];
|
||||||
|
}
|
||||||
|
return isAppPermission(entry) ? [{app: entry.app, role: entry.role}] : [];
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const expiryFromNow = (): Date => {
|
const expiryFromNow = (): Date => {
|
||||||
@@ -61,12 +78,12 @@ const expiryFromNow = (): Date => {
|
|||||||
export const createInvitation = async (
|
export const createInvitation = async (
|
||||||
email: string,
|
email: string,
|
||||||
name: string,
|
name: string,
|
||||||
apps: AppName[],
|
permissions: AppPermission[],
|
||||||
invitedBy: string | null
|
invitedBy: string | null
|
||||||
): Promise<{id: number; token: string; expiresAt: Date}> => {
|
): Promise<{id: number; token: string; expiresAt: Date}> => {
|
||||||
const token = generateToken();
|
const token = generateToken();
|
||||||
const expiresAt = expiryFromNow();
|
const expiresAt = expiryFromNow();
|
||||||
const validApps = Array.from(new Set(apps)).filter(app => APP_NAMES.includes(app));
|
const valid = permissions.filter(isAppPermission);
|
||||||
|
|
||||||
const id = await db.transaction().execute(async trx => {
|
const id = await db.transaction().execute(async trx => {
|
||||||
await trx
|
await trx
|
||||||
@@ -83,7 +100,7 @@ export const createInvitation = async (
|
|||||||
email,
|
email,
|
||||||
name,
|
name,
|
||||||
token_hash: hashToken(token),
|
token_hash: hashToken(token),
|
||||||
apps: JSON.stringify(validApps),
|
permissions: JSON.stringify(valid),
|
||||||
invited_by: invitedBy,
|
invited_by: invitedBy,
|
||||||
created_at: new Date(),
|
created_at: new Date(),
|
||||||
expires_at: expiresAt
|
expires_at: expiresAt
|
||||||
@@ -105,7 +122,7 @@ export const createInvitation = async (
|
|||||||
export const findByToken = async (token: string): Promise<AcceptableInvitation | null> => {
|
export const findByToken = async (token: string): Promise<AcceptableInvitation | null> => {
|
||||||
const row = await db
|
const row = await db
|
||||||
.selectFrom('invitations')
|
.selectFrom('invitations')
|
||||||
.select(['id', 'email', 'name', 'apps'])
|
.select(['id', 'email', 'name', 'permissions'])
|
||||||
.where('token_hash', '=', hashToken(token))
|
.where('token_hash', '=', hashToken(token))
|
||||||
.where('accepted_at', 'is', null)
|
.where('accepted_at', 'is', null)
|
||||||
.where('revoked_at', 'is', null)
|
.where('revoked_at', 'is', null)
|
||||||
@@ -116,7 +133,7 @@ export const findByToken = async (token: string): Promise<AcceptableInvitation |
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {id: row.id, email: row.email, name: row.name, apps: parseApps(row.apps)};
|
return {id: row.id, email: row.email, name: row.name, permissions: parsePermissions(row.permissions)};
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Marks the invitation accepted. Conditional on it still being open so two
|
/** Marks the invitation accepted. Conditional on it still being open so two
|
||||||
@@ -149,7 +166,7 @@ export const unmarkAccepted = async (invitationId: number): Promise<void> => {
|
|||||||
export const listOpenInvitations = async (): Promise<OpenInvitation[]> => {
|
export const listOpenInvitations = async (): Promise<OpenInvitation[]> => {
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.selectFrom('invitations')
|
.selectFrom('invitations')
|
||||||
.select(['id', 'email', 'name', 'apps', 'invited_by', 'created_at', 'expires_at'])
|
.select(['id', 'email', 'name', 'permissions', 'invited_by', 'created_at', 'expires_at'])
|
||||||
.where('accepted_at', 'is', null)
|
.where('accepted_at', 'is', null)
|
||||||
.where('revoked_at', 'is', null)
|
.where('revoked_at', 'is', null)
|
||||||
.where('expires_at', '>', new Date())
|
.where('expires_at', '>', new Date())
|
||||||
@@ -160,7 +177,7 @@ export const listOpenInvitations = async (): Promise<OpenInvitation[]> => {
|
|||||||
id: row.id,
|
id: row.id,
|
||||||
email: row.email,
|
email: row.email,
|
||||||
name: row.name,
|
name: row.name,
|
||||||
apps: parseApps(row.apps),
|
permissions: parsePermissions(row.permissions),
|
||||||
invitedBy: row.invited_by,
|
invitedBy: row.invited_by,
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
expiresAt: row.expires_at
|
expiresAt: row.expires_at
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import * as UsersService from './users.admin.service.js';
|
import * as UsersService from './users.admin.service.js';
|
||||||
import {AppName, isAppName} from '../admin.schema.js';
|
import {toPermissions} from '../admin.schema.js';
|
||||||
import {sendServerError} from '../admin.errors.js';
|
import {sendServerError} from '../admin.errors.js';
|
||||||
|
|
||||||
export const usersAdminRouter = express.Router();
|
export const usersAdminRouter = express.Router();
|
||||||
@@ -90,26 +90,40 @@ usersAdminRouter.get('/:userId', async (req: Request, res: Response) => {
|
|||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
* apps:
|
* permissions:
|
||||||
* type: array
|
* type: array
|
||||||
|
* description: >
|
||||||
|
* One entry per (app, role). `access` is the only role today.
|
||||||
|
* A plain array of app names is also accepted and means the
|
||||||
|
* same at the `access` role.
|
||||||
* items:
|
* items:
|
||||||
* type: string
|
* type: object
|
||||||
* enum: [calendar, feedback, tickets, admin]
|
* properties:
|
||||||
|
* app:
|
||||||
|
* type: string
|
||||||
|
* enum: [calendar, feedback, tickets, admin]
|
||||||
|
* role:
|
||||||
|
* type: string
|
||||||
|
* enum: [access]
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
* 400:
|
* 400:
|
||||||
* description: Invalid app name
|
* description: Invalid app or role
|
||||||
* 409:
|
* 409:
|
||||||
* description: Would lock the last admin out
|
* description: Would lock the last admin out
|
||||||
*/
|
*/
|
||||||
usersAdminRouter.put('/:userId/permissions', async (req: Request, res: Response) => {
|
usersAdminRouter.put('/:userId/permissions', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const userId = req.params.userId;
|
const userId = req.params.userId;
|
||||||
const apps: unknown = req.body?.apps;
|
|
||||||
|
|
||||||
if (!Array.isArray(apps) || !apps.every(isAppName)) {
|
// `permissions: [{app, role}]` is the real shape; `apps: ['tickets']` is
|
||||||
res.status(400).send({status: 'BAD_REQUEST', message: 'Ungültige App-Liste.'});
|
// accepted as shorthand for the same thing at the `access` role, so a
|
||||||
|
// caller that predates roles keeps working.
|
||||||
|
const permissions = toPermissions(req.body?.permissions ?? req.body?.apps);
|
||||||
|
|
||||||
|
if (!permissions) {
|
||||||
|
res.status(400).send({status: 'BAD_REQUEST', message: 'Ungültige Berechtigungsliste.'});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +133,8 @@ usersAdminRouter.put('/:userId/permissions', async (req: Request, res: Response)
|
|||||||
}
|
}
|
||||||
|
|
||||||
const target = await UsersService.loadAccess(userId);
|
const target = await UsersService.loadAccess(userId);
|
||||||
const losesAdmin = Boolean(target?.apps.includes('admin')) && !(apps as AppName[]).includes('admin');
|
const keepsAdmin = permissions.some(permission => permission.app === 'admin');
|
||||||
|
const losesAdmin = Boolean(target?.apps.includes('admin')) && !keepsAdmin;
|
||||||
|
|
||||||
// Self-lockout is checked here because it needs the caller's identity,
|
// Self-lockout is checked here because it needs the caller's identity,
|
||||||
// which the service has no business knowing. The last-admin check is
|
// which the service has no business knowing. The last-admin check is
|
||||||
@@ -130,7 +145,7 @@ usersAdminRouter.put('/:userId/permissions', async (req: Request, res: Response)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await UsersService.setPermissionsGuarded(userId, apps as AppName[], res.locals.admin.id);
|
const result = await UsersService.setPermissionsGuarded(userId, permissions, res.locals.admin.id);
|
||||||
if (result === 'last-admin') {
|
if (result === 'last-admin') {
|
||||||
conflict(res, 'Die letzte Admin-Berechtigung kann nicht entzogen werden.');
|
conflict(res, 'Die letzte Admin-Berechtigung kann nicht entzogen werden.');
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
import {Transaction} from 'kysely';
|
import {Transaction} from 'kysely';
|
||||||
import {NachklangAdminDB} from '../Admin.db.js';
|
import {NachklangAdminDB} from '../Admin.db.js';
|
||||||
import {AdminDatabase, AppName, APP_NAMES} from '../admin.schema.js';
|
import {
|
||||||
|
AdminDatabase,
|
||||||
|
AppName,
|
||||||
|
AppPermission,
|
||||||
|
AppRole,
|
||||||
|
ACCESS_ROLE,
|
||||||
|
appsOf,
|
||||||
|
isAppName,
|
||||||
|
isAppRole
|
||||||
|
} from '../admin.schema.js';
|
||||||
|
|
||||||
const db = NachklangAdminDB.db;
|
const db = NachklangAdminDB.db;
|
||||||
|
|
||||||
@@ -18,6 +27,10 @@ export interface UserAccess {
|
|||||||
email: string;
|
email: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
|
/** Every (app, role) grant this user holds. */
|
||||||
|
permissions: AppPermission[];
|
||||||
|
/** The distinct apps the above grants any access to. Derived, kept because
|
||||||
|
* most callers only ever ask "may they open this app at all?". */
|
||||||
apps: AppName[];
|
apps: AppName[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,6 +40,7 @@ export interface UserListEntry {
|
|||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
permissions: AppPermission[];
|
||||||
apps: AppName[];
|
apps: AppName[];
|
||||||
status: UserStatus;
|
status: UserStatus;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
@@ -61,7 +75,8 @@ export const loadAccess = async (userId: string): Promise<UserAccess | null> =>
|
|||||||
'user.email as email',
|
'user.email as email',
|
||||||
'user.name as name',
|
'user.name as name',
|
||||||
'user.disabled as disabled',
|
'user.disabled as disabled',
|
||||||
'user_app_permissions.app as app'
|
'user_app_permissions.app as app',
|
||||||
|
'user_app_permissions.role as role'
|
||||||
])
|
])
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
@@ -69,16 +84,32 @@ export const loadAccess = async (userId: string): Promise<UserAccess | null> =>
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const permissions = toPermissionRows(rows);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: rows[0].id,
|
id: rows[0].id,
|
||||||
email: rows[0].email,
|
email: rows[0].email,
|
||||||
displayName: rows[0].name,
|
displayName: rows[0].name,
|
||||||
// MySQL TINYINT(1) comes back as 0/1 through mysql2.
|
// MySQL TINYINT(1) comes back as 0/1 through mysql2.
|
||||||
disabled: Boolean(rows[0].disabled),
|
disabled: Boolean(rows[0].disabled),
|
||||||
apps: rows.map(row => row.app).filter((app): app is AppName => app !== null)
|
permissions,
|
||||||
|
apps: appsOf(permissions)
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns joined permission rows into AppPermission[]. The left join produces one
|
||||||
|
* row with a null app for a user who holds nothing, and a role written directly
|
||||||
|
* into the database that no longer appears in APP_ROLES is dropped rather than
|
||||||
|
* trusted - the table is the store, APP_ROLES is the contract.
|
||||||
|
*/
|
||||||
|
const toPermissionRows = (rows: {app: AppName | null; role: string | null}[]): AppPermission[] => {
|
||||||
|
return rows
|
||||||
|
.filter((row): row is {app: AppName; role: string} =>
|
||||||
|
isAppName(row.app) && isAppRole(row.app, row.role))
|
||||||
|
.map(row => ({app: row.app, role: row.role}));
|
||||||
|
};
|
||||||
|
|
||||||
export const listUsers = async (): Promise<UserListEntry[]> => {
|
export const listUsers = async (): Promise<UserListEntry[]> => {
|
||||||
const users = await db
|
const users = await db
|
||||||
.selectFrom('user')
|
.selectFrom('user')
|
||||||
@@ -88,7 +119,7 @@ export const listUsers = async (): Promise<UserListEntry[]> => {
|
|||||||
|
|
||||||
const permissions = await db
|
const permissions = await db
|
||||||
.selectFrom('user_app_permissions')
|
.selectFrom('user_app_permissions')
|
||||||
.select(['user_id', 'app'])
|
.select(['user_id', 'app', 'role'])
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
// Last sign-in is derived from the newest session rather than stored: a
|
// Last sign-in is derived from the newest session rather than stored: a
|
||||||
@@ -107,26 +138,33 @@ export const listUsers = async (): Promise<UserListEntry[]> => {
|
|||||||
.groupBy('userId')
|
.groupBy('userId')
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
const appsByUser = new Map<string, AppName[]>();
|
const permissionsByUser = new Map<string, AppPermission[]>();
|
||||||
for (const row of permissions) {
|
for (const row of permissions) {
|
||||||
const apps = appsByUser.get(row.user_id) || [];
|
if (!isAppRole(row.app, row.role)) {
|
||||||
apps.push(row.app);
|
continue;
|
||||||
appsByUser.set(row.user_id, apps);
|
}
|
||||||
|
const held = permissionsByUser.get(row.user_id) || [];
|
||||||
|
held.push({app: row.app, role: row.role});
|
||||||
|
permissionsByUser.set(row.user_id, held);
|
||||||
}
|
}
|
||||||
|
|
||||||
const lastSignInByUser = new Map<string, Date | null>(
|
const lastSignInByUser = new Map<string, Date | null>(
|
||||||
lastSessions.map(row => [row.userId, row.lastSignInAt as Date | null])
|
lastSessions.map(row => [row.userId, row.lastSignInAt as Date | null])
|
||||||
);
|
);
|
||||||
|
|
||||||
return users.map(user => ({
|
return users.map(user => {
|
||||||
id: user.id,
|
const held = permissionsByUser.get(user.id) || [];
|
||||||
email: user.email,
|
return {
|
||||||
name: user.name,
|
id: user.id,
|
||||||
apps: appsByUser.get(user.id) || [],
|
email: user.email,
|
||||||
status: user.disabled ? 'deaktiviert' : 'aktiv',
|
name: user.name,
|
||||||
createdAt: user.createdAt,
|
permissions: held,
|
||||||
lastSignInAt: lastSignInByUser.get(user.id) ?? null
|
apps: appsOf(held),
|
||||||
}));
|
status: user.disabled ? ('deaktiviert' as const) : ('aktiv' as const),
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
lastSignInAt: lastSignInByUser.get(user.id) ?? null
|
||||||
|
};
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getUserDetail = async (userId: string): Promise<UserDetail | null> => {
|
export const getUserDetail = async (userId: string): Promise<UserDetail | null> => {
|
||||||
@@ -141,7 +179,11 @@ export const getUserDetail = async (userId: string): Promise<UserDetail | null>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const [permissions, sessions, passkeys] = await Promise.all([
|
const [permissions, sessions, passkeys] = await Promise.all([
|
||||||
db.selectFrom('user_app_permissions').select('app').where('user_id', '=', userId).execute(),
|
db
|
||||||
|
.selectFrom('user_app_permissions')
|
||||||
|
.select(['app', 'role'])
|
||||||
|
.where('user_id', '=', userId)
|
||||||
|
.execute(),
|
||||||
db
|
db
|
||||||
.selectFrom('session')
|
.selectFrom('session')
|
||||||
.select(['id', 'createdAt', 'expiresAt', 'ipAddress', 'userAgent'])
|
.select(['id', 'createdAt', 'expiresAt', 'ipAddress', 'userAgent'])
|
||||||
@@ -156,11 +198,14 @@ export const getUserDetail = async (userId: string): Promise<UserDetail | null>
|
|||||||
.executeTakeFirst()
|
.executeTakeFirst()
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const held = toPermissionRows(permissions);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
apps: permissions.map(row => row.app),
|
permissions: held,
|
||||||
|
apps: appsOf(held),
|
||||||
status: user.disabled ? 'deaktiviert' : 'aktiv',
|
status: user.disabled ? 'deaktiviert' : 'aktiv',
|
||||||
createdAt: user.createdAt,
|
createdAt: user.createdAt,
|
||||||
lastSignInAt: sessions.length > 0 ? sessions[0].createdAt : null,
|
lastSignInAt: sessions.length > 0 ? sessions[0].createdAt : null,
|
||||||
@@ -174,25 +219,51 @@ export const getUserDetail = async (userId: string): Promise<UserDetail | null>
|
|||||||
* transaction rather than a diff: the set is at most four rows, and a diff
|
* transaction rather than a diff: the set is at most four rows, and a diff
|
||||||
* would only add branches for no measurable gain.
|
* would only add branches for no measurable gain.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/** The rows a permission list becomes. One row per (app, role). */
|
||||||
|
const permissionRows = (
|
||||||
|
userId: string,
|
||||||
|
permissions: AppPermission[],
|
||||||
|
grantedBy: string | null
|
||||||
|
) => {
|
||||||
|
return permissions.map(permission => ({
|
||||||
|
user_id: userId,
|
||||||
|
app: permission.app,
|
||||||
|
role: permission.role,
|
||||||
|
granted_by: grantedBy,
|
||||||
|
granted_at: new Date()
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Drops anything not in APP_ROLES and de-duplicates on (app, role). */
|
||||||
|
const validPermissions = (permissions: AppPermission[]): AppPermission[] => {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
return permissions.filter(permission => {
|
||||||
|
if (!isAppName(permission.app) || !isAppRole(permission.app, permission.role)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const key = `${permission.app}:${permission.role}`;
|
||||||
|
if (seen.has(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
seen.add(key);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export const setPermissions = async (
|
export const setPermissions = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
apps: AppName[],
|
permissions: AppPermission[],
|
||||||
grantedBy: string | null
|
grantedBy: string | null
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
const unique = Array.from(new Set(apps)).filter(app => APP_NAMES.includes(app));
|
const valid = validPermissions(permissions);
|
||||||
|
|
||||||
await db.transaction().execute(async trx => {
|
await db.transaction().execute(async trx => {
|
||||||
await trx.deleteFrom('user_app_permissions').where('user_id', '=', userId).execute();
|
await trx.deleteFrom('user_app_permissions').where('user_id', '=', userId).execute();
|
||||||
if (unique.length > 0) {
|
if (valid.length > 0) {
|
||||||
await trx
|
await trx
|
||||||
.insertInto('user_app_permissions')
|
.insertInto('user_app_permissions')
|
||||||
.values(unique.map(app => ({
|
.values(permissionRows(userId, valid, grantedBy))
|
||||||
user_id: userId,
|
|
||||||
app,
|
|
||||||
role: 'admin',
|
|
||||||
granted_by: grantedBy,
|
|
||||||
granted_at: new Date()
|
|
||||||
})))
|
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -217,7 +288,11 @@ const countActiveAdminsForUpdate = async (trx: Transaction<AdminDatabase>): Prom
|
|||||||
.innerJoin('user', 'user.id', 'user_app_permissions.user_id')
|
.innerJoin('user', 'user.id', 'user_app_permissions.user_id')
|
||||||
.where('user_app_permissions.app', '=', 'admin')
|
.where('user_app_permissions.app', '=', 'admin')
|
||||||
.where('user.disabled', '=', false)
|
.where('user.disabled', '=', false)
|
||||||
.select(({fn}) => fn.countAll<number>().as('count'))
|
// countDistinct, not countAll: with (user_id, app, role) as the key one
|
||||||
|
// user can hold several roles on `admin`, and counting rows would make a
|
||||||
|
// single admin with two roles look like two admins - defeating the guard
|
||||||
|
// at exactly the moment it matters.
|
||||||
|
.select(({fn}) => fn.count<number>('user_app_permissions.user_id').distinct().as('count'))
|
||||||
.forUpdate()
|
.forUpdate()
|
||||||
.executeTakeFirst();
|
.executeTakeFirst();
|
||||||
|
|
||||||
@@ -230,10 +305,11 @@ const countActiveAdminsForUpdate = async (trx: Transaction<AdminDatabase>): Prom
|
|||||||
*/
|
*/
|
||||||
export const setPermissionsGuarded = async (
|
export const setPermissionsGuarded = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
apps: AppName[],
|
permissions: AppPermission[],
|
||||||
grantedBy: string | null
|
grantedBy: string | null
|
||||||
): Promise<LastAdminGuardResult> => {
|
): Promise<LastAdminGuardResult> => {
|
||||||
const unique = Array.from(new Set(apps)).filter(app => APP_NAMES.includes(app));
|
const valid = validPermissions(permissions);
|
||||||
|
const keepsAdmin = valid.some(permission => permission.app === 'admin');
|
||||||
|
|
||||||
return db.transaction().execute(async trx => {
|
return db.transaction().execute(async trx => {
|
||||||
const target = await trx
|
const target = await trx
|
||||||
@@ -242,25 +318,20 @@ export const setPermissionsGuarded = async (
|
|||||||
.where('user_app_permissions.user_id', '=', userId)
|
.where('user_app_permissions.user_id', '=', userId)
|
||||||
.where('user_app_permissions.app', '=', 'admin')
|
.where('user_app_permissions.app', '=', 'admin')
|
||||||
.select(['user.disabled as disabled'])
|
.select(['user.disabled as disabled'])
|
||||||
|
.limit(1)
|
||||||
.forUpdate()
|
.forUpdate()
|
||||||
.executeTakeFirst();
|
.executeTakeFirst();
|
||||||
|
|
||||||
const losesAdmin = Boolean(target) && !unique.includes('admin');
|
const losesAdmin = Boolean(target) && !keepsAdmin;
|
||||||
if (losesAdmin && !target?.disabled && (await countActiveAdminsForUpdate(trx)) <= 1) {
|
if (losesAdmin && !target?.disabled && (await countActiveAdminsForUpdate(trx)) <= 1) {
|
||||||
return 'last-admin';
|
return 'last-admin';
|
||||||
}
|
}
|
||||||
|
|
||||||
await trx.deleteFrom('user_app_permissions').where('user_id', '=', userId).execute();
|
await trx.deleteFrom('user_app_permissions').where('user_id', '=', userId).execute();
|
||||||
if (unique.length > 0) {
|
if (valid.length > 0) {
|
||||||
await trx
|
await trx
|
||||||
.insertInto('user_app_permissions')
|
.insertInto('user_app_permissions')
|
||||||
.values(unique.map(app => ({
|
.values(permissionRows(userId, valid, grantedBy))
|
||||||
user_id: userId,
|
|
||||||
app,
|
|
||||||
role: 'admin',
|
|
||||||
granted_by: grantedBy,
|
|
||||||
granted_at: new Date()
|
|
||||||
})))
|
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,6 +352,7 @@ export const disableUserGuarded = async (userId: string): Promise<LastAdminGuard
|
|||||||
.where('user_app_permissions.app', '=', 'admin')
|
.where('user_app_permissions.app', '=', 'admin')
|
||||||
.where('user.disabled', '=', false)
|
.where('user.disabled', '=', false)
|
||||||
.select('user_app_permissions.user_id')
|
.select('user_app_permissions.user_id')
|
||||||
|
.limit(1)
|
||||||
.forUpdate()
|
.forUpdate()
|
||||||
.executeTakeFirst();
|
.executeTakeFirst();
|
||||||
|
|
||||||
@@ -298,12 +370,16 @@ export const disableUserGuarded = async (userId: string): Promise<LastAdminGuard
|
|||||||
export const grantPermission = async (
|
export const grantPermission = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
app: AppName,
|
app: AppName,
|
||||||
grantedBy: string | null
|
grantedBy: string | null,
|
||||||
|
role: AppRole = ACCESS_ROLE
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
await db
|
await db
|
||||||
.insertInto('user_app_permissions')
|
.insertInto('user_app_permissions')
|
||||||
.values({user_id: userId, app, role: 'admin', granted_by: grantedBy, granted_at: new Date()})
|
.values({user_id: userId, app, role, granted_by: grantedBy, granted_at: new Date()})
|
||||||
.onDuplicateKeyUpdate({role: 'admin'})
|
// The row already existing is the success case - this is "make sure they
|
||||||
|
// hold it", not "re-grant it" - so nothing is overwritten and granted_by
|
||||||
|
// keeps naming whoever granted it first.
|
||||||
|
.onDuplicateKeyUpdate({role})
|
||||||
.execute();
|
.execute();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -361,3 +437,30 @@ export const findUserByEmail = async (email: string): Promise<{id: string; email
|
|||||||
|
|
||||||
return row ?? null;
|
return row ?? null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display names for a set of user ids, as an id -> name map. Ids that no
|
||||||
|
* longer exist are simply absent from the map rather than mapping to a
|
||||||
|
* placeholder, so callers can distinguish "deleted account" from "never had
|
||||||
|
* one" and choose their own fallback.
|
||||||
|
*
|
||||||
|
* This exists for the calendar migration (docs/calendar-auth-migration.md
|
||||||
|
* step 3): the calendar lives in a different database, so it cannot join
|
||||||
|
* against `user` to render "created by". One lookup per result set keeps that
|
||||||
|
* cheap without coupling the two schemas.
|
||||||
|
*/
|
||||||
|
export const findDisplayNames = async (ids: readonly string[]): Promise<Map<string, string>> => {
|
||||||
|
const distinct = Array.from(new Set(ids.filter(id => id)));
|
||||||
|
if (distinct.length === 0) {
|
||||||
|
// Kysely renders `in ()` for an empty list, which MariaDB rejects.
|
||||||
|
return new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.selectFrom('user')
|
||||||
|
.select(['id', 'name'])
|
||||||
|
.where('id', 'in', distinct)
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
return new Map(rows.map(row => [row.id, row.name]));
|
||||||
|
};
|
||||||
@@ -5,7 +5,6 @@ import express, {Request, Response} from 'express';
|
|||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../middleware/logger.js';
|
import logger from '../../middleware/logger.js';
|
||||||
import {eventsRouter} from './events/events.router.js';
|
import {eventsRouter} from './events/events.router.js';
|
||||||
import {usersRouter} from './users/users.router.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router Definition
|
* Router Definition
|
||||||
@@ -13,7 +12,13 @@ import {usersRouter} from './users/users.router.js';
|
|||||||
export const calendarRouter = express.Router();
|
export const calendarRouter = express.Router();
|
||||||
|
|
||||||
calendarRouter.use('/events', eventsRouter);
|
calendarRouter.use('/events', eventsRouter);
|
||||||
calendarRouter.use('/users', usersRouter);
|
|
||||||
|
/*
|
||||||
|
* There is no /calendar/users any more. It held this module's own accounts -
|
||||||
|
* registration, login, activation, password reset, and the session table the
|
||||||
|
* feedback and tickets admin areas used to authenticate against - and every one
|
||||||
|
* of those moved to the admin module. See docs/calendar-auth-migration.md.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,73 +1,61 @@
|
|||||||
import * as dotenv from 'dotenv';
|
import * as dotenv from 'dotenv';
|
||||||
import * as UserService from '../users/users.service.js';
|
|
||||||
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the password gives admin privileges (view / create / edit / delete)
|
* The shared calendar passwords, and nothing else.
|
||||||
* @param password
|
*
|
||||||
|
* Before the step 4 cutover each function here also took a sessionId/sessionKey
|
||||||
|
* pair and checked it against the calendar's own sessions table, so "is this a
|
||||||
|
* signed-in user?" and "did they send the right shared password?" were tangled
|
||||||
|
* together in five places. Signed-in access is now decided by
|
||||||
|
* requireAppAccess('calendar') before the handler runs; what is left is the
|
||||||
|
* fallback for people who have no account at all.
|
||||||
|
*
|
||||||
|
* That fallback survives on purpose, for one reason: an iCal client subscribing
|
||||||
|
* to a calendar URL cannot send a cookie. Everything the Angular app does goes
|
||||||
|
* through the session cookie instead. See docs/calendar-auth-migration.md.
|
||||||
|
*
|
||||||
|
* `public` is deliberately open to everyone with no credential of any kind -
|
||||||
|
* nachklang.art reads it anonymously to show the next upcoming event. Pinned by
|
||||||
|
* test/calendar/credentials.service.test.ts.
|
||||||
*/
|
*/
|
||||||
export const checkAdminPrivileges = async (sessionId: string, sessionKey: string, ip: string) => {
|
|
||||||
if(sessionId) {
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
return user?.isActive ?? false;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the password gives member view privileges
|
* The shared password for a calendar, or undefined for `public` (which needs
|
||||||
* @param password
|
* none), an unknown calendar, or one whose credential is not configured.
|
||||||
|
* Exported for the subscriptions endpoint, which hands signed-in editors the
|
||||||
|
* ready-made iCal URLs - see GET /calendar/events/subscriptions.
|
||||||
*/
|
*/
|
||||||
export const checkMemberPrivileges = async (sessionId: string, sessionKey: string, password: string, ip: string) => {
|
export const credentialFor = (calendarName: string): string | undefined => {
|
||||||
if(sessionId) {
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
return user?.isActive ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return password == process.env.MEMBER_CREDENTIAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the password gives choir view privileges
|
|
||||||
* @param password
|
|
||||||
*/
|
|
||||||
export const checkChoirPrivileges = async (sessionId: string, sessionKey: string, password: string, ip: string) => {
|
|
||||||
if(sessionId) {
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
return user?.isActive ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return password == process.env.CHOIR_CREDENTIAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the password gives management view privileges
|
|
||||||
* @param password
|
|
||||||
*/
|
|
||||||
export const checkManagementPrivileges = async (sessionId: string, sessionKey: string, password: string, ip: string) => {
|
|
||||||
if(sessionId) {
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
return user?.isActive ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return password == process.env.MANAGEMENT_CREDENTIAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const hasAccess = async (calendarName: string, sessionId: string, sessionKey: string, password: string, ip: string) => {
|
|
||||||
switch (calendarName) {
|
switch (calendarName) {
|
||||||
case 'public':
|
|
||||||
return true;
|
|
||||||
case 'members':
|
case 'members':
|
||||||
return await checkMemberPrivileges(sessionId, sessionKey, password, ip);
|
return process.env.MEMBER_CREDENTIAL;
|
||||||
case 'choir':
|
case 'choir':
|
||||||
return await checkChoirPrivileges(sessionId, sessionKey, password, ip);
|
case 'birthdays':
|
||||||
|
return process.env.CHOIR_CREDENTIAL;
|
||||||
case 'management':
|
case 'management':
|
||||||
return await checkManagementPrivileges(sessionId, sessionKey, password, ip);
|
return process.env.MANAGEMENT_CREDENTIAL;
|
||||||
case 'birthdays':
|
|
||||||
return await checkChoirPrivileges(sessionId, sessionKey, password, ip);
|
|
||||||
default:
|
default:
|
||||||
return false;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the given shared password opens the given calendar. Answers false
|
||||||
|
* for an unknown calendar, and - importantly - for a calendar whose credential
|
||||||
|
* is not configured at all: an unset MEMBER_CREDENTIAL must not turn into
|
||||||
|
* "everyone with an empty password gets in".
|
||||||
|
*/
|
||||||
|
export const hasAccess = async (calendarName: string, password: string): Promise<boolean> => {
|
||||||
|
if (calendarName === 'public') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expected = credentialFor(calendarName);
|
||||||
|
if (!expected) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return password === expected;
|
||||||
|
};
|
||||||
@@ -14,7 +14,6 @@
|
|||||||
* - endDateTime
|
* - endDateTime
|
||||||
* - createdDate
|
* - createdDate
|
||||||
* - location
|
* - location
|
||||||
* - createdById
|
|
||||||
* - url
|
* - url
|
||||||
* - wholeDay
|
* - wholeDay
|
||||||
* properties:
|
* properties:
|
||||||
@@ -65,18 +64,20 @@
|
|||||||
* type: string
|
* type: string
|
||||||
* description: The name of the user who created the event
|
* description: The name of the user who created the event
|
||||||
* example: "John Doe"
|
* example: "John Doe"
|
||||||
* createdById:
|
* createdByUserId:
|
||||||
* type: integer
|
* type: string
|
||||||
* description: The ID of the user who created the event
|
* nullable: true
|
||||||
* example: 456
|
* description: The admin-module user id of the creator, once it has one
|
||||||
|
* example: "8f1c0f2e-0f1a-4b9e-9a7c-2d5f1b3c4d5e"
|
||||||
* lastModifiedBy:
|
* lastModifiedBy:
|
||||||
* type: string
|
* type: string
|
||||||
* description: The name of the user who last modified the event
|
* description: The name of the user who last modified the event
|
||||||
* example: "John Doe"
|
* example: "John Doe"
|
||||||
* lastModifiedById:
|
* lastModifiedByUserId:
|
||||||
* type: integer
|
* type: string
|
||||||
* description: The ID of the user who last modified the event
|
* nullable: true
|
||||||
* example: 456
|
* description: The admin-module user id of the last editor, once it has one
|
||||||
|
* example: "8f1c0f2e-0f1a-4b9e-9a7c-2d5f1b3c4d5e"
|
||||||
* url:
|
* url:
|
||||||
* type: string
|
* type: string
|
||||||
* description: A URL with more information about the event
|
* description: A URL with more information about the event
|
||||||
@@ -102,10 +103,13 @@ export interface Event {
|
|||||||
createdDate: Date;
|
createdDate: Date;
|
||||||
lastModifiedDate?: Date;
|
lastModifiedDate?: Date;
|
||||||
location: string;
|
location: string;
|
||||||
|
/** Display name of the creator: the live admin name when the id below
|
||||||
|
* resolves, otherwise the name archived before the legacy users table was
|
||||||
|
* removed. See docs/calendar-auth-migration.md. */
|
||||||
createdBy?: string;
|
createdBy?: string;
|
||||||
createdById: number;
|
createdByUserId?: string | null;
|
||||||
lastModifiedBy?: string;
|
lastModifiedBy?: string;
|
||||||
lastModifiedById?: number;
|
lastModifiedByUserId?: string | null;
|
||||||
url: string;
|
url: string;
|
||||||
wholeDay: boolean;
|
wholeDay: boolean;
|
||||||
repeatFrequency: string;
|
repeatFrequency: string;
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import {Event} from './event.interface.js';
|
|||||||
import * as EventService from './events.service.js';
|
import * as EventService from './events.service.js';
|
||||||
import * as iCalService from './icalgenerator.service.js';
|
import * as iCalService from './icalgenerator.service.js';
|
||||||
import * as CredentialService from './credentials.service.js';
|
import * as CredentialService from './credentials.service.js';
|
||||||
import * as UserService from '../users/users.service.js';
|
import {requireAppAccess, resolveAccess, AdminAccess} from '../../admin/admin.middleware.js';
|
||||||
|
import {API_BASE_URL} from '../../admin/admin.config.js';
|
||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import logger from '../../../middleware/logger.js';
|
import logger from '../../../middleware/logger.js';
|
||||||
|
|
||||||
@@ -29,6 +30,44 @@ export const calendarNames = new Map<string, any>([
|
|||||||
['birthdays', {id: 5, name: 'Nachklang_birthday_calendar'}]
|
['birthdays', {id: 5, name: 'Nachklang_birthday_calendar'}]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The gate on everything that writes. Step 4 of
|
||||||
|
* docs/calendar-auth-migration.md replaced a sessionId/sessionKey pair in the
|
||||||
|
* query string (DEFERRED_SECURITY.md item 1) with the same session cookie the
|
||||||
|
* other three apps use, and "any activated @nachklang.art account" with an
|
||||||
|
* explicit per-user calendar permission.
|
||||||
|
*/
|
||||||
|
const requireCalendarAccess = requireAppAccess('calendar');
|
||||||
|
|
||||||
|
/** Set by requireCalendarAccess; the writer's admin identity. */
|
||||||
|
const adminOf = (res: Response): AdminAccess => res.locals.admin as AdminAccess;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a signed-in calendar user for the *read* routes, or null.
|
||||||
|
*
|
||||||
|
* Reads cannot use the middleware: the same URL serves an anonymous visitor
|
||||||
|
* (the public calendar the website polls), someone holding a shared password
|
||||||
|
* (an iCal subscription), and a signed-in editor who should see drafts. So it
|
||||||
|
* answers "who is this, if anyone?" instead of refusing the request, and each
|
||||||
|
* handler decides what that means.
|
||||||
|
*
|
||||||
|
* A failure to reach the admin database is swallowed for the same reason the
|
||||||
|
* name lookup in events.service.ts swallows one: it must not be able to take
|
||||||
|
* the anonymous public calendar down.
|
||||||
|
*/
|
||||||
|
const signedInEditor = async (req: Request): Promise<AdminAccess | null> => {
|
||||||
|
try {
|
||||||
|
const access = await resolveAccess(req);
|
||||||
|
if (!access || access.disabled || !access.apps.includes('calendar')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return access;
|
||||||
|
} catch (e: any) {
|
||||||
|
logger.warn('Calendar: could not resolve the session, continuing as anonymous: ' + e.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Controller Definitions
|
* Controller Definitions
|
||||||
@@ -39,7 +78,10 @@ export const calendarNames = new Map<string, any>([
|
|||||||
* /calendar/events/{calendar}/json:
|
* /calendar/events/{calendar}/json:
|
||||||
* get:
|
* get:
|
||||||
* summary: Get all events from a specific calendar in JSON format
|
* summary: Get all events from a specific calendar in JSON format
|
||||||
* description: Returns all events from the specified calendar in JSON format. Authentication required.
|
* description: >
|
||||||
|
* Returns the calendar's events. The public calendar is open to everyone; the
|
||||||
|
* others need either a signed-in account with the calendar permission - which
|
||||||
|
* also unlocks drafts - or the calendar's shared password.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
* parameters:
|
* parameters:
|
||||||
@@ -48,23 +90,13 @@ export const calendarNames = new Map<string, any>([
|
|||||||
* required: true
|
* required: true
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* enum: [public, members, choir, management]
|
* enum: [public, members, choir, management, birthdays]
|
||||||
* description: The name of the calendar to get events from
|
* description: The name of the calendar to get events from
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: sessionId
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: password
|
* name: password
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* description: Password for calendar access (if not using session authentication)
|
* description: The calendar's shared password, for callers with no account
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
@@ -109,10 +141,7 @@ eventsRouter.get('/:calendar/json', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
// Get request params
|
// Get request params
|
||||||
let calendarName: string = req.params.calendar as string ?? '';
|
let calendarName: string = req.params.calendar as string ?? '';
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let password: string = req.query.password as string ?? '';
|
let password: string = req.query.password as string ?? '';
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
if (calendarName.length < 1) {
|
if (calendarName.length < 1) {
|
||||||
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
||||||
@@ -126,23 +155,19 @@ eventsRouter.get('/:calendar/json', async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
let calendarId: number = calendarNames.get(calendarName)!.id;
|
let calendarId: number = calendarNames.get(calendarName)!.id;
|
||||||
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
const editor = await signedInEditor(req);
|
||||||
|
|
||||||
// If no user was found, check if the password gives access to the calendar
|
// Not signed in: fall back to the shared password for this calendar.
|
||||||
if(user === null || !user.isActive) {
|
if (!editor && ! await CredentialService.hasAccess(calendarName, password)) {
|
||||||
if (! await CredentialService.hasAccess(calendarName, sessionId, sessionKey, password, ip)) {
|
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let events: Event[];
|
// Editors get the admin view (drafts included, calendar includes ignored);
|
||||||
|
// everyone else gets published events only.
|
||||||
if(user?.isActive) {
|
let events: Event[] = editor
|
||||||
events = await EventService.getAllEventsAdmin(calendarId);
|
? await EventService.getAllEventsAdmin(calendarId)
|
||||||
} else {
|
: await EventService.getAllEvents(calendarId);
|
||||||
events = await EventService.getAllEvents(calendarId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the events back
|
// Send the events back
|
||||||
res.status(200).send(events);
|
res.status(200).send(events);
|
||||||
@@ -158,7 +183,10 @@ eventsRouter.get('/:calendar/json', async (req: Request, res: Response) => {
|
|||||||
* /calendar/events/{calendar}/json/next:
|
* /calendar/events/{calendar}/json/next:
|
||||||
* get:
|
* get:
|
||||||
* summary: Get the next upcoming event from a calendar
|
* summary: Get the next upcoming event from a calendar
|
||||||
* description: Returns the next upcoming event from the specified calendar. Authentication required.
|
* description: >
|
||||||
|
* The next upcoming event. The public calendar is open to everyone; the
|
||||||
|
* others need either a signed-in account with the calendar permission or the
|
||||||
|
* calendar's shared password.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
* parameters:
|
* parameters:
|
||||||
@@ -167,23 +195,13 @@ eventsRouter.get('/:calendar/json', async (req: Request, res: Response) => {
|
|||||||
* required: true
|
* required: true
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* enum: [public, members, choir, management]
|
* enum: [public, members, choir, management, birthdays]
|
||||||
* description: The name of the calendar to get the next event from
|
* description: The name of the calendar to get the next event from
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: sessionId
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: password
|
* name: password
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* description: Password for calendar access (if not using session authentication)
|
* description: The calendar's shared password, for callers with no account
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
@@ -242,10 +260,7 @@ eventsRouter.get('/:calendar/json/next', async (req: Request, res: Response) =>
|
|||||||
try {
|
try {
|
||||||
// Get request params
|
// Get request params
|
||||||
let calendarName: string = req.params.calendar as string ?? '';
|
let calendarName: string = req.params.calendar as string ?? '';
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let password: string = req.query.password as string ?? '';
|
let password: string = req.query.password as string ?? '';
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
if (calendarName.length < 1) {
|
if (calendarName.length < 1) {
|
||||||
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
||||||
@@ -259,7 +274,19 @@ eventsRouter.get('/:calendar/json/next', async (req: Request, res: Response) =>
|
|||||||
|
|
||||||
let calendarId: number = calendarNames.get(calendarName)!.id;
|
let calendarId: number = calendarNames.get(calendarName)!.id;
|
||||||
|
|
||||||
if (! await CredentialService.hasAccess(calendarName, sessionId, sessionKey, password, ip)) {
|
// Holding the calendar's shared password, or signed in. The password path
|
||||||
|
// is what keeps iCal subscriptions working - a calendar client cannot
|
||||||
|
// send a cookie.
|
||||||
|
//
|
||||||
|
// The password is checked FIRST so that `public`, which needs no
|
||||||
|
// credential at all, short-circuits before signedInEditor runs. Otherwise
|
||||||
|
// every request from a browser that happens to hold a .nachklang.art
|
||||||
|
// cookie - which is any signed-in user on any of the four apps - would put
|
||||||
|
// an admin-database query in front of the anonymous public feed, with no
|
||||||
|
// timeout. Both operands are side-effect free, so the order is free to
|
||||||
|
// choose; this order is the one that keeps the public calendar
|
||||||
|
// independent of the admin database.
|
||||||
|
if (! await CredentialService.hasAccess(calendarName, password) && !await signedInEditor(req)) {
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -290,7 +317,10 @@ eventsRouter.get('/:calendar/json/next', async (req: Request, res: Response) =>
|
|||||||
* /calendar/events/{calendar}/ical:
|
* /calendar/events/{calendar}/ical:
|
||||||
* get:
|
* get:
|
||||||
* summary: Get all events from a specific calendar in iCal format
|
* summary: Get all events from a specific calendar in iCal format
|
||||||
* description: Returns all events from the specified calendar in iCal format for calendar applications. Authentication required.
|
* description: >
|
||||||
|
* The calendar in iCal format. The public calendar is open to everyone; the
|
||||||
|
* others take the calendar's shared password in the query string, which is
|
||||||
|
* why that mechanism survives - an iCal client cannot send a cookie.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
* parameters:
|
* parameters:
|
||||||
@@ -299,23 +329,13 @@ eventsRouter.get('/:calendar/json/next', async (req: Request, res: Response) =>
|
|||||||
* required: true
|
* required: true
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* enum: [public, members, choir, management]
|
* enum: [public, members, choir, management, birthdays]
|
||||||
* description: The name of the calendar to get events from
|
* description: The name of the calendar to get events from
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: sessionId
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: password
|
* name: password
|
||||||
* schema:
|
* schema:
|
||||||
* type: string
|
* type: string
|
||||||
* description: Password for calendar access (if not using session authentication)
|
* description: The calendar's shared password, for callers with no account
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success - returns iCal file
|
* description: Success - returns iCal file
|
||||||
@@ -365,10 +385,7 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
try {
|
try {
|
||||||
// Get request params
|
// Get request params
|
||||||
let calendarName: string = req.params.calendar as string ?? '';
|
let calendarName: string = req.params.calendar as string ?? '';
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let password: string = req.query.password as string ?? '';
|
let password: string = req.query.password as string ?? '';
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
if (calendarName.length < 1) {
|
if (calendarName.length < 1) {
|
||||||
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
res.status(400).send({'message': 'Please state the name of the calendar you want events from.'});
|
||||||
@@ -382,7 +399,19 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
let calendarId: number = calendarNames.get(calendarName)!.id;
|
let calendarId: number = calendarNames.get(calendarName)!.id;
|
||||||
|
|
||||||
if (! await CredentialService.hasAccess(calendarName, sessionId, sessionKey, password, ip)) {
|
// Holding the calendar's shared password, or signed in. The password path
|
||||||
|
// is what keeps iCal subscriptions working - a calendar client cannot
|
||||||
|
// send a cookie.
|
||||||
|
//
|
||||||
|
// The password is checked FIRST so that `public`, which needs no
|
||||||
|
// credential at all, short-circuits before signedInEditor runs. Otherwise
|
||||||
|
// every request from a browser that happens to hold a .nachklang.art
|
||||||
|
// cookie - which is any signed-in user on any of the four apps - would put
|
||||||
|
// an admin-database query in front of the anonymous public feed, with no
|
||||||
|
// timeout. Both operands are side-effect free, so the order is free to
|
||||||
|
// choose; this order is the one that keeps the public calendar
|
||||||
|
// independent of the admin database.
|
||||||
|
if (! await CredentialService.hasAccess(calendarName, password) && !await signedInEditor(req)) {
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -395,7 +424,12 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
let file = await iCalService.convertToIcal(events);
|
let file = await iCalService.convertToIcal(events);
|
||||||
|
|
||||||
// Send the ical file back
|
// Send the ical file back
|
||||||
res.set({'Content-Disposition': 'attachment; filename=' + fileName + '.ics'});
|
// text/calendar, not the text/html that send() infers from a string - calendar apps
|
||||||
|
// coped with the wrong type, but it was wrong (RFC 5545 §8.1).
|
||||||
|
res.set({
|
||||||
|
'Content-Type': 'text/calendar; charset=utf-8',
|
||||||
|
'Content-Disposition': 'attachment; filename=' + fileName + '.ics'
|
||||||
|
});
|
||||||
res.status(200).send(file);
|
res.status(200).send(file);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
let errorGuid = Guid.create().toString();
|
let errorGuid = Guid.create().toString();
|
||||||
@@ -408,27 +442,69 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /calendar/events/subscriptions:
|
||||||
|
* get:
|
||||||
|
* summary: The iCal subscription URL of every calendar
|
||||||
|
* description: >
|
||||||
|
* Ready-to-use iCal URLs for each calendar, with the calendar's shared password
|
||||||
|
* already in the query string where it needs one - for the calendar app's
|
||||||
|
* "Abonnieren" dialog. A calendar whose password is not configured is left out
|
||||||
|
* rather than listed with a URL that cannot work. Requires a signed-in account
|
||||||
|
* with the calendar permission: those editors can read every event anyway, so the
|
||||||
|
* passwords tell them nothing new. Never cached.
|
||||||
|
* tags:
|
||||||
|
* - calendar
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: array
|
||||||
|
* items:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* calendar:
|
||||||
|
* type: string
|
||||||
|
* example: members
|
||||||
|
* icalUrl:
|
||||||
|
* type: string
|
||||||
|
* example: https://api.nachklang.art/calendar/events/members/ical?password=…
|
||||||
|
* 401:
|
||||||
|
* description: Unauthorized - not signed in
|
||||||
|
* 403:
|
||||||
|
* description: Forbidden - the account lacks the calendar permission
|
||||||
|
*/
|
||||||
|
eventsRouter.get('/subscriptions', requireCalendarAccess, (req: Request, res: Response) => {
|
||||||
|
const base = API_BASE_URL.replace(/\/+$/, '');
|
||||||
|
const subscriptions = Array.from(calendarNames.keys()).flatMap((calendar) => {
|
||||||
|
const url = `${base}/calendar/events/${calendar}/ical`;
|
||||||
|
if (calendar === 'public') {
|
||||||
|
return [{calendar, icalUrl: url}];
|
||||||
|
}
|
||||||
|
const password = CredentialService.credentialFor(calendar);
|
||||||
|
return password ? [{calendar, icalUrl: `${url}?password=${encodeURIComponent(password)}`}] : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
// These URLs carry the shared passwords; keep them out of every cache on the way.
|
||||||
|
res.set('Cache-Control', 'no-store');
|
||||||
|
res.status(200).send(subscriptions);
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /calendar/events:
|
* /calendar/events:
|
||||||
* post:
|
* post:
|
||||||
* summary: Create a new event
|
* summary: Create a new event
|
||||||
* description: Creates a new event in the specified calendar. Authentication required.
|
* description: Creates a new event. Requires a signed-in account with the calendar permission.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
* parameters:
|
* security:
|
||||||
* - in: query
|
* - AdminSessionCookie: []
|
||||||
* name: sessionId
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -495,16 +571,32 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: Required parameters missing
|
* example: Required parameters missing
|
||||||
* 403:
|
* 401:
|
||||||
* description: Forbidden - no access to create events
|
* description: Unauthorized - not signed in
|
||||||
* content:
|
* content:
|
||||||
* application/json:
|
* application/json:
|
||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: UNAUTHORIZED
|
||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: You do not have access to the specified calendar.
|
* example: Anmeldung erforderlich.
|
||||||
|
* 403:
|
||||||
|
* description: Forbidden - the account lacks the calendar permission
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: FORBIDDEN
|
||||||
|
* message:
|
||||||
|
* type: string
|
||||||
|
* example: "Für diesen Bereich fehlt dir die Berechtigung."
|
||||||
* 500:
|
* 500:
|
||||||
* description: Server error
|
* description: Server error
|
||||||
* content:
|
* content:
|
||||||
@@ -522,19 +614,9 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => {
|
|||||||
* type: string
|
* type: string
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
||||||
*/
|
*/
|
||||||
eventsRouter.post('/', async (req: Request, res: Response) => {
|
eventsRouter.post('/', requireCalendarAccess, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
// Get params
|
const admin = adminOf(res);
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
if (!user?.isActive) {
|
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
req.body.calendarId === undefined ||
|
req.body.calendarId === undefined ||
|
||||||
@@ -556,7 +638,9 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
endDateTime: new Date(req.body.endDateTime),
|
endDateTime: new Date(req.body.endDateTime),
|
||||||
createdDate: new Date(),
|
createdDate: new Date(),
|
||||||
location: req.body.location ?? '',
|
location: req.body.location ?? '',
|
||||||
createdById: user.userId ?? -1,
|
// LEGACY createdById is deliberately not set: there is no calendar
|
||||||
|
// user id any more, and migration 003 made the column nullable.
|
||||||
|
createdByUserId: admin.id,
|
||||||
url: req.body.url ?? '',
|
url: req.body.url ?? '',
|
||||||
wholeDay: req.body.wholeDay ?? false,
|
wholeDay: req.body.wholeDay ?? false,
|
||||||
repeatFrequency: req.body.repeatFrequency ?? '',
|
repeatFrequency: req.body.repeatFrequency ?? '',
|
||||||
@@ -585,9 +669,11 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* /calendar/events/{eventId}:
|
* /calendar/events/{eventId}:
|
||||||
* put:
|
* put:
|
||||||
* summary: Update an existing event
|
* summary: Update an existing event
|
||||||
* description: Updates an existing event with the provided data. Authentication required.
|
* description: Updates an existing event. Requires a signed-in account with the calendar permission.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
@@ -595,18 +681,6 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* schema:
|
* schema:
|
||||||
* type: integer
|
* type: integer
|
||||||
* description: The ID of the event to update
|
* description: The ID of the event to update
|
||||||
* - in: query
|
|
||||||
* name: sessionId
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -639,9 +713,6 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* location:
|
* location:
|
||||||
* type: string
|
* type: string
|
||||||
* example: "Musikhochschule, Karlsruhe"
|
* example: "Musikhochschule, Karlsruhe"
|
||||||
* createdBy:
|
|
||||||
* type: string
|
|
||||||
* example: "John Doe"
|
|
||||||
* url:
|
* url:
|
||||||
* type: string
|
* type: string
|
||||||
* example: "https://www.nachklang.art/events/concert"
|
* example: "https://www.nachklang.art/events/concert"
|
||||||
@@ -673,16 +744,32 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: Required parameters missing
|
* example: Required parameters missing
|
||||||
* 403:
|
* 401:
|
||||||
* description: Forbidden - no access to update events
|
* description: Unauthorized - not signed in
|
||||||
* content:
|
* content:
|
||||||
* application/json:
|
* application/json:
|
||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: UNAUTHORIZED
|
||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: You do not have access to the specified calendar.
|
* example: Anmeldung erforderlich.
|
||||||
|
* 403:
|
||||||
|
* description: Forbidden - the account lacks the calendar permission
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: FORBIDDEN
|
||||||
|
* message:
|
||||||
|
* type: string
|
||||||
|
* example: "Für diesen Bereich fehlt dir die Berechtigung."
|
||||||
* 500:
|
* 500:
|
||||||
* description: Server error
|
* description: Server error
|
||||||
* content:
|
* content:
|
||||||
@@ -700,19 +787,9 @@ eventsRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* type: string
|
* type: string
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
||||||
*/
|
*/
|
||||||
eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
eventsRouter.put('/:eventId', requireCalendarAccess, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
// Get params
|
const admin = adminOf(res);
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
if (!user?.isActive) {
|
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
req.params.eventId === undefined ||
|
req.params.eventId === undefined ||
|
||||||
@@ -735,8 +812,9 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
endDateTime: new Date(req.body.endDateTime),
|
endDateTime: new Date(req.body.endDateTime),
|
||||||
createdDate: new Date(),
|
createdDate: new Date(),
|
||||||
location: req.body.location ?? '',
|
location: req.body.location ?? '',
|
||||||
createdBy: req.body.createdBy ?? '',
|
// LEGACY createdById is deliberately not set: there is no calendar
|
||||||
createdById: user.userId ?? -1,
|
// user id any more, and migration 003 made the column nullable.
|
||||||
|
createdByUserId: admin.id,
|
||||||
url: req.body.url ?? '',
|
url: req.body.url ?? '',
|
||||||
wholeDay: req.body.wholeDay ?? false,
|
wholeDay: req.body.wholeDay ?? false,
|
||||||
repeatFrequency: req.body.repeatFrequency ?? '',
|
repeatFrequency: req.body.repeatFrequency ?? '',
|
||||||
@@ -768,9 +846,11 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* /calendar/events/move/{eventId}:
|
* /calendar/events/move/{eventId}:
|
||||||
* put:
|
* put:
|
||||||
* summary: Move an event to a different calendar
|
* summary: Move an event to a different calendar
|
||||||
* description: Moves an existing event to a different calendar. Authentication required.
|
* description: Moves an event to a different calendar. Requires a signed-in account with the calendar permission.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
@@ -778,18 +858,6 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* schema:
|
* schema:
|
||||||
* type: integer
|
* type: integer
|
||||||
* description: The ID of the event to move
|
* description: The ID of the event to move
|
||||||
* - in: query
|
|
||||||
* name: sessionId
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -820,9 +888,6 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* location:
|
* location:
|
||||||
* type: string
|
* type: string
|
||||||
* example: "Musikhochschule, Karlsruhe"
|
* example: "Musikhochschule, Karlsruhe"
|
||||||
* createdBy:
|
|
||||||
* type: string
|
|
||||||
* example: "John Doe"
|
|
||||||
* url:
|
* url:
|
||||||
* type: string
|
* type: string
|
||||||
* example: "https://www.nachklang.art/events/concert"
|
* example: "https://www.nachklang.art/events/concert"
|
||||||
@@ -854,16 +919,32 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: Required parameters missing
|
* example: Required parameters missing
|
||||||
* 403:
|
* 401:
|
||||||
* description: Forbidden - no access to move events
|
* description: Unauthorized - not signed in
|
||||||
* content:
|
* content:
|
||||||
* application/json:
|
* application/json:
|
||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: UNAUTHORIZED
|
||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: You do not have access to the specified calendar.
|
* example: Anmeldung erforderlich.
|
||||||
|
* 403:
|
||||||
|
* description: Forbidden - the account lacks the calendar permission
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: FORBIDDEN
|
||||||
|
* message:
|
||||||
|
* type: string
|
||||||
|
* example: "Für diesen Bereich fehlt dir die Berechtigung."
|
||||||
* 500:
|
* 500:
|
||||||
* description: Server error
|
* description: Server error
|
||||||
* content:
|
* content:
|
||||||
@@ -881,19 +962,9 @@ eventsRouter.put('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* type: string
|
* type: string
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
||||||
*/
|
*/
|
||||||
eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
eventsRouter.put('/move/:eventId', requireCalendarAccess, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
// Get params
|
const admin = adminOf(res);
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
if (!user?.isActive) {
|
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
req.params.eventId === undefined ||
|
req.params.eventId === undefined ||
|
||||||
@@ -913,8 +984,9 @@ eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
|||||||
endDateTime: new Date(req.body.endDateTime),
|
endDateTime: new Date(req.body.endDateTime),
|
||||||
createdDate: new Date(),
|
createdDate: new Date(),
|
||||||
location: req.body.location ?? '',
|
location: req.body.location ?? '',
|
||||||
createdBy: req.body.createdBy ?? '',
|
// LEGACY createdById is deliberately not set: there is no calendar
|
||||||
createdById: user.userId ?? -1,
|
// user id any more, and migration 003 made the column nullable.
|
||||||
|
createdByUserId: admin.id,
|
||||||
url: req.body.url ?? '',
|
url: req.body.url ?? '',
|
||||||
wholeDay: req.body.wholeDay ?? false,
|
wholeDay: req.body.wholeDay ?? false,
|
||||||
repeatFrequency: req.body.repeatFrequency ?? '',
|
repeatFrequency: req.body.repeatFrequency ?? '',
|
||||||
@@ -944,9 +1016,11 @@ eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
|||||||
* /calendar/events/{eventId}:
|
* /calendar/events/{eventId}:
|
||||||
* delete:
|
* delete:
|
||||||
* summary: Delete an event
|
* summary: Delete an event
|
||||||
* description: Deletes an existing event. Authentication required.
|
* description: Deletes an event. Requires a signed-in account with the calendar permission.
|
||||||
* tags:
|
* tags:
|
||||||
* - calendar
|
* - calendar
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
@@ -954,18 +1028,6 @@ eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
|||||||
* schema:
|
* schema:
|
||||||
* type: integer
|
* type: integer
|
||||||
* description: The ID of the event to delete
|
* description: The ID of the event to delete
|
||||||
* - in: query
|
|
||||||
* name: sessionId
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session ID for authentication
|
|
||||||
* - in: query
|
|
||||||
* name: sessionKey
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: Session key for authentication
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Event deleted successfully
|
* description: Event deleted successfully
|
||||||
@@ -987,16 +1049,32 @@ eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
|||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: Required parameters missing
|
* example: Required parameters missing
|
||||||
* 403:
|
* 401:
|
||||||
* description: Forbidden - no access to delete events
|
* description: Unauthorized - not signed in
|
||||||
* content:
|
* content:
|
||||||
* application/json:
|
* application/json:
|
||||||
* schema:
|
* schema:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: UNAUTHORIZED
|
||||||
* message:
|
* message:
|
||||||
* type: string
|
* type: string
|
||||||
* example: You do not have access to the specified calendar.
|
* example: Anmeldung erforderlich.
|
||||||
|
* 403:
|
||||||
|
* description: Forbidden - the account lacks the calendar permission
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* status:
|
||||||
|
* type: string
|
||||||
|
* example: FORBIDDEN
|
||||||
|
* message:
|
||||||
|
* type: string
|
||||||
|
* example: "Für diesen Bereich fehlt dir die Berechtigung."
|
||||||
* 500:
|
* 500:
|
||||||
* description: Server error
|
* description: Server error
|
||||||
* content:
|
* content:
|
||||||
@@ -1014,19 +1092,9 @@ eventsRouter.put('/move/:eventId', async (req: Request, res: Response) => {
|
|||||||
* type: string
|
* type: string
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
||||||
*/
|
*/
|
||||||
eventsRouter.delete('/:eventId', async (req: Request, res: Response) => {
|
eventsRouter.delete('/:eventId', requireCalendarAccess, async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
// Get params
|
const admin = adminOf(res);
|
||||||
let sessionId: string = req.query.sessionId as string ?? '';
|
|
||||||
let sessionKey: string = req.query.sessionKey as string ?? '';
|
|
||||||
let ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
let user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
if (!user?.isActive) {
|
|
||||||
res.status(403).send({'message': 'You do not have access to the specified calendar.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
req.params.eventId === undefined
|
req.params.eventId === undefined
|
||||||
@@ -1046,7 +1114,9 @@ eventsRouter.delete('/:eventId', async (req: Request, res: Response) => {
|
|||||||
createdDate: new Date(),
|
createdDate: new Date(),
|
||||||
location: '',
|
location: '',
|
||||||
createdBy: '',
|
createdBy: '',
|
||||||
createdById: user.userId ?? -1,
|
// LEGACY createdById is deliberately not set: there is no calendar
|
||||||
|
// user id any more, and migration 003 made the column nullable.
|
||||||
|
createdByUserId: admin.id,
|
||||||
url: '',
|
url: '',
|
||||||
wholeDay: false,
|
wholeDay: false,
|
||||||
repeatFrequency: '',
|
repeatFrequency: '',
|
||||||
|
|||||||
@@ -2,28 +2,42 @@ import * as dotenv from 'dotenv';
|
|||||||
import {Guid} from 'guid-typescript';
|
import {Guid} from 'guid-typescript';
|
||||||
import {Event} from './event.interface.js';
|
import {Event} from './event.interface.js';
|
||||||
import {NachklangCalendarDB} from '../Calendar.db.js';
|
import {NachklangCalendarDB} from '../Calendar.db.js';
|
||||||
|
import * as AdminUsersService from '../../admin/users/users.admin.service.js';
|
||||||
|
import logger from '../../../middleware/logger.js';
|
||||||
|
|
||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all events for the given calendar
|
* How an event's creator is resolved, after step 5 of
|
||||||
* @param calendarId The calendar Id
|
* docs/calendar-auth-migration.md removed the legacy path.
|
||||||
|
*
|
||||||
|
* The creator is only ever rendered as a name - nothing authorises on it, there
|
||||||
|
* is no "only the creator may edit" rule anywhere - which is why an unresolvable
|
||||||
|
* one degrades to blank rather than to an error.
|
||||||
|
*
|
||||||
|
* Two sources remain, weaker first:
|
||||||
|
*
|
||||||
|
* 1. `created_by_name`, a snapshot of the name as it stood when the calendar
|
||||||
|
* had its own `users` table. Migration 002 took it, migration 004 dropped
|
||||||
|
* the table it was taken from, and nothing has written it since. It exists
|
||||||
|
* so the authorship of pre-cutover events survived that removal.
|
||||||
|
* 2. The admin module's `user.name`, looked up live for rows carrying an admin
|
||||||
|
* id. It wins, because it is the only one that follows a rename.
|
||||||
|
*
|
||||||
|
* The third source - joining the calendar's own `users` table on
|
||||||
|
* `created_by_id` - is gone with the table and the column.
|
||||||
*/
|
*/
|
||||||
export const getAllEvents = async (calendarId: number): Promise<Event[]> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
let eventRows: Event[] = [];
|
|
||||||
try {
|
|
||||||
const calendarQuery = 'SELECT calendar_id, includes_calendars FROM calendars WHERE calendar_id = ?';
|
|
||||||
const calendarRes = await conn.query(calendarQuery, calendarId);
|
|
||||||
let calendarsToFetch: number[] = [calendarId];
|
|
||||||
for(let row of calendarRes) {
|
|
||||||
let includes: number[] = JSON.parse(row.includes_calendars);
|
|
||||||
calendarsToFetch = [...calendarsToFetch, ...includes];
|
|
||||||
}
|
|
||||||
|
|
||||||
const eventsQuery = `
|
/**
|
||||||
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_id, u.full_name as created_by_name, u2.full_name as last_modified_by_name, v.* FROM events e
|
* The one SELECT the four read paths share; callers append their own WHERE and
|
||||||
|
* ORDER BY. `v.*` carries the version row's own creator columns, so only the
|
||||||
|
* `events` columns need naming.
|
||||||
|
*
|
||||||
|
* There are no joins to a users table any more. There is no users table.
|
||||||
|
*/
|
||||||
|
const EVENT_SELECT = `
|
||||||
|
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_user_id, e.created_by_name, v.* FROM events e
|
||||||
INNER JOIN (
|
INNER JOIN (
|
||||||
SELECT event_id, MAX(event_version_id) AS latest_version
|
SELECT event_id, MAX(event_version_id) AS latest_version
|
||||||
FROM event_versions
|
FROM event_versions
|
||||||
@@ -31,36 +45,120 @@ export const getAllEvents = async (calendarId: number): Promise<Event[]> => {
|
|||||||
) latest_versions
|
) latest_versions
|
||||||
ON e.event_id = latest_versions.event_id
|
ON e.event_id = latest_versions.event_id
|
||||||
INNER JOIN event_versions v
|
INNER JOIN event_versions v
|
||||||
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version
|
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version`;
|
||||||
LEFT OUTER JOIN users u ON u.user_id = e.created_by_id
|
|
||||||
LEFT OUTER JOIN users u2 ON u2.user_id = v.version_created_by_id
|
|
||||||
WHERE e.calendar_id IN (?) AND v.status = 'PUBLIC'
|
|
||||||
ORDER BY e.event_id`;
|
|
||||||
const eventsRes = await conn.query(eventsQuery, [calendarsToFetch]);
|
|
||||||
|
|
||||||
for (let row of eventsRes) {
|
/**
|
||||||
eventRows.push({
|
* Maps a result row to an Event. `status` is included only where it always
|
||||||
eventId: row.event_id,
|
* was: the admin views and the by-id lookup return it, the two public listings
|
||||||
calendarId: row.calendar_id,
|
* do not.
|
||||||
uuid: row.uuid,
|
*/
|
||||||
name: row.name,
|
const toEvent = (row: any, includeStatus: boolean): Event => {
|
||||||
description: row.description,
|
const event: Event = {
|
||||||
startDateTime: row.start_datetime,
|
eventId: row.event_id,
|
||||||
endDateTime: row.end_datetime,
|
calendarId: row.calendar_id,
|
||||||
createdDate: row.created_date,
|
uuid: row.uuid,
|
||||||
lastModifiedDate: row.version_created_at,
|
name: row.name,
|
||||||
location: row.location,
|
description: row.description,
|
||||||
createdBy: row.created_by_name,
|
startDateTime: row.start_datetime,
|
||||||
createdById: row.created_by_id,
|
endDateTime: row.end_datetime,
|
||||||
lastModifiedBy: row.last_modified_by_name,
|
createdDate: row.created_date,
|
||||||
lastModifiedById: row.version_created_by_id,
|
lastModifiedDate: row.version_created_at,
|
||||||
url: row.url,
|
location: row.location,
|
||||||
wholeDay: row.whole_day,
|
// The archived name. resolveAdminNames below overwrites it for rows that
|
||||||
repeatFrequency: row.repeat_frequency
|
// carry an admin id, which is the only source that follows a rename.
|
||||||
});
|
createdBy: row.created_by_name,
|
||||||
|
createdByUserId: row.created_by_user_id ?? null,
|
||||||
|
lastModifiedBy: row.version_created_by_name,
|
||||||
|
lastModifiedByUserId: row.version_created_by_user_id ?? null,
|
||||||
|
url: row.url,
|
||||||
|
wholeDay: row.whole_day,
|
||||||
|
repeatFrequency: row.repeat_frequency
|
||||||
|
};
|
||||||
|
|
||||||
|
if (includeStatus) {
|
||||||
|
event.status = row.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
return event;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fills in creator/editor names for rows that carry an admin user id, by way
|
||||||
|
* of a single lookup against the admin database. The calendar cannot join
|
||||||
|
* against `user` - it is a different schema behind a different pool - and
|
||||||
|
* making it one would tie the two schemas together as tightly as a foreign key
|
||||||
|
* would.
|
||||||
|
*
|
||||||
|
* A failure here is swallowed on purpose. These endpoints include the public
|
||||||
|
* calendar the website reads anonymously, and a name is decoration: if the
|
||||||
|
* admin database is unreachable, an event should still render with whatever
|
||||||
|
* the snapshot holds rather than 500 the whole listing. The alternative
|
||||||
|
* would widen the public calendar's blast radius to include the admin
|
||||||
|
* database, which it has never depended on before.
|
||||||
|
*/
|
||||||
|
const resolveAdminNames = async (events: Event[]): Promise<void> => {
|
||||||
|
const ids = events
|
||||||
|
.flatMap(event => [event.createdByUserId, event.lastModifiedByUserId])
|
||||||
|
.filter((id): id is string => Boolean(id));
|
||||||
|
|
||||||
|
if (ids.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let names: Map<string, string>;
|
||||||
|
try {
|
||||||
|
names = await AdminUsersService.findDisplayNames(ids);
|
||||||
|
} catch (e: any) {
|
||||||
|
logger.warn('Calendar: could not resolve creator names from the admin database: ' + e.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const event of events) {
|
||||||
|
const createdBy = event.createdByUserId ? names.get(event.createdByUserId) : undefined;
|
||||||
|
if (createdBy) {
|
||||||
|
event.createdBy = createdBy;
|
||||||
}
|
}
|
||||||
|
|
||||||
return eventRows;
|
const lastModifiedBy = event.lastModifiedByUserId ? names.get(event.lastModifiedByUserId) : undefined;
|
||||||
|
if (lastModifiedBy) {
|
||||||
|
event.lastModifiedBy = lastModifiedBy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The calendars a listing has to cover: the requested one plus whatever it
|
||||||
|
* declares in `includes_calendars`.
|
||||||
|
*/
|
||||||
|
const calendarsToFetch = async (conn: any, calendarId: number): Promise<number[]> => {
|
||||||
|
const calendarQuery = 'SELECT calendar_id, includes_calendars FROM calendars WHERE calendar_id = ?';
|
||||||
|
const calendarRes = await conn.query(calendarQuery, calendarId);
|
||||||
|
let calendars: number[] = [calendarId];
|
||||||
|
for (let row of calendarRes) {
|
||||||
|
let includes: number[] = JSON.parse(row.includes_calendars);
|
||||||
|
calendars = [...calendars, ...includes];
|
||||||
|
}
|
||||||
|
return calendars;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns all events for the given calendar
|
||||||
|
* @param calendarId The calendar Id
|
||||||
|
*/
|
||||||
|
export const getAllEvents = async (calendarId: number): Promise<Event[]> => {
|
||||||
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
|
try {
|
||||||
|
const calendars = await calendarsToFetch(conn, calendarId);
|
||||||
|
|
||||||
|
const eventsQuery = `${EVENT_SELECT}
|
||||||
|
WHERE e.calendar_id IN (?) AND v.status = 'PUBLIC'
|
||||||
|
ORDER BY e.event_id`;
|
||||||
|
const eventsRes = await conn.query(eventsQuery, [calendars]);
|
||||||
|
|
||||||
|
const events = eventsRes.map((row: any) => toEvent(row, false));
|
||||||
|
await resolveAdminNames(events);
|
||||||
|
|
||||||
|
return events;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -76,48 +174,16 @@ export const getAllEvents = async (calendarId: number): Promise<Event[]> => {
|
|||||||
*/
|
*/
|
||||||
export const getAllEventsAdmin = async (calendarId: number): Promise<Event[]> => {
|
export const getAllEventsAdmin = async (calendarId: number): Promise<Event[]> => {
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
let eventRows: Event[] = [];
|
|
||||||
try {
|
try {
|
||||||
const eventsQuery = `
|
const eventsQuery = `${EVENT_SELECT}
|
||||||
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_id, u.full_name as created_by_name, u2.full_name as last_modified_by_name, v.* FROM events e
|
|
||||||
INNER JOIN (
|
|
||||||
SELECT event_id, MAX(event_version_id) AS latest_version
|
|
||||||
FROM event_versions
|
|
||||||
GROUP BY event_id
|
|
||||||
) latest_versions
|
|
||||||
ON e.event_id = latest_versions.event_id
|
|
||||||
INNER JOIN event_versions v
|
|
||||||
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version
|
|
||||||
LEFT OUTER JOIN users u ON u.user_id = e.created_by_id
|
|
||||||
LEFT OUTER JOIN users u2 ON u2.user_id = v.version_created_by_id
|
|
||||||
WHERE e.calendar_id = ?
|
WHERE e.calendar_id = ?
|
||||||
ORDER BY e.event_id`;
|
ORDER BY e.event_id`;
|
||||||
const eventsRes = await conn.query(eventsQuery, calendarId);
|
const eventsRes = await conn.query(eventsQuery, calendarId);
|
||||||
|
|
||||||
for (let row of eventsRes) {
|
const events = eventsRes.map((row: any) => toEvent(row, true));
|
||||||
eventRows.push({
|
await resolveAdminNames(events);
|
||||||
eventId: row.event_id,
|
|
||||||
calendarId: row.calendar_id,
|
|
||||||
uuid: row.uuid,
|
|
||||||
name: row.name,
|
|
||||||
description: row.description,
|
|
||||||
startDateTime: row.start_datetime,
|
|
||||||
endDateTime: row.end_datetime,
|
|
||||||
createdDate: row.created_date,
|
|
||||||
lastModifiedDate: row.version_created_at,
|
|
||||||
location: row.location,
|
|
||||||
createdBy: row.created_by_name,
|
|
||||||
createdById: row.created_by_id,
|
|
||||||
lastModifiedBy: row.last_modified_by_name,
|
|
||||||
lastModifiedById: row.version_created_by_id,
|
|
||||||
url: row.url,
|
|
||||||
wholeDay: row.whole_day,
|
|
||||||
repeatFrequency: row.repeat_frequency,
|
|
||||||
status: row.status
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return eventRows;
|
return events;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -136,18 +202,7 @@ export const getAllEventsAdmin = async (calendarId: number): Promise<Event[]> =>
|
|||||||
export const getEventById = async (eventId: number): Promise<Event | null> => {
|
export const getEventById = async (eventId: number): Promise<Event | null> => {
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
try {
|
try {
|
||||||
const eventsQuery = `
|
const eventsQuery = `${EVENT_SELECT}
|
||||||
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_id, u.full_name as created_by_name, u2.full_name as last_modified_by_name, v.* FROM events e
|
|
||||||
INNER JOIN (
|
|
||||||
SELECT event_id, MAX(event_version_id) AS latest_version
|
|
||||||
FROM event_versions
|
|
||||||
GROUP BY event_id
|
|
||||||
) latest_versions
|
|
||||||
ON e.event_id = latest_versions.event_id
|
|
||||||
INNER JOIN event_versions v
|
|
||||||
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version
|
|
||||||
LEFT OUTER JOIN users u ON u.user_id = e.created_by_id
|
|
||||||
LEFT OUTER JOIN users u2 ON u2.user_id = v.version_created_by_id
|
|
||||||
WHERE e.event_id = ?`;
|
WHERE e.event_id = ?`;
|
||||||
const eventsRes = await conn.query(eventsQuery, eventId);
|
const eventsRes = await conn.query(eventsQuery, eventId);
|
||||||
|
|
||||||
@@ -155,27 +210,10 @@ export const getEventById = async (eventId: number): Promise<Event | null> => {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const row = eventsRes[0];
|
const event = toEvent(eventsRes[0], true);
|
||||||
return {
|
await resolveAdminNames([event]);
|
||||||
eventId: row.event_id,
|
|
||||||
calendarId: row.calendar_id,
|
return event;
|
||||||
uuid: row.uuid,
|
|
||||||
name: row.name,
|
|
||||||
description: row.description,
|
|
||||||
startDateTime: row.start_datetime,
|
|
||||||
endDateTime: row.end_datetime,
|
|
||||||
createdDate: row.created_date,
|
|
||||||
lastModifiedDate: row.version_created_at,
|
|
||||||
location: row.location,
|
|
||||||
createdBy: row.created_by_name,
|
|
||||||
createdById: row.created_by_id,
|
|
||||||
lastModifiedBy: row.last_modified_by_name,
|
|
||||||
lastModifiedById: row.version_created_by_id,
|
|
||||||
url: row.url,
|
|
||||||
wholeDay: row.whole_day,
|
|
||||||
repeatFrequency: row.repeat_frequency,
|
|
||||||
status: row.status
|
|
||||||
} as Event;
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -193,11 +231,11 @@ export const createEvent = async (event: Event): Promise<number> => {
|
|||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
let eventUUID = Guid.create().toString();
|
let eventUUID = Guid.create().toString();
|
||||||
const eventsQuery = 'INSERT INTO events (calendar_id, uuid, created_by_id) VALUES (?,?,?) RETURNING event_id';
|
const eventsQuery = 'INSERT INTO events (calendar_id, uuid, created_by_user_id) VALUES (?,?,?) RETURNING event_id';
|
||||||
const eventsRes = await conn.execute(eventsQuery, [event.calendarId, eventUUID, event.createdById]);
|
const eventsRes = await conn.execute(eventsQuery, [event.calendarId, eventUUID, event.createdByUserId ?? null]);
|
||||||
|
|
||||||
const versionQuery = 'INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, repeat_frequency, location, url, status, version_created_by_id) VALUES (?,?,?,?,?,?,?,?,?,?,?);'
|
const versionQuery = 'INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, repeat_frequency, location, url, status, version_created_by_user_id) VALUES (?,?,?,?,?,?,?,?,?,?,?);'
|
||||||
await conn.execute(versionQuery, [eventsRes[0].event_id, event.name, event.description, event.startDateTime, event.endDateTime, event.wholeDay, event.repeatFrequency, event.location, event.url, event.status, event.createdById]);
|
await conn.execute(versionQuery, [eventsRes[0].event_id, event.name, event.description, event.startDateTime, event.endDateTime, event.wholeDay, event.repeatFrequency, event.location, event.url, event.status, event.createdByUserId ?? null]);
|
||||||
|
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
@@ -218,8 +256,8 @@ export const updateEvent = async (event: Event): Promise<number> => {
|
|||||||
let conn = await NachklangCalendarDB.getConnection();
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
const versionQuery = 'INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, repeat_frequency, location, url, status, version_created_by_id) VALUES (?,?,?,?,?,?,?,?,?,?,?);'
|
const versionQuery = 'INSERT INTO event_versions (event_id, name, description, start_datetime, end_datetime, whole_day, repeat_frequency, location, url, status, version_created_by_user_id) VALUES (?,?,?,?,?,?,?,?,?,?,?);'
|
||||||
const versionRes = await conn.execute(versionQuery, [event.eventId, event.name, event.description, event.startDateTime, event.endDateTime, event.wholeDay, event.repeatFrequency, event.location, event.url, event.status, event.createdById]);
|
const versionRes = await conn.execute(versionQuery, [event.eventId, event.name, event.description, event.startDateTime, event.endDateTime, event.wholeDay, event.repeatFrequency, event.location, event.url, event.status, event.createdByUserId ?? null]);
|
||||||
|
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
@@ -240,8 +278,8 @@ export const deleteEvent = async (event: Event): Promise<boolean> => {
|
|||||||
let conn = await NachklangCalendarDB.getConnection();
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
const versionQuery = 'INSERT INTO event_versions (event_id, status, version_created_by_id) VALUES (?,?,?);'
|
const versionQuery = 'INSERT INTO event_versions (event_id, status, version_created_by_user_id) VALUES (?,?,?);'
|
||||||
const versionRes = await conn.execute(versionQuery, [event.eventId, 'DELETED', event.createdById]);
|
const versionRes = await conn.execute(versionQuery, [event.eventId, 'DELETED', event.createdByUserId ?? null]);
|
||||||
|
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
|
|
||||||
@@ -283,56 +321,23 @@ export const moveEvent = async (event: Event): Promise<boolean> => {
|
|||||||
export const getNextUpcomingEvent = async (calendarId: number): Promise<Event | null> => {
|
export const getNextUpcomingEvent = async (calendarId: number): Promise<Event | null> => {
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
let conn = await NachklangCalendarDB.getConnection();
|
||||||
try {
|
try {
|
||||||
const calendarQuery = 'SELECT calendar_id, includes_calendars FROM calendars WHERE calendar_id = ?';
|
const calendars = await calendarsToFetch(conn, calendarId);
|
||||||
const calendarRes = await conn.query(calendarQuery, calendarId);
|
|
||||||
let calendarsToFetch: number[] = [calendarId];
|
|
||||||
for(let row of calendarRes) {
|
|
||||||
let includes: number[] = JSON.parse(row.includes_calendars);
|
|
||||||
calendarsToFetch = [...calendarsToFetch, ...includes];
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const eventsQuery = `
|
const eventsQuery = `${EVENT_SELECT}
|
||||||
SELECT e.calendar_id, e.uuid, e.created_date, e.created_by_id, u.full_name as created_by_name, u2.full_name as last_modified_by_name, v.* FROM events e
|
|
||||||
INNER JOIN (
|
|
||||||
SELECT event_id, MAX(event_version_id) AS latest_version
|
|
||||||
FROM event_versions
|
|
||||||
GROUP BY event_id
|
|
||||||
) latest_versions
|
|
||||||
ON e.event_id = latest_versions.event_id
|
|
||||||
INNER JOIN event_versions v
|
|
||||||
ON v.event_id = latest_versions.event_id AND v.event_version_id = latest_versions.latest_version
|
|
||||||
LEFT OUTER JOIN users u ON u.user_id = e.created_by_id
|
|
||||||
LEFT OUTER JOIN users u2 ON u2.user_id = v.version_created_by_id
|
|
||||||
WHERE e.calendar_id IN (?) AND v.status = 'PUBLIC' AND v.start_datetime > ?
|
WHERE e.calendar_id IN (?) AND v.status = 'PUBLIC' AND v.start_datetime > ?
|
||||||
ORDER BY v.start_datetime ASC
|
ORDER BY v.start_datetime ASC
|
||||||
LIMIT 1`;
|
LIMIT 1`;
|
||||||
const eventsRes = await conn.query(eventsQuery, [calendarsToFetch, now]);
|
const eventsRes = await conn.query(eventsQuery, [calendars, now]);
|
||||||
|
|
||||||
if (eventsRes.length === 0) {
|
if (eventsRes.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const row = eventsRes[0];
|
const event = toEvent(eventsRes[0], false);
|
||||||
return {
|
await resolveAdminNames([event]);
|
||||||
eventId: row.event_id,
|
|
||||||
calendarId: row.calendar_id,
|
return event;
|
||||||
uuid: row.uuid,
|
|
||||||
name: row.name,
|
|
||||||
description: row.description,
|
|
||||||
startDateTime: row.start_datetime,
|
|
||||||
endDateTime: row.end_datetime,
|
|
||||||
createdDate: row.created_date,
|
|
||||||
lastModifiedDate: row.version_created_at,
|
|
||||||
location: row.location,
|
|
||||||
createdBy: row.created_by_name,
|
|
||||||
createdById: row.created_by_id,
|
|
||||||
lastModifiedBy: row.last_modified_by_name,
|
|
||||||
lastModifiedById: row.version_created_by_id,
|
|
||||||
url: row.url,
|
|
||||||
wholeDay: row.whole_day,
|
|
||||||
repeatFrequency: row.repeat_frequency
|
|
||||||
} as Event;
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export const convertToIcal = async (events: Event[]): Promise<string> => {
|
|||||||
addEventToFile(ical, event);
|
addEventToFile(ical, event);
|
||||||
}
|
}
|
||||||
|
|
||||||
return serializeIcalFile(ical);
|
return toContentLines(serializeIcalFile(ical));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
@@ -116,9 +116,11 @@ const addEventToFile = (ical: iCalFile, event: Event) => {
|
|||||||
* @param event
|
* @param event
|
||||||
*/
|
*/
|
||||||
const createIcalEvent = (event: Event): iCalEvent => {
|
const createIcalEvent = (event: Event): iCalEvent => {
|
||||||
let description = event.description ? event.description + '\n' : '';
|
// Free text is escaped (see escapeText); the URL is a URI value, which has
|
||||||
let location = event.location ? event.location + '\n' : '';
|
// no escapes - it only must not break the line.
|
||||||
let url = event.url ? event.url + '\n' : '';
|
let description = event.description ? escapeText(event.description) + '\n' : '';
|
||||||
|
let location = event.location ? escapeText(event.location) + '\n' : '';
|
||||||
|
let url = event.url ? event.url.replace(/[\r\n]+/g, '') + '\n' : '';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
header: 'BEGIN:VEVENT\n',
|
header: 'BEGIN:VEVENT\n',
|
||||||
@@ -128,7 +130,7 @@ const createIcalEvent = (event: Event): iCalEvent => {
|
|||||||
start: formatDate(event.startDateTime, event.wholeDay) + '\n',
|
start: formatDate(event.startDateTime, event.wholeDay) + '\n',
|
||||||
end: formatDate(event.endDateTime, event.wholeDay, true) + '\n',
|
end: formatDate(event.endDateTime, event.wholeDay, true) + '\n',
|
||||||
repeatFrequency: event.repeatFrequency ? event.repeatFrequency + '\n' : '',
|
repeatFrequency: event.repeatFrequency ? event.repeatFrequency + '\n' : '',
|
||||||
summary: event.name + '\n',
|
summary: escapeText(event.name) + '\n',
|
||||||
description: description,
|
description: description,
|
||||||
location: location,
|
location: location,
|
||||||
url: url,
|
url: url,
|
||||||
@@ -143,8 +145,11 @@ const createIcalEvent = (event: Event): iCalEvent => {
|
|||||||
* @param wholeDayFormat
|
* @param wholeDayFormat
|
||||||
* @param isEndDate
|
* @param isEndDate
|
||||||
*/
|
*/
|
||||||
const formatDate = (date: Date, wholeDayFormat: boolean = false, isEndDate: boolean = false): string => {
|
const formatDate = (input: Date, wholeDayFormat: boolean = false, isEndDate: boolean = false): string => {
|
||||||
let returnString = '';
|
let returnString = '';
|
||||||
|
// A copy: this used to shift the caller's Date in place, so the event object
|
||||||
|
// came out of the export with its end a day later than it went in.
|
||||||
|
const date = new Date(input);
|
||||||
|
|
||||||
// We need to do this for whole day events as otherwise the event ends one day too early
|
// We need to do this for whole day events as otherwise the event ends one day too early
|
||||||
if(wholeDayFormat && isEndDate) date.setDate(date.getDate() + 1)
|
if(wholeDayFormat && isEndDate) date.setDate(date.getDate() + 1)
|
||||||
@@ -184,6 +189,58 @@ export interface iCalEvent {
|
|||||||
footer: string;
|
footer: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RFC 5545 §3.3.11 TEXT escaping. Without it a description with a line break
|
||||||
|
* ended the DESCRIPTION property early and the rest of the text was read as a
|
||||||
|
* new (garbage) property, and an unescaped `,` or `;` is invalid in the value.
|
||||||
|
* The backslash goes first, or the escapes added after it would be doubled.
|
||||||
|
*/
|
||||||
|
export const escapeText = (value: string): string =>
|
||||||
|
value
|
||||||
|
.replace(/\\/g, '\\\\')
|
||||||
|
.replace(/;/g, '\\;')
|
||||||
|
.replace(/,/g, '\\,')
|
||||||
|
.replace(/\r\n|\r|\n/g, '\\n');
|
||||||
|
|
||||||
|
const MAX_LINE_OCTETS = 75;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RFC 5545 §3.1 line folding: no content line longer than 75 octets, a longer
|
||||||
|
* one continues on the next line after a single leading space. Counts UTF-8
|
||||||
|
* octets, not characters, and never splits inside a character - "ü" is two
|
||||||
|
* octets and a fold between them corrupts it.
|
||||||
|
*/
|
||||||
|
export const foldLine = (line: string): string => {
|
||||||
|
const parts: string[] = [];
|
||||||
|
let current = '';
|
||||||
|
let octets = 0;
|
||||||
|
for (const char of line) {
|
||||||
|
const size = Buffer.byteLength(char, 'utf8');
|
||||||
|
// A continuation line's leading space counts towards its 75.
|
||||||
|
const limit = parts.length === 0 ? MAX_LINE_OCTETS : MAX_LINE_OCTETS - 1;
|
||||||
|
if (octets + size > limit) {
|
||||||
|
parts.push(current);
|
||||||
|
current = '';
|
||||||
|
octets = 0;
|
||||||
|
}
|
||||||
|
current += char;
|
||||||
|
octets += size;
|
||||||
|
}
|
||||||
|
parts.push(current);
|
||||||
|
return parts.join('\r\n ');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The generator builds the file with bare `\n` line ends; the format wants
|
||||||
|
* every content line folded and terminated by CRLF (RFC 5545 §3.1).
|
||||||
|
*/
|
||||||
|
const toContentLines = (ical: string): string =>
|
||||||
|
ical
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => line !== '')
|
||||||
|
.map(foldLine)
|
||||||
|
.join('\r\n') + '\r\n';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if a given string is null, undefined or blank
|
* Checks if a given string is null, undefined or blank
|
||||||
* @param str The string to check
|
* @param str The string to check
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* components:
|
|
||||||
* schemas:
|
|
||||||
* Session:
|
|
||||||
* type: object
|
|
||||||
* required:
|
|
||||||
* - sessionId
|
|
||||||
* - userId
|
|
||||||
* - sessionKey
|
|
||||||
* - sessionKeyHash
|
|
||||||
* - lastIP
|
|
||||||
* properties:
|
|
||||||
* sessionId:
|
|
||||||
* type: integer
|
|
||||||
* description: The unique identifier for the session
|
|
||||||
* example: 789
|
|
||||||
* userId:
|
|
||||||
* type: integer
|
|
||||||
* description: The ID of the user this session belongs to
|
|
||||||
* example: 456
|
|
||||||
* sessionKey:
|
|
||||||
* type: string
|
|
||||||
* description: The session key used for authentication
|
|
||||||
* example: "abc123def456"
|
|
||||||
* sessionKeyHash:
|
|
||||||
* type: string
|
|
||||||
* description: The hashed session key (not returned in API responses)
|
|
||||||
* example: "$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG"
|
|
||||||
* createdDate:
|
|
||||||
* type: string
|
|
||||||
* format: date-time
|
|
||||||
* description: The date and time when the session was created
|
|
||||||
* example: "2023-05-01T10:00:00.000Z"
|
|
||||||
* validUntil:
|
|
||||||
* type: string
|
|
||||||
* format: date-time
|
|
||||||
* description: The date and time until when the session is valid
|
|
||||||
* example: "2023-05-08T10:00:00.000Z"
|
|
||||||
* lastIP:
|
|
||||||
* type: string
|
|
||||||
* description: The last IP address used with this session
|
|
||||||
* example: "192.168.1.1"
|
|
||||||
*/
|
|
||||||
export interface Session {
|
|
||||||
sessionId: number;
|
|
||||||
userId: number;
|
|
||||||
sessionKey: string;
|
|
||||||
sessionKeyHash: string;
|
|
||||||
createdDate?: Date;
|
|
||||||
validUntil?: Date;
|
|
||||||
lastIP: string;
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* components:
|
|
||||||
* schemas:
|
|
||||||
* User:
|
|
||||||
* type: object
|
|
||||||
* required:
|
|
||||||
* - userId
|
|
||||||
* - fullName
|
|
||||||
* - passwordHash
|
|
||||||
* - email
|
|
||||||
* - isActive
|
|
||||||
* properties:
|
|
||||||
* userId:
|
|
||||||
* type: integer
|
|
||||||
* description: The unique identifier for the user
|
|
||||||
* example: 456
|
|
||||||
* fullName:
|
|
||||||
* type: string
|
|
||||||
* description: The full name of the user
|
|
||||||
* example: "John Doe"
|
|
||||||
* passwordHash:
|
|
||||||
* type: string
|
|
||||||
* description: The hashed password of the user (not returned in API responses)
|
|
||||||
* example: "$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG"
|
|
||||||
* email:
|
|
||||||
* type: string
|
|
||||||
* format: email
|
|
||||||
* description: The email address of the user
|
|
||||||
* example: "john.doe@nachklang.art"
|
|
||||||
* isActive:
|
|
||||||
* type: boolean
|
|
||||||
* description: Whether the user account is active
|
|
||||||
* example: true
|
|
||||||
*/
|
|
||||||
export interface User {
|
|
||||||
userId: number;
|
|
||||||
fullName: string;
|
|
||||||
passwordHash: string;
|
|
||||||
email: string;
|
|
||||||
isActive: boolean;
|
|
||||||
}
|
|
||||||
@@ -1,671 +0,0 @@
|
|||||||
/**
|
|
||||||
* Required External Modules and Interfaces
|
|
||||||
*/
|
|
||||||
|
|
||||||
import express, {Request, Response} from 'express';
|
|
||||||
import * as UserService from './users.service.js';
|
|
||||||
import {Session} from './session.interface.js';
|
|
||||||
import {User} from './user.interface.js';
|
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import logger from '../../../middleware/logger.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Router Definition
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const usersRouter = express.Router();
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Controller Definitions
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/register:
|
|
||||||
* post:
|
|
||||||
* summary: Register a new user
|
|
||||||
* description: Creates a new user account with the provided email, password, and full name. Only accepts official Nachklang email addresses.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* requestBody:
|
|
||||||
* required: true
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* required:
|
|
||||||
* - email
|
|
||||||
* - password
|
|
||||||
* - fullName
|
|
||||||
* properties:
|
|
||||||
* email:
|
|
||||||
* type: string
|
|
||||||
* format: email
|
|
||||||
* example: john.doe@nachklang.art
|
|
||||||
* description: Must be an official Nachklang email address
|
|
||||||
* password:
|
|
||||||
* type: string
|
|
||||||
* format: password
|
|
||||||
* example: securePassword123
|
|
||||||
* fullName:
|
|
||||||
* type: string
|
|
||||||
* example: John Doe
|
|
||||||
* responses:
|
|
||||||
* 201:
|
|
||||||
* description: User registered successfully
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* sessionId:
|
|
||||||
* type: integer
|
|
||||||
* example: 123
|
|
||||||
* sessionKey:
|
|
||||||
* type: string
|
|
||||||
* example: abc123def456
|
|
||||||
* 400:
|
|
||||||
* description: Bad request - missing or invalid parameters
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Missing parameters
|
|
||||||
* 500:
|
|
||||||
* description: Server error
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
*/
|
|
||||||
// POST users/register
|
|
||||||
usersRouter.post('/register', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const password: string = req.body.password;
|
|
||||||
const email: string = req.body.email;
|
|
||||||
const fullName: string = req.body.fullName;
|
|
||||||
const ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
if (!password || !email || !fullName) {
|
|
||||||
// Missing
|
|
||||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const emailRegex = /^[a-zA-Z0-9\_\-\.]+@nachklang\.art$/;
|
|
||||||
|
|
||||||
if(!emailRegex.test(email)) {
|
|
||||||
res.status(400).send(JSON.stringify({message: 'Must use an official Nachklang email address'}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the user and a session
|
|
||||||
const session: Session = await UserService.createUser(email, password, fullName, ip);
|
|
||||||
|
|
||||||
// Send the session details back to the user
|
|
||||||
res.status(201).send({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
sessionKey: session.sessionKey
|
|
||||||
});
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/activate:
|
|
||||||
* get:
|
|
||||||
* summary: Activate a user account
|
|
||||||
* description: Activates a user account using the provided user ID and activation token.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* parameters:
|
|
||||||
* - in: query
|
|
||||||
* name: id
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: integer
|
|
||||||
* description: The ID of the user to activate
|
|
||||||
* - in: query
|
|
||||||
* name: token
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* description: The activation token sent to the user's email
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: User activated successfully
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: OK
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: User activated
|
|
||||||
* 400:
|
|
||||||
* description: Bad request - missing parameters or activation failed
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Error activating user. Please contact your administrator.
|
|
||||||
* 500:
|
|
||||||
* description: Server error
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
*/
|
|
||||||
// GET /users/activate
|
|
||||||
usersRouter.get('/activate', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const userId: number = parseInt(req.query.id as string ?? '-1', 10);
|
|
||||||
const token: string = req.query.token as string ?? '';
|
|
||||||
|
|
||||||
if (!userId || !token) {
|
|
||||||
// Missing
|
|
||||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the user and a session
|
|
||||||
const success: boolean = await UserService.activateUser(userId, token);
|
|
||||||
|
|
||||||
// Send the session details back to the user
|
|
||||||
if(success) {
|
|
||||||
res.status(200).send({
|
|
||||||
'status': 'OK',
|
|
||||||
'message': 'User activated'
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.status(400).send({'status': 'PROCESSING_ERROR','message': 'Error activating user. Please contact your administrator.'});
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/login:
|
|
||||||
* post:
|
|
||||||
* summary: Login a user
|
|
||||||
* description: Authenticates a user with the provided email and password and returns a session.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* requestBody:
|
|
||||||
* required: true
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* required:
|
|
||||||
* - email
|
|
||||||
* - password
|
|
||||||
* properties:
|
|
||||||
* email:
|
|
||||||
* type: string
|
|
||||||
* format: email
|
|
||||||
* example: john.doe@nachklang.art
|
|
||||||
* password:
|
|
||||||
* type: string
|
|
||||||
* format: password
|
|
||||||
* example: securePassword123
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: Login successful
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* sessionId:
|
|
||||||
* type: integer
|
|
||||||
* example: 123
|
|
||||||
* sessionKey:
|
|
||||||
* type: string
|
|
||||||
* example: abc123def456
|
|
||||||
* 400:
|
|
||||||
* description: Bad request - missing parameters
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Missing parameters
|
|
||||||
* 401:
|
|
||||||
* description: Unauthorized - invalid credentials
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Wrong username and / or password
|
|
||||||
* sessionId:
|
|
||||||
* type: integer
|
|
||||||
* example: -1
|
|
||||||
* sessionKey:
|
|
||||||
* type: string
|
|
||||||
* example: ""
|
|
||||||
* 500:
|
|
||||||
* description: Server error
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
*/
|
|
||||||
// POST users/login
|
|
||||||
usersRouter.post('/login', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const password: string = req.body.password;
|
|
||||||
const email: string = req.body.email;
|
|
||||||
const ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
|
|
||||||
if (!password || !email) {
|
|
||||||
// Missing
|
|
||||||
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a session
|
|
||||||
const session: Session | null = await UserService.login(email, password, ip);
|
|
||||||
|
|
||||||
if (!session || !session.sessionId) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(401).send(JSON.stringify({message: 'Wrong username and / or password', sessionId: -1, sessionKey: ''}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the session details back to the user
|
|
||||||
res.status(200).send({
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
sessionKey: session.sessionKey
|
|
||||||
});
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/checkSessionValid:
|
|
||||||
* post:
|
|
||||||
* summary: Check if a session is valid
|
|
||||||
* description: Checks if the provided session is valid and returns the user information if it is.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* requestBody:
|
|
||||||
* required: true
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* required:
|
|
||||||
* - sessionId
|
|
||||||
* - sessionKey
|
|
||||||
* properties:
|
|
||||||
* sessionId:
|
|
||||||
* type: integer
|
|
||||||
* example: 123
|
|
||||||
* sessionKey:
|
|
||||||
* type: string
|
|
||||||
* example: abc123def456
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: Session is valid
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* $ref: '#/components/schemas/User'
|
|
||||||
* 401:
|
|
||||||
* description: Unauthorized - invalid session
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: ["Invalid session"]
|
|
||||||
* 500:
|
|
||||||
* description: Server error
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
*/
|
|
||||||
// POST users/checkSessionValid
|
|
||||||
usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const ip: string = req.socket.remoteAddress ?? '';
|
|
||||||
const session_id = req.body.sessionId;
|
|
||||||
const session_key = req.body.sessionKey;
|
|
||||||
|
|
||||||
if (!session_id || !session_key) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(401).send(JSON.stringify({messages: ['No session detected']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const user: User | null = await UserService.checkSession(session_id, session_key, ip);
|
|
||||||
|
|
||||||
if (!user || !user.userId) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(401).send(JSON.stringify({messages: ['Invalid session']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(200).send(user);
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/initiatePasswordReset:
|
|
||||||
* post:
|
|
||||||
* summary: Initiates a password reset
|
|
||||||
* description: Checks if the user exists and if so, initiates a password reset by sending an email to the user.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: Success
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Success
|
|
||||||
* description: A list of status messages
|
|
||||||
* 400:
|
|
||||||
* description: Problem with the request. Please consider the returned detailed error.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Missing parameters
|
|
||||||
* description: A list of error messages
|
|
||||||
* 401:
|
|
||||||
* description: Problem with authorizing the user. Please check the provided credentials.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Invalid session
|
|
||||||
* description: A list of error messages
|
|
||||||
* 500:
|
|
||||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* description: The response status
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* description: The detailed error message
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* description: An error reference for getting support concerning this error.
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
* requestBody:
|
|
||||||
* required: true
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* email:
|
|
||||||
* type: string
|
|
||||||
* example: patrick@nachklang.art
|
|
||||||
*/
|
|
||||||
usersRouter.post('/initiatePasswordReset', async(req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const username = req.body.username;
|
|
||||||
|
|
||||||
if (!username) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(400).send(JSON.stringify({messages: ['No username given']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const success: boolean = await UserService.initiatePasswordReset(username);
|
|
||||||
|
|
||||||
if (!success) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(401).send(JSON.stringify({messages: ['Error']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(200).send(JSON.stringify({messages: ['Success']}));
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @swagger
|
|
||||||
* /calendar/users/finalizePasswordReset:
|
|
||||||
* post:
|
|
||||||
* summary: Finalizes the password reset
|
|
||||||
* description: Checks if the given token is valid and if so, finalizes the password reset by setting the new password.
|
|
||||||
* tags:
|
|
||||||
* - calendar
|
|
||||||
* responses:
|
|
||||||
* 200:
|
|
||||||
* description: Success
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Success
|
|
||||||
* description: A list of status messages
|
|
||||||
* 400:
|
|
||||||
* description: Problem with the request. Please consider the returned detailed error.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Missing parameters
|
|
||||||
* description: A list of error messages
|
|
||||||
* 401:
|
|
||||||
* description: Problem with authorizing the user. Please check the provided credentials.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* messages:
|
|
||||||
* type: array
|
|
||||||
* items:
|
|
||||||
* type: string
|
|
||||||
* example: Invalid session
|
|
||||||
* description: A list of error messages
|
|
||||||
* 500:
|
|
||||||
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* status:
|
|
||||||
* type: string
|
|
||||||
* description: The response status
|
|
||||||
* example: PROCESSING_ERROR
|
|
||||||
* message:
|
|
||||||
* type: string
|
|
||||||
* description: The detailed error message
|
|
||||||
* example: Internal Server Error. Try again later.
|
|
||||||
* reference:
|
|
||||||
* type: string
|
|
||||||
* description: An error reference for getting support concerning this error.
|
|
||||||
* example: 6ec1361c-4175-4e81-b2ef-a0792a9a1dc3
|
|
||||||
* requestBody:
|
|
||||||
* required: true
|
|
||||||
* content:
|
|
||||||
* application/json:
|
|
||||||
* schema:
|
|
||||||
* type: object
|
|
||||||
* properties:
|
|
||||||
* email:
|
|
||||||
* type: string
|
|
||||||
* example: patrick@nachklang.art
|
|
||||||
* token:
|
|
||||||
* type: string
|
|
||||||
* example: 3ccd147f-720b-4e29-a8b7-46b63de31555
|
|
||||||
* password:
|
|
||||||
* type: string
|
|
||||||
* example: ExtremelyBadPassword
|
|
||||||
*/
|
|
||||||
usersRouter.post('/finalizePasswordReset', async(req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const username = req.body.username;
|
|
||||||
const token = req.body.token;
|
|
||||||
const newPassword = req.body.password;
|
|
||||||
|
|
||||||
if (!username) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(400).send(JSON.stringify({messages: ['No username, token or password given']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const success: boolean = await UserService.finalizePasswordReset(username, token, newPassword);
|
|
||||||
|
|
||||||
if (!success) {
|
|
||||||
// Error logging in, probably wrong username / password
|
|
||||||
res.status(401).send(JSON.stringify({messages: ['Error']}));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(200).send(JSON.stringify({messages: ['Success']}));
|
|
||||||
} catch (e: any) {
|
|
||||||
let errorGuid = Guid.create().toString();
|
|
||||||
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
|
|
||||||
res.status(500).send({
|
|
||||||
'status': 'PROCESSING_ERROR',
|
|
||||||
'message': 'Internal Server Error. Try again later.',
|
|
||||||
'reference': errorGuid
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
import * as dotenv from 'dotenv';
|
|
||||||
import bcrypt from 'bcrypt';
|
|
||||||
import {Guid} from 'guid-typescript';
|
|
||||||
import {User} from './user.interface.js';
|
|
||||||
import {Session} from './session.interface.js';
|
|
||||||
import {NachklangCalendarDB} from '../Calendar.db.js';
|
|
||||||
import {MailService} from '../../../common/common.mail.js';
|
|
||||||
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Data Model Interfaces
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service Methods
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a user record in the database, also creates a session. Returns the session if successful.
|
|
||||||
*/
|
|
||||||
export const createUser = async (email: string, password: string, fullName: string, ip: string): Promise<Session> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
// Hash password and generate + hash session key
|
|
||||||
const pwHash = bcrypt.hashSync(password, 10);
|
|
||||||
const sessionKey = Guid.create().toString();
|
|
||||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
|
||||||
|
|
||||||
const activationToken = Guid.create().toString();
|
|
||||||
const activationTokenHash = bcrypt.hashSync(activationToken, 10);
|
|
||||||
|
|
||||||
// Create user entry in SQL
|
|
||||||
const userQuery = 'INSERT INTO users (email, password_hash, full_name, activation_token) VALUES (?, ?, ?, ?) RETURNING user_id';
|
|
||||||
const userIdRes = await conn.query(userQuery, [email, pwHash, fullName, activationTokenHash]);
|
|
||||||
|
|
||||||
// Get user id of the created user
|
|
||||||
let userId: number = -1;
|
|
||||||
for (const row of userIdRes) {
|
|
||||||
userId = row.user_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create session
|
|
||||||
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_date, valid_until, last_ip) VALUES (?,?,NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),?) RETURNING session_id';
|
|
||||||
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
|
|
||||||
await conn.commit();
|
|
||||||
|
|
||||||
// Get session id of the created session
|
|
||||||
let sessionId: number = -1;
|
|
||||||
for (const row of sessionIdRes) {
|
|
||||||
sessionId = row.session_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send email with activation link (after commit so we don't block on email
|
|
||||||
// delivery). sendMail never throws on a delivery failure - it logs and
|
|
||||||
// returns false - so a mail-server problem here can't roll back the
|
|
||||||
// already-committed user and leave registration reporting a false error.
|
|
||||||
await MailService.sendMail(email, 'Activate your Nachklang account', `Hi ${fullName},\n\nPlease click on the following link to activate your account:\n\nhttps://api.nachklang.art/calendar/users/activate?id=${userId}&token=${activationToken}`);
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId: sessionId,
|
|
||||||
userId: userId,
|
|
||||||
sessionKey: sessionKey,
|
|
||||||
sessionKeyHash: 'HIDDEN',
|
|
||||||
lastIP: ip
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const activateUser = async (userId: number, token: string): Promise<boolean> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
const checkTokenQuery = 'SELECT user_id, activation_token FROM users WHERE user_id = ? AND is_active = 0';
|
|
||||||
const userNameRes = await conn.query(checkTokenQuery, [userId]);
|
|
||||||
let storedTokenHash = '';
|
|
||||||
for (const row of userNameRes) {
|
|
||||||
storedTokenHash = row.activation_token;
|
|
||||||
}
|
|
||||||
if (!storedTokenHash || !bcrypt.compareSync(token, storedTokenHash)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const activateQuery = 'UPDATE users SET is_active = 1, activation_token = null WHERE user_id = ?';
|
|
||||||
const activateRes = await conn.execute(activateQuery, [userId]);
|
|
||||||
await conn.commit();
|
|
||||||
return activateRes.affectedRows !== 0;
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the given credentials are valid and creates a new session if they are.
|
|
||||||
* Returns the session information in case of a successful login
|
|
||||||
*/
|
|
||||||
export const login = async (email: string, password: string, ip: string): Promise<Session | null> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
// Get saved password hash
|
|
||||||
const query = 'SELECT user_id, password_hash FROM users WHERE email = ?';
|
|
||||||
const userRows = await conn.query(query, email);
|
|
||||||
let savedHash = '';
|
|
||||||
let userId = -1;
|
|
||||||
for (const row of userRows) {
|
|
||||||
savedHash = row.password_hash;
|
|
||||||
userId = row.user_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for correct password
|
|
||||||
if (!bcrypt.compareSync(password, savedHash)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate + hash session key
|
|
||||||
const sessionKey = Guid.create().toString();
|
|
||||||
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
|
|
||||||
|
|
||||||
// Create session
|
|
||||||
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_date, valid_until, last_ip) VALUES (?,?,NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),?) RETURNING session_id';
|
|
||||||
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
|
|
||||||
await conn.commit();
|
|
||||||
|
|
||||||
// Get session id of the created session
|
|
||||||
let sessionId: number = -1;
|
|
||||||
for (const row of sessionIdRes) {
|
|
||||||
sessionId = row.session_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId: sessionId,
|
|
||||||
userId: userId,
|
|
||||||
sessionKey: sessionKey,
|
|
||||||
sessionKeyHash: 'HIDDEN',
|
|
||||||
lastIP: ip
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the given session information are valid and returns the user information if they are
|
|
||||||
*/
|
|
||||||
export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User | null> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
// Get saved session key hash
|
|
||||||
const query = 'SELECT user_id, session_key_hash, valid_until FROM sessions WHERE session_id = ?';
|
|
||||||
const sessionRows = await conn.query(query, sessionId);
|
|
||||||
let savedHash = '';
|
|
||||||
let userId = -1;
|
|
||||||
let validUntil = new Date();
|
|
||||||
for (const row of sessionRows) {
|
|
||||||
savedHash = row.session_key_hash;
|
|
||||||
userId = row.user_id;
|
|
||||||
validUntil = row.valid_until;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for correct key
|
|
||||||
if (!bcrypt.compareSync(sessionKey, savedHash)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the session is still valid
|
|
||||||
if (validUntil <= new Date()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update session entry in SQL
|
|
||||||
const updateSessionsQuery = 'UPDATE sessions SET last_IP = ? WHERE session_id = ?';
|
|
||||||
await conn.query(updateSessionsQuery, [ip, sessionId]);
|
|
||||||
await conn.commit();
|
|
||||||
|
|
||||||
// Get the other required user information
|
|
||||||
const userQuery = 'SELECT user_id, email, full_name, is_active FROM users WHERE user_id = ?';
|
|
||||||
const userRows = await conn.query(userQuery, userId);
|
|
||||||
let email = '';
|
|
||||||
let fullName = '';
|
|
||||||
let is_active = false;
|
|
||||||
for (const row of userRows) {
|
|
||||||
email = row.email;
|
|
||||||
fullName = row.full_name;
|
|
||||||
is_active = row.is_active;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Everything is fine, return user information
|
|
||||||
return {
|
|
||||||
userId: userId,
|
|
||||||
email: email,
|
|
||||||
passwordHash: 'HIDDEN',
|
|
||||||
fullName: fullName,
|
|
||||||
isActive: is_active
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const initiatePasswordReset = async (email: string): Promise<boolean> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
const checkUsernameQuery = 'SELECT user_id, full_Name FROM users WHERE email = ?';
|
|
||||||
const userNameRes = await conn.query(checkUsernameQuery, [email]);
|
|
||||||
if (userNameRes.length === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let userId: number = -1;
|
|
||||||
let fullName: string = '';
|
|
||||||
for(let row of userNameRes) {
|
|
||||||
userId = row.user_id;
|
|
||||||
fullName = row.full_Name;
|
|
||||||
}
|
|
||||||
|
|
||||||
let resetToken = Guid.create().toString();
|
|
||||||
let resetTokenHash = bcrypt.hashSync(resetToken, 10);
|
|
||||||
|
|
||||||
const updateQuery = 'UPDATE users SET pw_reset_token_hash = ? WHERE user_id = ?';
|
|
||||||
const updateRes = await conn.execute(updateQuery, [resetTokenHash, userId]);
|
|
||||||
|
|
||||||
if(updateRes.affectedRows === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
await conn.commit();
|
|
||||||
|
|
||||||
await MailService.sendMail(email, 'Password Reset', `Hello ${fullName},\n\nYou requested a password reset for your BonkApp account. If you did not request this, please ignore this email.\n\nTo reset your password, please use the following reset token:\n\n${resetToken}`);
|
|
||||||
return true;
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const finalizePasswordReset = async (email: string, token: string, newPassword: string): Promise<boolean> => {
|
|
||||||
let conn = await NachklangCalendarDB.getConnection();
|
|
||||||
try {
|
|
||||||
await conn.beginTransaction();
|
|
||||||
|
|
||||||
const checkTokenQuery = 'SELECT user_id, pw_reset_token_hash FROM users WHERE email = ?';
|
|
||||||
const userNameRes = await conn.query(checkTokenQuery, [email]);
|
|
||||||
if (userNameRes.length === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let userId: string = '';
|
|
||||||
let tokenHash: string = '';
|
|
||||||
for(let row of userNameRes) {
|
|
||||||
userId = row.user_id;
|
|
||||||
tokenHash = row.pw_reset_token_hash;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!bcrypt.compareSync(token, tokenHash)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pwHash = bcrypt.hashSync(newPassword, 10);
|
|
||||||
const updatePasswordQuery = 'UPDATE users SET password_hash = ?, pw_reset_token_hash = NULL WHERE user_id = ?';
|
|
||||||
const updateRes = await conn.execute(updatePasswordQuery, [pwHash, userId]);
|
|
||||||
|
|
||||||
if(updateRes.affectedRows > 0) {
|
|
||||||
await conn.commit();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
} catch (err) {
|
|
||||||
await conn.rollback();
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
await conn.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* components:
|
* components:
|
||||||
* parameters:
|
|
||||||
* SessionIdHeader:
|
|
||||||
* in: header
|
|
||||||
* name: X-Session-Id
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* SessionKeyHeader:
|
|
||||||
* in: header
|
|
||||||
* name: X-Session-Key
|
|
||||||
* required: true
|
|
||||||
* schema:
|
|
||||||
* type: string
|
|
||||||
* schemas:
|
* schemas:
|
||||||
* EventAdminSummary:
|
* EventAdminSummary:
|
||||||
* type: object
|
* type: object
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {requireAdminAuth} from '../feedback.auth.js';
|
import {requireAdminAuth} from '../feedback.auth.js';
|
||||||
|
import {isReadOnly} from '../../admin/admin.schema.js';
|
||||||
import {sendServerError} from '../feedback.errors.js';
|
import {sendServerError} from '../feedback.errors.js';
|
||||||
import {eventsAdminRouter} from './events.admin.router.js';
|
import {eventsAdminRouter} from './events.admin.router.js';
|
||||||
import {songsAdminRouter} from './songs.admin.router.js';
|
import {songsAdminRouter} from './songs.admin.router.js';
|
||||||
@@ -26,9 +27,8 @@ adminRouter.use(requireAdminAuth);
|
|||||||
* summary: Validate the current admin session
|
* summary: Validate the current admin session
|
||||||
* description: Used by the Next.js middleware/proxy to gate /admin. Returns the authenticated admin's identity.
|
* description: Used by the Next.js middleware/proxy to gate /admin. Returns the authenticated admin's identity.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
@@ -41,11 +41,21 @@ adminRouter.use(requireAdminAuth);
|
|||||||
* type: string
|
* type: string
|
||||||
* fullName:
|
* fullName:
|
||||||
* type: string
|
* type: string
|
||||||
|
* readOnly:
|
||||||
|
* type: boolean
|
||||||
|
* description: Holds only the read role for feedback - every write answers 403.
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
adminRouter.get('/me', (req: Request, res: Response) => {
|
adminRouter.get('/me', (req: Request, res: Response) => {
|
||||||
res.status(200).send({email: res.locals.admin.email, fullName: res.locals.admin.displayName});
|
res.status(200).send({
|
||||||
|
email: res.locals.admin.email,
|
||||||
|
fullName: res.locals.admin.displayName,
|
||||||
|
// Lets the frontend hide what the API would refuse anyway.
|
||||||
|
readOnly: isReadOnly(res.locals.admin.permissions, 'feedback')
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,9 +65,9 @@ adminRouter.get('/me', (req: Request, res: Response) => {
|
|||||||
* summary: Delete a single submission
|
* summary: Delete a single submission
|
||||||
* description: Removes the submission and everything under it (its answers, guest book entry, newsletter signup) - for removing an individual abusive or inappropriate entry. Not a bulk moderation tool.
|
* description: Removes the submission and everything under it (its answers, guest book entry, newsletter signup) - for removing an individual abusive or inappropriate entry. Not a bulk moderation tool.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: submissionId
|
* name: submissionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -70,6 +80,8 @@ adminRouter.get('/me', (req: Request, res: Response) => {
|
|||||||
* description: Unknown submission
|
* description: Unknown submission
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
adminRouter.delete('/submissions/:submissionId', async (req: Request, res: Response) => {
|
adminRouter.delete('/submissions/:submissionId', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -18,9 +18,8 @@ export const eventsAdminRouter = express.Router();
|
|||||||
* summary: List all events (admin)
|
* summary: List all events (admin)
|
||||||
* description: All events, published or not, past or future, with submission counts.
|
* description: All events, published or not, past or future, with submission counts.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
@@ -32,13 +31,14 @@ export const eventsAdminRouter = express.Router();
|
|||||||
* $ref: '#/components/schemas/EventAdminSummary'
|
* $ref: '#/components/schemas/EventAdminSummary'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* post:
|
* post:
|
||||||
* summary: Create an event
|
* summary: Create an event
|
||||||
* description: Auto-generates the slug from the name and event year; defaults feedback_deadline to event_date + 14 days 23:59:59 unless supplied.
|
* description: Auto-generates the slug from the name and event year; defaults feedback_deadline to event_date + 14 days 23:59:59 unless supplied.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -68,6 +68,8 @@ export const eventsAdminRouter = express.Router();
|
|||||||
* description: Missing required fields
|
* description: Missing required fields
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -101,9 +103,9 @@ eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* summary: Get one event (admin)
|
* summary: Get one event (admin)
|
||||||
* description: Full event detail including setlist and assigned questions.
|
* description: Full event detail including setlist and assigned questions.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -120,12 +122,14 @@ eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* description: Unknown event
|
* description: Unknown event
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* put:
|
* put:
|
||||||
* summary: Update an event
|
* summary: Update an event
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -138,13 +142,15 @@ eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* description: Unknown event
|
* description: Unknown event
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* delete:
|
* delete:
|
||||||
* summary: Delete an event
|
* summary: Delete an event
|
||||||
* description: Refuses with 409 if submissions exist unless ?force=true is passed.
|
* description: Refuses with 409 if submissions exist unless ?force=true is passed.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -163,6 +169,8 @@ eventsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* description: Submissions exist and force was not set
|
* description: Submissions exist and force was not set
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/:eventId', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/:eventId', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -214,9 +222,9 @@ eventsAdminRouter.delete('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get an event's setlist
|
* summary: Get an event's setlist
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -227,12 +235,14 @@ eventsAdminRouter.delete('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* post:
|
* post:
|
||||||
* summary: Add a song to an event's setlist
|
* summary: Add a song to an event's setlist
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -257,6 +267,8 @@ eventsAdminRouter.delete('/:eventId', async (req: Request, res: Response) => {
|
|||||||
* description: Missing title
|
* description: Missing title
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/:eventId/songs', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/:eventId/songs', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -292,9 +304,9 @@ eventsAdminRouter.post('/:eventId/songs', async (req: Request, res: Response) =>
|
|||||||
* summary: Bulk reorder an event's setlist
|
* summary: Bulk reorder an event's setlist
|
||||||
* description: Rewrites song positions as a dense 0..n-1 sequence in one transaction.
|
* description: Rewrites song positions as a dense 0..n-1 sequence in one transaction.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -317,6 +329,8 @@ eventsAdminRouter.post('/:eventId/songs', async (req: Request, res: Response) =>
|
|||||||
* description: Reordered
|
* description: Reordered
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.put('/:eventId/songs/order', async (req: Request, res: Response) => {
|
eventsAdminRouter.put('/:eventId/songs/order', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -334,9 +348,9 @@ eventsAdminRouter.put('/:eventId/songs/order', async (req: Request, res: Respons
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get an event's assigned questions
|
* summary: Get an event's assigned questions
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -347,13 +361,15 @@ eventsAdminRouter.put('/:eventId/songs/order', async (req: Request, res: Respons
|
|||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* put:
|
* put:
|
||||||
* summary: Bulk-set an event's assigned questions
|
* summary: Bulk-set an event's assigned questions
|
||||||
* description: One transaction - inserts new, updates existing, deletes removed. Keeps the admin UI a simple save-the-whole-list form.
|
* description: One transaction - inserts new, updates existing, deletes removed. Keeps the admin UI a simple save-the-whole-list form.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -383,6 +399,8 @@ eventsAdminRouter.put('/:eventId/songs/order', async (req: Request, res: Respons
|
|||||||
* description: Saved
|
* description: Saved
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/:eventId/questions', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/:eventId/questions', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ export const questionsAdminRouter = express.Router();
|
|||||||
* get:
|
* get:
|
||||||
* summary: List the question library
|
* summary: List the question library
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: includeArchived
|
* name: includeArchived
|
||||||
* schema:
|
* schema:
|
||||||
@@ -34,12 +34,13 @@ export const questionsAdminRouter = express.Router();
|
|||||||
* $ref: '#/components/schemas/AdminQuestion'
|
* $ref: '#/components/schemas/AdminQuestion'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* post:
|
* post:
|
||||||
* summary: Create a question
|
* summary: Create a question
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -61,6 +62,8 @@ export const questionsAdminRouter = express.Router();
|
|||||||
* description: Missing or invalid fields
|
* description: Missing or invalid fields
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
questionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
questionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -94,9 +97,9 @@ questionsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* summary: Edit a question's label/help text
|
* summary: Edit a question's label/help text
|
||||||
* description: question_type is immutable after creation - the admin UI offers "archive and create new" instead.
|
* description: question_type is immutable after creation - the admin UI offers "archive and create new" instead.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: questionId
|
* name: questionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -123,13 +126,15 @@ questionsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* description: Unknown question
|
* description: Unknown question
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* delete:
|
* delete:
|
||||||
* summary: Archive (or hard-delete) a question
|
* summary: Archive (or hard-delete) a question
|
||||||
* description: Archives the question if it has ever been used; hard-deletes it if it has never been assigned to any event.
|
* description: Archives the question if it has ever been used; hard-deletes it if it has never been assigned to any event.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: questionId
|
* name: questionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -142,6 +147,8 @@ questionsAdminRouter.post('/', async (req: Request, res: Response) => {
|
|||||||
* description: Unknown question
|
* description: Unknown question
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
questionsAdminRouter.put('/:questionId', async (req: Request, res: Response) => {
|
questionsAdminRouter.put('/:questionId', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -19,9 +19,9 @@ export const reportsAdminRouter = express.Router();
|
|||||||
* summary: Aggregated feedback report for one event
|
* summary: Aggregated feedback report for one event
|
||||||
* description: Song-pick vote counts, song-rating averages, capped free-text list, guest book count, and newsletter sync counts.
|
* description: Song-pick vote counts, song-rating averages, capped free-text list, guest book count, and newsletter sync counts.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -34,6 +34,8 @@ export const reportsAdminRouter = express.Router();
|
|||||||
* description: Unknown event
|
* description: Unknown event
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
reportsAdminRouter.get('/:eventId/report', async (req: Request, res: Response) => {
|
reportsAdminRouter.get('/:eventId/report', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -55,9 +57,9 @@ reportsAdminRouter.get('/:eventId/report', async (req: Request, res: Response) =
|
|||||||
* summary: Guest Book entries for one event
|
* summary: Guest Book entries for one event
|
||||||
* description: Newest first, paginated.
|
* description: Newest first, paginated.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -81,6 +83,8 @@ reportsAdminRouter.get('/:eventId/report', async (req: Request, res: Response) =
|
|||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
reportsAdminRouter.get('/:eventId/guestbook', async (req: Request, res: Response) => {
|
reportsAdminRouter.get('/:eventId/guestbook', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -101,9 +105,9 @@ reportsAdminRouter.get('/:eventId/guestbook', async (req: Request, res: Response
|
|||||||
* summary: Newsletter signups for one event
|
* summary: Newsletter signups for one event
|
||||||
* description: Includes sync_status, so failures can be handled manually. Newest first, paginated.
|
* description: Includes sync_status, so failures can be handled manually. Newest first, paginated.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -127,6 +131,8 @@ reportsAdminRouter.get('/:eventId/guestbook', async (req: Request, res: Response
|
|||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
reportsAdminRouter.get('/:eventId/newsletter', async (req: Request, res: Response) => {
|
reportsAdminRouter.get('/:eventId/newsletter', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -147,9 +153,9 @@ reportsAdminRouter.get('/:eventId/newsletter', async (req: Request, res: Respons
|
|||||||
* summary: CSV export of all answers for one event
|
* summary: CSV export of all answers for one event
|
||||||
* description: Long format, one row per answer. UTF-8 BOM, `;` separator, RFC 4180 escaping, formula-injection guard.
|
* description: Long format, one row per answer. UTF-8 BOM, `;` separator, RFC 4180 escaping, formula-injection guard.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -162,6 +168,8 @@ reportsAdminRouter.get('/:eventId/newsletter', async (req: Request, res: Respons
|
|||||||
* text/csv: {}
|
* text/csv: {}
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
reportsAdminRouter.get('/:eventId/export/responses.csv', async (req: Request, res: Response) => {
|
reportsAdminRouter.get('/:eventId/export/responses.csv', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -187,9 +195,9 @@ reportsAdminRouter.get('/:eventId/export/responses.csv', async (req: Request, re
|
|||||||
* get:
|
* get:
|
||||||
* summary: CSV export of Guest Book entries for one event
|
* summary: CSV export of Guest Book entries for one event
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -202,6 +210,8 @@ reportsAdminRouter.get('/:eventId/export/responses.csv', async (req: Request, re
|
|||||||
* text/csv: {}
|
* text/csv: {}
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
reportsAdminRouter.get('/:eventId/export/guestbook.csv', async (req: Request, res: Response) => {
|
reportsAdminRouter.get('/:eventId/export/guestbook.csv', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ export const songsAdminRouter = express.Router();
|
|||||||
* put:
|
* put:
|
||||||
* summary: Edit a song's title/composer
|
* summary: Edit a song's title/composer
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: songId
|
* name: songId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -45,13 +45,15 @@ export const songsAdminRouter = express.Router();
|
|||||||
* description: Unknown song
|
* description: Unknown song
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* delete:
|
* delete:
|
||||||
* summary: Remove a song
|
* summary: Remove a song
|
||||||
* description: Past answers keep their song_title_snapshot even after the song is removed.
|
* description: Past answers keep their song_title_snapshot even after the song is removed.
|
||||||
* tags: [feedback-admin]
|
* tags: [feedback-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: songId
|
* name: songId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -64,6 +66,8 @@ export const songsAdminRouter = express.Router();
|
|||||||
* description: Unknown song
|
* description: Unknown song
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
songsAdminRouter.put('/:songId', async (req: Request, res: Response) => {
|
songsAdminRouter.put('/:songId', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,78 +1,38 @@
|
|||||||
import express from 'express';
|
import {requireAppAccess} from '../admin/admin.middleware.js';
|
||||||
import * as UserService from '../calendar/users/users.service.js';
|
|
||||||
import {sendServerError} from './feedback.errors.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This file is the ONLY place in the feedback module that knows how admin
|
* This file is the ONLY place in the feedback module that knows how admin
|
||||||
* authentication works today. No route handler and no service outside this
|
* authentication works. No route handler and no service outside this file may
|
||||||
* file may import users.service, read session headers, or touch bcrypt.
|
* read session headers or resolve a user itself.
|
||||||
*
|
*
|
||||||
* Today: reuses the existing Calendar users/sessions mechanism. Any
|
* Today: the shared admin identity in `src/models/admin/`. A session cookie
|
||||||
* activated @nachklang.art account may administer feedback — no roles.
|
* set by /admin/auth on admin.nachklang.art, plus a `feedback` permission on
|
||||||
* Migrating to Keycloak later means writing a keycloakJwtAuthenticator
|
* the account. Both are re-checked on every request, so disabling a user or
|
||||||
* below and changing the one `activeAuthenticator` binding (plus the
|
* taking their feedback permission away takes effect immediately.
|
||||||
* frontend's login route handler) — nothing else in the feedback module
|
|
||||||
* needs to change.
|
|
||||||
*
|
*
|
||||||
* Explicitly forbidden: accepting sessionId/sessionKey from query
|
* Before 2026-09-06 this was a header session against the calendar users
|
||||||
* parameters, even "temporarily". That is the exact mistake documented in
|
* table, and any activated @nachklang.art account could administer feedback.
|
||||||
* DEFERRED_SECURITY.md item 1 for the Calendar domain, where credentials
|
* That is why the swap is a one-line binding: everything downstream only ever
|
||||||
* end up in access logs, browser history, proxy logs, and Referer headers.
|
* saw `requireAdminAuth` and `res.locals.admin`, and both still mean what
|
||||||
* Headers only.
|
* they meant. What changed is that access is now granted per user rather than
|
||||||
|
* implied by having an account.
|
||||||
|
*
|
||||||
|
* Explicitly forbidden: accepting session credentials from query parameters,
|
||||||
|
* even "temporarily". That is the exact mistake documented in
|
||||||
|
* DEFERRED_SECURITY.md item 1 for the Calendar domain, where credentials end
|
||||||
|
* up in access logs, browser history, proxy logs, and Referer headers.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// The only thing the rest of the feedback module knows about an admin.
|
// The only thing the rest of the feedback module knows about an admin. The
|
||||||
|
// shared middleware puts a superset of this on res.locals.admin.
|
||||||
export interface AdminIdentity {
|
export interface AdminIdentity {
|
||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pluggable strategy: extract + verify credentials from a request.
|
|
||||||
// Returns the identity, or null if unauthenticated. Throws only on
|
|
||||||
// infrastructure errors (e.g. the DB being unreachable).
|
|
||||||
export type AdminAuthenticator = (req: express.Request) => Promise<AdminIdentity | null>;
|
|
||||||
|
|
||||||
// Current implementation: reads X-Session-Id / X-Session-Key headers,
|
|
||||||
// delegates to the existing calendar UserService.checkSession(...).
|
|
||||||
export const sessionHeaderAuthenticator: AdminAuthenticator = async (req) => {
|
|
||||||
const sessionId = req.header('X-Session-Id');
|
|
||||||
const sessionKey = req.header('X-Session-Key');
|
|
||||||
if (!sessionId || !sessionKey) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ip = req.ip || '';
|
|
||||||
const user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
// Mirrors the Calendar domain's own convention: a valid session on an
|
|
||||||
// inactive (not yet activated) account is not sufficient.
|
|
||||||
if (!user || !user.isActive) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: String(user.userId),
|
|
||||||
email: user.email,
|
|
||||||
displayName: user.fullName
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// Swap point: change this one binding to migrate to Keycloak.
|
|
||||||
export const activeAuthenticator: AdminAuthenticator = sessionHeaderAuthenticator;
|
|
||||||
|
|
||||||
// Express middleware used by every admin route. On success:
|
// Express middleware used by every admin route. On success:
|
||||||
// res.locals.admin = AdminIdentity, calls next(). On failure: 401.
|
// res.locals.admin = AdminAccess (an AdminIdentity plus permissions), calls
|
||||||
export const requireAdminAuth: express.RequestHandler = async (req, res, next) => {
|
// next(). On failure: 401 when not signed in, 403 when signed in without the
|
||||||
try {
|
// feedback permission.
|
||||||
const identity = await activeAuthenticator(req);
|
export const requireAdminAuth = requireAppAccess('feedback');
|
||||||
if (!identity) {
|
|
||||||
res.status(401).send({status: 'UNAUTHORIZED', message: 'Anmeldung erforderlich.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.locals.admin = identity;
|
|
||||||
next();
|
|
||||||
} catch (e: any) {
|
|
||||||
sendServerError(res, e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -56,6 +56,10 @@
|
|||||||
* website:
|
* website:
|
||||||
* type: string
|
* type: string
|
||||||
* description: Honeypot field. Must stay empty; a real visitor never fills it in.
|
* description: Honeypot field. Must stay empty; a real visitor never fills it in.
|
||||||
|
* clientToken:
|
||||||
|
* type: string
|
||||||
|
* format: uuid
|
||||||
|
* description: Generated once per form and resent on every retry. A retry whose token is already stored for this event returns the original submissionId instead of saving a duplicate. Optional; a value that isn't a UUID is ignored.
|
||||||
* SubmissionResponse:
|
* SubmissionResponse:
|
||||||
* type: object
|
* type: object
|
||||||
* properties:
|
* properties:
|
||||||
@@ -95,4 +99,5 @@ export interface SubmissionRequestBody {
|
|||||||
guestBook?: GuestBookInput;
|
guestBook?: GuestBookInput;
|
||||||
newsletter?: NewsletterInput;
|
newsletter?: NewsletterInput;
|
||||||
website?: string;
|
website?: string;
|
||||||
|
clientToken?: string;
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,8 @@ const CONSENT_TEXT_VERSION = '2026-08-02';
|
|||||||
|
|
||||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
const CLIENT_TOKEN_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
// A real setlist tops out around a few dozen songs and a handful of
|
// A real setlist tops out around a few dozen songs and a handful of
|
||||||
// questions, so a legitimate submission never comes close to this. Caps
|
// questions, so a legitimate submission never comes close to this. Caps
|
||||||
// total generated rows regardless of how large the client's answers/ratings
|
// total generated rows regardless of how large the client's answers/ratings
|
||||||
@@ -136,6 +138,33 @@ export const validateNewsletter = (input?: NewsletterInput): ValidatedNewsletter
|
|||||||
return {firstName, lastName, email};
|
return {firstName, lastName, email};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form generates one UUID per visit and resends it on every retry, so a
|
||||||
|
* request whose response was lost (the row saved, but the phone never heard
|
||||||
|
* back) can be told apart from a genuinely new submission. Anything that
|
||||||
|
* isn't a UUID is treated as "no token" rather than rejected - an old cached
|
||||||
|
* copy of the form must still be able to submit.
|
||||||
|
*/
|
||||||
|
export const normalizeClientToken = (token: unknown): string | null => {
|
||||||
|
return typeof token === 'string' && CLIENT_TOKEN_RE.test(token) ? token.toLowerCase() : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Scoped to the event: the token is per form visit, and one visit can move
|
||||||
|
// on to another concert's form, so a match for a different event is not a
|
||||||
|
// retry of this one.
|
||||||
|
const findSubmissionIdByClientToken = async (clientToken: string, slug: string): Promise<number | null> => {
|
||||||
|
const conn = await NachklangFeedbackDB.getConnection();
|
||||||
|
try {
|
||||||
|
const rows = await conn.query(
|
||||||
|
'SELECT s.submission_id FROM submissions s JOIN events e ON e.event_id = s.event_id WHERE s.client_token = ? AND e.slug = ?',
|
||||||
|
[clientToken, slug]
|
||||||
|
);
|
||||||
|
return rows.length > 0 ? rows[0].submission_id : null;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export type SubmitResult =
|
export type SubmitResult =
|
||||||
| { status: 'OK'; submissionId: number; newsletterDropped: boolean }
|
| { status: 'OK'; submissionId: number; newsletterDropped: boolean }
|
||||||
| { status: 'NOT_FOUND' }
|
| { status: 'NOT_FOUND' }
|
||||||
@@ -146,9 +175,29 @@ export type SubmitResult =
|
|||||||
* Validates and persists one feedback submission. Re-checks event
|
* Validates and persists one feedback submission. Re-checks event
|
||||||
* eligibility (the window may have closed between page load and submit),
|
* eligibility (the window may have closed between page load and submit),
|
||||||
* validates every answer against the event's live questions/songs, then
|
* validates every answer against the event's live questions/songs, then
|
||||||
* inserts everything in a single transaction.
|
* inserts everything in a single transaction. A retry carrying an already
|
||||||
|
* stored client token gets the original submission back instead of a copy.
|
||||||
*/
|
*/
|
||||||
export const submitFeedback = async (slug: string, body: SubmissionRequestBody, ipHash: string | null): Promise<SubmitResult> => {
|
export const submitFeedback = async (slug: string, body: SubmissionRequestBody, ipHash: string | null): Promise<SubmitResult> => {
|
||||||
|
const clientToken = normalizeClientToken(body.clientToken);
|
||||||
|
const newsletter = validateNewsletter(body.newsletter);
|
||||||
|
// body.newsletter is only sent at all when the visitor had the opt-in
|
||||||
|
// checkbox on (see FeedbackForm.tsx), so a present-but-invalid block
|
||||||
|
// (e.g. a mistyped email) is distinguishable from "didn't opt in" - the
|
||||||
|
// rest of the submission still saves, but the client can tell the
|
||||||
|
// visitor their newsletter signup specifically didn't go through.
|
||||||
|
const newsletterDropped = !!body.newsletter && !newsletter;
|
||||||
|
|
||||||
|
// Checked before eligibility, so a retry still succeeds if the feedback
|
||||||
|
// window closed in the seconds after the original saved.
|
||||||
|
if (clientToken) {
|
||||||
|
const existingId = await findSubmissionIdByClientToken(clientToken, slug);
|
||||||
|
if (existingId !== null) {
|
||||||
|
logger.info('Feedback submission retry answered with the stored submission', {submissionId: existingId});
|
||||||
|
return {status: 'OK', submissionId: existingId, newsletterDropped};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const lookup = await getEventConfigBySlug(slug);
|
const lookup = await getEventConfigBySlug(slug);
|
||||||
if (lookup.status === 'NOT_FOUND') return {status: 'NOT_FOUND'};
|
if (lookup.status === 'NOT_FOUND') return {status: 'NOT_FOUND'};
|
||||||
if (lookup.status === 'CLOSED') return {status: 'CLOSED'};
|
if (lookup.status === 'CLOSED') return {status: 'CLOSED'};
|
||||||
@@ -159,13 +208,6 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
|
|||||||
|
|
||||||
const answerRows = validateAnswers(body.answers || [], questionsById, songTitleById);
|
const answerRows = validateAnswers(body.answers || [], questionsById, songTitleById);
|
||||||
const guestBook = validateGuestBook(body.guestBook);
|
const guestBook = validateGuestBook(body.guestBook);
|
||||||
const newsletter = validateNewsletter(body.newsletter);
|
|
||||||
// body.newsletter is only sent at all when the visitor had the opt-in
|
|
||||||
// checkbox on (see FeedbackForm.tsx), so a present-but-invalid block
|
|
||||||
// (e.g. a mistyped email) is distinguishable from "didn't opt in" - the
|
|
||||||
// rest of the submission still saves, but the client can tell the
|
|
||||||
// visitor their newsletter signup specifically didn't go through.
|
|
||||||
const newsletterDropped = !!body.newsletter && !newsletter;
|
|
||||||
|
|
||||||
if (answerRows.length === 0 && !guestBook && !newsletter) {
|
if (answerRows.length === 0 && !guestBook && !newsletter) {
|
||||||
return {status: 'EMPTY'};
|
return {status: 'EMPTY'};
|
||||||
@@ -175,8 +217,8 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
|
|||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
|
|
||||||
const subQuery = 'INSERT INTO submissions (event_id, ip_hash, has_guestbook, has_newsletter) VALUES (?,?,?,?) RETURNING submission_id';
|
const subQuery = 'INSERT INTO submissions (event_id, ip_hash, has_guestbook, has_newsletter, client_token) VALUES (?,?,?,?,?) RETURNING submission_id';
|
||||||
const subRes = await conn.query(subQuery, [eventId, ipHash, guestBook ? 1 : 0, newsletter ? 1 : 0]);
|
const subRes = await conn.query(subQuery, [eventId, ipHash, guestBook ? 1 : 0, newsletter ? 1 : 0, clientToken]);
|
||||||
const submissionId = subRes[0].submission_id;
|
const submissionId = subRes[0].submission_id;
|
||||||
|
|
||||||
for (const row of answerRows) {
|
for (const row of answerRows) {
|
||||||
@@ -220,8 +262,16 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {status: 'OK', submissionId, newsletterDropped};
|
return {status: 'OK', submissionId, newsletterDropped};
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
await conn.rollback();
|
await conn.rollback();
|
||||||
|
// Two copies of the same retry both got past the lookup above; the
|
||||||
|
// unique index on (event_id, client_token) let only one of them commit.
|
||||||
|
if (clientToken && err?.code === 'ER_DUP_ENTRY') {
|
||||||
|
const existingId = await findSubmissionIdByClientToken(clientToken, slug);
|
||||||
|
if (existingId !== null) {
|
||||||
|
return {status: 'OK', submissionId: existingId, newsletterDropped};
|
||||||
|
}
|
||||||
|
}
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
await conn.end();
|
await conn.end();
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import express, {Request, Response} from 'express';
|
import express, {Request, Response} from 'express';
|
||||||
import {requireAdminAuth} from '../tickets.auth.js';
|
import {requireAdminAuth} from '../tickets.auth.js';
|
||||||
|
import {isReadOnly} from '../../admin/admin.schema.js';
|
||||||
import {vouchersAdminRouter} from './vouchers.admin.router.js';
|
import {vouchersAdminRouter} from './vouchers.admin.router.js';
|
||||||
import {redemptionsAdminRouter, voucherHistoryRouter} from './redemptions.admin.router.js';
|
import {redemptionsAdminRouter, voucherHistoryRouter} from './redemptions.admin.router.js';
|
||||||
import {eventsAdminRouter} from './events.admin.router.js';
|
import {eventsAdminRouter} from './events.admin.router.js';
|
||||||
@@ -16,17 +17,35 @@ adminRouter.use(requireAdminAuth);
|
|||||||
* get:
|
* get:
|
||||||
* summary: Validate the current admin session
|
* summary: Validate the current admin session
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
|
* content:
|
||||||
|
* application/json:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* email:
|
||||||
|
* type: string
|
||||||
|
* fullName:
|
||||||
|
* type: string
|
||||||
|
* readOnly:
|
||||||
|
* type: boolean
|
||||||
|
* description: Holds only the read role for tickets - every write answers 403.
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
adminRouter.get('/me', (req: Request, res: Response) => {
|
adminRouter.get('/me', (req: Request, res: Response) => {
|
||||||
res.status(200).send({email: res.locals.admin.email, fullName: res.locals.admin.displayName});
|
res.status(200).send({
|
||||||
|
email: res.locals.admin.email,
|
||||||
|
fullName: res.locals.admin.displayName,
|
||||||
|
// Lets the frontend hide what the API would refuse anyway.
|
||||||
|
readOnly: isReadOnly(res.locals.admin.permissions, 'tickets')
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
adminRouter.use('/vouchers', vouchersAdminRouter);
|
adminRouter.use('/vouchers', vouchersAdminRouter);
|
||||||
|
|||||||
@@ -11,14 +11,15 @@ export const eventsAdminRouter = express.Router();
|
|||||||
* summary: List concerts for the admin event picker
|
* summary: List concerts for the admin event picker
|
||||||
* description: Wraps the Calendar module's public-calendar admin listing (includes DRAFT events).
|
* description: Wraps the Calendar module's public-calendar admin listing (includes DRAFT events).
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -35,14 +36,15 @@ eventsAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* summary: List public-calendar events not yet added to the ticket shop
|
* summary: List public-calendar events not yet added to the ticket shop
|
||||||
* description: Source list for the "add a concert" picker - the public calendar holds more than concerts, so events only appear in the ticket shop once explicitly added.
|
* description: Source list for the "add a concert" picker - the public calendar holds more than concerts, so events only appear in the ticket shop once explicitly added.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Success
|
* description: Success
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/available', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/available', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -58,9 +60,9 @@ eventsAdminRouter.get('/available', async (req: Request, res: Response) => {
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get a concert's voucher/capacity stats
|
* summary: Get a concert's voucher/capacity stats
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -75,6 +77,8 @@ eventsAdminRouter.get('/available', async (req: Request, res: Response) => {
|
|||||||
* $ref: '#/components/schemas/EventStats'
|
* $ref: '#/components/schemas/EventStats'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.get('/:eventId/stats', async (req: Request, res: Response) => {
|
eventsAdminRouter.get('/:eventId/stats', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -89,11 +93,11 @@ eventsAdminRouter.get('/:eventId/stats', async (req: Request, res: Response) =>
|
|||||||
* /tickets/admin/events/{eventId}/settings:
|
* /tickets/admin/events/{eventId}/settings:
|
||||||
* put:
|
* put:
|
||||||
* summary: Set a concert's voucher settings
|
* summary: Set a concert's voucher settings
|
||||||
* description: Upserts capacity (null = uncapped), redemption deadline (null = none), and whether to collect a mailing address.
|
* description: Upserts capacity (null = uncapped), redemption deadline (null = none), whether to collect a mailing address, and whether tickets are mailed to guests.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -118,15 +122,20 @@ eventsAdminRouter.get('/:eventId/stats', async (req: Request, res: Response) =>
|
|||||||
* requireAddress:
|
* requireAddress:
|
||||||
* type: boolean
|
* type: boolean
|
||||||
* description: Only meaningful when collectAddress is true.
|
* description: Only meaningful when collectAddress is true.
|
||||||
|
* ticketsMailed:
|
||||||
|
* type: boolean
|
||||||
|
* description: When false, the redemption confirmation email tells the guest their tickets await pickup at the Abendkasse instead.
|
||||||
* responses:
|
* responses:
|
||||||
* 200:
|
* 200:
|
||||||
* description: Saved
|
* description: Saved
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response) => {
|
eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const {capacity, redemptionDeadline, collectAddress, requireAddress} = req.body || {};
|
const {capacity, redemptionDeadline, collectAddress, requireAddress, ticketsMailed} = req.body || {};
|
||||||
await EventsAdminService.setEventSettings(Number(req.params.eventId), {
|
await EventsAdminService.setEventSettings(Number(req.params.eventId), {
|
||||||
capacity: capacity ?? null,
|
capacity: capacity ?? null,
|
||||||
// The mariadb driver needs an actual Date to serialize a DATETIME
|
// The mariadb driver needs an actual Date to serialize a DATETIME
|
||||||
@@ -134,7 +143,8 @@ eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response)
|
|||||||
// rejected with "Incorrect datetime value".
|
// rejected with "Incorrect datetime value".
|
||||||
redemptionDeadline: redemptionDeadline ? new Date(redemptionDeadline) : null,
|
redemptionDeadline: redemptionDeadline ? new Date(redemptionDeadline) : null,
|
||||||
collectAddress: !!collectAddress,
|
collectAddress: !!collectAddress,
|
||||||
requireAddress: !!collectAddress && !!requireAddress
|
requireAddress: !!collectAddress && !!requireAddress,
|
||||||
|
ticketsMailed: !!ticketsMailed
|
||||||
});
|
});
|
||||||
res.status(200).send({status: 'OK'});
|
res.status(200).send({status: 'OK'});
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -149,9 +159,9 @@ eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response)
|
|||||||
* summary: Remove an event from the ticket shop
|
* summary: Remove an event from the ticket shop
|
||||||
* description: Deletes its settings row, so it drops out of the picker and reappears in the "add" list. Refused with 409 if vouchers already reference the event - existing vouchers/redemptions stay valid either way.
|
* description: Deletes its settings row, so it drops out of the picker and reappears in the "add" list. Refused with 409 if vouchers already reference the event - existing vouchers/redemptions stay valid either way.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -164,6 +174,8 @@ eventsAdminRouter.put('/:eventId/settings', async (req: Request, res: Response)
|
|||||||
* description: Vouchers already reference this event
|
* description: Vouchers already reference this event
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
eventsAdminRouter.delete('/:eventId/settings', async (req: Request, res: Response) => {
|
eventsAdminRouter.delete('/:eventId/settings', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export interface EventPickerEntry {
|
|||||||
startDateTime: Date;
|
startDateTime: Date;
|
||||||
location: string;
|
location: string;
|
||||||
status: string | undefined;
|
status: string | undefined;
|
||||||
|
redemptionDeadline: Date | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,19 +27,26 @@ export interface EventPickerEntry {
|
|||||||
*/
|
*/
|
||||||
export const listEventsForPicker = async (): Promise<EventPickerEntry[]> => {
|
export const listEventsForPicker = async (): Promise<EventPickerEntry[]> => {
|
||||||
let conn = await NachklangTicketsDB.getConnection();
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
let enabledEventIds: number[];
|
let deadlineByEventId: Map<number, Date | null>;
|
||||||
try {
|
try {
|
||||||
const rows = await conn.query('SELECT event_id FROM event_ticket_settings');
|
const rows = await conn.query('SELECT event_id, redemption_deadline FROM event_ticket_settings');
|
||||||
enabledEventIds = rows.map((r: any) => r.event_id);
|
deadlineByEventId = new Map(rows.map((r: any) => [r.event_id, r.redemption_deadline]));
|
||||||
} finally {
|
} finally {
|
||||||
await conn.end();
|
await conn.end();
|
||||||
}
|
}
|
||||||
if (enabledEventIds.length === 0) return [];
|
if (deadlineByEventId.size === 0) return [];
|
||||||
|
|
||||||
const events = await Promise.all(enabledEventIds.map(id => CalendarEventsService.getEventById(id)));
|
const events = await Promise.all([...deadlineByEventId.keys()].map(id => CalendarEventsService.getEventById(id)));
|
||||||
return events
|
return events
|
||||||
.filter((e): e is NonNullable<typeof e> => e !== null && e.status !== 'DELETED')
|
.filter((e): e is NonNullable<typeof e> => e !== null && e.status !== 'DELETED')
|
||||||
.map(e => ({eventId: e.eventId, name: e.name, startDateTime: e.startDateTime, location: e.location, status: e.status}))
|
.map(e => ({
|
||||||
|
eventId: e.eventId,
|
||||||
|
name: e.name,
|
||||||
|
startDateTime: e.startDateTime,
|
||||||
|
location: e.location,
|
||||||
|
status: e.status,
|
||||||
|
redemptionDeadline: deadlineByEventId.get(e.eventId) ?? null
|
||||||
|
}))
|
||||||
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -59,7 +67,9 @@ export const listAvailableEventsToAdd = async (): Promise<EventPickerEntry[]> =>
|
|||||||
const events = await CalendarEventsService.getAllEventsAdmin(PUBLIC_CALENDAR_ID);
|
const events = await CalendarEventsService.getAllEventsAdmin(PUBLIC_CALENDAR_ID);
|
||||||
return events
|
return events
|
||||||
.filter(e => e.status !== 'DELETED' && !enabledEventIds.has(e.eventId))
|
.filter(e => e.status !== 'DELETED' && !enabledEventIds.has(e.eventId))
|
||||||
.map(e => ({eventId: e.eventId, name: e.name, startDateTime: e.startDateTime, location: e.location, status: e.status}))
|
// Not yet added to the ticket shop, so there's no event_ticket_settings
|
||||||
|
// row and therefore no deadline to report.
|
||||||
|
.map(e => ({eventId: e.eventId, name: e.name, startDateTime: e.startDateTime, location: e.location, status: e.status, redemptionDeadline: null}))
|
||||||
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
.sort((a, b) => a.startDateTime.getTime() - b.startDateTime.getTime());
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -89,6 +99,7 @@ export const getEventStats = async (eventId: number): Promise<EventStats> => {
|
|||||||
redemptionDeadline: ticketState.redemptionDeadline,
|
redemptionDeadline: ticketState.redemptionDeadline,
|
||||||
collectAddress: ticketState.collectAddress,
|
collectAddress: ticketState.collectAddress,
|
||||||
requireAddress: ticketState.requireAddress,
|
requireAddress: ticketState.requireAddress,
|
||||||
|
ticketsMailed: ticketState.ticketsMailed,
|
||||||
guestsUsed: ticketState.guestsUsed,
|
guestsUsed: ticketState.guestsUsed,
|
||||||
spotsRemaining: ticketState.spotsRemaining,
|
spotsRemaining: ticketState.spotsRemaining,
|
||||||
unusedCodes,
|
unusedCodes,
|
||||||
@@ -109,10 +120,10 @@ export const setEventSettings = async (eventId: number, settings: Omit<EventTick
|
|||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
await conn.query(
|
await conn.query(
|
||||||
`INSERT INTO event_ticket_settings (event_id, capacity, redemption_deadline, collect_address, require_address)
|
`INSERT INTO event_ticket_settings (event_id, capacity, redemption_deadline, collect_address, require_address, tickets_mailed)
|
||||||
VALUES (?,?,?,?,?)
|
VALUES (?,?,?,?,?,?)
|
||||||
ON DUPLICATE KEY UPDATE capacity = VALUES(capacity), redemption_deadline = VALUES(redemption_deadline), collect_address = VALUES(collect_address), require_address = VALUES(require_address)`,
|
ON DUPLICATE KEY UPDATE capacity = VALUES(capacity), redemption_deadline = VALUES(redemption_deadline), collect_address = VALUES(collect_address), require_address = VALUES(require_address), tickets_mailed = VALUES(tickets_mailed)`,
|
||||||
[eventId, settings.capacity, settings.redemptionDeadline, settings.collectAddress ? 1 : 0, settings.requireAddress ? 1 : 0]
|
[eventId, settings.capacity, settings.redemptionDeadline, settings.collectAddress ? 1 : 0, settings.requireAddress ? 1 : 0, settings.ticketsMailed ? 1 : 0]
|
||||||
);
|
);
|
||||||
await conn.commit();
|
await conn.commit();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ export const redemptionsAdminRouter = express.Router();
|
|||||||
* summary: List redemptions (admin)
|
* summary: List redemptions (admin)
|
||||||
* description: Filterable by event and status (ACTIVE/UNDONE).
|
* description: Filterable by event and status (ACTIVE/UNDONE).
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* schema:
|
* schema:
|
||||||
@@ -33,6 +33,8 @@ export const redemptionsAdminRouter = express.Router();
|
|||||||
* $ref: '#/components/schemas/RedemptionSummary'
|
* $ref: '#/components/schemas/RedemptionSummary'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -50,9 +52,9 @@ redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get a single redemption (admin)
|
* summary: Get a single redemption (admin)
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: redemptionId
|
* name: redemptionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -65,13 +67,15 @@ redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* description: Unknown redemption
|
* description: Unknown redemption
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
* patch:
|
* patch:
|
||||||
* summary: Edit a redemption's contact info and/or guest list
|
* summary: Edit a redemption's contact info and/or guest list
|
||||||
* description: Only fields present in the body are changed. Growing the guest count is re-checked against the voucher's max guests and the event's remaining capacity. Logs to the audit trail with an optional admin-supplied reason.
|
* description: Only fields present in the body are changed. Growing the guest count is re-checked against the voucher's max guests and the event's remaining capacity. Logs to the audit trail with an optional admin-supplied reason.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: redemptionId
|
* name: redemptionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -105,6 +109,8 @@ redemptionsAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* description: Not active, exceeds max guests, or exceeds remaining capacity
|
* description: Not active, exceeds max guests, or exceeds remaining capacity
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
redemptionsAdminRouter.get('/:redemptionId', async (req: Request, res: Response) => {
|
redemptionsAdminRouter.get('/:redemptionId', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -161,9 +167,9 @@ redemptionsAdminRouter.patch('/:redemptionId', async (req: Request, res: Respons
|
|||||||
* summary: Undo a redemption
|
* summary: Undo a redemption
|
||||||
* description: Reopens the code (back to UNUSED) and marks the redemption UNDONE. Guest data is kept for the audit trail; a later re-redemption creates a new redemption record.
|
* description: Reopens the code (back to UNUSED) and marks the redemption UNDONE. Guest data is kept for the audit trail; a later re-redemption creates a new redemption record.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: redemptionId
|
* name: redemptionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -186,6 +192,8 @@ redemptionsAdminRouter.patch('/:redemptionId', async (req: Request, res: Respons
|
|||||||
* description: Redemption is not active
|
* description: Redemption is not active
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Response) => {
|
redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -211,9 +219,9 @@ redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Res
|
|||||||
* summary: Resend the redemption confirmation email
|
* summary: Resend the redemption confirmation email
|
||||||
* description: Rebuilds the confirmation email from the stored redemption data and sends it again, then records the outcome on the redemption. Intended for redemptions whose original confirmation email failed.
|
* description: Rebuilds the confirmation email from the stored redemption data and sends it again, then records the outcome on the redemption. Intended for redemptions whose original confirmation email failed.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: redemptionId
|
* name: redemptionId
|
||||||
* required: true
|
* required: true
|
||||||
@@ -230,6 +238,8 @@ redemptionsAdminRouter.post('/:redemptionId/undo', async (req: Request, res: Res
|
|||||||
* description: The email relay rejected the send
|
* description: The email relay rejected the send
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
redemptionsAdminRouter.post('/:redemptionId/resend-confirmation', async (req: Request, res: Response) => {
|
redemptionsAdminRouter.post('/:redemptionId/resend-confirmation', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -259,9 +269,9 @@ redemptionsAdminRouter.post('/:redemptionId/resend-confirmation', async (req: Re
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get a voucher's admin-action audit trail
|
* summary: Get a voucher's admin-action audit trail
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: code
|
* name: code
|
||||||
* required: true
|
* required: true
|
||||||
@@ -278,6 +288,8 @@ redemptionsAdminRouter.post('/:redemptionId/resend-confirmation', async (req: Re
|
|||||||
* $ref: '#/components/schemas/AuditLogEntry'
|
* $ref: '#/components/schemas/AuditLogEntry'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
export const voucherHistoryRouter = express.Router();
|
export const voucherHistoryRouter = express.Router();
|
||||||
voucherHistoryRouter.get('/:code/history', async (req: Request, res: Response) => {
|
voucherHistoryRouter.get('/:code/history', async (req: Request, res: Response) => {
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ export const vouchersAdminRouter = express.Router();
|
|||||||
* summary: List vouchers (admin)
|
* summary: List vouchers (admin)
|
||||||
* description: Filterable by event and status.
|
* description: Filterable by event and status.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: eventId
|
* name: eventId
|
||||||
* schema:
|
* schema:
|
||||||
@@ -33,6 +33,8 @@ export const vouchersAdminRouter = express.Router();
|
|||||||
* $ref: '#/components/schemas/VoucherCode'
|
* $ref: '#/components/schemas/VoucherCode'
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
vouchersAdminRouter.get('/', async (req: Request, res: Response) => {
|
vouchersAdminRouter.get('/', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -51,9 +53,8 @@ vouchersAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* summary: Batch-generate wildcard codes
|
* summary: Batch-generate wildcard codes
|
||||||
* description: Generates `quantity` codes sharing the same eligible events and max-guest count, grouped under one batchId.
|
* description: Generates `quantity` codes sharing the same eligible events and max-guest count, grouped under one batchId.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -87,6 +88,8 @@ vouchersAdminRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
* description: Invalid input
|
* description: Invalid input
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -112,9 +115,8 @@ vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
|||||||
* summary: Bulk-create personalized codes
|
* summary: Bulk-create personalized codes
|
||||||
* description: One code per row (name, email, eligible events, max guests), grouped under one batchId.
|
* description: One code per row (name, email, eligible events, max guests), grouped under one batchId.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
* parameters:
|
* security:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
* - AdminSessionCookie: []
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* requestBody:
|
* requestBody:
|
||||||
* required: true
|
* required: true
|
||||||
* content:
|
* content:
|
||||||
@@ -127,12 +129,13 @@ vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
|||||||
* type: array
|
* type: array
|
||||||
* items:
|
* items:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [name, email, eventIds]
|
* required: [name, eventIds]
|
||||||
* properties:
|
* properties:
|
||||||
* name:
|
* name:
|
||||||
* type: string
|
* type: string
|
||||||
* email:
|
* email:
|
||||||
* type: string
|
* type: string
|
||||||
|
* description: Optional - a guest can supply their own email when redeeming.
|
||||||
* eventIds:
|
* eventIds:
|
||||||
* type: array
|
* type: array
|
||||||
* items:
|
* items:
|
||||||
@@ -147,6 +150,8 @@ vouchersAdminRouter.post('/wildcard', async (req: Request, res: Response) => {
|
|||||||
* description: Invalid input
|
* description: Invalid input
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
vouchersAdminRouter.post('/personalized', async (req: Request, res: Response) => {
|
vouchersAdminRouter.post('/personalized', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -169,9 +174,9 @@ vouchersAdminRouter.post('/personalized', async (req: Request, res: Response) =>
|
|||||||
* get:
|
* get:
|
||||||
* summary: Get a single voucher (admin)
|
* summary: Get a single voucher (admin)
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: code
|
* name: code
|
||||||
* required: true
|
* required: true
|
||||||
@@ -184,6 +189,8 @@ vouchersAdminRouter.post('/personalized', async (req: Request, res: Response) =>
|
|||||||
* description: Unknown code
|
* description: Unknown code
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
vouchersAdminRouter.get('/:code', async (req: Request, res: Response) => {
|
vouchersAdminRouter.get('/:code', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -205,9 +212,9 @@ vouchersAdminRouter.get('/:code', async (req: Request, res: Response) => {
|
|||||||
* summary: Void an unredeemed code
|
* summary: Void an unredeemed code
|
||||||
* description: Only allowed while the code is UNUSED. Logs to the voucher's audit trail.
|
* description: Only allowed while the code is UNUSED. Logs to the voucher's audit trail.
|
||||||
* tags: [tickets-admin]
|
* tags: [tickets-admin]
|
||||||
|
* security:
|
||||||
|
* - AdminSessionCookie: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - $ref: '#/components/parameters/SessionIdHeader'
|
|
||||||
* - $ref: '#/components/parameters/SessionKeyHeader'
|
|
||||||
* - in: path
|
* - in: path
|
||||||
* name: code
|
* name: code
|
||||||
* required: true
|
* required: true
|
||||||
@@ -230,6 +237,8 @@ vouchersAdminRouter.get('/:code', async (req: Request, res: Response) => {
|
|||||||
* description: Code is not in UNUSED status
|
* description: Code is not in UNUSED status
|
||||||
* 401:
|
* 401:
|
||||||
* description: Unauthorized
|
* description: Unauthorized
|
||||||
|
* 403:
|
||||||
|
* description: Signed in without the permission for this app, or account disabled
|
||||||
*/
|
*/
|
||||||
vouchersAdminRouter.post('/:code/void', async (req: Request, res: Response) => {
|
vouchersAdminRouter.post('/:code/void', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -123,10 +123,10 @@ export const generatePersonalizedBatch = async (rows: PersonalizedRowInput[], cr
|
|||||||
throw new Error('at least one row is required');
|
throw new Error('at least one row is required');
|
||||||
}
|
}
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (!row.name || !row.email || row.eventIds.length === 0) {
|
if (!row.name || row.eventIds.length === 0) {
|
||||||
throw new Error('each row requires a name, email, and at least one eligible event');
|
throw new Error('each row requires a name and at least one eligible event');
|
||||||
}
|
}
|
||||||
if (!isValidEmail(row.email)) {
|
if (row.email && !isValidEmail(row.email)) {
|
||||||
throw new Error(`"${row.email}" does not look like a valid email address`);
|
throw new Error(`"${row.email}" does not look like a valid email address`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,7 +147,7 @@ export const generatePersonalizedBatch = async (rows: PersonalizedRowInput[], cr
|
|||||||
codes.push(code);
|
codes.push(code);
|
||||||
await conn.query(
|
await conn.query(
|
||||||
'INSERT INTO voucher_codes (code, status, max_guests, prefill_name, prefill_email, batch_id, created_by_email) VALUES (?,?,?,?,?,?,?)',
|
'INSERT INTO voucher_codes (code, status, max_guests, prefill_name, prefill_email, batch_id, created_by_email) VALUES (?,?,?,?,?,?,?)',
|
||||||
[code, 'UNUSED', row.maxGuests, row.name, row.email, batchId, createdByEmail]
|
[code, 'UNUSED', row.maxGuests, row.name, row.email || null, batchId, createdByEmail]
|
||||||
);
|
);
|
||||||
for (const eventId of row.eventIds) {
|
for (const eventId of row.eventIds) {
|
||||||
await conn.query('INSERT INTO voucher_code_events (code, event_id) VALUES (?,?)', [code, eventId]);
|
await conn.query('INSERT INTO voucher_code_events (code, event_id) VALUES (?,?)', [code, eventId]);
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export const validateVoucher = async (code: string): Promise<VoucherValidation |
|
|||||||
name: event.name,
|
name: event.name,
|
||||||
startDateTime: event.startDateTime,
|
startDateTime: event.startDateTime,
|
||||||
location: event.location,
|
location: event.location,
|
||||||
|
redemptionDeadline: ticketState.redemptionDeadline,
|
||||||
deadlinePassed: ticketState.redemptionDeadline !== null && now > new Date(ticketState.redemptionDeadline),
|
deadlinePassed: ticketState.redemptionDeadline !== null && now > new Date(ticketState.redemptionDeadline),
|
||||||
isFull: ticketState.spotsRemaining !== null && ticketState.spotsRemaining <= 0,
|
isFull: ticketState.spotsRemaining !== null && ticketState.spotsRemaining <= 0,
|
||||||
spotsRemaining: ticketState.spotsRemaining,
|
spotsRemaining: ticketState.spotsRemaining,
|
||||||
|
|||||||
@@ -1,20 +1,23 @@
|
|||||||
import express from 'express';
|
import {requireAppAccess} from '../admin/admin.middleware.js';
|
||||||
import * as UserService from '../calendar/users/users.service.js';
|
|
||||||
import {sendServerError} from './tickets.errors.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mirrors the Feedback module's feedback.auth.ts: this is the ONLY place in
|
* Mirrors the Feedback module's feedback.auth.ts: this is the ONLY place in
|
||||||
* the tickets module that knows how admin authentication works. No route
|
* the tickets module that knows how admin authentication works. No route
|
||||||
* handler and no service outside this file may import users.service, read
|
* handler and no service outside this file may read session headers or
|
||||||
* session headers, or touch bcrypt.
|
* resolve a user itself.
|
||||||
*
|
*
|
||||||
* Today: reuses the existing Calendar users/sessions mechanism. Any
|
* Today: the shared admin identity in `src/models/admin/`. A session cookie
|
||||||
* activated @nachklang.art account may administer vouchers - no roles, same
|
* set by /admin/auth on admin.nachklang.art, plus a `tickets` permission on
|
||||||
* policy as Feedback (see docs/plan-ticket-shop.md). A dedicated
|
* the account. Both are re-checked on every request, so disabling a user or
|
||||||
* roles/permissions model is explicitly out of scope for v1.
|
* taking their tickets permission away takes effect immediately.
|
||||||
*
|
*
|
||||||
* Explicitly forbidden: accepting sessionId/sessionKey from query
|
* Before 2026-09-06 this was a header session against the calendar users
|
||||||
* parameters - headers only (see DEFERRED_SECURITY.md item 1).
|
* table, and any activated @nachklang.art account could administer vouchers
|
||||||
|
* (see docs/plan-ticket-shop.md, which called a roles model out of scope for
|
||||||
|
* v1). It is in scope now, and lives in the admin module rather than here.
|
||||||
|
*
|
||||||
|
* Explicitly forbidden: accepting session credentials from query parameters -
|
||||||
|
* see DEFERRED_SECURITY.md item 1.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface AdminIdentity {
|
export interface AdminIdentity {
|
||||||
@@ -23,41 +26,6 @@ export interface AdminIdentity {
|
|||||||
displayName: string;
|
displayName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AdminAuthenticator = (req: express.Request) => Promise<AdminIdentity | null>;
|
// On failure: 401 when not signed in, 403 when signed in without the tickets
|
||||||
|
// permission.
|
||||||
export const sessionHeaderAuthenticator: AdminAuthenticator = async (req) => {
|
export const requireAdminAuth = requireAppAccess('tickets');
|
||||||
const sessionId = req.header('X-Session-Id');
|
|
||||||
const sessionKey = req.header('X-Session-Key');
|
|
||||||
if (!sessionId || !sessionKey) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ip = req.ip || '';
|
|
||||||
const user = await UserService.checkSession(sessionId, sessionKey, ip);
|
|
||||||
|
|
||||||
if (!user || !user.isActive) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: String(user.userId),
|
|
||||||
email: user.email,
|
|
||||||
displayName: user.fullName
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const activeAuthenticator: AdminAuthenticator = sessionHeaderAuthenticator;
|
|
||||||
|
|
||||||
export const requireAdminAuth: express.RequestHandler = async (req, res, next) => {
|
|
||||||
try {
|
|
||||||
const identity = await activeAuthenticator(req);
|
|
||||||
if (!identity) {
|
|
||||||
res.status(401).send({status: 'UNAUTHORIZED', message: 'Anmeldung erforderlich.'});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.locals.admin = identity;
|
|
||||||
next();
|
|
||||||
} catch (e: any) {
|
|
||||||
sendServerError(res, e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -4,6 +4,7 @@ export interface EventTicketState {
|
|||||||
redemptionDeadline: Date | null;
|
redemptionDeadline: Date | null;
|
||||||
collectAddress: boolean;
|
collectAddress: boolean;
|
||||||
requireAddress: boolean;
|
requireAddress: boolean;
|
||||||
|
ticketsMailed: boolean;
|
||||||
guestsUsed: number;
|
guestsUsed: number;
|
||||||
spotsRemaining: number | null;
|
spotsRemaining: number | null;
|
||||||
}
|
}
|
||||||
@@ -21,7 +22,7 @@ export interface EventTicketState {
|
|||||||
* (uncapped) don't need this - there's no cap to race against.
|
* (uncapped) don't need this - there's no cap to race against.
|
||||||
*/
|
*/
|
||||||
export const getEventTicketState = async (conn: any, eventId: number, forUpdate = false): Promise<EventTicketState> => {
|
export const getEventTicketState = async (conn: any, eventId: number, forUpdate = false): Promise<EventTicketState> => {
|
||||||
const settingsQuery = `SELECT capacity, redemption_deadline, collect_address, require_address FROM event_ticket_settings WHERE event_id = ?${forUpdate ? ' FOR UPDATE' : ''}`;
|
const settingsQuery = `SELECT capacity, redemption_deadline, collect_address, require_address, tickets_mailed FROM event_ticket_settings WHERE event_id = ?${forUpdate ? ' FOR UPDATE' : ''}`;
|
||||||
const settingsRows = await conn.query(settingsQuery, [eventId]);
|
const settingsRows = await conn.query(settingsQuery, [eventId]);
|
||||||
const capacity = settingsRows.length > 0 ? settingsRows[0].capacity : null;
|
const capacity = settingsRows.length > 0 ? settingsRows[0].capacity : null;
|
||||||
const redemptionDeadline = settingsRows.length > 0 ? settingsRows[0].redemption_deadline : null;
|
const redemptionDeadline = settingsRows.length > 0 ? settingsRows[0].redemption_deadline : null;
|
||||||
@@ -29,6 +30,7 @@ export const getEventTicketState = async (conn: any, eventId: number, forUpdate
|
|||||||
// Only meaningful when collectAddress is also true - the field isn't
|
// Only meaningful when collectAddress is also true - the field isn't
|
||||||
// shown/collected at all otherwise, so "required" is moot.
|
// shown/collected at all otherwise, so "required" is moot.
|
||||||
const requireAddress = collectAddress && settingsRows.length > 0 ? !!settingsRows[0].require_address : false;
|
const requireAddress = collectAddress && settingsRows.length > 0 ? !!settingsRows[0].require_address : false;
|
||||||
|
const ticketsMailed = settingsRows.length > 0 ? !!settingsRows[0].tickets_mailed : false;
|
||||||
|
|
||||||
const usedRows = await conn.query(
|
const usedRows = await conn.query(
|
||||||
"SELECT COALESCE(SUM(guest_count), 0) as used FROM redemptions WHERE event_id = ? AND status = 'ACTIVE'",
|
"SELECT COALESCE(SUM(guest_count), 0) as used FROM redemptions WHERE event_id = ? AND status = 'ACTIVE'",
|
||||||
@@ -37,5 +39,5 @@ export const getEventTicketState = async (conn: any, eventId: number, forUpdate
|
|||||||
const guestsUsed = Number(usedRows[0].used);
|
const guestsUsed = Number(usedRows[0].used);
|
||||||
const spotsRemaining = capacity === null ? null : Math.max(0, capacity - guestsUsed);
|
const spotsRemaining = capacity === null ? null : Math.max(0, capacity - guestsUsed);
|
||||||
|
|
||||||
return {eventId, capacity, redemptionDeadline, collectAddress, requireAddress, guestsUsed, spotsRemaining};
|
return {eventId, capacity, redemptionDeadline, collectAddress, requireAddress, ticketsMailed, guestsUsed, spotsRemaining};
|
||||||
};
|
};
|
||||||
@@ -24,6 +24,23 @@ export interface ConfirmationRecipient {
|
|||||||
guestNames: string[];
|
guestNames: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an event's tickets are mailed to guests - read directly rather than
|
||||||
|
* via getEventTicketState (tickets.capacity.ts) since that also computes a
|
||||||
|
* live guest count this function doesn't need. Absent settings row (no
|
||||||
|
* ticket-shop config yet) defaults to false, same "absence over sentinels"
|
||||||
|
* convention as the rest of event_ticket_settings.
|
||||||
|
*/
|
||||||
|
const ticketsAreMailed = async (eventId: number): Promise<boolean> => {
|
||||||
|
let conn = await NachklangTicketsDB.getConnection();
|
||||||
|
try {
|
||||||
|
const rows = await conn.query('SELECT tickets_mailed FROM event_ticket_settings WHERE event_id = ?', [eventId]);
|
||||||
|
return rows.length > 0 ? !!rows[0].tickets_mailed : false;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends the redemption confirmation email for one redemption. Returns whether
|
* Sends the redemption confirmation email for one redemption. Returns whether
|
||||||
* the mail was accepted by the relay. Never throws: a missing event is treated
|
* the mail was accepted by the relay. Never throws: a missing event is treated
|
||||||
@@ -36,14 +53,20 @@ export const sendRedemptionConfirmation = async (recipient: ConfirmationRecipien
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ticketsMailed = await ticketsAreMailed(recipient.eventId);
|
||||||
|
const pickupNotice = ticketsMailed
|
||||||
|
? ''
|
||||||
|
: `\n\nDeine Tickets werden nicht postalisch versendet: Sie liegen am Konzertabend unter dem Namen ${recipient.contactName} für dich an der Abendkasse bereit.`;
|
||||||
|
|
||||||
const guestList = recipient.guestNames.map(name => `- ${name}`).join('\n');
|
const guestList = recipient.guestNames.map(name => `- ${name}`).join('\n');
|
||||||
const body =
|
const body =
|
||||||
`Hallo ${recipient.contactName},\n\n` +
|
`Hallo ${recipient.contactName},\n\n` +
|
||||||
`vielen Dank für deine Anmeldung zu "${event.name}"!\n\n` +
|
`vielen Dank für deine Anmeldung zu "${event.name}"!\n\n` +
|
||||||
`Termin: ${formatGermanDateTime(event.startDateTime)}\n` +
|
`Termin: ${formatGermanDateTime(event.startDateTime)}\n` +
|
||||||
`Ort: ${event.location}\n\n` +
|
`Ort: ${event.location}\n\n` +
|
||||||
`Angemeldete Gäste:\n${guestList}\n\n` +
|
`Angemeldete Gäste:\n${guestList}` +
|
||||||
`Wir freuen uns auf dich!\n\nDein Nachklang-Team`;
|
pickupNotice +
|
||||||
|
`\n\nWir freuen uns auf dich!\n\nDein Nachklang-Team`;
|
||||||
|
|
||||||
let icsAttachment;
|
let icsAttachment;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
* enum: [ACTIVE, UNDONE]
|
* enum: [ACTIVE, UNDONE]
|
||||||
* EligibleEvent:
|
* EligibleEvent:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [eventId, name, startDateTime, location, deadlinePassed, isFull, collectAddress, requireAddress]
|
* required: [eventId, name, startDateTime, location, redemptionDeadline, deadlinePassed, isFull, collectAddress, requireAddress]
|
||||||
* properties:
|
* properties:
|
||||||
* eventId:
|
* eventId:
|
||||||
* type: integer
|
* type: integer
|
||||||
@@ -23,6 +23,11 @@
|
|||||||
* format: date-time
|
* format: date-time
|
||||||
* location:
|
* location:
|
||||||
* type: string
|
* type: string
|
||||||
|
* redemptionDeadline:
|
||||||
|
* type: string
|
||||||
|
* format: date-time
|
||||||
|
* nullable: true
|
||||||
|
* description: null when the event has no redemption deadline set
|
||||||
* deadlinePassed:
|
* deadlinePassed:
|
||||||
* type: boolean
|
* type: boolean
|
||||||
* isFull:
|
* isFull:
|
||||||
@@ -144,7 +149,7 @@
|
|||||||
* type: integer
|
* type: integer
|
||||||
* EventTicketSettings:
|
* EventTicketSettings:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [eventId, collectAddress, requireAddress]
|
* required: [eventId, collectAddress, requireAddress, ticketsMailed]
|
||||||
* properties:
|
* properties:
|
||||||
* eventId:
|
* eventId:
|
||||||
* type: integer
|
* type: integer
|
||||||
@@ -160,9 +165,12 @@
|
|||||||
* requireAddress:
|
* requireAddress:
|
||||||
* type: boolean
|
* type: boolean
|
||||||
* description: Only meaningful when collectAddress is true.
|
* description: Only meaningful when collectAddress is true.
|
||||||
|
* ticketsMailed:
|
||||||
|
* type: boolean
|
||||||
|
* description: When false, the redemption confirmation email tells the guest their tickets await pickup at the Abendkasse instead.
|
||||||
* EventStats:
|
* EventStats:
|
||||||
* type: object
|
* type: object
|
||||||
* required: [eventId, collectAddress, requireAddress, guestsUsed, unusedCodes, redeemedCodes, voidCodes]
|
* required: [eventId, collectAddress, requireAddress, ticketsMailed, guestsUsed, unusedCodes, redeemedCodes, voidCodes]
|
||||||
* properties:
|
* properties:
|
||||||
* eventId:
|
* eventId:
|
||||||
* type: integer
|
* type: integer
|
||||||
@@ -177,6 +185,8 @@
|
|||||||
* type: boolean
|
* type: boolean
|
||||||
* requireAddress:
|
* requireAddress:
|
||||||
* type: boolean
|
* type: boolean
|
||||||
|
* ticketsMailed:
|
||||||
|
* type: boolean
|
||||||
* guestsUsed:
|
* guestsUsed:
|
||||||
* type: integer
|
* type: integer
|
||||||
* spotsRemaining:
|
* spotsRemaining:
|
||||||
@@ -224,6 +234,7 @@ export interface EligibleEvent {
|
|||||||
name: string;
|
name: string;
|
||||||
startDateTime: Date;
|
startDateTime: Date;
|
||||||
location: string;
|
location: string;
|
||||||
|
redemptionDeadline: Date | null;
|
||||||
deadlinePassed: boolean;
|
deadlinePassed: boolean;
|
||||||
isFull: boolean;
|
isFull: boolean;
|
||||||
spotsRemaining: number | null;
|
spotsRemaining: number | null;
|
||||||
@@ -285,6 +296,7 @@ export interface EventTicketSettings {
|
|||||||
redemptionDeadline: Date | null;
|
redemptionDeadline: Date | null;
|
||||||
collectAddress: boolean;
|
collectAddress: boolean;
|
||||||
requireAddress: boolean;
|
requireAddress: boolean;
|
||||||
|
ticketsMailed: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EventStats extends EventTicketSettings {
|
export interface EventStats extends EventTicketSettings {
|
||||||
|
|||||||
@@ -79,7 +79,12 @@ describe('bootstrapAdmin', () => {
|
|||||||
|
|
||||||
await bootstrapAdmin();
|
await bootstrapAdmin();
|
||||||
|
|
||||||
expect(createInvitation).toHaveBeenCalledWith('boss@nachklang.art', 'Nachklang Admin', ['admin'], null);
|
expect(createInvitation).toHaveBeenCalledWith(
|
||||||
|
'boss@nachklang.art',
|
||||||
|
'Nachklang Admin',
|
||||||
|
[{app: 'admin', role: 'access'}],
|
||||||
|
null
|
||||||
|
);
|
||||||
expect(mockMail).toHaveBeenCalled();
|
expect(mockMail).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
|
// admin.config calls dotenv.config(), which would read the repo's own .env and
|
||||||
|
// quietly reintroduce NODE_ENV=development - the exact value several of these
|
||||||
|
// cases exist to remove. Stub it so the tests see only what they set.
|
||||||
|
vi.mock('dotenv', () => ({config: vi.fn()}));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* admin.config reads the environment once at import, so every case here has to
|
||||||
|
* reset the module registry and re-import it. The two things worth pinning are
|
||||||
|
* the ones that are silent when wrong: which client-IP header is trusted, and
|
||||||
|
* whether an unset NODE_ENV counts as production.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ORIGINAL_ENV = {...process.env};
|
||||||
|
|
||||||
|
const loadConfig = async () => {
|
||||||
|
vi.resetModules();
|
||||||
|
return import('../../src/models/admin/admin.config.js');
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env = {...ORIGINAL_ENV};
|
||||||
|
// dotenv.config() in admin.config does not overwrite what is already set,
|
||||||
|
// so setting these here is enough to keep the local .env out of the test.
|
||||||
|
process.env.NODE_ENV = 'test';
|
||||||
|
delete process.env.CLIENT_IP_HEADERS;
|
||||||
|
delete process.env.TRUSTED_PROXY_IPS;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env = {...ORIGINAL_ENV};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CLIENT_IP_HEADERS', () => {
|
||||||
|
it('defaults to the single header Plesk nginx sets', async () => {
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual(['x-real-ip']);
|
||||||
|
expect(config.TRUST_NO_CLIENT_IP_HEADER).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads a comma-separated list', async () => {
|
||||||
|
process.env.CLIENT_IP_HEADERS = 'x-real-ip, cf-connecting-ip';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual(['x-real-ip', 'cf-connecting-ip']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trusts nothing when set to "none"', async () => {
|
||||||
|
// The escape hatch. An empty list is what better-auth reads as "no
|
||||||
|
// headers" - it only falls back to its own default when the option is
|
||||||
|
// absent - so this really does stop any header being believed.
|
||||||
|
process.env.CLIENT_IP_HEADERS = 'none';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual([]);
|
||||||
|
expect(config.TRUST_NO_CLIENT_IP_HEADER).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts the hatch case-insensitively and with stray whitespace', async () => {
|
||||||
|
process.env.CLIENT_IP_HEADERS = ' NONE ';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats an empty value as "use the default", not as the hatch', async () => {
|
||||||
|
// A blank line in a .env must not silently change how requests are
|
||||||
|
// bucketed - only the explicit word does that.
|
||||||
|
process.env.CLIENT_IP_HEADERS = '';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual(['x-real-ip']);
|
||||||
|
expect(config.TRUST_NO_CLIENT_IP_HEADER).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not mistake a header actually named none-ish for the hatch', async () => {
|
||||||
|
process.env.CLIENT_IP_HEADERS = 'x-none';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.CLIENT_IP_HEADERS).toEqual(['x-none']);
|
||||||
|
expect(config.TRUST_NO_CLIENT_IP_HEADER).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('APP_ORIGINS', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
delete process.env.APP_ORIGINS;
|
||||||
|
});
|
||||||
|
|
||||||
|
// These reach better-auth's trustedOrigins, and the step 4 cutover made the
|
||||||
|
// tickets and feedback origins load-bearing: without them their sign-out
|
||||||
|
// call is rejected while everything else still works.
|
||||||
|
it('defaults to the three production frontends', async () => {
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.APP_ORIGINS).toEqual([
|
||||||
|
'https://tickets.nachklang.art',
|
||||||
|
'https://feedback.nachklang.art',
|
||||||
|
'https://calendar.nachklang.art'
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is overridden wholesale by the environment, for a staging host', async () => {
|
||||||
|
process.env.APP_ORIGINS = 'https://tickets.staging.example, https://feedback.staging.example/';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.APP_ORIGINS).toEqual([
|
||||||
|
'https://tickets.staging.example',
|
||||||
|
// Trailing slash stripped: an origin with one never matches.
|
||||||
|
'https://feedback.staging.example'
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('always includes the admin app itself in ADMIN_ALLOWED_ORIGINS', async () => {
|
||||||
|
process.env.ADMIN_APP_URL = 'https://admin.nachklang.art';
|
||||||
|
const config = await loadConfig();
|
||||||
|
expect(config.ADMIN_ALLOWED_ORIGINS).toContain('https://admin.nachklang.art');
|
||||||
|
expect(config.ADMIN_ALLOWED_ORIGINS).toContain('https://tickets.nachklang.art');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isProd', () => {
|
||||||
|
it('is false only for the explicit relaxed environments', async () => {
|
||||||
|
process.env.NODE_ENV = 'development';
|
||||||
|
expect((await loadConfig()).isProd).toBe(false);
|
||||||
|
|
||||||
|
process.env.NODE_ENV = 'test';
|
||||||
|
expect((await loadConfig()).isProd).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats an unset NODE_ENV as production, which is what a bare vhost gives', async () => {
|
||||||
|
delete process.env.NODE_ENV;
|
||||||
|
// Strict mode refuses to boot without these; supply them so the import
|
||||||
|
// gets far enough to answer the question being asked.
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'x'.repeat(48);
|
||||||
|
process.env.API_BASE_URL = 'https://api.nachklang.art';
|
||||||
|
process.env.ADMIN_APP_URL = 'https://admin.nachklang.art';
|
||||||
|
|
||||||
|
expect((await loadConfig()).isProd).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses to start without a signing key outside development', async () => {
|
||||||
|
delete process.env.NODE_ENV;
|
||||||
|
delete process.env.BETTER_AUTH_SECRET;
|
||||||
|
process.env.API_BASE_URL = 'https://api.nachklang.art';
|
||||||
|
process.env.ADMIN_APP_URL = 'https://admin.nachklang.art';
|
||||||
|
|
||||||
|
await expect(loadConfig()).rejects.toThrow(/BETTER_AUTH_SECRET/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -15,7 +15,7 @@ import {requireAppAccess, requireSignedIn, resolveAccess} from '../../src/models
|
|||||||
const mockGetSession = auth.api.getSession as unknown as Mock;
|
const mockGetSession = auth.api.getSession as unknown as Mock;
|
||||||
const mockLoadAccess = UsersService.loadAccess as Mock;
|
const mockLoadAccess = UsersService.loadAccess as Mock;
|
||||||
|
|
||||||
const makeReq = (): Request => ({headers: {cookie: 'nachklang.session_token=abc'}} as unknown as Request);
|
const makeReq = (method = 'GET'): Request => ({method, headers: {cookie: 'nachklang.session_token=abc'}} as unknown as Request);
|
||||||
|
|
||||||
const makeRes = (): Response => {
|
const makeRes = (): Response => {
|
||||||
const res: any = {};
|
const res: any = {};
|
||||||
@@ -30,6 +30,10 @@ const activeUser = {
|
|||||||
email: 'a@nachklang.art',
|
email: 'a@nachklang.art',
|
||||||
displayName: 'A',
|
displayName: 'A',
|
||||||
disabled: false,
|
disabled: false,
|
||||||
|
permissions: [
|
||||||
|
{app: 'feedback', role: 'access'},
|
||||||
|
{app: 'admin', role: 'access'}
|
||||||
|
],
|
||||||
apps: ['feedback', 'admin']
|
apps: ['feedback', 'admin']
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -60,6 +64,10 @@ describe('resolveAccess', () => {
|
|||||||
email: 'a@nachklang.art',
|
email: 'a@nachklang.art',
|
||||||
displayName: 'A',
|
displayName: 'A',
|
||||||
disabled: false,
|
disabled: false,
|
||||||
|
permissions: [
|
||||||
|
{app: 'feedback', role: 'access'},
|
||||||
|
{app: 'admin', role: 'access'}
|
||||||
|
],
|
||||||
apps: ['feedback', 'admin']
|
apps: ['feedback', 'admin']
|
||||||
});
|
});
|
||||||
// No cookieCache: exactly one lookup per request, never zero.
|
// No cookieCache: exactly one lookup per request, never zero.
|
||||||
@@ -127,7 +135,11 @@ describe('requireAppAccess', () => {
|
|||||||
|
|
||||||
it('403s a signed-in user without that app permission', async () => {
|
it('403s a signed-in user without that app permission', async () => {
|
||||||
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
mockLoadAccess.mockResolvedValue({...activeUser, apps: ['feedback']});
|
mockLoadAccess.mockResolvedValue({
|
||||||
|
...activeUser,
|
||||||
|
permissions: [{app: 'feedback', role: 'access'}],
|
||||||
|
apps: ['feedback']
|
||||||
|
});
|
||||||
const res = makeRes();
|
const res = makeRes();
|
||||||
const next = vi.fn();
|
const next = vi.fn();
|
||||||
|
|
||||||
@@ -171,4 +183,98 @@ describe('requireAppAccess', () => {
|
|||||||
expect(res.status).toHaveBeenCalledWith(500);
|
expect(res.status).toHaveBeenCalledWith(500);
|
||||||
expect(next).not.toHaveBeenCalled();
|
expect(next).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The seam a finer per-app permission arrives through. Nothing passes a role
|
||||||
|
// today, so these two pin the behaviour before there is anything to break.
|
||||||
|
it('403s when a specific role is required and the user only holds another', async () => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue({
|
||||||
|
...activeUser,
|
||||||
|
permissions: [{app: 'tickets', role: 'access'}],
|
||||||
|
apps: ['tickets']
|
||||||
|
});
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('tickets', 'refund')(makeReq(), res, next);
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes when the user holds exactly the required role', async () => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue({
|
||||||
|
...activeUser,
|
||||||
|
permissions: [
|
||||||
|
{app: 'tickets', role: 'access'},
|
||||||
|
{app: 'tickets', role: 'refund'}
|
||||||
|
],
|
||||||
|
apps: ['tickets']
|
||||||
|
});
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('tickets', 'refund')(makeReq(), res, next);
|
||||||
|
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('read-only grant', () => {
|
||||||
|
const readOnlyUser = {
|
||||||
|
...activeUser,
|
||||||
|
permissions: [{app: 'tickets', role: 'read'}],
|
||||||
|
apps: ['tickets']
|
||||||
|
};
|
||||||
|
|
||||||
|
it.each(['GET', 'HEAD', 'OPTIONS'])('lets %s through', async method => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue(readOnlyUser);
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('tickets')(makeReq(method), res, next);
|
||||||
|
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['POST', 'PUT', 'PATCH', 'DELETE'])('403s %s', async method => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue(readOnlyUser);
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('tickets')(makeReq(method), res, next);
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(res.send).toHaveBeenCalledWith(expect.objectContaining({message: 'Du hast für diesen Bereich nur Lesezugriff.'}));
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let full access to another app write here', async () => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue({
|
||||||
|
...activeUser,
|
||||||
|
permissions: [{app: 'tickets', role: 'read'}, {app: 'feedback', role: 'access'}],
|
||||||
|
apps: ['feedback', 'tickets']
|
||||||
|
});
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('tickets')(makeReq('POST'), res, next);
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets full access write', async () => {
|
||||||
|
mockGetSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
mockLoadAccess.mockResolvedValue(activeUser);
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
|
||||||
|
await requireAppAccess('feedback')(makeReq('DELETE'), res, next);
|
||||||
|
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
import {
|
||||||
|
ACCESS_ROLE,
|
||||||
|
READ_ROLE,
|
||||||
|
appsOf,
|
||||||
|
canWrite,
|
||||||
|
isAppPermission,
|
||||||
|
isAppRole,
|
||||||
|
isReadOnly,
|
||||||
|
toPermissions
|
||||||
|
} from '../../src/models/admin/admin.schema.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The permission model is (app, role). These tests pin the two properties the
|
||||||
|
* rest of the module leans on: that the older `['tickets']` shape still means
|
||||||
|
* "tickets at the access role", and that nothing outside APP_ROLES gets in.
|
||||||
|
*/
|
||||||
|
|
||||||
|
describe('toPermissions', () => {
|
||||||
|
it('reads the full (app, role) form', () => {
|
||||||
|
expect(toPermissions([{app: 'tickets', role: 'access'}])).toEqual([
|
||||||
|
{app: 'tickets', role: 'access'}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads a plain app list as that app at the access role', () => {
|
||||||
|
expect(toPermissions(['feedback', 'admin'])).toEqual([
|
||||||
|
{app: 'feedback', role: ACCESS_ROLE},
|
||||||
|
{app: 'admin', role: ACCESS_ROLE}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts the two forms mixed, which is what a half-migrated caller sends', () => {
|
||||||
|
expect(toPermissions(['feedback', {app: 'tickets', role: 'access'}])).toEqual([
|
||||||
|
{app: 'feedback', role: ACCESS_ROLE},
|
||||||
|
{app: 'tickets', role: ACCESS_ROLE}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops duplicates of the same (app, role)', () => {
|
||||||
|
expect(toPermissions(['tickets', {app: 'tickets', role: 'access'}])).toEqual([
|
||||||
|
{app: 'tickets', role: ACCESS_ROLE}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects rather than silently dropping an unknown app', () => {
|
||||||
|
// Silently ignoring it would let "grant calendar + nonsense" look like a
|
||||||
|
// success while granting less than the caller asked for.
|
||||||
|
expect(toPermissions(['calendar', 'nonsense'])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown role', () => {
|
||||||
|
expect(toPermissions([{app: 'tickets', role: 'refund'}])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects anything that is not a list', () => {
|
||||||
|
expect(toPermissions('admin')).toBeNull();
|
||||||
|
expect(toPermissions(null)).toBeNull();
|
||||||
|
expect(toPermissions({app: 'admin', role: 'access'})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads an empty list as "no permissions", not as invalid', () => {
|
||||||
|
expect(toPermissions([])).toEqual([]);
|
||||||
|
});
|
||||||
|
it('reads the read-only role', () => {
|
||||||
|
expect(toPermissions([{app: 'tickets', role: READ_ROLE}])).toEqual([
|
||||||
|
{app: 'tickets', role: READ_ROLE}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects full and read-only access to the same app together', () => {
|
||||||
|
expect(toPermissions(['tickets', {app: 'tickets', role: READ_ROLE}])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows full access to one app next to read-only access to another', () => {
|
||||||
|
expect(toPermissions(['tickets', {app: 'feedback', role: READ_ROLE}])).toEqual([
|
||||||
|
{app: 'tickets', role: ACCESS_ROLE},
|
||||||
|
{app: 'feedback', role: READ_ROLE}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects read-only access to user management', () => {
|
||||||
|
expect(toPermissions([{app: 'admin', role: READ_ROLE}])).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('canWrite / isReadOnly', () => {
|
||||||
|
it('lets only the access role write', () => {
|
||||||
|
const permissions = [
|
||||||
|
{app: 'tickets' as const, role: ACCESS_ROLE},
|
||||||
|
{app: 'feedback' as const, role: READ_ROLE}
|
||||||
|
];
|
||||||
|
expect(canWrite(permissions, 'tickets')).toBe(true);
|
||||||
|
expect(canWrite(permissions, 'feedback')).toBe(false);
|
||||||
|
expect(isReadOnly(permissions, 'tickets')).toBe(false);
|
||||||
|
expect(isReadOnly(permissions, 'feedback')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is neither for an app without any grant', () => {
|
||||||
|
expect(canWrite([], 'calendar')).toBe(false);
|
||||||
|
expect(isReadOnly([], 'calendar')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isAppRole', () => {
|
||||||
|
it('accepts the access role for every app', () => {
|
||||||
|
expect(isAppRole('admin', ACCESS_ROLE)).toBe(true);
|
||||||
|
expect(isAppRole('calendar', ACCESS_ROLE)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a role that does not exist yet', () => {
|
||||||
|
expect(isAppRole('tickets', 'refund')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isAppPermission', () => {
|
||||||
|
it('needs both halves to be valid', () => {
|
||||||
|
expect(isAppPermission({app: 'tickets', role: ACCESS_ROLE})).toBe(true);
|
||||||
|
expect(isAppPermission({app: 'tickets'})).toBe(false);
|
||||||
|
expect(isAppPermission({role: ACCESS_ROLE})).toBe(false);
|
||||||
|
expect(isAppPermission(null)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('appsOf', () => {
|
||||||
|
it('collapses several roles on one app to a single entry', () => {
|
||||||
|
// The point of the derived list: a user with two roles on tickets has
|
||||||
|
// access to tickets once, not twice.
|
||||||
|
const apps = appsOf([
|
||||||
|
{app: 'tickets', role: ACCESS_ROLE},
|
||||||
|
{app: 'tickets', role: 'future-role'},
|
||||||
|
{app: 'admin', role: ACCESS_ROLE}
|
||||||
|
]);
|
||||||
|
expect(apps).toEqual(['tickets', 'admin']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is empty for no permissions', () => {
|
||||||
|
expect(appsOf([])).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
||||||
|
import express, {Request, Response} from 'express';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared body for the two cutover tests (2026-09-06). feedback.auth.ts and
|
||||||
|
* tickets.auth.ts used to carry their own header-session authenticator against
|
||||||
|
* the calendar users table; both are now one binding to the shared admin gate.
|
||||||
|
*
|
||||||
|
* What is worth asserting is not how that gate works - admin.middleware.test.ts
|
||||||
|
* owns that - but that each module is bound to *its own* app. The mocks live in
|
||||||
|
* the calling file because vi.mock is per-module-graph; only the assertions are
|
||||||
|
* shared.
|
||||||
|
*
|
||||||
|
* There used to be a tripwire here asserting neither module fell back to the
|
||||||
|
* calendar's header sessions. It went with step 5: the calendar users service
|
||||||
|
* no longer exists, so there is nothing left to fall back to and nothing to
|
||||||
|
* assert against.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface BindingMocks {
|
||||||
|
/** auth.api.getSession from the mocked admin.auth.js */
|
||||||
|
getSession: Mock;
|
||||||
|
/** loadAccess from the mocked users.admin.service.js */
|
||||||
|
loadAccess: Mock;
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeReq = (): Request => ({headers: {cookie: 'nachklang.session_token=abc'}} as unknown as Request);
|
||||||
|
|
||||||
|
const makeRes = (): Response => {
|
||||||
|
const res: any = {};
|
||||||
|
res.status = vi.fn().mockReturnValue(res);
|
||||||
|
res.send = vi.fn().mockReturnValue(res);
|
||||||
|
res.locals = {};
|
||||||
|
return res as Response;
|
||||||
|
};
|
||||||
|
|
||||||
|
const userWith = (...apps: string[]) => ({
|
||||||
|
id: 'u1',
|
||||||
|
email: 'a@nachklang.art',
|
||||||
|
displayName: 'Anna Admin',
|
||||||
|
disabled: false,
|
||||||
|
permissions: apps.map(app => ({app, role: 'access'})),
|
||||||
|
apps
|
||||||
|
});
|
||||||
|
|
||||||
|
export const describeAdminBinding = (
|
||||||
|
app: string,
|
||||||
|
otherApp: string,
|
||||||
|
middleware: express.RequestHandler,
|
||||||
|
mocks: () => BindingMocks
|
||||||
|
): void => {
|
||||||
|
describe(`${app} requireAdminAuth`, () => {
|
||||||
|
let m: BindingMocks;
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
const res = makeRes();
|
||||||
|
const next = vi.fn();
|
||||||
|
await middleware(makeReq(), res, next);
|
||||||
|
return {res, next};
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
m = mocks();
|
||||||
|
m.getSession.mockReset();
|
||||||
|
m.loadAccess.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('responds 401 and does not call next() without a session', async () => {
|
||||||
|
m.getSession.mockResolvedValue(null);
|
||||||
|
|
||||||
|
const {res, next} = await run();
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`responds 403 for a signed-in user who only has ${otherApp}`, async () => {
|
||||||
|
m.getSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
m.loadAccess.mockResolvedValue(userWith(otherApp));
|
||||||
|
|
||||||
|
const {res, next} = await run();
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('responds 403 for a disabled user who still holds the permission', async () => {
|
||||||
|
m.getSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
m.loadAccess.mockResolvedValue({...userWith(app), disabled: true});
|
||||||
|
|
||||||
|
const {res, next} = await run();
|
||||||
|
|
||||||
|
expect(res.status).toHaveBeenCalledWith(403);
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets res.locals.admin and calls next() with the permission', async () => {
|
||||||
|
m.getSession.mockResolvedValue({user: {id: 'u1'}});
|
||||||
|
m.loadAccess.mockResolvedValue(userWith(app));
|
||||||
|
|
||||||
|
const {res, next} = await run();
|
||||||
|
|
||||||
|
expect(next).toHaveBeenCalled();
|
||||||
|
expect(res.locals.admin).toMatchObject({id: 'u1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -97,7 +97,37 @@ describe('PUT /admin/users/:id/permissions', () => {
|
|||||||
const res = await request(makeApp('me')).put('/admin/users/other/permissions').send({apps: ['tickets']});
|
const res = await request(makeApp('me')).put('/admin/users/other/permissions').send({apps: ['tickets']});
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(service.setPermissionsGuarded).toHaveBeenCalledWith('other', ['tickets'], 'me');
|
expect(service.setPermissionsGuarded).toHaveBeenCalledWith(
|
||||||
|
'other',
|
||||||
|
[{app: 'tickets', role: 'access'}],
|
||||||
|
'me'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts the richer {permissions} body', async () => {
|
||||||
|
service.loadAccess.mockResolvedValue({id: 'other', disabled: false, apps: []});
|
||||||
|
|
||||||
|
const res = await request(makeApp('me'))
|
||||||
|
.put('/admin/users/other/permissions')
|
||||||
|
.send({permissions: [{app: 'tickets', role: 'access'}]});
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(service.setPermissionsGuarded).toHaveBeenCalledWith(
|
||||||
|
'other',
|
||||||
|
[{app: 'tickets', role: 'access'}],
|
||||||
|
'me'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a role that does not exist', async () => {
|
||||||
|
service.loadAccess.mockResolvedValue({id: 'other', disabled: false, apps: []});
|
||||||
|
|
||||||
|
const res = await request(makeApp('me'))
|
||||||
|
.put('/admin/users/other/permissions')
|
||||||
|
.send({permissions: [{app: 'tickets', role: 'refund'}]});
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(service.setPermissionsGuarded).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows granting permissions to someone who has none', async () => {
|
it('allows granting permissions to someone who has none', async () => {
|
||||||
@@ -106,7 +136,11 @@ describe('PUT /admin/users/:id/permissions', () => {
|
|||||||
const res = await request(makeApp('me')).put('/admin/users/other/permissions').send({apps: ['feedback', 'tickets']});
|
const res = await request(makeApp('me')).put('/admin/users/other/permissions').send({apps: ['feedback', 'tickets']});
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(service.setPermissionsGuarded).toHaveBeenCalledWith('other', ['feedback', 'tickets'], 'me');
|
expect(service.setPermissionsGuarded).toHaveBeenCalledWith(
|
||||||
|
'other',
|
||||||
|
[{app: 'feedback', role: 'access'}, {app: 'tickets', role: 'access'}],
|
||||||
|
'me'
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import {describe, expect, it, beforeEach} from 'vitest';
|
||||||
|
|
||||||
|
import * as CredentialService from '../../src/models/calendar/events/credentials.service.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The public calendar is read anonymously by nachklang.art to show the next
|
||||||
|
* upcoming event. That is a load-bearing property, not an accident: the step 4
|
||||||
|
* cutover moved every signed-in path onto session cookies and left these shared
|
||||||
|
* passwords behind only for iCal subscriptions, and the failure mode of getting
|
||||||
|
* it wrong is the public website silently losing its events feed.
|
||||||
|
*
|
||||||
|
* So this pins both halves: public needs nothing, and the restricted calendars
|
||||||
|
* still need something.
|
||||||
|
*/
|
||||||
|
describe('hasAccess', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env.MEMBER_CREDENTIAL = 'member-secret';
|
||||||
|
process.env.CHOIR_CREDENTIAL = 'choir-secret';
|
||||||
|
process.env.MANAGEMENT_CREDENTIAL = 'management-secret';
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets anyone read the public calendar with no password at all', async () => {
|
||||||
|
await expect(CredentialService.hasAccess('public', '')).resolves.toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['members', 'member-secret'],
|
||||||
|
['choir', 'choir-secret'],
|
||||||
|
['management', 'management-secret'],
|
||||||
|
['birthdays', 'choir-secret']
|
||||||
|
])('refuses %s without the credential and allows it with one', async (calendar, secret) => {
|
||||||
|
await expect(CredentialService.hasAccess(calendar, '')).resolves.toBe(false);
|
||||||
|
await expect(CredentialService.hasAccess(calendar, 'wrong')).resolves.toBe(false);
|
||||||
|
await expect(CredentialService.hasAccess(calendar, secret)).resolves.toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses an unknown calendar outright', async () => {
|
||||||
|
await expect(CredentialService.hasAccess('nope', 'member-secret')).resolves.toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a calendar whose credential is not configured', async () => {
|
||||||
|
// An unset MEMBER_CREDENTIAL must not become "any password works", and in
|
||||||
|
// particular must not become "an absent password works".
|
||||||
|
delete process.env.MEMBER_CREDENTIAL;
|
||||||
|
|
||||||
|
await expect(CredentialService.hasAccess('members', '')).resolves.toBe(false);
|
||||||
|
await expect(CredentialService.hasAccess('members', undefined as any)).resolves.toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
import {describe, expect, it, vi, beforeEach} from 'vitest';
|
||||||
|
import express from 'express';
|
||||||
|
import request from 'supertest';
|
||||||
|
|
||||||
|
vi.mock('../../src/models/calendar/events/events.service.js', () => ({
|
||||||
|
getAllEvents: vi.fn(),
|
||||||
|
getAllEventsAdmin: vi.fn(),
|
||||||
|
getEventById: vi.fn(),
|
||||||
|
createEvent: vi.fn(),
|
||||||
|
updateEvent: vi.fn(),
|
||||||
|
deleteEvent: vi.fn(),
|
||||||
|
moveEvent: vi.fn(),
|
||||||
|
getNextUpcomingEvent: vi.fn()
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../src/models/admin/admin.auth.js', () => ({
|
||||||
|
auth: {api: {getSession: vi.fn()}}
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../src/models/admin/users/users.admin.service.js', () => ({
|
||||||
|
loadAccess: vi.fn()
|
||||||
|
}));
|
||||||
|
|
||||||
|
import * as EventService from '../../src/models/calendar/events/events.service.js';
|
||||||
|
import {auth} from '../../src/models/admin/admin.auth.js';
|
||||||
|
import * as UsersService from '../../src/models/admin/users/users.admin.service.js';
|
||||||
|
import {eventsRouter} from '../../src/models/calendar/events/events.router.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Step 4 of docs/calendar-auth-migration.md at the route level. The unit test
|
||||||
|
* on credentials.service covers the password table; this covers the thing that
|
||||||
|
* table is wired into, which is where the interesting mistakes live:
|
||||||
|
*
|
||||||
|
* - the public calendar has to stay readable with no session and no password,
|
||||||
|
* - the shared password has to keep working for the restricted calendars,
|
||||||
|
* because iCal clients cannot send a cookie,
|
||||||
|
* - and every write has to be behind the session cookie *and* an explicit
|
||||||
|
* calendar permission, not merely behind "is signed in".
|
||||||
|
*/
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
app.use(express.json());
|
||||||
|
app.use('/calendar/events', eventsRouter);
|
||||||
|
|
||||||
|
const signedInAs = (apps: string[], disabled = false) => {
|
||||||
|
(auth.api.getSession as any).mockResolvedValue({user: {id: 'admin-1'}});
|
||||||
|
(UsersService.loadAccess as any).mockResolvedValue({
|
||||||
|
id: 'admin-1',
|
||||||
|
email: 'a@nachklang.art',
|
||||||
|
displayName: 'A',
|
||||||
|
disabled,
|
||||||
|
permissions: apps.map(app => ({app, role: 'access'})),
|
||||||
|
apps
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const signedOut = () => {
|
||||||
|
(auth.api.getSession as any).mockResolvedValue(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const validEvent = {
|
||||||
|
calendarId: 1,
|
||||||
|
name: 'Konzert',
|
||||||
|
startDateTime: '2026-04-18T19:00:00Z',
|
||||||
|
endDateTime: '2026-04-18T21:00:00Z'
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
process.env.MEMBER_CREDENTIAL = 'member-secret';
|
||||||
|
process.env.CHOIR_CREDENTIAL = 'choir & more';
|
||||||
|
process.env.MANAGEMENT_CREDENTIAL = '';
|
||||||
|
(EventService.getAllEvents as any).mockResolvedValue([]);
|
||||||
|
(EventService.getAllEventsAdmin as any).mockResolvedValue([]);
|
||||||
|
(EventService.getNextUpcomingEvent as any).mockResolvedValue({eventId: 1, name: 'Konzert'});
|
||||||
|
(EventService.createEvent as any).mockResolvedValue(1);
|
||||||
|
(EventService.updateEvent as any).mockResolvedValue(1);
|
||||||
|
(EventService.moveEvent as any).mockResolvedValue(true);
|
||||||
|
(EventService.deleteEvent as any).mockResolvedValue(true);
|
||||||
|
signedOut();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reading', () => {
|
||||||
|
it('serves the public calendar anonymously', async () => {
|
||||||
|
// The property nachklang.art depends on. No cookie, no password.
|
||||||
|
await request(app).get('/calendar/events/public/json').expect(200);
|
||||||
|
|
||||||
|
// And as the non-admin view: an anonymous caller must not see drafts.
|
||||||
|
expect(EventService.getAllEvents).toHaveBeenCalled();
|
||||||
|
expect(EventService.getAllEventsAdmin).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a restricted calendar with neither session nor password', async () => {
|
||||||
|
await request(app).get('/calendar/events/members/json').expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves a restricted calendar to a shared password, without drafts', async () => {
|
||||||
|
await request(app)
|
||||||
|
.get('/calendar/events/members/json')
|
||||||
|
.query({password: 'member-secret'})
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(EventService.getAllEvents).toHaveBeenCalled();
|
||||||
|
expect(EventService.getAllEventsAdmin).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives a signed-in editor the admin view instead', async () => {
|
||||||
|
signedInAs(['calendar']);
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/members/json').expect(200);
|
||||||
|
|
||||||
|
expect(EventService.getAllEventsAdmin).toHaveBeenCalled();
|
||||||
|
expect(EventService.getAllEvents).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a signed-in user without the calendar permission as anonymous', async () => {
|
||||||
|
// Not a 403: they may still read the public calendar like anyone else.
|
||||||
|
signedInAs(['tickets']);
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/public/json').expect(200);
|
||||||
|
expect(EventService.getAllEvents).toHaveBeenCalled();
|
||||||
|
expect(EventService.getAllEventsAdmin).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/members/json').expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still serves the public calendar when the admin database is down', async () => {
|
||||||
|
(auth.api.getSession as any).mockRejectedValue(new Error('ECONNREFUSED'));
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/public/json').expect(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The endpoint www.nachklang.art actually calls for its next-event teaser.
|
||||||
|
// Tested separately from /json because it takes a different code path - it
|
||||||
|
// has no admin view and no editor branch - so covering /json proves nothing
|
||||||
|
// about it, and its failure is invisible until someone notices the website
|
||||||
|
// has gone quiet.
|
||||||
|
it('serves the next upcoming event anonymously on the public calendar', async () => {
|
||||||
|
await request(app).get('/calendar/events/public/json/next').expect(200);
|
||||||
|
|
||||||
|
// And without asking the admin database who the caller is: the public
|
||||||
|
// feed must not acquire a dependency it has never had.
|
||||||
|
expect(auth.api.getSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses the next upcoming event on a restricted calendar without a credential', async () => {
|
||||||
|
await request(app).get('/calendar/events/members/json/next').expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves the next upcoming event to a shared password', async () => {
|
||||||
|
await request(app)
|
||||||
|
.get('/calendar/events/members/json/next')
|
||||||
|
.query({password: 'member-secret'})
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves the next upcoming event to a signed-in editor', async () => {
|
||||||
|
signedInAs(['calendar']);
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/members/json/next').expect(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not consult the admin database for the anonymous public iCal export', async () => {
|
||||||
|
await request(app).get('/calendar/events/public/ical').expect(200);
|
||||||
|
|
||||||
|
expect(auth.api.getSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves the iCal export as text/calendar', async () => {
|
||||||
|
const res = await request(app).get('/calendar/events/public/ical').expect(200);
|
||||||
|
|
||||||
|
expect(res.headers['content-type']).toBe('text/calendar; charset=utf-8');
|
||||||
|
expect(res.headers['content-disposition']).toBe('attachment; filename=Nachklang_calendar.ics');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the shared password working on the iCal export', async () => {
|
||||||
|
(EventService.getAllEvents as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
await request(app).get('/calendar/events/public/ical').expect(200);
|
||||||
|
await request(app).get('/calendar/events/members/ical').expect(403);
|
||||||
|
await request(app)
|
||||||
|
.get('/calendar/events/members/ical')
|
||||||
|
.query({password: 'member-secret'})
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('writing', () => {
|
||||||
|
it.each([
|
||||||
|
['post', '/calendar/events'],
|
||||||
|
['put', '/calendar/events/1'],
|
||||||
|
['put', '/calendar/events/move/1'],
|
||||||
|
['delete', '/calendar/events/1']
|
||||||
|
])('%s %s answers 401 when signed out', async (method, path) => {
|
||||||
|
await (request(app) as any)[method](path).send(validEvent).expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['post', '/calendar/events'],
|
||||||
|
['put', '/calendar/events/1'],
|
||||||
|
['put', '/calendar/events/move/1'],
|
||||||
|
['delete', '/calendar/events/1']
|
||||||
|
])('%s %s answers 403 without the calendar permission', async (method, path) => {
|
||||||
|
signedInAs(['tickets', 'feedback', 'admin']);
|
||||||
|
await (request(app) as any)[method](path).send(validEvent).expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers 403 for a disabled account that still holds the permission', async () => {
|
||||||
|
signedInAs(['calendar'], true);
|
||||||
|
await request(app).post('/calendar/events').send(validEvent).expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records the writer as an admin user id, never a legacy one', async () => {
|
||||||
|
signedInAs(['calendar']);
|
||||||
|
|
||||||
|
await request(app).post('/calendar/events').send(validEvent).expect(201);
|
||||||
|
|
||||||
|
const written = (EventService.createEvent as any).mock.calls[0][0];
|
||||||
|
expect(written.createdByUserId).toBe('admin-1');
|
||||||
|
// Migration 003 made the legacy column nullable precisely so this can be unset.
|
||||||
|
expect(written.createdById).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses the shared password as a way to write', async () => {
|
||||||
|
// The passwords are a read fallback for clients that cannot hold a
|
||||||
|
// session. They must never become an editing credential.
|
||||||
|
await request(app)
|
||||||
|
.post('/calendar/events')
|
||||||
|
.query({password: 'member-secret'})
|
||||||
|
.send(validEvent)
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('subscriptions', () => {
|
||||||
|
it('is not for anyone signed out, or signed in without the calendar permission', async () => {
|
||||||
|
await request(app).get('/calendar/events/subscriptions').expect(401);
|
||||||
|
|
||||||
|
signedInAs(['tickets']);
|
||||||
|
await request(app).get('/calendar/events/subscriptions').expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses the shared password as a way in', async () => {
|
||||||
|
// Otherwise one calendar's password would unlock all the others.
|
||||||
|
await request(app).get('/calendar/events/subscriptions').query({password: 'member-secret'}).expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists a ready-made iCal URL per configured calendar, never cached', async () => {
|
||||||
|
signedInAs(['calendar']);
|
||||||
|
|
||||||
|
const res = await request(app).get('/calendar/events/subscriptions').expect(200);
|
||||||
|
|
||||||
|
expect(res.headers['cache-control']).toBe('no-store');
|
||||||
|
expect(res.body).toEqual([
|
||||||
|
{calendar: 'public', icalUrl: 'http://localhost:3000/calendar/events/public/ical'},
|
||||||
|
{calendar: 'members', icalUrl: 'http://localhost:3000/calendar/events/members/ical?password=member-secret'},
|
||||||
|
// URL-encoded, so a password with & or spaces survives.
|
||||||
|
{calendar: 'choir', icalUrl: 'http://localhost:3000/calendar/events/choir/ical?password=choir%20%26%20more'},
|
||||||
|
// management is missing: its credential is unset, and a URL without one could never work.
|
||||||
|
{calendar: 'birthdays', icalUrl: 'http://localhost:3000/calendar/events/birthdays/ical?password=choir%20%26%20more'}
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hands out URLs that actually open the calendar', async () => {
|
||||||
|
signedInAs(['calendar']);
|
||||||
|
const res = await request(app).get('/calendar/events/subscriptions').expect(200);
|
||||||
|
const members = res.body.find((s: {calendar: string}) => s.calendar === 'members');
|
||||||
|
|
||||||
|
signedOut();
|
||||||
|
const path = new URL(members.icalUrl);
|
||||||
|
await request(app).get(path.pathname + path.search).expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import {describe, expect, it, vi, beforeEach} from 'vitest';
|
||||||
|
|
||||||
|
const connection = {
|
||||||
|
query: vi.fn(),
|
||||||
|
execute: vi.fn(),
|
||||||
|
beginTransaction: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
rollback: vi.fn(),
|
||||||
|
end: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock('../../src/models/calendar/Calendar.db.js', () => ({
|
||||||
|
NachklangCalendarDB: {getConnection: vi.fn(async () => connection)}
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../src/models/admin/users/users.admin.service.js', () => ({
|
||||||
|
findDisplayNames: vi.fn()
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {NachklangCalendarDB} from '../../src/models/calendar/Calendar.db.js';
|
||||||
|
import * as AdminUsersService from '../../src/models/admin/users/users.admin.service.js';
|
||||||
|
import * as EventService from '../../src/models/calendar/events/events.service.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Step 3 of docs/calendar-auth-migration.md. The property under test is that
|
||||||
|
* an event's creator resolves from the stronger of its two remaining sources -
|
||||||
|
* the live admin name, else the name archived before the legacy users table was
|
||||||
|
* removed - and that a failure to reach the admin database costs a name rather
|
||||||
|
* than the whole response: the public calendar is read anonymously by the
|
||||||
|
* website and has never depended on the admin database being up.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// One row of the shape the shared SELECT produces.
|
||||||
|
const row = (over: Record<string, unknown> = {}) => ({
|
||||||
|
event_id: 1,
|
||||||
|
calendar_id: 1,
|
||||||
|
uuid: 'uuid-1',
|
||||||
|
name: 'Konzert',
|
||||||
|
description: '',
|
||||||
|
start_datetime: new Date('2026-04-18T19:00:00Z'),
|
||||||
|
end_datetime: new Date('2026-04-18T21:00:00Z'),
|
||||||
|
created_date: new Date('2026-01-01T00:00:00Z'),
|
||||||
|
version_created_at: new Date('2026-01-02T00:00:00Z'),
|
||||||
|
location: '',
|
||||||
|
created_by_user_id: null,
|
||||||
|
created_by_name: 'Archived Person',
|
||||||
|
version_created_by_user_id: null,
|
||||||
|
version_created_by_name: 'Archived Person',
|
||||||
|
url: '',
|
||||||
|
whole_day: 0,
|
||||||
|
repeat_frequency: '',
|
||||||
|
status: 'PUBLIC',
|
||||||
|
...over
|
||||||
|
});
|
||||||
|
|
||||||
|
/** getAllEvents runs the calendars lookup first, then the events query. */
|
||||||
|
const givenEvents = (...rows: unknown[]) => {
|
||||||
|
connection.query.mockReset();
|
||||||
|
connection.query
|
||||||
|
.mockResolvedValueOnce([{calendar_id: 1, includes_calendars: '[]'}])
|
||||||
|
.mockResolvedValueOnce(rows);
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
connection.end.mockResolvedValue(undefined);
|
||||||
|
(NachklangCalendarDB.getConnection as any).mockResolvedValue(connection);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('creator names', () => {
|
||||||
|
it('uses the archived name when the row has no admin id', async () => {
|
||||||
|
givenEvents(row());
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events[0].createdBy).toBe('Archived Person');
|
||||||
|
expect(events[0].createdByUserId).toBeNull();
|
||||||
|
// Nothing to resolve, so the admin database is not touched at all.
|
||||||
|
expect(AdminUsersService.findDisplayNames).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prefers the admin name when the row carries an admin id', async () => {
|
||||||
|
givenEvents(row({
|
||||||
|
created_by_user_id: 'admin-1',
|
||||||
|
version_created_by_user_id: 'admin-2'
|
||||||
|
}));
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockResolvedValue(
|
||||||
|
new Map([['admin-1', 'Neue Person'], ['admin-2', 'Andere Person']])
|
||||||
|
);
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events[0].createdBy).toBe('Neue Person');
|
||||||
|
expect(events[0].lastModifiedBy).toBe('Andere Person');
|
||||||
|
expect(events[0].createdByUserId).toBe('admin-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prefers the live admin name over the snapshot', async () => {
|
||||||
|
// A renamed account has to win over an archive that was correct when it
|
||||||
|
// was taken - otherwise renaming someone would leave stale names behind.
|
||||||
|
givenEvents(row({created_by_user_id: 'admin-1', created_by_name: 'Archived Person'}));
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockResolvedValue(new Map([['admin-1', 'Neue Person']]));
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events[0].createdBy).toBe('Neue Person');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the archived name when the admin account is gone', async () => {
|
||||||
|
givenEvents(row({created_by_user_id: 'deleted'}));
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockResolvedValue(new Map());
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events[0].createdBy).toBe('Archived Person');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the name blank when a row has neither source', async () => {
|
||||||
|
// A post-cutover event whose author was later deleted from the admin
|
||||||
|
// module: no snapshot was ever taken for it, and the id resolves to
|
||||||
|
// nothing. Blank is the designed outcome - the creator is decoration.
|
||||||
|
givenEvents(row({created_by_user_id: 'deleted', created_by_name: null}));
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockResolvedValue(new Map());
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events[0].createdBy).toBeNull();
|
||||||
|
expect(events).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves a mixed result set in a single lookup', async () => {
|
||||||
|
givenEvents(
|
||||||
|
row({event_id: 1}),
|
||||||
|
row({event_id: 2, created_by_user_id: 'admin-1', version_created_by_user_id: 'admin-1'}),
|
||||||
|
row({event_id: 3, created_by_user_id: 'admin-1', version_created_by_user_id: 'admin-1'})
|
||||||
|
);
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockResolvedValue(new Map([['admin-1', 'Neue Person']]));
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events.map(e => e.createdBy)).toEqual(['Archived Person', 'Neue Person', 'Neue Person']);
|
||||||
|
expect(AdminUsersService.findDisplayNames).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still returns the events when the admin database is unreachable', async () => {
|
||||||
|
givenEvents(row({created_by_user_id: 'admin-1'}));
|
||||||
|
(AdminUsersService.findDisplayNames as any).mockRejectedValue(new Error('ECONNREFUSED'));
|
||||||
|
|
||||||
|
const events = await EventService.getAllEvents(1);
|
||||||
|
|
||||||
|
expect(events).toHaveLength(1);
|
||||||
|
expect(events[0].name).toBe('Konzert');
|
||||||
|
// Degrades to the archived name rather than failing the request.
|
||||||
|
expect(events[0].createdBy).toBe('Archived Person');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('status', () => {
|
||||||
|
it('is omitted from the public listing and present in the admin one', async () => {
|
||||||
|
givenEvents(row());
|
||||||
|
const publicEvents = await EventService.getAllEvents(1);
|
||||||
|
expect(publicEvents[0].status).toBeUndefined();
|
||||||
|
|
||||||
|
connection.query.mockReset();
|
||||||
|
connection.query.mockResolvedValueOnce([row()]);
|
||||||
|
const adminEvents = await EventService.getAllEventsAdmin(1);
|
||||||
|
expect(adminEvents[0].status).toBe('PUBLIC');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {convertToIcal, escapeText, foldLine} from '../../src/models/calendar/events/icalgenerator.service.js';
|
||||||
|
import {Event} from '../../src/models/calendar/events/event.interface.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The iCal export is read by every subscribed calendar app, so a malformed
|
||||||
|
* file is an outage nobody on our side sees. These pin RFC 5545's text
|
||||||
|
* escaping and line folding, which the generator did not do before: a line
|
||||||
|
* break in a description ended the DESCRIPTION property early, and the new
|
||||||
|
* calendar frontend's multi-line description field would have produced
|
||||||
|
* exactly that.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const event = (overrides: Partial<Event> = {}): Event => ({
|
||||||
|
eventId: 1,
|
||||||
|
calendarId: 1,
|
||||||
|
uuid: 'uuid-1',
|
||||||
|
name: 'Konzert',
|
||||||
|
description: '',
|
||||||
|
startDateTime: new Date('2026-10-03T17:00:00Z'),
|
||||||
|
endDateTime: new Date('2026-10-03T19:00:00Z'),
|
||||||
|
createdDate: new Date('2026-01-01T12:00:00Z'),
|
||||||
|
location: '',
|
||||||
|
createdBy: 'Anna',
|
||||||
|
url: '',
|
||||||
|
wholeDay: false,
|
||||||
|
repeatFrequency: '',
|
||||||
|
...overrides
|
||||||
|
});
|
||||||
|
|
||||||
|
/** RFC 5545 unfolding: a CRLF followed by one space or tab joins the lines. */
|
||||||
|
const unfold = (ical: string): string[] => ical.replace(/\r\n[ \t]/g, '').split('\r\n').filter(Boolean);
|
||||||
|
|
||||||
|
describe('escapeText', () => {
|
||||||
|
it('escapes backslash, semicolon, comma and line breaks', () => {
|
||||||
|
expect(escapeText('a\\b;c,d')).toBe('a\\\\b\\;c\\,d');
|
||||||
|
expect(escapeText('Zeile 1\nZeile 2\r\nZeile 3\rZeile 4')).toBe('Zeile 1\\nZeile 2\\nZeile 3\\nZeile 4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('escapes the backslash first, so the others are not doubled', () => {
|
||||||
|
expect(escapeText(';')).toBe('\\;');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('foldLine', () => {
|
||||||
|
it('leaves a short line alone', () => {
|
||||||
|
expect(foldLine('SUMMARY:Konzert')).toBe('SUMMARY:Konzert');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps every physical line within 75 octets and unfolds back to the original', () => {
|
||||||
|
const line = 'DESCRIPTION:' + 'Probe im Gemeindehaus Süd – bitte Noten mitbringen. '.repeat(6);
|
||||||
|
const folded = foldLine(line);
|
||||||
|
for (const physical of folded.split('\r\n')) {
|
||||||
|
expect(Buffer.byteLength(physical, 'utf8')).toBeLessThanOrEqual(75);
|
||||||
|
}
|
||||||
|
expect(folded.replace(/\r\n /g, '')).toBe(line);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never splits a multi-byte character', () => {
|
||||||
|
const line = 'SUMMARY:' + 'ü'.repeat(80);
|
||||||
|
for (const physical of foldLine(line).split('\r\n')) {
|
||||||
|
expect(physical.replace(/^ /, '')).toMatch(/^(SUMMARY:)?ü*$/);
|
||||||
|
expect(Buffer.byteLength(physical, 'utf8')).toBeLessThanOrEqual(75);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('convertToIcal', () => {
|
||||||
|
it('terminates every line with CRLF', async () => {
|
||||||
|
const ical = await convertToIcal([event()]);
|
||||||
|
expect(ical.endsWith('END:VCALENDAR\r\n')).toBe(true);
|
||||||
|
expect(ical.replace(/\r\n/g, '')).not.toContain('\n');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a multi-line description inside one DESCRIPTION property', async () => {
|
||||||
|
const ical = await convertToIcal([event({description: 'Einlass 18:30\nBeginn 19:00; Eintritt frei, Spenden willkommen'})]);
|
||||||
|
const lines = unfold(ical);
|
||||||
|
expect(lines).toContain('DESCRIPTION:Einlass 18:30\\nBeginn 19:00\\; Eintritt frei\\, Spenden willkommen');
|
||||||
|
// Nothing leaked out as a line of its own.
|
||||||
|
expect(lines.some((l) => l.startsWith('Beginn'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('escapes the title and the location too', async () => {
|
||||||
|
const lines = unfold(await convertToIcal([event({name: 'Konzert, Teil 2', location: 'Kirche; Karlsruhe'})]));
|
||||||
|
expect(lines).toContain('SUMMARY:Konzert\\, Teil 2');
|
||||||
|
expect(lines).toContain('LOCATION:Kirche\\; Karlsruhe');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not escape the URL, but keeps it on one line', async () => {
|
||||||
|
const lines = unfold(await convertToIcal([event({url: 'https://nachklang.art/konzert?a=1,2'})]));
|
||||||
|
expect(lines).toContain('URL:https://nachklang.art/konzert?a=1,2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still writes the yearly rule for birthdays', async () => {
|
||||||
|
const lines = unfold(await convertToIcal([event({repeatFrequency: 'YEARLY', wholeDay: true})]));
|
||||||
|
expect(lines).toContain('RRULE:FREQ=YEARLY');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the event\'s own dates untouched', async () => {
|
||||||
|
// formatDate used to add the whole-day end's extra day to the caller's Date in place.
|
||||||
|
const whole = event({
|
||||||
|
wholeDay: true,
|
||||||
|
startDateTime: new Date('2026-10-03T00:00:00'),
|
||||||
|
endDateTime: new Date('2026-10-03T23:59:00')
|
||||||
|
});
|
||||||
|
const endBefore = whole.endDateTime.getTime();
|
||||||
|
await convertToIcal([whole]);
|
||||||
|
expect(whole.endDateTime.getTime()).toBe(endBefore);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,88 +1,18 @@
|
|||||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
import {vi, type Mock} from 'vitest';
|
||||||
import {Request, Response} from 'express';
|
|
||||||
|
|
||||||
vi.mock('../../src/models/calendar/users/users.service.js', () => ({
|
vi.mock('../../src/models/admin/admin.auth.js', () => ({
|
||||||
checkSession: vi.fn()
|
auth: {api: {getSession: vi.fn()}}
|
||||||
|
}));
|
||||||
|
vi.mock('../../src/models/admin/users/users.admin.service.js', () => ({
|
||||||
|
loadAccess: vi.fn()
|
||||||
}));
|
}));
|
||||||
|
|
||||||
import * as UserService from '../../src/models/calendar/users/users.service.js';
|
import {auth} from '../../src/models/admin/admin.auth.js';
|
||||||
import {requireAdminAuth, sessionHeaderAuthenticator} from '../../src/models/feedback/feedback.auth.js';
|
import * as UsersService from '../../src/models/admin/users/users.admin.service.js';
|
||||||
|
import {requireAdminAuth} from '../../src/models/feedback/feedback.auth.js';
|
||||||
|
import {describeAdminBinding} from '../admin/auth-binding.js';
|
||||||
|
|
||||||
const mockCheckSession = UserService.checkSession as Mock;
|
describeAdminBinding('feedback', 'tickets', requireAdminAuth, () => ({
|
||||||
|
getSession: auth.api.getSession as unknown as Mock,
|
||||||
const makeReq = (headers: Record<string, string>): Request => {
|
loadAccess: UsersService.loadAccess as Mock
|
||||||
return {
|
}));
|
||||||
header: (name: string) => headers[name],
|
|
||||||
ip: '203.0.113.42'
|
|
||||||
} as unknown as Request;
|
|
||||||
};
|
|
||||||
|
|
||||||
const makeRes = (): Response => {
|
|
||||||
const res: any = {};
|
|
||||||
res.status = vi.fn().mockReturnValue(res);
|
|
||||||
res.send = vi.fn().mockReturnValue(res);
|
|
||||||
res.locals = {};
|
|
||||||
return res as Response;
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('sessionHeaderAuthenticator', () => {
|
|
||||||
beforeEach(() => mockCheckSession.mockReset());
|
|
||||||
|
|
||||||
it('returns null when headers are missing', async () => {
|
|
||||||
const identity = await sessionHeaderAuthenticator(makeReq({}));
|
|
||||||
expect(identity).toBeNull();
|
|
||||||
expect(mockCheckSession).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns null when checkSession finds no user', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue(null);
|
|
||||||
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
|
|
||||||
expect(identity).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns null for a valid session on an inactive account', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: false});
|
|
||||||
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
|
|
||||||
expect(identity).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns the identity for a valid session on an active account', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
|
|
||||||
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
|
|
||||||
expect(identity).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('passes the session id and key from headers through to checkSession, never from query params', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: true});
|
|
||||||
await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '42', 'X-Session-Key': 'sekret'}));
|
|
||||||
expect(mockCheckSession).toHaveBeenCalledWith('42', 'sekret', '203.0.113.42');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('requireAdminAuth', () => {
|
|
||||||
beforeEach(() => mockCheckSession.mockReset());
|
|
||||||
|
|
||||||
it('responds 401 and does not call next() when unauthenticated', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue(null);
|
|
||||||
const req = makeReq({});
|
|
||||||
const res = makeRes();
|
|
||||||
const next = vi.fn();
|
|
||||||
|
|
||||||
await requireAdminAuth(req, res, next);
|
|
||||||
|
|
||||||
expect(res.status).toHaveBeenCalledWith(401);
|
|
||||||
expect(next).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sets res.locals.admin and calls next() when authenticated', async () => {
|
|
||||||
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
|
|
||||||
const req = makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'});
|
|
||||||
const res = makeRes();
|
|
||||||
const next = vi.fn();
|
|
||||||
|
|
||||||
await requireAdminAuth(req, res, next);
|
|
||||||
|
|
||||||
expect(next).toHaveBeenCalled();
|
|
||||||
expect(res.locals.admin).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
||||||
|
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
|
||||||
|
NachklangFeedbackDB: {getConnection: vi.fn()}
|
||||||
|
}));
|
||||||
|
vi.mock('../../src/models/feedback/public/events.public.service.js', () => ({
|
||||||
|
getEventConfigBySlug: vi.fn()
|
||||||
|
}));
|
||||||
|
vi.mock('../../src/models/feedback/integrations/salesforce.service.js', () => ({
|
||||||
|
syncNewsletterSignup: vi.fn().mockResolvedValue(undefined)
|
||||||
|
}));
|
||||||
|
vi.mock('../../src/middleware/logger.js', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {info: vi.fn(), error: vi.fn()}
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {NachklangFeedbackDB} from '../../src/models/feedback/Feedback.db.js';
|
||||||
|
import {getEventConfigBySlug} from '../../src/models/feedback/public/events.public.service.js';
|
||||||
|
import {submitFeedback} from '../../src/models/feedback/public/submissions.service.js';
|
||||||
|
|
||||||
|
const mockGetConnection = NachklangFeedbackDB.getConnection as Mock;
|
||||||
|
const mockGetEventConfigBySlug = getEventConfigBySlug as Mock;
|
||||||
|
|
||||||
|
const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f';
|
||||||
|
const BODY = {answers: [{eventQuestionId: 26, text: 'Danke!'}], clientToken: TOKEN};
|
||||||
|
|
||||||
|
const SLUG = 'sommerkonzert-2026';
|
||||||
|
const LOOKUP_SQL = 'SELECT s.submission_id FROM submissions s';
|
||||||
|
|
||||||
|
// One fake connection serves every query; `existingId` is what a lookup by
|
||||||
|
// client_token finds when it was stored for `existingSlug`, and
|
||||||
|
// `insertError` makes the submissions INSERT throw.
|
||||||
|
const makeConn = ({existingId = null, existingSlug = SLUG, insertError = null}: {existingId?: number | null; existingSlug?: string; insertError?: any} = {}) => ({
|
||||||
|
query: vi.fn(async (sql: string, params: any[] = []) => {
|
||||||
|
if (sql.startsWith(LOOKUP_SQL)) {
|
||||||
|
return existingId === null || params[1] !== existingSlug ? [] : [{submission_id: existingId}];
|
||||||
|
}
|
||||||
|
if (sql.startsWith('INSERT INTO submissions')) {
|
||||||
|
if (insertError) throw insertError;
|
||||||
|
return [{submission_id: 90}];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}),
|
||||||
|
beginTransaction: vi.fn().mockResolvedValue(undefined),
|
||||||
|
commit: vi.fn().mockResolvedValue(undefined),
|
||||||
|
rollback: vi.fn().mockResolvedValue(undefined),
|
||||||
|
end: vi.fn().mockResolvedValue(undefined)
|
||||||
|
});
|
||||||
|
|
||||||
|
const allQueries = (conn: ReturnType<typeof makeConn>): [string, any[]][] => conn.query.mock.calls as any;
|
||||||
|
|
||||||
|
describe('submitFeedback - client token idempotency', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockGetConnection.mockReset();
|
||||||
|
mockGetEventConfigBySlug.mockReset();
|
||||||
|
mockGetEventConfigBySlug.mockResolvedValue({
|
||||||
|
status: 'OK',
|
||||||
|
eventId: 22,
|
||||||
|
event: {
|
||||||
|
questions: [{eventQuestionId: 26, questionId: 4, type: 'FREE_TEXT', label: 'Sonstiges', position: 0}],
|
||||||
|
songs: []
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the already-saved submission for a repeated token without inserting again', async () => {
|
||||||
|
const conn = makeConn({existingId: 82});
|
||||||
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
|
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||||
|
|
||||||
|
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
|
||||||
|
expect(allQueries(conn).some(([sql]) => sql.startsWith('INSERT'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still answers a retry with the saved submission after the feedback window closed', async () => {
|
||||||
|
mockGetConnection.mockResolvedValue(makeConn({existingId: 82}));
|
||||||
|
mockGetEventConfigBySlug.mockResolvedValue({status: 'CLOSED'});
|
||||||
|
|
||||||
|
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||||
|
|
||||||
|
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores a new token, lowercased, on the submissions row', async () => {
|
||||||
|
const conn = makeConn();
|
||||||
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
|
const result = await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: TOKEN.toUpperCase()}, 'hash');
|
||||||
|
|
||||||
|
expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false});
|
||||||
|
const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
|
||||||
|
expect(insert[1]).toContain(TOKEN);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saves a new submission when the token was only ever used for a different event', async () => {
|
||||||
|
// Same browser tab, two concerts: the token must not make the second
|
||||||
|
// event's feedback come back as the first event's submission.
|
||||||
|
const conn = makeConn({existingId: 82, existingSlug: 'winterkonzert-2026'});
|
||||||
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
|
const result = await submitFeedback(SLUG, BODY, 'hash');
|
||||||
|
|
||||||
|
expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false});
|
||||||
|
expect(allQueries(conn).find(([sql]) => sql.startsWith(LOOKUP_SQL))![1]).toEqual([TOKEN, SLUG]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores a malformed token: no lookup, and the row is stored without one', async () => {
|
||||||
|
const conn = makeConn();
|
||||||
|
mockGetConnection.mockResolvedValue(conn);
|
||||||
|
|
||||||
|
await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: 'not-a-uuid'}, 'hash');
|
||||||
|
|
||||||
|
expect(allQueries(conn).some(([sql]) => sql.startsWith(LOOKUP_SQL))).toBe(false);
|
||||||
|
const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
|
||||||
|
expect(insert[1]).not.toContain('not-a-uuid');
|
||||||
|
expect(insert[1][insert[1].length - 1]).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves a concurrent duplicate that loses the race on the unique index to the winning submission', async () => {
|
||||||
|
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
|
||||||
|
const racingConn = makeConn({insertError: dupError});
|
||||||
|
// First lookup (before the INSERT) finds nothing; the one after the
|
||||||
|
// duplicate-key error finds the row the other request committed.
|
||||||
|
const lookupAfterRace = makeConn({existingId: 83});
|
||||||
|
mockGetConnection
|
||||||
|
.mockResolvedValueOnce(makeConn())
|
||||||
|
.mockResolvedValueOnce(racingConn)
|
||||||
|
.mockResolvedValueOnce(lookupAfterRace);
|
||||||
|
|
||||||
|
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||||
|
|
||||||
|
expect(result).toEqual({status: 'OK', submissionId: 83, newsletterDropped: false});
|
||||||
|
expect(racingConn.rollback).toHaveBeenCalled();
|
||||||
|
expect(racingConn.commit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rethrows a duplicate-key error when the request carried no token', async () => {
|
||||||
|
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
|
||||||
|
mockGetConnection.mockResolvedValue(makeConn({insertError: dupError}));
|
||||||
|
|
||||||
|
await expect(submitFeedback('sommerkonzert-2026', {answers: BODY.answers}, 'hash')).rejects.toThrow('Duplicate entry');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -9,7 +9,8 @@ import {
|
|||||||
createAndAcceptInvitation,
|
createAndAcceptInvitation,
|
||||||
resetDatabase,
|
resetDatabase,
|
||||||
sessionCookieFrom,
|
sessionCookieFrom,
|
||||||
SESSION_COOKIE
|
SESSION_COOKIE,
|
||||||
|
accessTo
|
||||||
} from './helpers.js';
|
} from './helpers.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,7 +67,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('sets the session cookie under the configured prefix', async () => {
|
it('sets the session cookie under the configured prefix', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('b@nachklang.art', 'B', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('b@nachklang.art', 'B', accessTo('feedback'), null);
|
||||||
|
|
||||||
const res = await request(app)
|
const res = await request(app)
|
||||||
.post('/admin/auth/invitations/accept')
|
.post('/admin/auth/invitations/accept')
|
||||||
@@ -89,7 +90,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('previews an invitation without revealing the granted apps', async () => {
|
it('previews an invitation without revealing the granted apps', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('d@nachklang.art', 'D', ['admin'], null);
|
const invitation = await InvitationsService.createInvitation('d@nachklang.art', 'D', accessTo('admin'), null);
|
||||||
|
|
||||||
const res = await request(app)
|
const res = await request(app)
|
||||||
.post('/admin/auth/invitations/preview')
|
.post('/admin/auth/invitations/preview')
|
||||||
@@ -100,7 +101,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('answers an unknown token exactly like an expired one', async () => {
|
it('answers an unknown token exactly like an expired one', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('e@nachklang.art', 'E', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('e@nachklang.art', 'E', accessTo('feedback'), null);
|
||||||
await InvitationsService.revokeInvitation(invitation.id);
|
await InvitationsService.revokeInvitation(invitation.id);
|
||||||
|
|
||||||
const unknown = await request(app).post('/admin/auth/invitations/preview').send({token: 'no-such-token'});
|
const unknown = await request(app).post('/admin/auth/invitations/preview').send({token: 'no-such-token'});
|
||||||
@@ -111,7 +112,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('cannot be redeemed twice', async () => {
|
it('cannot be redeemed twice', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('f@nachklang.art', 'F', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('f@nachklang.art', 'F', accessTo('feedback'), null);
|
||||||
|
|
||||||
const first = await request(app)
|
const first = await request(app)
|
||||||
.post('/admin/auth/invitations/accept')
|
.post('/admin/auth/invitations/accept')
|
||||||
@@ -125,7 +126,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('rejects an expired invitation', async () => {
|
it('rejects an expired invitation', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('g@nachklang.art', 'G', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('g@nachklang.art', 'G', accessTo('feedback'), null);
|
||||||
// Reach past the service to age it: there is deliberately no API for this.
|
// Reach past the service to age it: there is deliberately no API for this.
|
||||||
const {NachklangAdminDB} = await import('../../src/models/admin/Admin.db.js');
|
const {NachklangAdminDB} = await import('../../src/models/admin/Admin.db.js');
|
||||||
await NachklangAdminDB.db
|
await NachklangAdminDB.db
|
||||||
@@ -142,7 +143,7 @@ describe('invitation acceptance', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a password below the minimum length', async () => {
|
it('rejects a password below the minimum length', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('h@nachklang.art', 'H', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('h@nachklang.art', 'H', accessTo('feedback'), null);
|
||||||
|
|
||||||
const res = await request(app)
|
const res = await request(app)
|
||||||
.post('/admin/auth/invitations/accept')
|
.post('/admin/auth/invitations/accept')
|
||||||
@@ -220,16 +221,32 @@ describe('requireAppAccess', () => {
|
|||||||
expect(Array.isArray(res.body)).toBe(true);
|
expect(Array.isArray(res.body)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Step 2 deliberately does NOT swap the feedback and tickets authenticators:
|
// The step 4 cutover (2026-09-06): the feedback and tickets admin areas now
|
||||||
// they still authenticate against the legacy calendar sessions, so an admin
|
// sit behind this same gate, so one sign-in reaches every app the user has a
|
||||||
// cookie means nothing to them yet. This asserts that boundary rather than
|
// permission for - and reaches no further. Until step 4 these two returned
|
||||||
// the end state - when step 4 lands, these two expectations become 200/403
|
// 401 for an admin cookie, because each module still ran its own header
|
||||||
// and this comment goes away.
|
// session against the calendar users table.
|
||||||
it('leaves the feedback and tickets admin areas on their legacy authenticator', async () => {
|
it('lets an admin cookie into the feedback and tickets admin areas', async () => {
|
||||||
const user = await createAndAcceptInvitation(app, 'o@nachklang.art', 'O', ['feedback', 'tickets']);
|
const user = await createAndAcceptInvitation(app, 'o@nachklang.art', 'O', ['feedback', 'tickets']);
|
||||||
|
|
||||||
expect((await user.agent.get('/feedback/admin/me')).status).toBe(401);
|
expect((await user.agent.get('/feedback/admin/me')).status).toBe(200);
|
||||||
expect((await user.agent.get('/tickets/admin/me')).status).toBe(401);
|
expect((await user.agent.get('/tickets/admin/me')).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('403s each app separately for a user who only holds the other one', async () => {
|
||||||
|
const user = await createAndAcceptInvitation(app, 'q@nachklang.art', 'Q', ['feedback']);
|
||||||
|
|
||||||
|
expect((await user.agent.get('/feedback/admin/me')).status).toBe(200);
|
||||||
|
expect((await user.agent.get('/tickets/admin/me')).status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('401s the feedback and tickets admin areas for a legacy header session', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/feedback/admin/me')
|
||||||
|
.set('X-Session-Id', '1')
|
||||||
|
.set('X-Session-Key', 'whatever');
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -259,7 +276,7 @@ describe('origin checks', () => {
|
|||||||
|
|
||||||
describe('the session cookie is not readable by scripts', () => {
|
describe('the session cookie is not readable by scripts', () => {
|
||||||
it('is HttpOnly and SameSite=Lax', async () => {
|
it('is HttpOnly and SameSite=Lax', async () => {
|
||||||
const invitation = await InvitationsService.createInvitation('r@nachklang.art', 'R', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('r@nachklang.art', 'R', accessTo('feedback'), null);
|
||||||
const res = await request(app)
|
const res = await request(app)
|
||||||
.post('/admin/auth/invitations/accept')
|
.post('/admin/auth/invitations/accept')
|
||||||
.send({token: invitation.token, password: 'devpassword123'});
|
.send({token: invitation.token, password: 'devpassword123'});
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import {describe, it, expect, beforeAll, beforeEach, afterAll} from 'vitest';
|
||||||
|
import type {Application} from 'express';
|
||||||
|
import {createApp} from '../../src/app.factory.js';
|
||||||
|
import {READ_ROLE} from '../../src/models/admin/admin.schema.js';
|
||||||
|
import {closeDatabase, createAndAcceptInvitation, resetDatabase} from './helpers.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The read-only role end to end: a real session cookie through the real
|
||||||
|
* middleware into each app's routers. The writes are rejected before any
|
||||||
|
* handler runs, which is why this suite needs no tickets/feedback/calendar
|
||||||
|
* database - a 403 here proves the gate held, not that a query failed.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let app: Application;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
app = createApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await resetDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await closeDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
const readOnlyEverywhere = async () => {
|
||||||
|
return createAndAcceptInvitation(app, 'reader@nachklang.art', 'Reader', [
|
||||||
|
{app: 'tickets', role: READ_ROLE},
|
||||||
|
{app: 'feedback', role: READ_ROLE},
|
||||||
|
{app: 'calendar', role: READ_ROLE}
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('read-only access', () => {
|
||||||
|
it('reports readOnly on each app\'s /me', async () => {
|
||||||
|
const {agent} = await readOnlyEverywhere();
|
||||||
|
|
||||||
|
const tickets = await agent.get('/tickets/admin/me');
|
||||||
|
const feedback = await agent.get('/feedback/admin/me');
|
||||||
|
|
||||||
|
expect(tickets.status).toBe(200);
|
||||||
|
expect(tickets.body.readOnly).toBe(true);
|
||||||
|
expect(feedback.status).toBe(200);
|
||||||
|
expect(feedback.body.readOnly).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports readOnly false for full access', async () => {
|
||||||
|
const {agent} = await createAndAcceptInvitation(app, 'full@nachklang.art', 'Full', ['tickets']);
|
||||||
|
|
||||||
|
const res = await agent.get('/tickets/admin/me');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.readOnly).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['post', '/tickets/admin/vouchers/wildcard'],
|
||||||
|
['post', '/tickets/admin/redemptions/1/resend-confirmation'],
|
||||||
|
['patch', '/tickets/admin/redemptions/1'],
|
||||||
|
['put', '/tickets/admin/events/1/settings'],
|
||||||
|
['delete', '/feedback/admin/submissions/1'],
|
||||||
|
['post', '/feedback/admin/events'],
|
||||||
|
['post', '/calendar/events'],
|
||||||
|
['delete', '/calendar/events/1']
|
||||||
|
] as const)('refuses %s %s', async (method, path) => {
|
||||||
|
const {agent} = await readOnlyEverywhere();
|
||||||
|
|
||||||
|
const res = await agent[method](path).send({});
|
||||||
|
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(res.body.message).toBe('Du hast für diesen Bereich nur Lesezugriff.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not open user management', async () => {
|
||||||
|
const {agent} = await readOnlyEverywhere();
|
||||||
|
|
||||||
|
expect((await agent.get('/admin/users')).status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('granting read-only access', () => {
|
||||||
|
const signedInAdmin = () => createAndAcceptInvitation(app, 'admin@nachklang.art', 'Admin', ['admin']);
|
||||||
|
|
||||||
|
it('stores the read role per app', async () => {
|
||||||
|
const {agent} = await signedInAdmin();
|
||||||
|
const other = await createAndAcceptInvitation(app, 'user@nachklang.art', 'User', ['feedback']);
|
||||||
|
|
||||||
|
const res = await agent
|
||||||
|
.put(`/admin/users/${other.userId}/permissions`)
|
||||||
|
.send({permissions: [{app: 'tickets', role: READ_ROLE}, {app: 'feedback', role: 'access'}]});
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.permissions).toEqual(expect.arrayContaining([
|
||||||
|
{app: 'tickets', role: READ_ROLE},
|
||||||
|
{app: 'feedback', role: 'access'}
|
||||||
|
]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects full and read-only access to the same app', async () => {
|
||||||
|
const {agent} = await signedInAdmin();
|
||||||
|
const other = await createAndAcceptInvitation(app, 'user@nachklang.art', 'User', ['feedback']);
|
||||||
|
|
||||||
|
const res = await agent
|
||||||
|
.put(`/admin/users/${other.userId}/permissions`)
|
||||||
|
.send({permissions: [{app: 'tickets', role: READ_ROLE}, {app: 'tickets', role: 'access'}]});
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects inviting someone with read-only user management', async () => {
|
||||||
|
const {agent} = await signedInAdmin();
|
||||||
|
|
||||||
|
const res = await agent
|
||||||
|
.post('/admin/invitations')
|
||||||
|
.send({email: 'new@nachklang.art', name: 'New', permissions: [{app: 'admin', role: READ_ROLE}]});
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,7 +5,7 @@ import {createApp} from '../../src/app.factory.js';
|
|||||||
import * as InvitationsService from '../../src/models/admin/invitations/invitations.service.js';
|
import * as InvitationsService from '../../src/models/admin/invitations/invitations.service.js';
|
||||||
import * as UsersService from '../../src/models/admin/users/users.admin.service.js';
|
import * as UsersService from '../../src/models/admin/users/users.admin.service.js';
|
||||||
import {bootstrapAdmin} from '../../src/models/admin/admin.bootstrap.js';
|
import {bootstrapAdmin} from '../../src/models/admin/admin.bootstrap.js';
|
||||||
import {closeDatabase, createAndAcceptInvitation, resetDatabase} from './helpers.js';
|
import {accessTo, closeDatabase, createAndAcceptInvitation, resetDatabase} from './helpers.js';
|
||||||
|
|
||||||
let app: Application;
|
let app: Application;
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ describe('invitations', () => {
|
|||||||
|
|
||||||
it('invalidates the previous link on resend', async () => {
|
it('invalidates the previous link on resend', async () => {
|
||||||
const {agent} = await signedInAdmin();
|
const {agent} = await signedInAdmin();
|
||||||
const original = await InvitationsService.createInvitation('new@nachklang.art', 'New', ['feedback'], null);
|
const original = await InvitationsService.createInvitation('new@nachklang.art', 'New', accessTo('feedback'), null);
|
||||||
|
|
||||||
const resent = await agent.post(`/admin/invitations/${original.id}/resend`);
|
const resent = await agent.post(`/admin/invitations/${original.id}/resend`);
|
||||||
expect(resent.status).toBe(200);
|
expect(resent.status).toBe(200);
|
||||||
@@ -198,7 +198,7 @@ describe('invitations', () => {
|
|||||||
|
|
||||||
it('revokes an invitation', async () => {
|
it('revokes an invitation', async () => {
|
||||||
const {agent} = await signedInAdmin();
|
const {agent} = await signedInAdmin();
|
||||||
const invitation = await InvitationsService.createInvitation('new@nachklang.art', 'New', ['feedback'], null);
|
const invitation = await InvitationsService.createInvitation('new@nachklang.art', 'New', accessTo('feedback'), null);
|
||||||
|
|
||||||
expect((await agent.delete(`/admin/invitations/${invitation.id}`)).status).toBe(204);
|
expect((await agent.delete(`/admin/invitations/${invitation.id}`)).status).toBe(204);
|
||||||
expect((await agent.delete(`/admin/invitations/${invitation.id}`)).status).toBe(404);
|
expect((await agent.delete(`/admin/invitations/${invitation.id}`)).status).toBe(404);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type {Application} from 'express';
|
|||||||
import request from 'supertest';
|
import request from 'supertest';
|
||||||
import {NachklangAdminDB} from '../../src/models/admin/Admin.db.js';
|
import {NachklangAdminDB} from '../../src/models/admin/Admin.db.js';
|
||||||
import * as InvitationsService from '../../src/models/admin/invitations/invitations.service.js';
|
import * as InvitationsService from '../../src/models/admin/invitations/invitations.service.js';
|
||||||
import {AppName} from '../../src/models/admin/admin.schema.js';
|
import {ACCESS_ROLE, AppName, AppPermission, toPermissions} from '../../src/models/admin/admin.schema.js';
|
||||||
|
|
||||||
const db = NachklangAdminDB.db;
|
const db = NachklangAdminDB.db;
|
||||||
|
|
||||||
@@ -44,10 +44,13 @@ export const createAndAcceptInvitation = async (
|
|||||||
app: Application,
|
app: Application,
|
||||||
email: string,
|
email: string,
|
||||||
name: string,
|
name: string,
|
||||||
apps: AppName[],
|
// Takes the shorthand as well as the full form: most tests only care that
|
||||||
|
// someone can open an app, and `['tickets']` says that with less noise.
|
||||||
|
grants: (AppName | AppPermission)[],
|
||||||
password = 'devpassword123'
|
password = 'devpassword123'
|
||||||
) => {
|
) => {
|
||||||
const invitation = await InvitationsService.createInvitation(email, name, apps, null);
|
const permissions = toPermissions(grants) ?? [];
|
||||||
|
const invitation = await InvitationsService.createInvitation(email, name, permissions, null);
|
||||||
|
|
||||||
const agent = request.agent(app);
|
const agent = request.agent(app);
|
||||||
const res = await agent
|
const res = await agent
|
||||||
@@ -66,3 +69,9 @@ export const cookieHeader = (res: request.Response): string[] => {
|
|||||||
export const sessionCookieFrom = (res: request.Response): string | undefined => {
|
export const sessionCookieFrom = (res: request.Response): string | undefined => {
|
||||||
return cookieHeader(res).find(cookie => cookie.startsWith(SESSION_COOKIE));
|
return cookieHeader(res).find(cookie => cookie.startsWith(SESSION_COOKIE));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** `accessTo('feedback')` reads better than the (app, role) literal in tests
|
||||||
|
* that only care that someone can open an app. */
|
||||||
|
export const accessTo = (...apps: AppName[]): AppPermission[] => {
|
||||||
|
return apps.map(app => ({app, role: ACCESS_ROLE}));
|
||||||
|
};
|
||||||
@@ -47,11 +47,19 @@ const RECIPIENT = {
|
|||||||
guestNames: ['Erika Mustermann', 'Hans Mustermann']
|
guestNames: ['Erika Mustermann', 'Hans Mustermann']
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Default: no event_ticket_settings row, same "absence over sentinels" case
|
||||||
|
// as everywhere else - ticketsAreMailed reads this as false (not mailed).
|
||||||
|
const makeSettingsConn = (ticketsMailed?: boolean) => ({
|
||||||
|
query: vi.fn().mockResolvedValue(ticketsMailed === undefined ? [] : [{tickets_mailed: ticketsMailed ? 1 : 0}]),
|
||||||
|
end: vi.fn().mockResolvedValue(undefined)
|
||||||
|
});
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
mockGetEvent.mockResolvedValue(EVENT);
|
mockGetEvent.mockResolvedValue(EVENT);
|
||||||
mockToIcal.mockResolvedValue('BEGIN:VCALENDAR\nEND:VCALENDAR');
|
mockToIcal.mockResolvedValue('BEGIN:VCALENDAR\nEND:VCALENDAR');
|
||||||
mockSendMail.mockResolvedValue(true);
|
mockSendMail.mockResolvedValue(true);
|
||||||
|
mockGetConnection.mockResolvedValue(makeSettingsConn());
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('sendRedemptionConfirmation', () => {
|
describe('sendRedemptionConfirmation', () => {
|
||||||
@@ -95,6 +103,32 @@ describe('sendRedemptionConfirmation', () => {
|
|||||||
|
|
||||||
expect(await sendRedemptionConfirmation(RECIPIENT)).toBe(false);
|
expect(await sendRedemptionConfirmation(RECIPIENT)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('adds the Abendkasse pickup notice when the event does not mail tickets', async () => {
|
||||||
|
mockGetConnection.mockResolvedValue(makeSettingsConn(false));
|
||||||
|
|
||||||
|
await sendRedemptionConfirmation(RECIPIENT);
|
||||||
|
|
||||||
|
const body = mockSendMail.mock.calls[0][2];
|
||||||
|
expect(body).toContain('Abendkasse');
|
||||||
|
expect(body).toContain('Erika Mustermann');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds the pickup notice when there is no ticket-shop settings row at all', async () => {
|
||||||
|
mockGetConnection.mockResolvedValue(makeSettingsConn());
|
||||||
|
|
||||||
|
await sendRedemptionConfirmation(RECIPIENT);
|
||||||
|
|
||||||
|
expect(mockSendMail.mock.calls[0][2]).toContain('Abendkasse');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits the pickup notice when the event mails tickets', async () => {
|
||||||
|
mockGetConnection.mockResolvedValue(makeSettingsConn(true));
|
||||||
|
|
||||||
|
await sendRedemptionConfirmation(RECIPIENT);
|
||||||
|
|
||||||
|
expect(mockSendMail.mock.calls[0][2]).not.toContain('Abendkasse');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('recordConfirmationEmailResult', () => {
|
describe('recordConfirmationEmailResult', () => {
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import {vi, type Mock} from 'vitest';
|
||||||
|
|
||||||
|
vi.mock('../../src/models/admin/admin.auth.js', () => ({
|
||||||
|
auth: {api: {getSession: vi.fn()}}
|
||||||
|
}));
|
||||||
|
vi.mock('../../src/models/admin/users/users.admin.service.js', () => ({
|
||||||
|
loadAccess: vi.fn()
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {auth} from '../../src/models/admin/admin.auth.js';
|
||||||
|
import * as UsersService from '../../src/models/admin/users/users.admin.service.js';
|
||||||
|
import {requireAdminAuth} from '../../src/models/tickets/tickets.auth.js';
|
||||||
|
import {describeAdminBinding} from '../admin/auth-binding.js';
|
||||||
|
|
||||||
|
describeAdminBinding('tickets', 'feedback', requireAdminAuth, () => ({
|
||||||
|
getSession: auth.api.getSession as unknown as Mock,
|
||||||
|
loadAccess: UsersService.loadAccess as Mock
|
||||||
|
}));
|
||||||
@@ -14,10 +14,6 @@ export default defineConfig({
|
|||||||
env: {
|
env: {
|
||||||
FEEDBACK_IP_SALT: 'vitest-salt'
|
FEEDBACK_IP_SALT: 'vitest-salt'
|
||||||
},
|
},
|
||||||
reporters: [
|
|
||||||
'default',
|
|
||||||
['vitest-sonar-reporter', {outputFile: 'testResults/sonar-report.xml'}]
|
|
||||||
],
|
|
||||||
coverage: {
|
coverage: {
|
||||||
provider: 'v8',
|
provider: 'v8',
|
||||||
reporter: ['text-summary', 'lcov'],
|
reporter: ['text-summary', 'lcov'],
|
||||||
|
|||||||
Reference in new issue
Block a user