From 83f73aeb585bd05d021c65785f447e8af2d30965 Mon Sep 17 00:00:00 2001 From: Luka Romih Date: Thu, 1 Oct 2026 00:49:26 +0200 Subject: [PATCH] CJVT updates August and September 2026 --- .dockerignore | 24 - .gitea/workflows/build-and-stage.yml | 63 + .gitea/workflows/deploy-dispatch.yml | 32 + .gitea/workflows/release-prod.yml | 54 + .gitignore | 2 + .playwright/cli.config.json | 8 + README.md | 110 +- concordancer/Dockerfile | 3 +- concordancer/Dockerfile.prod | 3 +- dev/.env | 48 + dev/authentik/README.md | 157 ++ dev/authentik/blueprints/uni-lj-stand-in.yaml | 166 ++ dev/ci/README.md | 352 ++++ dev/ci/build.sh | 31 + dev/ci/ci-deploy-wrapper.sh | 44 + dev/ci/deploy.sh | 32 + dev/ci/promote.sh | 18 + dev/util-tools/compose-config-diff.sh | 61 + docker-compose.prod.override.example.yml | 46 + docker-compose.prod.yml | 38 +- docker-compose.yml | 116 +- express/.dockerignore | 8 + express/Dockerfile | 11 +- express/Dockerfile.prod | 18 +- express/app.js | 2 + express/config/helmet.js | 2 +- express/config/keys.js | 17 +- express/config/university-domains.js | 32 + express/controllers/api/v1/consultancy.js | 9 - express/controllers/api/v1/dictionaries.js | 87 +- express/controllers/api/v1/users.js | 17 + express/controllers/consultancy.js | 28 +- express/controllers/dictionaries.js | 175 +- express/controllers/helpers/dictionary.js | 49 +- .../search-filter-data-suggestion-importer.js | 2 +- express/controllers/index.js | 4 + express/controllers/oidc.js | 272 +++ express/controllers/users.js | 10 + .../lib/passport-remember-me-extended/LICENSE | 20 + .../passport-remember-me-extended/README.md | 28 + .../passport-remember-me-extended/index.js | 10 + .../passport-remember-me-extended/strategy.js | 114 ++ .../passport-remember-me-extended/utils.js | 23 + express/middleware/auth.js | 123 +- express/middleware/index.js | 2 +- express/models/consultancy-entry.js | 26 +- express/models/dictionary.js | 362 ++-- express/models/entry.js | 2 + express/models/extraction.js | 106 +- .../models/helpers/dictionary/import-file.js | 5 +- .../helpers/dictionary/import-json-file.js | 26 + express/models/helpers/dictionary/index.js | 33 + express/models/helpers/index.js | 13 + express/models/helpers/user/index.js | 4 + express/models/user.js | 173 +- express/package-lock.json | 155 +- express/package.json | 10 +- express/public/javascripts/admin.js | 165 +- express/public/javascripts/comments.js | 40 +- express/public/javascripts/consultancy.js | 11 +- express/public/javascripts/date-utils.js | 67 + express/public/javascripts/dictionaries.js | 552 +++--- .../public/javascripts/dictionary-export.js | 24 - .../javascripts/dictionary-list-table.js | 291 +++ .../public/javascripts/extraction-edit-own.js | 17 +- .../javascripts/extraction-files-edit.js | 7 +- .../public/javascripts/extraction-oss-edit.js | 5 +- express/public/javascripts/offset-header.js | 22 + express/public/javascripts/oidc-forms.js | 38 + .../public/javascripts/query-focus-handler.js | 7 +- express/public/javascripts/scripts.js | 111 +- .../javascripts/view-resources-details.js | 28 + express/public/locales/en/core.json | 56 +- express/public/locales/sl/core.json | 54 +- .../_admin-dictionaries-filter.scss | 7 + .../sass/components/_extraction-main.scss | 19 + .../sass/components/_header-section.scss | 6 + .../sass/login-signup/_login-signup.scss | 42 + express/public/sass/style.scss | 1 + express/routes/api/v1/dictionaries.js | 28 + express/routes/api/v1/entries.js | 1 + express/routes/api/v1/users.js | 13 + express/routes/index.js | 9 + express/routes/view-resources.js | 19 + .../admin/consultancy-item-admin.pug | 2 +- .../consultancy/consultancy-item.pug | 5 +- .../dictionary-list-table-mixin.pug | 119 ++ .../components/login-signup/login-signup.pug | 8 + .../main-navigation-right-mixin.pug | 3 + .../email/dictionary-contact-authors_en.pug | 3 + .../email/dictionary-contact-authors_sl.pug | 3 + express/views/layout.pug | 1 + .../views/pages/admin/dictionaries-list.pug | 67 +- .../pages/admin/dictionary-description.pug | 1 + .../views/pages/admin/dictionary-export.pug | 1 - .../views/pages/consultancy/admin/edit.pug | 11 +- .../views/pages/consultancy/item-details.pug | 4 +- .../views/pages/dictionaries/description.pug | 1 + express/views/pages/dictionaries/export.pug | 1 - express/views/pages/dictionaries/list.pug | 8 +- express/views/pages/dictionaries/new.pug | 2 + express/views/pages/extraction/docs-edit.pug | 9 +- express/views/pages/extraction/edit-own.pug | 45 +- express/views/pages/extraction/list.pug | 42 +- .../pages/extraction/stop-terms-edit.pug | 9 +- express/views/pages/index.pug | 3 +- express/views/pages/oidc/convert-account.pug | 65 + express/views/pages/oidc/create-profile.pug | 60 + .../profile/my-profile-side-menu-mixin.pug | 13 +- express/views/pages/profile/my-profile.pug | 6 +- .../pages/reset-password/reset-password.pug | 3 +- .../view-resources/dictionary-details.pug | 51 + express/views/pages/view-resources/list.pug | 51 + express/views/utilities/comments-new.pug | 17 +- express/views/utilities/content-side-menu.pug | 2 +- .../dictionary-description-mixin.pug | 1 + .../dictionary-description-readonly-mixin.pug | 68 + .../dictionary-export-content-mixin.pug | 54 +- .../utilities/dictionary-import-mixin.pug | 119 +- .../utilities/dictionary-structure-input.pug | 361 +--- .../utilities/result-detail-side-menu.pug | 2 +- opensearch/Dockerfile | 1 + package-lock.json | 1714 +++++++++++------ package.json | 7 +- postgres/Dockerfile.debug.alpine | 1 + postgres/Dockerfile.debug.debian | 1 + postgres/init/001_structure.sql | 2 +- postgres/init/002_data-domain-primary.sql | 3 +- postgres/init/007_entry.sql | 2 +- postgres/init/010_function_dictionary_new.sql | 15 - .../init/022_dictionary_export_time_zone.sql | 5 + postgres/init/023_external_identity.sql | 18 + .../2026-08-27_add_oidc_sso_support.sql | 26 + .../remove_neopredeljeno_domain.sql | 56 + run-prod.sh | 18 + 135 files changed, 6146 insertions(+), 1970 deletions(-) delete mode 100644 .dockerignore create mode 100644 .gitea/workflows/build-and-stage.yml create mode 100644 .gitea/workflows/deploy-dispatch.yml create mode 100644 .gitea/workflows/release-prod.yml create mode 100644 .playwright/cli.config.json create mode 100644 dev/authentik/README.md create mode 100644 dev/authentik/blueprints/uni-lj-stand-in.yaml create mode 100644 dev/ci/README.md create mode 100755 dev/ci/build.sh create mode 100755 dev/ci/ci-deploy-wrapper.sh create mode 100755 dev/ci/deploy.sh create mode 100755 dev/ci/promote.sh create mode 100755 dev/util-tools/compose-config-diff.sh create mode 100644 docker-compose.prod.override.example.yml create mode 100644 express/.dockerignore create mode 100644 express/config/university-domains.js create mode 100644 express/controllers/oidc.js create mode 100644 express/lib/passport-remember-me-extended/LICENSE create mode 100644 express/lib/passport-remember-me-extended/README.md create mode 100644 express/lib/passport-remember-me-extended/index.js create mode 100644 express/lib/passport-remember-me-extended/strategy.js create mode 100644 express/lib/passport-remember-me-extended/utils.js create mode 100644 express/models/helpers/dictionary/import-json-file.js create mode 100644 express/public/javascripts/date-utils.js delete mode 100644 express/public/javascripts/dictionary-export.js create mode 100644 express/public/javascripts/dictionary-list-table.js create mode 100644 express/public/javascripts/offset-header.js create mode 100644 express/public/javascripts/oidc-forms.js create mode 100644 express/public/javascripts/view-resources-details.js create mode 100644 express/public/sass/components/_admin-dictionaries-filter.scss create mode 100644 express/routes/view-resources.js create mode 100644 express/views/components/dictionary/dictionary-list-table-mixin.pug create mode 100644 express/views/email/dictionary-contact-authors_en.pug create mode 100644 express/views/email/dictionary-contact-authors_sl.pug create mode 100644 express/views/pages/oidc/convert-account.pug create mode 100644 express/views/pages/oidc/create-profile.pug create mode 100644 express/views/pages/view-resources/dictionary-details.pug create mode 100644 express/views/pages/view-resources/list.pug create mode 100644 express/views/utilities/dictionary-description-readonly-mixin.pug create mode 100644 postgres/init/022_dictionary_export_time_zone.sql create mode 100644 postgres/init/023_external_identity.sql create mode 100644 postgres/manual-scripts/2026-08-27_add_oidc_sso_support.sql create mode 100644 postgres/manual-scripts/remove_neopredeljeno_domain.sql create mode 100755 run-prod.sh diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index b1f5669..0000000 --- a/.dockerignore +++ /dev/null @@ -1,24 +0,0 @@ -**/.classpath -**/.dockerignore -**/.env -**/.git -**/.gitignore -**/.project -**/.settings -**/.toolstarget -**/.vs -**/.vscode -**/*.*proj.user -**/*.dbmdl -**/*.jfm -**/azds.yaml -**/charts -**/docker-compose* -**/compose* -**/Dockerfile* -**/node_modules -**/npm-debug.log -**/obj -**/secrets.dev.yaml -**/values.dev.yaml -README.md diff --git a/.gitea/workflows/build-and-stage.yml b/.gitea/workflows/build-and-stage.yml new file mode 100644 index 0000000..48a2065 --- /dev/null +++ b/.gitea/workflows/build-and-stage.yml @@ -0,0 +1,63 @@ +# Builds the three custom images on every push to the default branch, pushes them to the +# Gitea container registry tagged sha-, then deploys that build to STAGING. +# +# Prerequisites (see README "Automated deployment"): +# - a repo-scoped Gitea Runner (gitea/runner) with the `self-hosted` label +# - the Gitea container registry enabled +# - REGISTRY_TOKEN secret: a PAT with write:package scope (the automatic GITEA_TOKEN is +# NOT authorized to push packages on this instance) +# - staging secrets: STAGING_SSH_HOST, STAGING_SSH_USER, STAGING_SSH_KEY, and optionally +# STAGING_SSH_PORT if the host's sshd doesn't listen on the default port 22 +# (the deploy user's forced-command wrapper on the host owns the checkout path) +name: build-and-stage + +on: + push: + branches: [master] + +jobs: + build: + runs-on: [self-hosted] + outputs: + registry: ${{ steps.meta.outputs.registry }} + tag: ${{ steps.meta.outputs.tag }} + steps: + - uses: actions/checkout@v4 + + - name: Compute registry + tag + id: meta + run: | + host="$(echo "${{ github.server_url }}" | sed -E 's#^https?://##')" + owner="${{ github.repository_owner }}" + echo "host=$host" >>"$GITHUB_OUTPUT" + # OCI repository paths must be lowercase; Gitea maps the lowercased owner back. + echo "registry=$host/${owner,,}" >>"$GITHUB_OUTPUT" + echo "tag=sha-$(git rev-parse --short HEAD)" >>"$GITHUB_OUTPUT" + + - name: Registry login + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" \ + | docker login "${{ steps.meta.outputs.host }}" -u "${{ github.actor }}" --password-stdin + + - name: Set up buildx (registry cache needs the docker-container driver) + run: docker buildx use ci 2>/dev/null || docker buildx create --name ci --driver docker-container --use + + - name: Build & push images + env: + REGISTRY: ${{ steps.meta.outputs.registry }} + TAG: ${{ steps.meta.outputs.tag }} + run: bash dev/ci/build.sh + + deploy-staging: + needs: build + runs-on: [self-hosted] + steps: + - uses: actions/checkout@v4 + - name: Deploy to staging + env: + DEPLOY_HOST: ${{ secrets.STAGING_SSH_HOST }} + DEPLOY_USER: ${{ secrets.STAGING_SSH_USER }} + DEPLOY_SSH_KEY: ${{ secrets.STAGING_SSH_KEY }} + DEPLOY_SSH_PORT: ${{ secrets.STAGING_SSH_PORT }} + IMAGE_TAG: ${{ needs.build.outputs.tag }} + run: bash dev/ci/deploy.sh diff --git a/.gitea/workflows/deploy-dispatch.yml b/.gitea/workflows/deploy-dispatch.yml new file mode 100644 index 0000000..01d71de --- /dev/null +++ b/.gitea/workflows/deploy-dispatch.yml @@ -0,0 +1,32 @@ +# Manual deploy of an arbitrary existing image tag to a chosen environment. +# Primary use: ROLLBACK (deploy a previous v* tag) and ad-hoc redeploys. +# +# The image_tag must already exist in the registry (e.g. v1.2.2 or sha-abc1234). deploy.sh +# derives the git ref to check out from it (strips a leading "sha-"). +name: deploy-dispatch + +on: + workflow_dispatch: + inputs: + environment: + description: Target environment + type: choice + options: [staging, prod] + required: true + image_tag: + description: Image tag to deploy, e.g. v1.2.2 or sha-abc1234 + type: string + required: true + +jobs: + deploy: + runs-on: [self-hosted] + steps: + - uses: actions/checkout@v4 + - name: Deploy ${{ inputs.image_tag }} to ${{ inputs.environment }} + env: + DEPLOY_HOST: ${{ inputs.environment == 'prod' && secrets.PROD_SSH_HOST || secrets.STAGING_SSH_HOST }} + DEPLOY_USER: ${{ inputs.environment == 'prod' && secrets.PROD_SSH_USER || secrets.STAGING_SSH_USER }} + DEPLOY_SSH_KEY: ${{ inputs.environment == 'prod' && secrets.PROD_SSH_KEY || secrets.STAGING_SSH_KEY }} + IMAGE_TAG: ${{ inputs.image_tag }} + run: bash dev/ci/deploy.sh diff --git a/.gitea/workflows/release-prod.yml b/.gitea/workflows/release-prod.yml new file mode 100644 index 0000000..47959d5 --- /dev/null +++ b/.gitea/workflows/release-prod.yml @@ -0,0 +1,54 @@ +# Production release. Triggered by pushing a version tag (v*). Pushing the tag IS the +# deliberate human gate. It promotes the images already built for that commit on the default +# branch (no rebuild) to the version tag, then deploys them to PRODUCTION. +# +# The tagged commit must already have been built on the default branch (build-and-stage), +# so its sha- images exist; otherwise promotion fails with a clear error. +# +# Prerequisites: REGISTRY_TOKEN secret (PAT with write:package; the automatic GITEA_TOKEN is +# not authorized to push packages), plus prod secrets PROD_SSH_HOST, PROD_SSH_USER, PROD_SSH_KEY +# (the deploy user's forced-command wrapper on the host owns the checkout path), and optionally +# PROD_SSH_PORT if the host's sshd doesn't listen on the default port 22. +name: release-prod + +on: + push: + tags: ["v*"] + +jobs: + promote-and-deploy: + runs-on: [self-hosted] + steps: + - uses: actions/checkout@v4 + + - name: Compute registry + tags + id: meta + run: | + host="$(echo "${{ github.server_url }}" | sed -E 's#^https?://##')" + owner="${{ github.repository_owner }}" + echo "host=$host" >>"$GITHUB_OUTPUT" + # OCI repository paths must be lowercase; Gitea maps the lowercased owner back. + echo "registry=$host/${owner,,}" >>"$GITHUB_OUTPUT" + echo "src_tag=sha-$(git rev-parse --short HEAD)" >>"$GITHUB_OUTPUT" + echo "dst_tag=${{ github.ref_name }}" >>"$GITHUB_OUTPUT" + + - name: Registry login + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" \ + | docker login "${{ steps.meta.outputs.host }}" -u "${{ github.actor }}" --password-stdin + + - name: Promote images (no rebuild) + env: + REGISTRY: ${{ steps.meta.outputs.registry }} + SRC_TAG: ${{ steps.meta.outputs.src_tag }} + DST_TAG: ${{ steps.meta.outputs.dst_tag }} + run: bash dev/ci/promote.sh + + - name: Deploy to production + env: + DEPLOY_HOST: ${{ secrets.PROD_SSH_HOST }} + DEPLOY_USER: ${{ secrets.PROD_SSH_USER }} + DEPLOY_SSH_KEY: ${{ secrets.PROD_SSH_KEY }} + DEPLOY_SSH_PORT: ${{ secrets.PROD_SSH_PORT }} + IMAGE_TAG: ${{ steps.meta.outputs.dst_tag }} + run: bash dev/ci/deploy.sh diff --git a/.gitignore b/.gitignore index 00d692d..f9624fc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ node_modules/ .vscode /.env +/docker-compose.prod.override.yml .idea +.playwright-cli express/public/stylesheets /draft/ diff --git a/.playwright/cli.config.json b/.playwright/cli.config.json new file mode 100644 index 0000000..587f73e --- /dev/null +++ b/.playwright/cli.config.json @@ -0,0 +1,8 @@ +{ + "browser": { + "browserName": "chromium", + "launchOptions": { + "channel": "chromium" + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index 1a803ac..c92ccf9 100644 --- a/README.md +++ b/README.md @@ -52,20 +52,21 @@ Alternatively, set your own preferred log aggregator as per [the official docume 2. Navigate into that directory and copy the _.env_ file from the _dev_ folder one level up (into the root directory of the portal). 3. Open the copied _.env_ file in a text editor and adjust the parameters of your portal. -### 4. (Advanced/optional) Adjust data storage locations +### 4. (Advanced/optional) Adjust data storage locations or other host-specific settings By default, all data is stored and persisted inside Docker's [volumes](https://docs.docker.com/storage/volumes/) -on your host's root partition. -If you have a setup where for any reason you want to store data elsewhere, -you can reconfigure the docker-compose.prod.yml to use [bind mounts](https://docs.docker.com/storage/bind-mounts/), -just be mindful not to break shared volume dependencies. - -_Using bind mounts has not been tested yet and might cause additional complications -regarding file system permissions._ +on your host's root partition. If you have a setup where for any reason you want to store data +elsewhere, e.g. using [bind mounts](https://docs.docker.com/storage/bind-mounts/), or need other +host-specific tweaks (resource limits, etc.), do **not** edit docker-compose.prod.yml directly. +Instead, copy docker-compose.prod.override.example.yml to docker-compose.prod.override.yml next to +it and adjust only the keys that need to differ on this host. `./run-prod.sh` (see next step) +automatically layers this override file in when present, so it never needs to be manually re-applied +after pulling changes to docker-compose.prod.yml. docker-compose.prod.override.yml is gitignored on +purpose — it's host-specific and shouldn't be tracked or committed. ### 5. Start the portal service cluster -1. Inside the portal directory, run the following command in CLI: `docker compose -f docker-compose.prod.yml --profile concordancer-manager up -d --build` +1. Inside the portal directory, run the following command in CLI: `./run-prod.sh --profile concordancer-manager up -d --build` 2. It's going to take some time for all the resources to get downloaded and built. Wait for control to be returned to CLI before continuing. @@ -121,6 +122,97 @@ Same as above, except replace with the value of CONCO Your portal should now be available at whichever address/domain your reverse proxy is set to listen to. +## Automated deployment (CI/CD) + +The generic guide above builds images on the host with `up -d --build`. For a maintainer who +runs one or more long-lived environments (e.g. staging + production VPSs), there is an automated +pipeline built on **Gitea Actions** and the **Gitea container registry**. It builds the three +custom images (`express`, `opensearch`, `concordancer`) once, pushes them to the registry, and +each host **pulls** them instead of building — no more copying files around or building on the VPS. + +**Flow:** + +- Push to the default branch → CI builds + pushes images tagged `sha-` → auto-deploys to **staging**. +- Push a version tag `vX.Y.Z` → CI **promotes** the exact staging-tested images to that tag (no + rebuild) → deploys to **production**. Pushing the tag is the deliberate human release gate. +- Rollback / ad-hoc deploy → run the **deploy-dispatch** workflow with a previous tag. + +The pieces live in the repo: + +- `docker-compose.prod.yml` — each built service has both an `image:` (registry ref, via + `${REGISTRY}`/`${IMAGE_TAG}`) and its `build:` block. Unset, the vars default to a local name so + the generic `up --build` path still works untouched. +- `.gitea/workflows/build-and-stage.yml`, `release-prod.yml`, `deploy-dispatch.yml`. +- `dev/ci/build.sh` (buildx build + push, registry layer cache), `dev/ci/promote.sh` (retag + without rebuild), `dev/ci/deploy.sh` (runner side: SSH the target the tag to deploy), + `dev/ci/ci-deploy-wrapper.sh` (host side: the forced command that validates the tag and runs + `git checkout` + `run-prod.sh pull` + `up -d`). The CI key is pinned to that wrapper, so a leaked + key can only ever trigger a tag deploy on one host — never an arbitrary command + (see [`dev/ci/README.md`](dev/ci/README.md#hardened-deploy-access)). + +### One-time setup + +1. **Enable Gitea Actions** and confirm the **container registry** is on (both are usually default + in recent Gitea). +2. **Register a runner.** On a build host — ideally a machine that is _not_ your public production + server but has Docker, disk, and internet (the concordancer build downloads a large lexicon) — + install the **Gitea Runner** (`gitea/runner`; formerly `act_runner`) and register it repo-scoped + with the `self-hosted` label the workflows target. The runner only needs outbound reachability to + Gitea and SSH reachability to the deploy hosts. Full step-by-step + smoke tests: + [`dev/ci/README.md`](dev/ci/README.md). +3. **Prepare each target host (staging, prod):** + - Create a dedicated `deploy` user (keeps automation out of your personal account and gives + clean audit/revocation); add it to the `docker` group. + - `git clone` the repo to a stable path, e.g. `/opt/termportal-staging` or `/opt/termportal-prod`. + - Put the host-only `.env` (with `REGISTRY=/` set) and, if used, + `docker-compose.prod.override.yml` in that directory. Both are gitignored, so `git checkout` + during deploys never touches them. + - `docker login ` once with a **read-only** registry token so `pull` works. + - Install the **hardened deploy key + forced-command wrapper** — full commands in + [`dev/ci/README.md`](dev/ci/README.md#hardened-deploy-access). In short: a **dedicated** CI + keypair (never your personal key), its public half pinned in the deploy user's + `authorized_keys` with `from="",restrict,command="…/ci-deploy-wrapper.sh"`, and its + private half stored as the Gitea secret below. + - Do the first-time concordancer setup (section 6 above) once, as usual. +4. **Add Gitea Actions secrets** (repo → Settings → Actions → Secrets): + `REGISTRY_TOKEN` — a Personal Access Token with `write:package` scope, used by CI to push + images (the automatic `GITEA_TOKEN` is not authorized to push packages); plus + `STAGING_SSH_HOST`, `STAGING_SSH_USER`, `STAGING_SSH_KEY` and the `PROD_*` equivalents; also + `STAGING_SSH_PORT` / `PROD_SSH_PORT` if a host's sshd doesn't listen on the default port 22 + (both default to 22 when unset). (No `*_DIR` secret is needed — each host's wrapper owns its + checkout path via `ci-deploy.conf`.) + +### Day-to-day + +- **Deploy to staging:** `git push` to the default branch. +- **Release to production:** `git tag -a v1.2.3 -m "…" && git push origin v1.2.3` (tag a commit + already built on the default branch, so its `sha-` images exist to promote). Use an + **annotated** tag (`-a`), not a lightweight one — this repo's release tags carry a tagger, date, + and message as a record of what shipped and why, which a lightweight tag (a bare pointer) doesn't + have. Both tag kinds trigger the `release-prod` workflow the same way, since it matches on the ref + name (`refs/tags/v*`); this only affects the tag's own metadata, not the deploy. +- **Rollback:** run the **deploy-dispatch** workflow with the previous `vX.Y.Z` (or `sha-…`) tag. + Note: this rolls back application code only — database/schema changes are forward-only (there is + no migration framework), so back up and treat schema changes deliberately. + +### Break-glass manual deploy + +If CI is unavailable, SSH into the host and run the same wrapper the pipeline triggers: + +```bash +/home/deploy/ci-deploy-wrapper.sh v1.2.3 # checkout, pull, up -d for that tag +``` + +Or drive the steps by hand (equivalent): + +```bash +cd /opt/termportal-prod +git fetch --tags origin && git checkout --force v1.2.3 +export IMAGE_TAG=v1.2.3 # REGISTRY comes from this host's .env +./run-prod.sh pull +./run-prod.sh up -d +``` + ## Linking your instance with others 1. Using a web browser, navigate to your portal's main page. diff --git a/concordancer/Dockerfile b/concordancer/Dockerfile index 69850f3..0c2fefb 100644 --- a/concordancer/Dockerfile +++ b/concordancer/Dockerfile @@ -1,6 +1,7 @@ +# syntax=docker/dockerfile:1 FROM alpine:3.16 AS builder WORKDIR /sloleks RUN wget -qO- "https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1230/Sloleks2.0.LMF.zip?sequence=3&isAllowed=y" | unzip - -FROM ghcr.io/clarinsi/rsdo-concordancer-api:v1.0.4 +FROM gitea.cjvt.si/rrejc/rsdo-concordancer-api:v1.1.1 COPY --from=builder /sloleks /sloleks diff --git a/concordancer/Dockerfile.prod b/concordancer/Dockerfile.prod index bf3ac67..0c6bb12 100644 --- a/concordancer/Dockerfile.prod +++ b/concordancer/Dockerfile.prod @@ -1,6 +1,7 @@ +# syntax=docker/dockerfile:1 FROM alpine:3.16 AS builder WORKDIR /sloleks RUN wget -qO- "https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1230/Sloleks2.0.LMF.zip?sequence=3&isAllowed=y" | unzip - -FROM ghcr.io/clarinsi/rsdo-concordancer-api-term-portal:v1.0.4 +FROM gitea.cjvt.si/rrejc/rsdo-concordancer-api-term-portal:v1.1.1 COPY --from=builder /sloleks /sloleks diff --git a/dev/.env b/dev/.env index 9aa349a..58027ac 100644 --- a/dev/.env +++ b/dev/.env @@ -61,6 +61,54 @@ CONCORDANCER_LISTEN_PORT=3003 # The origin, where the portal will be made available. URL_ORIGIN="https://mywebportal.com" +# OIDC/SSO federation with the University of Ljubljana (backed by Microsoft Entra ID). Register +# the portal as a confidential OIDC client in the target environment's University of +# Ljubljana/Entra app registration, with redirect URI "${URL_ORIGIN}/users/oidc/callback", then +# fill in the real values below. Not used in dev - dev/docker-compose.yml instead derives dev's +# OIDC_UNI_LJ_* values automatically from AUTHENTIK_OIDC_CLIENT_ID/_SECRET further down this file. +OIDC_UNI_LJ_CLIENT_ID="changeme" +OIDC_UNI_LJ_CLIENT_SECRET="changeme" +OIDC_UNI_LJ_DISCOVERY_URL="https://login.microsoftonline.com//v2.0/.well-known/openid-configuration" + +# Container image registry prefix, read only by docker-compose.prod.yml. +# Leave empty for a local `up --build` (images get a local name); for a registry-based CI/CD +# deploy set it to /, e.g. gitea.example.tld/myorg. The image tag is +# not set here — the deploy wrapper exports IMAGE_TAG per deploy. +REGISTRY="" + # Development only settings (not used in production) MAILDEV_WEB_GUI_PORT=3001 + +# Throwaway Authentik OIDC Identity Provider, used only for local SSO/OIDC login testing. +# Started with `docker compose --profile develop-idp up -d`. See dev/authentik/README.md. +# It stands in for the single real University of Ljubljana OIDC federation ('uni_lj' in the +# auth_provider enum) - it is not a production identity provider and none of its state is meant +# to be kept. + +# Exposed on host's localhost to reach the Authentik admin UI and the test IdP's login pages. +AUTHENTIK_LISTEN_PORT=9000 +# Used only by Authentik's own internal Postgres database - a separate, throwaway database +# dedicated to this test IdP, not the portal's own database. +AUTHENTIK_POSTGRES_PASSWORD="weak_authentik_postgres_password" +# Used by Authentik for its own cookie signing/encryption and unique user IDs. Generate a real +# random 50+ char value for anything beyond throwaway local testing, e.g.: +# openssl rand -base64 60 | tr -d '\n' +AUTHENTIK_SECRET_KEY="weak_authentik_secret_key_please_generate_a_real_one" + +# Credentials for Authentik's own built-in "akadmin" superuser, created automatically on first +# startup (Authentik's non-interactive/automated-install feature). Used to log into the Authentik +# admin UI at http://localhost:${AUTHENTIK_LISTEN_PORT}/if/admin/ - unrelated to the portal's own +# PORTAL_ADMIN_INITIAL_EMAIL/PASSWORD above, which is a completely separate account/app. +AUTHENTIK_BOOTSTRAP_EMAIL="admin@authentik.test" +AUTHENTIK_BOOTSTRAP_PASSWORD="weak_authentik_admin_password" +# API token for the akadmin user, also created on first startup. Not needed for manual UI use; +# documented here in case future scripted setup/debugging needs direct Authentik API access. +AUTHENTIK_BOOTSTRAP_TOKEN="weak_authentik_bootstrap_api_token" + +# Fixed OIDC client credentials for the single University-of-Ljubljana-stand-in test application +# that the blueprint in dev/authentik/blueprints/ registers in Authentik. Being dev-only throwaway +# values for a testing IdP, committing them is fine (same "weak_" pattern as EXPRESS_SECRET +# above). The express-side OIDC client needs these two values (see OIDC_UNI_LJ_* above). +AUTHENTIK_OIDC_CLIENT_ID="weak_uni_lj_test_client_id" +AUTHENTIK_OIDC_CLIENT_SECRET="weak_uni_lj_test_client_secret" diff --git a/dev/authentik/README.md b/dev/authentik/README.md new file mode 100644 index 0000000..4b71810 --- /dev/null +++ b/dev/authentik/README.md @@ -0,0 +1,157 @@ +# Authentik — throwaway local OIDC Identity Provider + +This directory holds a throwaway [Authentik](https://goauthentik.io/) instance, added to the dev +Docker Compose stack purely for **local testing of SSO/OIDC login**. It stands in for the single +real external identity federation the portal integrates with — the **University of Ljubljana** +(itself backed by Microsoft Entra ID) — which in the portal's schema is the one non-`local` value +of the `auth_provider` enum: `uni_lj`. + +This is infrastructure/dev-setup only. For the bigger picture of running the portal locally, see +the main [README](../../README.md). **Wiring the express app itself up as an OIDC client against +this (or the real University of Ljubljana) is a separate, later task** — nothing here touches +`express/`. + +> **Note:** This Authentik instance, its database, and every seeded user are throwaway. Nothing +> here is meant to be backed up, migrated, or taken into production. + +## What's here + +- `blueprints/uni-lj-stand-in.yaml` — a declarative [Authentik blueprint](https://docs.goauthentik.io/customize/blueprints/) + that, on every startup, seeds: one OIDC Provider + Application + (`Univerza v Ljubljani (test stand-in)`), two custom claim (scope) mappings restricted to the + business-relevant claims the University of Ljubljana/Entra actually sends — `email`, `name`, + `preferred_username` on the ID token, `given_name`, `family_name`, `picture` via `/userinfo` + (plus `sub`, which authentik always includes automatically) — and three test users (see below). + +## Bringing it up + +This is behind the `develop-idp` Docker Compose profile, so it's off by default: + + docker compose --profile develop-idp up -d + +(Combine with other profiles as needed, e.g. `docker compose --profile develop-idp --profile develop-concordancer up -d --build` if you're also working on the concordancer.) + +First startup takes a little longer than the rest of the stack: Authentik runs its own database +migrations and then applies the blueprint in `blueprints/`. Watch it with: + + docker compose logs -f authentik-server authentik-worker + +> **Note:** the blueprint is re-applied automatically roughly every 60 minutes, on container +> restart, and whenever the blueprint file changes — so if you ever poke at a seeded provider, +> application, mapping, or user through the admin UI, expect your changes to be silently reverted. +> Treat that as a feature: it's the reset mechanism (see _Resetting test data_ below). + +## Reaching the admin UI + +Once up, the Authentik admin UI is at `http://localhost:${AUTHENTIK_LISTEN_PORT}` (default +`9000`, from the root `.env`) — e.g. `http://localhost:9000/if/admin/`. + +Log in with the bootstrap admin account, created automatically on first startup from the root +`.env`: + +| | value (from `.env`) | +| -------- | ------------------------------------------------------------------------ | +| Email | `AUTHENTIK_BOOTSTRAP_EMAIL` (default `admin@authentik.test`) | +| Password | `AUTHENTIK_BOOTSTRAP_PASSWORD` (default `weak_authentik_admin_password`) | + +This account is Authentik's own superuser — unrelated to the portal's own +`PORTAL_ADMIN_INITIAL_EMAIL`/`PORTAL_ADMIN_INITIAL_PASSWORD` admin account, which is a completely +separate application. + +## The registered test application + +- **Application slug:** `uni-lj-test` +- **Redirect URI:** `http://localhost:${EXPRESS_LISTEN_PORT}/users/oidc/callback` (the portal's + planned generic OIDC callback route — provider selection is carried via session, not the URL) +- **Client ID / secret:** `AUTHENTIK_OIDC_CLIENT_ID` / `AUTHENTIK_OIDC_CLIENT_SECRET` in `.env` + (fixed, non-secret dev defaults — safe to commit, same pattern as `EXPRESS_SECRET`) +- **Scopes to request:** `openid email profile` +- **Discovery document:** + + - from your host/browser: `http://localhost:${AUTHENTIK_LISTEN_PORT}/application/o/uni-lj-test/.well-known/openid-configuration` + - from inside another container on the compose network (e.g. the future express OIDC client): + `http://authentik-server:9000/application/o/uni-lj-test/.well-known/openid-configuration` + + These are two different hosts on purpose: the authorization/redirect legs happen in the user's + browser (needs the `localhost` URL), while token/JWKS/userinfo calls happen server-to-server + (can use the internal `authentik-server` compose hostname). The future express-side OIDC client + task will need to account for this split. + +Only one provider/application is registered, matching the single `uni_lj` value in the +portal's `auth_provider` enum — this is not meant to model multiple external IdPs. + +## Test users + +All seeded users share the password **`IdpTest123!`** (log in with it on Authentik's own login +page during the OIDC redirect flow — this is _not_ a portal password). + +| Authentik username | Claims sent (ID token) / userinfo | Portal-side scenario it exercises | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ana.novak` | `name="Novak, Ana"`, `email=ana.novak@ff.uni-lj.si`, `preferred_username=novaka@ff.uni-lj.si` / userinfo: `given_name=Ana`, `family_name=Novak`, `picture=` | **(A) Brand new user, all claims present.** No pre-existing local account needed — log in via SSO, review the read-only data on `/users/create-profile`, and confirm to create the new portal account exactly as shown (nothing on that page is editable). | +| `berta.kolar.idp` | `name="Kolar, Berta"`, `email=berta.kolar@fri.uni-lj.si`, `preferred_username=kolarb@fri.uni-lj.si` / userinfo: `given_name=Berta`, `family_name=Kolar`, `picture=` | **(B) Email matches an existing LOCAL account → account conversion.** See below — you must register a matching local account first. Confirming with that account's password permanently overwrites its username/first/last name with the IdP data and removes its password — sign-in from then on is SSO-only. | +| `brez.imena` | `email=brez.imena@fri.uni-lj.si`, `preferred_username=brez.imena@fri.uni-lj.si` — **`given_name`/`family_name`/`name` absent** | **(C) Missing given_name/family_name claims → account creation/conversion is refused.** The claims are entirely absent from the ID token/userinfo response (not blank strings) — since there's nothing to review or persist, the portal shows a clear error and never renders a create/convert page. | + +> **Note on claim placement:** the real University of Ljubljana/Entra ID token never carries +> `given_name`/`family_name`/`picture` — only the `/userinfo` endpoint does (`name` and +> `preferred_username`, by contrast, _are_ on the real ID token). Authentik has no per-field way to +> split claims between the ID token and userinfo response — a single provider-level toggle either +> includes everything in both, or restricts the ID token to bare-minimum standard fields (which +> would also strip `email`/`preferred_username`, breaking parity there). This blueprint leaves that +> toggle at its default (`include_claims_in_id_token: true`), so Authentik's ID token ends up a +> harmless superset of the real one — it also carries `given_name`/`family_name`/`picture`. This is +> intentional and documented, not a bug: the app code (`express/middleware/auth.js`) only ever reads +> `given_name`/`family_name` from the `/userinfo` response, never from ID-token claims, so the extra +> keys in Authentik's ID token are inert. + +> **Note:** there is no seeded/default local user in this app's dev DB — registration is always +> manual, via the normal `/register` flow. So for scenario B, before testing SSO login as +> `berta.kolar.idp`, first manually register a local portal account with email exactly +> `berta.kolar@fri.uni-lj.si` (any other field can be anything you like), then log in via SSO as +> `berta.kolar.idp` and confirm the portal lands on `/users/convert-account`, showing that local +> account's current username alongside the (locked) IdP-derived data. Confirming with that local +> account's password converts it: username/first/last name are overwritten with the IdP data, its +> password is removed, and a subsequent local-password login attempt should fail with the usual +> "created via University of Ljubljana, no password" message. + +## Troubleshooting + +> **Note:** On a genuinely first-ever startup (empty `authentik-postgres-data` volume), the custom +> blueprint's very first apply attempt can race against Authentik's own built-in self-signed +> certificate being created (the blueprint's OIDC provider references that certificate as its +> signing key) — if the blueprint applies first, that one attempt fails and the provider ends up +> without a working configuration. Authentik retries blueprints roughly every 60 minutes on its +> own, but you don't need to wait: just re-apply it manually once, which always succeeds once the +> certificate exists (by then, well under a minute after startup): +> +> docker compose --profile develop-idp exec authentik-worker ak apply_blueprint /blueprints/custom/uni-lj-stand-in.yaml +> +> You can confirm whether this happened via the admin UI (System → Blueprints) or the API: +> +> curl -s -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \ +> "http://localhost:${AUTHENTIK_LISTEN_PORT}/api/v3/managed/blueprints/?search=Ljubljana" \ +> | grep -o '"status": *"[a-z]*"' +> +> A `"successful"` status means it's fine; `"error"` means run the manual re-apply above. + +## Resetting test data + +Because the blueprint uses `state: present`, Authentik reconciles all of the above back to these +exact values automatically (on restart, on blueprint file changes, and roughly every 60 minutes +regardless). So for most purposes, just wait or restart: + + docker compose --profile develop-idp restart authentik-server authentik-worker + +For a full wipe (new admin bootstrap, fresh database, blueprint re-applied from scratch): + + docker compose --profile develop-idp down + docker volume rm terminoloski_portal_authentik-postgres-data terminoloski_portal_authentik-data + docker compose --profile develop-idp up -d + +(Adjust the volume name prefix if your Compose project name differs from the directory name.) + +## Tearing it down + + docker compose --profile develop-idp down + +This only stops/removes the `authentik-postgres`, `authentik-server` and `authentik-worker` +containers — it never touches the portal's own `postgres`/`express`/etc. services or data. diff --git a/dev/authentik/blueprints/uni-lj-stand-in.yaml b/dev/authentik/blueprints/uni-lj-stand-in.yaml new file mode 100644 index 0000000..f6e2eb2 --- /dev/null +++ b/dev/authentik/blueprints/uni-lj-stand-in.yaml @@ -0,0 +1,166 @@ +version: 1 +metadata: + name: University of Ljubljana test stand-in - provider, application, claim mappings and test users + labels: + blueprints.goauthentik.io/description: | + Throwaway local Identity Provider setup for the Terminoloski portal's dev stack. Registers + ONE OIDC provider + application standing in for the single real University of Ljubljana/ + Entra ID federation (the portal's `auth_provider` enum only ever has one external value: + 'uni_lj'), whose claim set is deliberately restricted to the business-relevant fields the + University of Ljubljana actually sends: sub, email, name, preferred_username (ID token) and + given_name, family_name, picture (userinfo) - deliberately NOT Microsoft/Entra-proprietary + protocol claims (rh, aud, exp, iat, iss, nbf, oid, sid, tid, uti, ver), which app code never + reads and which authentik already has its own standard-OIDC equivalents for. authentik has + no way to split claims between the ID token and userinfo per-field, so (with + include_claims_in_id_token left at its default true) authentik's ID token ends up a harmless + superset of the real Entra one (it also carries given_name/family_name/picture) - see + dev/authentik/README.md. See dev/authentik/README.md for what each seeded test user is for. +entries: + # --- Claim (scope) mappings ------------------------------------------------------------- + # authentik's own built-in "email"/"profile" scopes emit extra claims (email_verified, + # nickname, groups) that the real University of Ljubljana/Entra federation does NOT send in + # this combination. These two replace them for this provider only, so dev testing matches + # production claims exactly. (name and picture ARE now included deliberately, in real-Entra + # shape - see below - unlike authentik's own defaults, which format them differently.) + - model: authentik_providers_oauth2.scopemapping + id: uni-lj-scope-email + state: present + identifiers: + name: "Univerza v Ljubljani test mapping: email" + attrs: + name: "Univerza v Ljubljani test mapping: email" + scope_name: email + description: "Only 'email' - no email_verified (the University of Ljubljana/Entra doesn't send it either)." + expression: | + return { + "email": request.user.email, + } + + - model: authentik_providers_oauth2.scopemapping + id: uni-lj-scope-profile + state: present + identifiers: + name: "Univerza v Ljubljani test mapping: profile" + attrs: + name: "Univerza v Ljubljani test mapping: profile" + scope_name: profile + description: > + given_name, family_name, name, preferred_username, picture - no nickname/groups. Mirrors + the real University of Ljubljana/Entra shape: given_name/family_name come from the user's + own attributes with NO fallback (delete_none_values() drops them entirely when unset, so a + test user can simulate the IdP omitting those claims); name is derived from those same two + attributes as ", " (also dropped, not just blank, when either is + missing - real Entra's ID token has no given_name/family_name at all, but DOES have name in + that exact format); preferred_username comes from a dedicated "preferred_username" + attribute (NOT request.user.username, which must stay the authentik login name) in the real + IdP's UPN-style "@" format; picture is the + fixed, non-user-specific Graph API URL every real account was observed to return. + expression: | + given_name = ak_obj_attr(request.user, "given_name") + family_name = ak_obj_attr(request.user, "family_name") + name = f"{family_name}, {given_name}" if given_name and family_name else None + + return delete_none_values({ + "given_name": given_name, + "family_name": family_name, + "name": name, + "preferred_username": ak_obj_attr(request.user, "preferred_username"), + "picture": "https://graph.microsoft.com/v1.0/me/photo/$value", + }) + + # --- Provider + Application -------------------------------------------------------------- + - model: authentik_providers_oauth2.oauth2provider + id: uni-lj-provider + state: present + identifiers: + name: "Univerza v Ljubljani (test stand-in)" + attrs: + name: "Univerza v Ljubljani (test stand-in)" + authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]] + invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]] + client_type: confidential + client_id: !Env AUTHENTIK_OIDC_CLIENT_ID + client_secret: !Env AUTHENTIK_OIDC_CLIENT_SECRET + # Not populated by any default when created via blueprint - without it the authorization + # endpoint rejects every request with "Invalid grant_type for provider" (verified locally). + grant_types: + - authorization_code + - refresh_token + redirect_uris: + - url: !Format ["http://localhost:%s/users/oidc/callback", !Env [IDP_REDIRECT_PORT, "3000"]] + matching_mode: strict + signing_key: !Find [authentik_crypto.certificatekeypair, [name, "authentik Self-signed Certificate"]] + property_mappings: + - !Find [authentik_providers_oauth2.scopemapping, [managed, "goauthentik.io/providers/oauth2/scope-openid"]] + - !KeyOf uni-lj-scope-email + - !KeyOf uni-lj-scope-profile + + - model: authentik_core.application + id: uni-lj-application + state: present + identifiers: + slug: uni-lj-test + attrs: + name: "Univerza v Ljubljani (test stand-in)" + slug: uni-lj-test + provider: !KeyOf uni-lj-provider + policy_engine_mode: any + meta_description: > + Throwaway local test application standing in for the single real University of Ljubljana + OIDC federation. Not a real IdP - dev/testing use only. + + # --- Test users -------------------------------------------------------------------------- + # All seeded users share the same fixed password so a tester can log in without hunting for + # per-user credentials. See dev/authentik/README.md for what portal-side scenario each covers, + # and for the exact local-account value scenario B requires you to register first. + + # (A) Brand new user via IdP only, every claim present. + - model: authentik_core.user + id: uni-lj-user-full + state: present + identifiers: + username: ana.novak + attrs: + name: "Ana Novak" + email: ana.novak@ff.uni-lj.si + is_active: true + attributes: + given_name: Ana + family_name: Novak + preferred_username: novaka@ff.uni-lj.si + password: "IdpTest123!" + + # (B) email claim matches a pre-existing LOCAL portal account -> account-conversion test. + - model: authentik_core.user + id: uni-lj-user-email-match + state: present + identifiers: + username: berta.kolar.idp + attrs: + name: "Berta Kolar" + email: berta.kolar@fri.uni-lj.si + is_active: true + attributes: + given_name: Berta + family_name: Kolar + preferred_username: kolarb@fri.uni-lj.si + password: "IdpTest123!" + + # (C) given_name/family_name attributes deliberately left unset -> those claims (and the derived + # `name`) are entirely absent from the ID token/userinfo response (not blank strings) -> the + # portal refuses to create/convert an account without a name (nothing to review or persist), + # with a clear error message rather than a blank editable form. No real first/last name + # exists to build a proper email/preferred_username from, so both deliberately reuse the same + # "brez.imena" placeholder local-part (only the domain suffix is updated for consistency). + - model: authentik_core.user + id: uni-lj-user-missing-name + state: present + identifiers: + username: brez.imena + attrs: + name: "Brez imena (missing given_name/family_name claims)" + email: brez.imena@fri.uni-lj.si + is_active: true + attributes: + preferred_username: brez.imena@fri.uni-lj.si + password: "IdpTest123!" diff --git a/dev/ci/README.md b/dev/ci/README.md new file mode 100644 index 0000000..c9da934 --- /dev/null +++ b/dev/ci/README.md @@ -0,0 +1,352 @@ +# CI/CD — pipeline internals + +This directory holds the runner-side scripts the Gitea Actions workflows in +`.gitea/workflows/` call: + +- `build.sh` — `docker buildx` build + push of the three custom images, with registry layer cache. +- `promote.sh` — retag an already-built image set to a new tag (no rebuild), for staging→prod promotion. +- `deploy.sh` — runner side: SSH the target host the tag to deploy (nothing more). +- `ci-deploy-wrapper.sh` — host side: the forced command that validates the tag and runs + `git checkout` + `run-prod.sh pull` + `up -d`. + +The end-to-end pipeline (what triggers what, the registry model, rollback) is documented in the +main [README](../../README.md#automated-deployment-cicd). This file covers two operational tasks in +depth: **standing up the runner on a build host**, and **hardening deploy access** to each host. + +## Setting up the Gitea Runner on a VPS + +The runner formerly known as `act_runner` was rebranded to **Gitea Runner** at the runner project's +own **v1.0.0** (separate versioning from the Gitea *server*). Use the `gitea/runner` image; +`gitea/act_runner` still works but is deprecated. + +Pick a build host that is **not** your public production server but has Docker, disk, and internet +(the concordancer build downloads a large lexicon). Our own choice is the private ~24/7 VPS. The +runner needs **outbound HTTPS** to Gitea, and later **outbound SSH** to the deploy targets. + +### 0. Prerequisites (on the VPS) + +```bash +docker --version && docker ps # Docker present, your user can reach the daemon +``` + +### 1. Get a registration token + +In Gitea: **repository → Settings → Actions → Runners → Create new runner**. Note your Gitea URL +and the (single-use, short-lived) **registration token**. Using the *repo's* runner page — not the +admin/org one — makes the runner **repo-scoped**, so no Gitea admin access is needed. + +### 2. Create the runner (Docker Compose) + +```bash +sudo mkdir -p /opt/gitea-runner/data +cd /opt/gitea-runner +``` + +`/opt/gitea-runner/docker-compose.yml`: + +```yaml +services: + runner: + image: gitea/runner:latest # NOT gitea/act_runner (deprecated) + restart: always + environment: + GITEA_INSTANCE_URL: https://gitea.example.tld # ← your Gitea + GITEA_RUNNER_REGISTRATION_TOKEN: "PASTE_TOKEN_HERE" # ← from step 1 + GITEA_RUNNER_NAME: vps-builder + # Maps the `self-hosted` label our workflows target to an image that already + # ships git, node, docker CLI and ssh. + GITEA_RUNNER_LABELS: "self-hosted:docker://catthehacker/ubuntu:act-latest" + volumes: + - ./data:/data + - /var/run/docker.sock:/var/run/docker.sock # jobs run docker/buildx on the host daemon +``` + +Two details that matter for this pipeline: + +- `self-hosted:docker://…` runs each job inside that image, which supplies `node` (required by + `actions/checkout`) plus `git`, `docker`, `ssh`. +- The socket mount is what lets the `docker buildx` / `docker login` calls in `build.sh` and + `promote.sh` reach a real daemon. + +### 3. Start and confirm registration + +```bash +docker compose up -d +docker compose logs -f +``` + +Wait for `runner registered successfully` → `waiting for tasks…`. The token is now consumed; the +runner identity persists in `./data/.runner`. To re-register later, wipe `./data` and use a fresh +token. + +### 4. Confirm in Gitea + +Back on **Settings → Actions → Runners**, `vps-builder` should show **Idle / online** (green) with +the `self-hosted` label. + +> **Binary / systemd alternative.** Instead of Docker, fetch the `gitea/runner` release binary and +> run `./runner register --no-interactive --instance --token --name vps-builder +> --labels "self-hosted:host"` then `./runner daemon`. Simpler socket story, but the VPS itself must +> then have `git`, `node`, `docker`, and `ssh` installed, since jobs won't inherit them from an image. + +## Smoke tests + +**A — online status (step 4).** Green = registration + Gitea↔runner networking are good. + +**B — it claims a job and has the toolchain (the real test).** On a scratch branch add +`.gitea/workflows/smoke.yml`, push it, watch the **Actions** tab, then delete it: + +```yaml +name: smoke +on: [push] +jobs: + check: + runs-on: [self-hosted] + steps: + - uses: actions/checkout@v4 + - run: | + git --version && node --version && ssh -V + docker version && docker buildx version + docker ps # proves the socket mount reaches the host daemon + echo OK +``` + +Green proves the runner runs jobs, `checkout` works, and `docker`/`buildx`/`ssh` + host socket are +all present — exactly what `build.sh`, `promote.sh`, and `deploy.sh` rely on. + +**C — registry push path (optional, once `REGISTRY_TOKEN` is set).** Validates registry auth +**and** the buildx `docker-container` cache driver together — the two things most likely to bite: + +```yaml + - run: | + echo "${{ secrets.REGISTRY_TOKEN }}" | docker login gitea.example.tld -u "${{ github.actor }}" --password-stdin + docker buildx create --name ci --driver docker-container --use 2>/dev/null || docker buildx use ci + printf 'FROM alpine\nRUN echo hi\n' > /tmp/Dockerfile + docker buildx build -f /tmp/Dockerfile -t gitea.example.tld//smoke:test --push /tmp +``` + +Notes learned the hard way (validated against a real Gitea instance): + +- **`REGISTRY_TOKEN`, not the automatic `GITEA_TOKEN`.** The auto token is repo-scoped and returns + `unauthorized` at the registry; you need a PAT with `write:package`. +- **The registry ignores the username** — it authenticates on the token alone, so `github.actor` + is safe (works whoever triggers the run). +- **Don't add a job-level `permissions:` block** — on Gitea it becomes a complete allow-list and + drops `contents: read`, breaking `actions/checkout` with `Repository not found`. +- **`` must be lowercase** — OCI repository paths reject uppercase, so a mixed-case Gitea + org/user (e.g. `Amebis`) must be lowercased (`amebis`). The real workflows do this in their + `meta` step via `${owner,,}`. + +## Troubleshooting quick hits + +- **Never turns green:** wrong `GITEA_INSTANCE_URL`, blocked outbound 443, or a reused token + (regenerate, wipe `./data`, retry) — check `docker compose logs`. +- **`docker ps` fails in-job / permission denied:** socket mount missing or host socket perms too tight. +- **`--cache-to type=registry` errors:** the default docker driver doesn't support registry cache — + that's why the workflow creates the `docker-container` builder first. +- **Config errors on first `up`:** verify env var names against the current `gitea/runner` docs and + `docker run --rm gitea/runner:latest --help`. + +## Hardened deploy access + +Gitea Actions secrets are **encrypted, not hashed** — they must be decryptable to be injected into +jobs. So the SSH private key you store is recoverable by anyone holding the Gitea server's +`SECRET_KEY` (a Gitea admin) and by anyone with write access to this repo (a workflow can print a +secret). You cannot hide it. The strategy is instead: **expose a key that is worth as little as +possible and is trivial to revoke.** Three measures, in priority order. + +### 1. A dedicated CI keypair (do this) + +Never put your personal key in Gitea. Generate a passphraseless key used only by this pipeline, so +a leak is revoked in isolation: + +```bash +ssh-keygen -t ed25519 -f ci_deploy_key -N "" -C "gitea-ci-deploy" +# private half (ci_deploy_key) -> Gitea secret STAGING_SSH_KEY / PROD_SSH_KEY +# public half (ci_deploy_key.pub) -> the deploy user's authorized_keys on each host (step 3) +``` + +Paste the **entire** `ci_deploy_key` file into `STAGING_SSH_KEY` / `PROD_SSH_KEY` — **including** +the `-----BEGIN OPENSSH PRIVATE KEY-----` and `-----END OPENSSH PRIVATE KEY-----` lines and the +trailing newline. Stripping the armor lines makes the key unparseable (`error in libcrypto` / +`invalid format` at deploy time). + +### 2. A dedicated `deploy` user per host + +Keeps automation out of your personal account → clean audit logs and clean revocation (delete the +user, the access is gone). It needs Docker, which means the `docker` group — and **docker group ≈ +root**, so this is about isolation/auditability, not privilege reduction. + +```bash +export DEPLOY_USER=deploy # the account these steps create — pick your own +export DEPLOY_DIR=/opt/termportal-prod # this host's repo checkout path — pick your own +sudo adduser --disabled-password --gecos "" "$DEPLOY_USER" # no password login (key/console only) +sudo usermod -aG docker "$DEPLOY_USER" # lets it run docker/compose without sudo +export DEPLOY_HOME="$(getent passwd "$DEPLOY_USER" | cut -d: -f6)" # its home, e.g. /home/deploy +``` + +> `DEPLOY_USER`, `DEPLOY_DIR`, and `DEPLOY_HOME` live in **this admin shell**. The commands below run +> as the deploy user via `sudo -H -u "$DEPLOY_USER"` — your shell expands these vars *before* the +> user switch, and `-H` sets the deploy user's `$HOME` so git/docker write their credentials under +> that account, not yours. + +> **This host involves two credentials — don't mix them up:** +> - the **CI SSH key** from step 1 (runner → this host): its *public* half goes into the deploy +> user's `authorized_keys` in step 3; its private half is the Gitea secret. +> - a **read-only PAT** (this host → Gitea, over HTTPS): lets the deploy user `clone`/`fetch` the +> repo **and** `docker pull` images. Created just below. + +**Create one read-only token** for the deploy user in Gitea → **Settings → Applications → Generate +New Token**, with scopes **`read:repository`** + **`read:package`** (older Gitea: `repo` + `package` +read). One token covers both git and the registry, so there's a single low-value credential to +rotate. + +**Clone the repo over HTTPS** to this host's checkout path, owned by the deploy user (`/opt` needs +root just to create the directory): + +```bash +sudo mkdir -p "$DEPLOY_DIR" +sudo chown "$DEPLOY_USER:$DEPLOY_USER" "$DEPLOY_DIR" +sudo -H -u "$DEPLOY_USER" git config --global credential.helper store # cache creds in ~deploy/.git-credentials (mode 600) +sudo -H -u "$DEPLOY_USER" git clone https://gitea.example.tld//.git "$DEPLOY_DIR" +# Username: +# Password: -> stored, so the wrapper's `git fetch` runs non-interactively later +``` + +**Place host-only files and log in to the registry** as the deploy user, reusing the same token: + +```bash +sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/.env" "$DEPLOY_DIR/.env" +sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_DIR/.env" # fill in real secrets, incl. the REGISTRY line (gitea.example.tld/) +# optional per-host tweaks: +# sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/docker-compose.prod.override.example.yml" "$DEPLOY_DIR/docker-compose.prod.override.yml" +sudo -H -u "$DEPLOY_USER" docker login gitea.example.tld -u # paste the SAME read PAT at the prompt +``` + +`.env` and `docker-compose.prod.override.yml` are gitignored, so the deploy-time `git checkout` +never touches them. The stored git credential and the cached `docker login` (in the deploy user's +`~/.git-credentials` and `~/.docker/config.json`, both mode 600) let deploy-time `git fetch` and +`docker pull` run without prompts. + +`docker login` prints a "credentials are stored unencrypted … Configure a credential helper" +warning — that's expected and fine here: the value is a read-only `read:package` token in a +mode-600 file under a dedicated account. A credential helper isn't worth the `pass`/GPG or +secret-service plumbing on a headless host. + +> **SSH instead of HTTPS (only if your Gitea has SSH enabled).** If the instance allows it, you can +> use a read-only **Deploy Key** rather than a PAT for git: as the deploy user, +> `ssh-keygen -t ed25519 -f ~/.ssh/gitea_ro -N ""`, add the `.pub` under repo → Settings → Deploy +> Keys (write access off), add a `Host` stanza in `~/.ssh/config` pointing at `gitea_ro`, and clone +> `git@gitea.example.tld:/.git`. You'd still need a `read:package` token for +> `docker login`. If Deploy Keys show "SSH Disabled", the admin has turned SSH off instance-wide — +> use the HTTPS path above. + +### 3. Pin the key to a forced command (this is what shrinks a leaked key) + +Install the wrapper **outside the git checkout** (so `git checkout` never rewrites the running +script) and tell it this host's checkout path: + +```bash +sudo -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/ci/ci-deploy-wrapper.sh" "$DEPLOY_HOME/ci-deploy-wrapper.sh" +sudo -u "$DEPLOY_USER" chmod 755 "$DEPLOY_HOME/ci-deploy-wrapper.sh" +echo "DEPLOY_DIR=$DEPLOY_DIR" | sudo -u "$DEPLOY_USER" tee "$DEPLOY_HOME/ci-deploy.conf" # the wrapper reads this +``` + +Then add the pinned CI key to the deploy user's `authorized_keys`. Open it in an editor (creating +the `.ssh` dir first if needed) — that way you can paste the key now and reopen the same file to add +`from=` later: + +```bash +sudo -u "$DEPLOY_USER" install -d -m 700 "$DEPLOY_HOME/.ssh" +sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_HOME/.ssh/authorized_keys" +``` + +Paste the CI **public** key as one line, prefixed with the forced-command options. The paths here +are **literal** (`authorized_keys` doesn't expand variables), so use the deploy user's real home for +`command=` — print it with `echo "$DEPLOY_HOME"`. Leave `from=` off for now (you add it once you +know the runner's source IP — see *Verify it*): + +``` +restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy +``` + +Later, reopen the file with the same editor command and prepend `from="",`: + +``` +from="",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy +``` + +- `command="…"` — a **forced command**: this key can *only* run the wrapper. The tag the runner + sends arrives as `$SSH_ORIGINAL_COMMAND`; the wrapper allow-lists it to `[A-Za-z0-9._-]`, so even + a fully compromised Gitea/workflow can at most deploy some existing tag — never a shell. +- `from=""` — the key works only from the address the **target's** `sshd` sees for the + runner's connection, so a leaked key is useless elsewhere. That address depends on topology: + - **Runner reaches this host over the network** (e.g. remote prod): it's the runner's public + egress IP — `curl -s ifconfig.me` from the runner. + - **Runner and this host are the same machine** (e.g. co-located staging): jobs run in a + container, so `sshd` sees a Docker-network address, not the public IP — and it can vary per + job, so pin the subnet, e.g. `from="172.16.0.0/12"`. (`DEPLOY_HOST` for such a host must also + be an address the container can reach — its routable IP, **not** `127.0.0.1`.) + When unsure, read the real value from the target after one test connection (see *Verify it*): + `sudo journalctl -u ssh | grep Accepted` (or `/var/log/auth.log`) shows `… from …`. +- `restrict` — no PTY, no port/agent forwarding, nothing but the command. + +Because you can't make the key un-leakable, keep rotation cheap: to revoke, delete the +`authorized_keys` line (and/or the `deploy` user) and replace the Gitea secret with a fresh key. + +### Verify it + +The private key lives in the Gitea secret, so drive the checks from the runner via the +**`deploy-dispatch`** workflow (Actions → Run workflow), not a local `ssh`. + +1. **Probe — no deploy.** Run `deploy-dispatch` with `environment` set to this host and + `image_tag = probe/invalid` (any character outside `[A-Za-z0-9._-]`). The job **should go red at + the deploy step, and that is the pass**: the key authenticates, then the wrapper refuses the + invalid tag *before* any `git fetch`/`pull`/`up`, so nothing deploys — one run verifies both auth + and the allow-list lock. +2. **Read the source IP** the target saw and pin it in `from=` (reopen `authorized_keys` with the + editor command above; use the subnet CIDR if it's a per-job Docker address): + ```bash + sudo journalctl -u ssh | grep 'Accepted publickey' | tail -1 # -> ... from port ... + ``` +3. **Full path.** When you actually want to deploy, run `deploy-dispatch` with a **valid** existing + tag (e.g. a `sha-…` already in the registry) to exercise checkout → pull → `up -d`. + +> **Stronger option if the admin threat is the real concern.** All of the above still exposes the +> key to the Gitea admin. If that is unacceptable, switch to **pull-based** deploy: the host pulls +> images itself (a cron or webhook running the wrapper), and Gitea holds only a read-only registry +> token — far lower value than an SSH key into prod. More setup, but no deploy key in Gitea at all. + +## Registry retention + +Every push to the default branch mints three `sha-` image tags (one per service), forever — +so without a policy the registry grows unbounded. The `v*` release tags grow slowly and are +meaningful, and `buildcache` is a single tag that is *overwritten* each build (it doesn't pile up). +So the only thing worth pruning is **old `sha-*` tags**. + +Use Gitea's built-in package **Cleanup Rules** (no scripting; runs on Gitea's package-cleanup cron): +org → **Settings → Packages → Cleanup Rules → Add Cleanup Rule** (needs org-owner access). Recommended: + +| Field (labels vary slightly by Gitea version) | Value | +|---|---| +| Package type | **Container** | +| Keep the most recent | **10** | +| Remove versions older than | **30 days** | +| **Keep** versions matching (regex) | `^(v.*\|buildcache\|latest)$` | +| **Remove** versions matching (regex) | `^sha-` | + +A version is deleted only if it matches **Remove** (`^sha-…`), is **not** among the 10 newest, is +older than 30 days, **and** doesn't match **Keep** — the patterns match the full tag name. Rationale: + +- **`v*` kept forever** — release tags are rollback targets; never let one you might revert to be + reaped. The `Keep` pattern protects them absolutely. +- **`buildcache` kept** — it warms rebuilds (notably the ~5-min concordancer); pruning it just makes + the next build cold. +- **`sha-*` bounded** — keeping ~10 recent (and anything under 30 days) still lets you roll a few + commits back while capping growth. Tune the two numbers to how often you deploy. +- **`Remove` restricted to `^sha-`** — belt-and-suspenders so the rule can only ever touch CI + artifacts, never a release or the cache. + +Caveat: a container tag also has underlying `sha256:…` manifest entries. `^sha-` doesn't match +`sha256:…`, so after the first cleanup run, check the package list — if orphaned `sha256:` digests +visibly accumulate, revisit it (carefully; don't delete a digest a kept tag still references). diff --git a/dev/ci/build.sh b/dev/ci/build.sh new file mode 100755 index 0000000..0562cdb --- /dev/null +++ b/dev/ci/build.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Build and push the three custom images to the registry. Runs on the CI runner. +# Requires a buildx builder that supports registry cache export (docker-container driver); +# the workflow sets one up. Uses registry-backed layer cache so unchanged images (notably +# the concordancer, whose build downloads a large lexicon from clarin.si) are near-instant. +# +# Required environment: +# REGISTRY image name prefix, e.g. gitea.example.tld/luka +# TAG tag to build, e.g. sha-abc1234 +set -euo pipefail +: "${REGISTRY:?}" "${TAG:?}" + +# service | context | dockerfile +builds=( + "termportal-express|express|express/Dockerfile.prod" + "termportal-opensearch|opensearch|opensearch/Dockerfile" + "termportal-concordancer|concordancer|concordancer/Dockerfile.prod" +) + +for spec in "${builds[@]}"; do + IFS='|' read -r name context dockerfile <<<"$spec" + ref="$REGISTRY/$name" + echo "+ build $ref:$TAG (context=$context, dockerfile=$dockerfile)" >&2 + docker buildx build \ + --file "$dockerfile" \ + --tag "$ref:$TAG" \ + --cache-from "type=registry,ref=$ref:buildcache" \ + --cache-to "type=registry,ref=$ref:buildcache,mode=max" \ + --push \ + "$context" +done diff --git a/dev/ci/ci-deploy-wrapper.sh b/dev/ci/ci-deploy-wrapper.sh new file mode 100755 index 0000000..5e01242 --- /dev/null +++ b/dev/ci/ci-deploy-wrapper.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Forced-command deploy wrapper — the ONLY thing the CI deploy key is allowed to run on a +# target host. Install it OUTSIDE the git checkout (so `git checkout` here can never rewrite +# the running script) and pin it as the forced command for the CI key in authorized_keys: +# +# from="",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA... gitea-ci-deploy +# +# With that line, the CI runner can only ever trigger a deploy of a validated image tag on +# THIS host — never an arbitrary shell command, port-forward, or PTY. The tag the runner asks +# for arrives as $SSH_ORIGINAL_COMMAND (ignored as a command, read here as data). +# +# Also runnable by hand for break-glass deploys / rollbacks: ./ci-deploy-wrapper.sh v1.2.3 +set -euo pipefail + +# Host-specific config lives next to the installed wrapper, so this script stays byte-identical +# across hosts. Create it once, e.g.: echo 'DEPLOY_DIR=/opt/termportal-prod' > ci-deploy.conf +conf="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/ci-deploy.conf" +# shellcheck source=/dev/null +[[ -f "$conf" ]] && source "$conf" +: "${DEPLOY_DIR:?set DEPLOY_DIR in ci-deploy.conf next to the wrapper}" + +# Tag from the argument (manual use) or the forced-command's SSH_ORIGINAL_COMMAND (CI use). +tag="${1:-${SSH_ORIGINAL_COMMAND:-}}" + +# Strict allow-list, matched against the WHOLE value (no tokenizing) so multi-token or +# metacharacter input fails closed and loud. Registry tags are [A-Za-z0-9._-]; the leading-char +# anchor also blocks option injection (a tag can't start with '-'). This stops a compromised +# Gitea/workflow from smuggling anything but a bare tag through SSH_ORIGINAL_COMMAND. +if [[ ! "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "ci-deploy-wrapper: refusing invalid tag: '${tag}'" >&2 + exit 2 +fi + +ref="${tag#sha-}" # sha-abc1234 -> abc1234 ; v1.2.3 stays v1.2.3 + +echo "+ deploy tag=${tag} ref=${ref} dir=${DEPLOY_DIR}" >&2 +cd "$DEPLOY_DIR" +git fetch --tags --prune origin +git checkout --force "$ref" +export IMAGE_TAG="$tag" # picked up by docker compose via run-prod.sh +echo "$tag" >.deployed_tag # small audit trail of what is running +./run-prod.sh pull +./run-prod.sh up -d +docker image prune -f diff --git a/dev/ci/deploy.sh b/dev/ci/deploy.sh new file mode 100755 index 0000000..681e6ca --- /dev/null +++ b/dev/ci/deploy.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Runner-side deploy trigger used by the Gitea Actions workflows in .gitea/workflows/. +# +# The target host's CI deploy key is pinned to a forced command (dev/ci/ci-deploy-wrapper.sh, +# installed on the host — see dev/ci/README.md). So the ONLY thing we send over SSH is the +# image tag: it arrives on the host as $SSH_ORIGINAL_COMMAND, the wrapper validates it and runs +# the deploy. The runner can never execute an arbitrary command on the target, and the host — +# not this script — owns its checkout path (DEPLOY_DIR in the host's ci-deploy.conf). +# +# Required environment: +# DEPLOY_HOST target hostname / IP +# DEPLOY_USER SSH user on the target (e.g. the dedicated `deploy` user) +# DEPLOY_SSH_KEY private SSH key contents (the CI deploy key) +# IMAGE_TAG image tag to deploy, e.g. v1.2.3 or sha-abc1234 +# Optional environment: +# DEPLOY_SSH_PORT SSH port on the target, if not the default 22 +set -euo pipefail +: "${DEPLOY_HOST:?}" "${DEPLOY_USER:?}" "${DEPLOY_SSH_KEY:?}" "${IMAGE_TAG:?}" +DEPLOY_SSH_PORT="${DEPLOY_SSH_PORT:-22}" + +key_file="$(mktemp)" +trap 'rm -f "$key_file"' EXIT +printf '%s\n' "$DEPLOY_SSH_KEY" >"$key_file" +chmod 600 "$key_file" + +echo "+ deploy ${DEPLOY_USER}@${DEPLOY_HOST}:${DEPLOY_SSH_PORT} tag=${IMAGE_TAG}" >&2 + +# StrictHostKeyChecking=accept-new trusts the host key on first connection and pins it after. +# The "command" we pass is delivered to the host's forced-command wrapper as +# $SSH_ORIGINAL_COMMAND — it is a tag, not a shell command. +exec ssh -i "$key_file" -p "$DEPLOY_SSH_PORT" -o StrictHostKeyChecking=accept-new -o BatchMode=yes \ + "${DEPLOY_USER}@${DEPLOY_HOST}" "$IMAGE_TAG" diff --git a/dev/ci/promote.sh b/dev/ci/promote.sh new file mode 100755 index 0000000..8fe5380 --- /dev/null +++ b/dev/ci/promote.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Promote an already-built set of images to a new tag WITHOUT rebuilding, by copying the +# registry manifest. Guarantees production runs the exact bytes staging tested. Runs on the +# CI runner. Fails clearly if the source tag does not exist (e.g. the commit was never built +# on the default branch before being tagged). +# +# Required environment: +# REGISTRY image name prefix, e.g. gitea.example.tld/luka +# SRC_TAG existing tag to promote from, e.g. sha-abc1234 +# DST_TAG new tag to create, e.g. v1.2.3 +set -euo pipefail +: "${REGISTRY:?}" "${SRC_TAG:?}" "${DST_TAG:?}" + +for name in termportal-express termportal-opensearch termportal-concordancer; do + ref="$REGISTRY/$name" + echo "+ promote $ref:$SRC_TAG -> :$DST_TAG" >&2 + docker buildx imagetools create --tag "$ref:$DST_TAG" "$ref:$SRC_TAG" +done diff --git a/dev/util-tools/compose-config-diff.sh b/dev/util-tools/compose-config-diff.sh new file mode 100755 index 0000000..a4305ae --- /dev/null +++ b/dev/util-tools/compose-config-diff.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Compares the fully resolved config of an old, full docker-compose file against a new +# base compose file + override compose file, to confirm a migration from "one full compose +# file per environment" to "one shared base + small per-environment override files" +# (see: https://github.com/compose-spec/compose-spec/blob/master/13-merge.md) produced an +# identical stack. Generic - not tied to this project; copy it wherever you're doing the +# same kind of migration, or keep one copy and point to it from any project's directory. +# +# Usage: compose-config-diff.sh [OLD_FILE] [NEW_FILE] [OVERRIDE_FILE] +# OLD_FILE defaults to docker-compose.prod.old.yml +# NEW_FILE defaults to docker-compose.prod.yml +# OVERRIDE_FILE defaults to docker-compose.prod.override.yml (optional - if missing, +# NEW_FILE is compared on its own, with a warning) +# +# Run from the directory containing these files (and .env, if the project uses one - +# docker compose picks it up from the current directory as usual, same as any other +# `docker compose` invocation there). +# +# Writes nothing to disk - both configs are held in memory and diffed via process +# substitution. +set -uo pipefail + +OLD="${1:-docker-compose.prod.old.yml}" +NEW="${2:-docker-compose.prod.yml}" +OVERRIDE="${3:-docker-compose.prod.override.yml}" + +if [[ ! -f "$OLD" ]]; then + echo "Missing $OLD - run this from the directory containing it, or pass its path as \$1." >&2 + exit 2 +fi +if [[ ! -f "$NEW" ]]; then + echo "Missing $NEW - run this from the directory containing it, or pass its path as \$2." >&2 + exit 2 +fi + +new_files=(-f "$NEW") +new_desc="$NEW" +if [[ -f "$OVERRIDE" ]]; then + new_files+=(-f "$OVERRIDE") + new_desc="$NEW + $OVERRIDE" +else + echo "Note: $OVERRIDE not found - comparing against $NEW on its own." >&2 +fi + +old_config="$(docker compose -f "$OLD" config)" +old_status=$? +new_config="$(docker compose "${new_files[@]}" config)" +new_status=$? + +if [[ $old_status -ne 0 || $new_status -ne 0 ]]; then + echo "FAILED: docker compose config errored (see messages above) - cannot compare." >&2 + exit 2 +fi + +if diff -u <(printf '%s\n' "$old_config") <(printf '%s\n' "$new_config"); then + echo "OK: resolved config is identical between $OLD and $new_desc." + exit 0 +else + echo "MISMATCH: resolved config differs (diff above) between $OLD and $new_desc." >&2 + exit 1 +fi diff --git a/docker-compose.prod.override.example.yml b/docker-compose.prod.override.example.yml new file mode 100644 index 0000000..9a1132c --- /dev/null +++ b/docker-compose.prod.override.example.yml @@ -0,0 +1,46 @@ +# Template for docker-compose.prod.override.yml, the host-specific patch layered on top of +# docker-compose.prod.yml via ./run-prod.sh (or `docker compose -f docker-compose.prod.yml +# -f docker-compose.prod.override.yml ...`). +# +# Copy this file to docker-compose.prod.override.yml next to docker-compose.prod.yml on the +# target host and keep only the services/keys that actually need to differ from the base. +# docker-compose.prod.override.yml is gitignored on purpose: it holds host-specific choices +# (storage layout, resource limits), not something the repo should carry or `git pull` should +# ever touch. +# +# Compose merge rules used below (see https://github.com/compose-spec/compose-spec/blob/master/13-merge.md): +# - environment (map syntax) merges key by key: only list the keys you're changing. +# - volumes merges by target path: only list the mount(s) you're changing, others are untouched. +# - !reset fully removes an attribute the base sets, instead of merging into it. +# - !override fully replaces an attribute instead of merging into it (e.g. to drop specific +# environment keys the base defines, since map-merge can only add/change keys, not remove them). + +services: + # Example: swap a named volume for a bind mount, only for the one mount that needs to change. + # express: + # volumes: + # - /data/term_portal/express_data:/usr/src/app/data_files + + # Example: override a single environment key, leaving the rest of the base's map untouched. + # opensearch: + # environment: + # OPENSEARCH_JAVA_OPTS: "-Xms2048m -Xmx2048m" + + # Example: this host can't grant memlock/nofile ulimits (e.g. a constrained VPS) - drop the + # attribute entirely rather than trying to merge different values into it. + # opensearch: + # ulimits: !reset null + + # Example: drop specific keys from a map the base defines, by replacing the whole map instead + # of merging into it (plain map-merge can only add/override keys, never remove them). + # opensearch: + # environment: !override + # cluster.name: term-portal + # node.name: node-1 + # DISABLE_INSTALL_DEMO_CONFIG: "true" + # DISABLE_SECURITY_PLUGIN: "true" + # discovery.type: single-node + +# Example: if every named volume the base declares has been replaced by bind mounts above, +# drop the now-unused top-level declarations explicitly rather than leaving them dangling. +# volumes: !reset null diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index b6b9d5a..0435377 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -1,7 +1,9 @@ -version: "3.4" - services: express: + # In CI this image is built and pushed to the registry; on a CI-managed host it is pulled. + # `build:` is kept so a plain `up --build` (the generic self-host path, no registry) still + # works: REGISTRY/IMAGE_TAG default to a local name and the image is built and tagged locally. + image: "${REGISTRY:-termportal-local}/termportal-express:${IMAGE_TAG:-local}" build: context: express dockerfile: Dockerfile.prod @@ -31,6 +33,14 @@ services: PORTAL_ADMIN_INITIAL_EMAIL: "${PORTAL_ADMIN_INITIAL_EMAIL:?}" PORTAL_ADMIN_INITIAL_PASSWORD: "${PORTAL_ADMIN_INITIAL_PASSWORD:?}" EXTRACTION_API_ORIGIN: "${EXTRACTION_API_ORIGIN:?}" + # OIDC/SSO (University of Ljubljana, backed by Microsoft Entra ID). Real per-environment + # app-registration values - see "Production only settings" in .env. No internal/external + # origin split in prod (the University of Ljubljana's discovery document is a single + # publicly-reachable URL), so OIDC_UNI_LJ_AUTHORIZATION_EXTERNAL_ORIGIN is intentionally + # left unset here. + OIDC_UNI_LJ_CLIENT_ID: "${OIDC_UNI_LJ_CLIENT_ID:?}" + OIDC_UNI_LJ_CLIENT_SECRET: "${OIDC_UNI_LJ_CLIENT_SECRET:?}" + OIDC_UNI_LJ_DISCOVERY_URL: "${OIDC_UNI_LJ_DISCOVERY_URL:?}" volumes: - express-data:/usr/src/app/data_files ports: @@ -60,16 +70,17 @@ services: command: redis-server /usr/local/etc/redis/redis.conf opensearch: + image: "${REGISTRY:-termportal-local}/termportal-opensearch:${IMAGE_TAG:-local}" build: opensearch restart: always environment: - - cluster.name=term-portal - - node.name=node-1 - - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping - - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM - - "DISABLE_INSTALL_DEMO_CONFIG=true" # disables execution of install_demo_configuration.sh bundled with security plugin, which installs demo certificates and security configurations to OpenSearch - - "DISABLE_SECURITY_PLUGIN=true" # disables security plugin entirely in OpenSearch by setting plugins.security.disabled: true in opensearch.yml - - "discovery.type=single-node" # disables bootstrap checks that are enabled when network.host is set to a non-loopback address + cluster.name: term-portal + node.name: node-1 + bootstrap.memory_lock: "true" # along with the memlock settings below, disables swapping + OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM + DISABLE_INSTALL_DEMO_CONFIG: "true" # disables execution of install_demo_configuration.sh bundled with security plugin, which installs demo certificates and security configurations to OpenSearch + DISABLE_SECURITY_PLUGIN: "true" # disables security plugin entirely in OpenSearch by setting plugins.security.disabled: true in opensearch.yml + discovery.type: single-node # disables bootstrap checks that are enabled when network.host is set to a non-loopback address ulimits: memlock: soft: -1 @@ -95,7 +106,7 @@ services: - "127.0.0.1:${OS_DASHBOARDS_LISTEN_PORT:?}:5601" concordancer: - # image: ghcr.io/clarinsi/rsdo-concordancer-api-term-portal:v1.0.4 + image: "${REGISTRY:-termportal-local}/termportal-concordancer:${IMAGE_TAG:-local}" build: context: concordancer dockerfile: Dockerfile.prod @@ -115,7 +126,7 @@ services: # Disabled by default. Enable if needed. concordancer-manager: - image: ghcr.io/clarinsi/rsdo-concordancer-systemmanager:v1.0.4 + image: gitea.cjvt.si/rrejc/rsdo-concordancer-systemmanager:v1.1.1 profiles: - concordancer-manager depends_on: @@ -129,9 +140,8 @@ services: - sloleks:/sloleks cron: - build: - context: express - dockerfile: Dockerfile.prod + # Reuses the express image (same source); only the entrypoint/command differ below. + image: "${REGISTRY:-termportal-local}/termportal-express:${IMAGE_TAG:-local}" init: true depends_on: - postgres diff --git a/docker-compose.yml b/docker-compose.yml index ea6aec0..628ab01 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,3 @@ -version: "3.4" - services: express: build: express @@ -30,6 +28,16 @@ services: PORTAL_ADMIN_INITIAL_EMAIL: "${PORTAL_ADMIN_INITIAL_EMAIL:?}" PORTAL_ADMIN_INITIAL_PASSWORD: "${PORTAL_ADMIN_INITIAL_PASSWORD:?}" EXTRACTION_API_ORIGIN: "${EXTRACTION_API_ORIGIN:?}" + # OIDC/SSO (University of Ljubljana stand-in). Values point express at the throwaway dev + # Authentik instance (started separately via `--profile develop-idp`) using the SAME + # underlying AUTHENTIK_OIDC_CLIENT_ID/_SECRET already baked into its blueprint - see + # dev/authentik/README.md. If that profile isn't running, SSO login simply fails + # gracefully when clicked (see express/middleware/auth.js) - it does not affect the rest + # of the app or block startup. + OIDC_UNI_LJ_CLIENT_ID: "${AUTHENTIK_OIDC_CLIENT_ID:?}" + OIDC_UNI_LJ_CLIENT_SECRET: "${AUTHENTIK_OIDC_CLIENT_SECRET:?}" + OIDC_UNI_LJ_DISCOVERY_URL: "http://authentik-server:9000/application/o/uni-lj-test/.well-known/openid-configuration" + OIDC_UNI_LJ_AUTHORIZATION_EXTERNAL_ORIGIN: "http://localhost:${AUTHENTIK_LISTEN_PORT:?}" volumes: # When developing/debugging concordancer, disable express bind mount and node_modules volume and enable express-data. # - express-data:/usr/src/app/data_files @@ -71,13 +79,13 @@ services: opensearch: build: opensearch environment: - - cluster.name=term-portal - - node.name=node-1 - # - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping - # - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM - - "DISABLE_INSTALL_DEMO_CONFIG=true" # disables execution of install_demo_configuration.sh bundled with security plugin, which installs demo certificates and security configurations to OpenSearch - - "DISABLE_SECURITY_PLUGIN=true" # disables security plugin entirely in OpenSearch by setting plugins.security.disabled: true in opensearch.yml - - "discovery.type=single-node" # disables bootstrap checks that are enabled when network.host is set to a non-loopback address + cluster.name: term-portal + node.name: node-1 + # bootstrap.memory_lock: "true" # along with the memlock settings below, disables swapping + # OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM + DISABLE_INSTALL_DEMO_CONFIG: "true" # disables execution of install_demo_configuration.sh bundled with security plugin, which installs demo certificates and security configurations to OpenSearch + DISABLE_SECURITY_PLUGIN: "true" # disables security plugin entirely in OpenSearch by setting plugins.security.disabled: true in opensearch.yml + discovery.type: single-node # disables bootstrap checks that are enabled when network.host is set to a non-loopback address # ulimits: # memlock: # soft: -1 @@ -102,7 +110,7 @@ services: - "127.0.0.1:${OS_DASHBOARDS_LISTEN_PORT:?}:5601" concordancer: - # image: ghcr.io/clarinsi/rsdo-concordancer-api:v1.0.4 + # image: gitea.cjvt.si/rrejc/rsdo-concordancer-api:v1.1.1 build: concordancer profiles: - develop-concordancer @@ -121,7 +129,7 @@ services: - sloleks:/sloleks concordancer-manager: - image: ghcr.io/clarinsi/rsdo-concordancer-systemmanager:v1.0.4 + image: gitea.cjvt.si/rrejc/rsdo-concordancer-systemmanager:v1.1.1 profiles: - develop-concordancer depends_on: @@ -175,6 +183,90 @@ services: ports: - "127.0.0.1:${MAILDEV_WEB_GUI_PORT:?}:1080" + # Disabled by default. Enable with `--profile develop-idp` for local SSO/OIDC login testing + # against a throwaway Authentik instance. It stands in for the single real University of + # Ljubljana OIDC federation this portal will integrate with (the `auth_provider` enum's + # 'uni_lj' value) - it is NOT itself a production identity provider. See + # dev/authentik/README.md. + # + # As of authentik 2025.10+, Redis is no longer required (caching/tasks moved to Postgres), so + # this only needs its own dedicated Postgres, kept fully separate from the portal's own DB. + authentik-postgres: + image: postgres:16.14-alpine3.24 + profiles: + - develop-idp + environment: + POSTGRES_DB: authentik + POSTGRES_USER: authentik + POSTGRES_PASSWORD: "${AUTHENTIK_POSTGRES_PASSWORD:?}" + volumes: + - authentik-postgres-data:/var/lib/postgresql/data + # Needed so authentik-server/authentik-worker's `depends_on: condition: service_healthy` + # actually waits for Postgres to accept connections, not just for the container to start. + healthcheck: + test: ["CMD-SHELL", "pg_isready -d authentik -U authentik"] + interval: 30s + timeout: 5s + retries: 5 + start_period: 20s + + authentik-server: + image: ghcr.io/goauthentik/server:2026.8.0 + command: server + profiles: + - develop-idp + depends_on: + authentik-postgres: + condition: service_healthy + environment: + AUTHENTIK_SECRET_KEY: "${AUTHENTIK_SECRET_KEY:?}" + AUTHENTIK_POSTGRESQL__HOST: authentik-postgres + AUTHENTIK_POSTGRESQL__NAME: authentik + AUTHENTIK_POSTGRESQL__USER: authentik + AUTHENTIK_POSTGRESQL__PASSWORD: "${AUTHENTIK_POSTGRES_PASSWORD:?}" + # Non-interactively creates/updates the built-in "akadmin" superuser on first startup. + AUTHENTIK_BOOTSTRAP_EMAIL: "${AUTHENTIK_BOOTSTRAP_EMAIL:?}" + AUTHENTIK_BOOTSTRAP_PASSWORD: "${AUTHENTIK_BOOTSTRAP_PASSWORD:?}" + AUTHENTIK_BOOTSTRAP_TOKEN: "${AUTHENTIK_BOOTSTRAP_TOKEN:?}" + # Read by the custom blueprint below (via !Env) to build the test app's redirect URI as + # http://localhost:/users/oidc/callback, matching the express service's own port. + IDP_REDIRECT_PORT: "${EXPRESS_LISTEN_PORT:?}" + # Fixed, non-secret dev-only OIDC client credentials for the single seeded test application. + AUTHENTIK_OIDC_CLIENT_ID: "${AUTHENTIK_OIDC_CLIENT_ID:?}" + AUTHENTIK_OIDC_CLIENT_SECRET: "${AUTHENTIK_OIDC_CLIENT_SECRET:?}" + volumes: + - authentik-data:/data + - ./dev/authentik/blueprints:/blueprints/custom + ports: + - "127.0.0.1:${AUTHENTIK_LISTEN_PORT:?}:9000" + # Recommended by upstream authentik to avoid a shared-memory-related crash in some subsystems. + shm_size: 512mb + + authentik-worker: + image: ghcr.io/goauthentik/server:2026.8.0 + command: worker + profiles: + - develop-idp + depends_on: + authentik-postgres: + condition: service_healthy + environment: + AUTHENTIK_SECRET_KEY: "${AUTHENTIK_SECRET_KEY:?}" + AUTHENTIK_POSTGRESQL__HOST: authentik-postgres + AUTHENTIK_POSTGRESQL__NAME: authentik + AUTHENTIK_POSTGRESQL__USER: authentik + AUTHENTIK_POSTGRESQL__PASSWORD: "${AUTHENTIK_POSTGRES_PASSWORD:?}" + AUTHENTIK_BOOTSTRAP_EMAIL: "${AUTHENTIK_BOOTSTRAP_EMAIL:?}" + AUTHENTIK_BOOTSTRAP_PASSWORD: "${AUTHENTIK_BOOTSTRAP_PASSWORD:?}" + AUTHENTIK_BOOTSTRAP_TOKEN: "${AUTHENTIK_BOOTSTRAP_TOKEN:?}" + IDP_REDIRECT_PORT: "${EXPRESS_LISTEN_PORT:?}" + AUTHENTIK_OIDC_CLIENT_ID: "${AUTHENTIK_OIDC_CLIENT_ID:?}" + AUTHENTIK_OIDC_CLIENT_SECRET: "${AUTHENTIK_OIDC_CLIENT_SECRET:?}" + volumes: + - authentik-data:/data + - ./dev/authentik/blueprints:/blueprints/custom + shm_size: 512mb + volumes: express-data: postgres-data: @@ -182,3 +274,5 @@ volumes: opensearch-data: maildev-data: sloleks: + authentik-postgres-data: + authentik-data: diff --git a/express/.dockerignore b/express/.dockerignore new file mode 100644 index 0000000..49980c9 --- /dev/null +++ b/express/.dockerignore @@ -0,0 +1,8 @@ +node_modules +npm-debug.log +.env +.env.* +Dockerfile* +.dockerignore +public/locales/dev +data_files diff --git a/express/Dockerfile b/express/Dockerfile index 51f2ec0..5de8ab6 100644 --- a/express/Dockerfile +++ b/express/Dockerfile @@ -1,16 +1,18 @@ # syntax=docker/dockerfile:1 # Use the non-alpine base image for easier container debugging. -# FROM node:14 -FROM node:16-alpine +# FROM node:24.18.0-bookworm +FROM node:24.18.0-alpine3.24 # Curl is used in cron batch file. RUN apk --no-cache add curl +# TODO: consider running as a non-root USER (both here and in Dockerfile.prod). + WORKDIR /usr/src/app -COPY package*.json . -RUN npm install +COPY package*.json ./ +RUN npm ci COPY . . @@ -20,6 +22,7 @@ RUN which crond && \ chmod 0744 scheduled/entrypoint.sh EXPOSE 3000 +EXPOSE 9229 # Use devstart-wait if you need code execution to pause until a debugger is attached. # CMD ["npm", "run", "devstart-wait"] diff --git a/express/Dockerfile.prod b/express/Dockerfile.prod index be851b5..b512d14 100644 --- a/express/Dockerfile.prod +++ b/express/Dockerfile.prod @@ -1,16 +1,30 @@ # syntax=docker/dockerfile:1 -FROM node:16-alpine +# ---- Compile SCSS to CSS (public/stylesheets is gitignored, not built by npm ci) ---- +FROM node:24.18.0-alpine3.24 AS assets + +WORKDIR /usr/src/app +COPY package*.json ./ +RUN npm ci --silent +COPY public/sass ./public/sass +RUN npm run sass:build:prod + +# ---- Production image ---- +FROM node:24.18.0-alpine3.24 # Curl is used in cron batch file. RUN apk --no-cache add curl +# TODO: consider running as a non-root USER (both here and in the dev Dockerfile). + WORKDIR /usr/src/app COPY package*.json ./ -RUN npm install --production --silent +RUN npm ci --omit=dev --silent COPY . . +RUN rm -rf public/sass +COPY --from=assets /usr/src/app/public/stylesheets ./public/stylesheets COPY scheduled/crontab /var/spool/cron/crontabs/root RUN which crond && \ diff --git a/express/app.js b/express/app.js index 5be8a26..9600bb0 100644 --- a/express/app.js +++ b/express/app.js @@ -26,6 +26,7 @@ const { capitalize } = require('./utils') const apiRouter = require('./routes/api') const adminRouter = require('./routes/admin') const dictionariesRouter = require('./routes/dictionaries') +const viewResourcesRouter = require('./routes/view-resources') const extractionRouter = require('./routes/extraction') const consultancyRouter = require('./routes/consultancy') const indexRouter = require('./routes/index') @@ -88,6 +89,7 @@ if (inDevEnv) { app.use('/api', apiRouter) app.use('/admin', adminRouter) app.use('/slovarji', dictionariesRouter) +app.use('/ogled-virov', viewResourcesRouter) app.use('/luscenje', extractionRouter) app.use('/svetovanje', consultancyRouter) app.use('/', indexRouter) diff --git a/express/config/helmet.js b/express/config/helmet.js index 85ac516..e6d6f35 100644 --- a/express/config/helmet.js +++ b/express/config/helmet.js @@ -13,7 +13,7 @@ module.exports = { 'https:', "'unsafe-inline'" ], - connectSrc: ["'self'"], + connectSrc: ["'self'", 'https://cdn.jsdelivr.net'], styleSrc: ["'self'", 'https:', "'unsafe-inline'"], fontSrc: ["'self'", 'https:'], imgSrc: ["'self'", 'data:'], diff --git a/express/config/keys.js b/express/config/keys.js index c294cf2..3dd9b28 100644 --- a/express/config/keys.js +++ b/express/config/keys.js @@ -13,5 +13,20 @@ module.exports = { origin: process.env.ORIGIN, portalAdminInitialEmail: process.env.PORTAL_ADMIN_INITIAL_EMAIL, portalAdminInitialPassword: process.env.PORTAL_ADMIN_INITIAL_PASSWORD, - extractionApiOrigin: process.env.EXTRACTION_API_ORIGIN + extractionApiOrigin: process.env.EXTRACTION_API_ORIGIN, + oidcUniLjClientId: process.env.OIDC_UNI_LJ_CLIENT_ID, + oidcUniLjClientSecret: process.env.OIDC_UNI_LJ_CLIENT_SECRET, + // Server-to-server discovery URL (internal `authentik-server:9000` host in dev; the one real + // public University of Ljubljana discovery URL in staging/prod - there is no internal/external + // split there). + oidcUniLjDiscoveryUrl: process.env.OIDC_UNI_LJ_DISCOVERY_URL, + // Optional. When set, overrides the *origin* (scheme+host+port) of the authorization_endpoint + // used to build the browser-facing redirect, without touching the endpoint discovered/used for + // server-to-server calls (token/JWKS/userinfo). Needed only in dev, where the browser can reach + // Authentik solely via `localhost:9000` while the express container can reach it only via the + // compose-internal `authentik-server:9000` hostname. Left unset (no-op) in staging/prod, where + // the University of Ljubljana's discovery document is presumed to be a single publicly-reachable + // URL. + oidcUniLjAuthorizationExternalOrigin: + process.env.OIDC_UNI_LJ_AUTHORIZATION_EXTERNAL_ORIGIN || null } diff --git a/express/config/university-domains.js b/express/config/university-domains.js new file mode 100644 index 0000000..4a480e0 --- /dev/null +++ b/express/config/university-domains.js @@ -0,0 +1,32 @@ +// Maps University of Ljubljana faculty/unit email domains to their standard abbreviation, for +// display purposes (e.g. suggesting an SSO username). Source: ul_domene_in_kratice.tsv (one-off +// reference list, not kept in the repo). +module.exports = { + 'uni-lj.si': 'UL', + 'ag.uni-lj.si': 'UL AG', + 'agrft.uni-lj.si': 'UL AGRFT', + 'aluo.uni-lj.si': 'UL ALUO', + 'bf.uni-lj.si': 'UL BF', + 'ef.uni-lj.si': 'UL EF', + 'fa.uni-lj.si': 'UL FA', + 'fdv.uni-lj.si': 'UL FDV', + 'fe.uni-lj.si': 'UL FE', + 'ffa.uni-lj.si': 'UL FFA', + 'fgg.uni-lj.si': 'UL FGG', + 'fkkt.uni-lj.si': 'UL FKKT', + 'fmf.uni-lj.si': 'UL FMF', + 'fpp.uni-lj.si': 'UL FPP', + 'fri.uni-lj.si': 'UL FRI', + 'fsd.uni-lj.si': 'UL FSD', + 'fs.uni-lj.si': 'UL FS', + 'fsp.uni-lj.si': 'UL FSP', + 'fu.uni-lj.si': 'UL FU', + 'ff.uni-lj.si': 'UL FF', + 'mf.uni-lj.si': 'UL MF', + 'ntf.uni-lj.si': 'UL NTF', + 'pef.uni-lj.si': 'UL PEF', + 'pf.uni-lj.si': 'UL PF', + 'teof.uni-lj.si': 'UL TEOF', + 'vf.uni-lj.si': 'UL VF', + 'zf.uni-lj.si': 'UL ZF' +} diff --git a/express/controllers/api/v1/consultancy.js b/express/controllers/api/v1/consultancy.js index 5fefd4a..5b7a8f0 100644 --- a/express/controllers/api/v1/consultancy.js +++ b/express/controllers/api/v1/consultancy.js @@ -499,15 +499,6 @@ async function consultancyRequestItems( } } - if (entry.timeCreated) { - // TODO i18n date format - const date = new Date(entry.timeCreated) - - entry.formattedTimeCreated = `${date.getDate()}. ${ - date.getMonth() + 1 - }. ${date.getFullYear()}` - } - return entry }) diff --git a/express/controllers/api/v1/dictionaries.js b/express/controllers/api/v1/dictionaries.js index 1192e62..4d9e182 100644 --- a/express/controllers/api/v1/dictionaries.js +++ b/express/controllers/api/v1/dictionaries.js @@ -1,8 +1,11 @@ const { rm } = require('fs/promises') +const { promisify } = require('util') const user = require('../../../middleware/user') const Dictionary = require('../../../models/dictionary') +const User = require('../../../models/user') const Entry = require('../../../models/entry') const Extraction = require('../../../models/extraction') +const email = require('../../../models/email') const { searchEntryIndex, deleteEntryFromIndex, @@ -11,11 +14,28 @@ const { const genEditorAllQuery = require('../../../models/helpers/search/generate-query/editor/all') const { prepareEditorEntries } = require('../../../models/helpers/search') const { DEFAULT_HITS_PER_PAGE } = require('../../../config/settings') -const { minEntriesRequirementCheckAndAct } = require('../../helpers/dictionary') +const { + minEntriesRequirementCheckAndAct, + resolveDictionarySort, + parseDictionaryListFilters +} = require('../../helpers/dictionary') const { getExportFilesPath } = require('../../../models/helpers/dictionary') const dictionary = {} +dictionary.checkNameCollision = async (req, res) => { + const { nameSl, nameSlShort, nameEn, excludeDictionaryId } = req.query + + const collision = await Dictionary.checkNameCollision({ + nameSl: nameSl || null, + nameSlShort: nameSlShort || null, + nameEn: nameEn || null, + excludeDictionaryId: excludeDictionaryId || null + }) + + res.send({ collision }) +} + dictionary.getEntry = async (req, res) => { const entryId = req.query.id const [entry, domainLabels] = await Promise.all([ @@ -133,6 +153,16 @@ dictionary.delete = async (req, res) => { res.end() } +dictionary.deleteExport = async (req, res) => { + const dictionaryId = +req.params.dictionaryId + const exportId = +req.params.exportId + await Dictionary.deleteExport(dictionaryId, exportId) + const exportFilePath = `${getExportFilesPath(dictionaryId)}/${exportId}` + await rm(exportFilePath, { force: true }) + + res.end() +} + dictionary.updateDomainLabels = [ (req, res, next) => { req.dictionaryId = req.body.params.dictionaryId @@ -166,17 +196,65 @@ dictionary.listDictionaries = async (req, res) => { const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE const page = +req.query.p > 0 ? +req.query.p : 1 + const { sortBy, sortDir } = resolveDictionarySort( + req.query.sort, + req.query.dir + ) + const filters = parseDictionaryListFilters(req.query) const { pages_total: numberOfAllPages, results } = await Dictionary.fetchAllAdminDictionaries( req.determinedLanguage, resultsPerPage, - page + page, + sortBy, + sortDir, + filters ) res.send({ page, numberOfAllPages, results }) } +dictionary.contactDictionaryAuthors = async (req, res) => { + const { dictionaryId } = req.params + const { message } = req.body + + const [name, recipients] = await Promise.all([ + Dictionary.fetchName(dictionaryId, req.determinedLanguage), + User.fetchAllWithDictionaryRights(dictionaryId) + ]) + + const renderAsync = promisify(req.app.render.bind(req.app)) + const senderName = `${req.user.firstName} ${req.user.lastName}` + const emailSubject = req.t('Sporočilo o slovarju "{{name}}"', { name }) + + await Promise.all( + recipients.map(async recipient => { + const emailHtml = await renderAsync( + `email/dictionary-contact-authors_${recipient.language}`, + { + senderName, + senderEmail: req.user.email, + dictionaryName: name, + message + } + ) + await email.send({ + to: recipient.email, + subject: emailSubject, + html: emailHtml, + replyTo: req.user.email + }) + }) + ) + // eslint-disable-next-line no-console + console.log( + `Sent email to ${recipients.map(r => r.email)} (subject: ${emailSubject})` + ) + + res.status(201).send() +} + dictionary.listDomainLabels = async (req, res) => { const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE const { dictionaryId } = req.params @@ -312,7 +390,10 @@ dictionary.exportBegin = async (req, res) => { req.body.isLanguageReviewedFilter === 'on' ? undefined : req.body.isLanguageReviewedFilter, - exportFileFormat: req.body.exportFileFormat + exportFileFormat: req.body.exportFileFormat, + timeZone: Intl.supportedValuesOf('timeZone').includes(req.body.timeZone) + ? req.body.timeZone + : 'UTC' } const exportId = await Dictionary.beginExport(dictionaryId, exportParams) diff --git a/express/controllers/api/v1/users.js b/express/controllers/api/v1/users.js index 2f7b638..de170c8 100644 --- a/express/controllers/api/v1/users.js +++ b/express/controllers/api/v1/users.js @@ -34,6 +34,17 @@ users.updateHitsPerPage = async (req, res) => { } users.updateBasicData = async (req, res) => { + if (req.user.isSso) { + const err = Error( + req.t( + 'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani, zato osebnih podatkov ni mogoče spreminjati na portalu.' + ) + ) + err.status = 403 + err.displayInProd = true + throw err + } + const { firstName, lastName, email: newEmail } = req.body // TODO Validation (valid email format, ...). @@ -121,6 +132,12 @@ users.updatePassword = async (req, res) => { } users.deleteCurrent = [ + // TODO This permanently anonymizes/closes the account with no re-authentication step - the + // client-side confirmation modal (public/javascripts/profile-scripts.js) is the only gate, and + // it's identical for local and SSO accounts (no password re-entry, no IdP reauth). Anyone with + // an active/hijacked session (e.g. an unattended logged-in browser) can delete the account + // outright. Consider requiring password re-entry for local accounts, and an equivalent reauth + // step for SSO accounts, before calling closeAccount. async (req, res, next) => { await User.closeAccount(req.user.id) next() diff --git a/express/controllers/consultancy.js b/express/controllers/consultancy.js index 9b02b77..d755e62 100644 --- a/express/controllers/consultancy.js +++ b/express/controllers/consultancy.js @@ -181,11 +181,19 @@ consultancyAdmin.statistics = async (req, res) => { res.render('pages/consultancy/admin/statistics') } +// Maps a consultancy entry's status to the sidebar item it should highlight +// and the URL slug that list page lives at (used as a fallback "back" link +// target when the page wasn't reached via that list page's own link). +const STATUS_META = { + new: { new: true, slug: 'novo' }, + rejected: { rejected: true, slug: 'zavrnjeno' }, + 'in progress': { inProgress: true, slug: 'v-delu' }, + review: { prepared: true, slug: 'pripravljeno' }, + published: { published: true, slug: 'objavljeno' } +} + consultancyAdmin.edit = async (req, res) => { const { id } = req.params - const key = req.query.sentFrom - const sentFrom = {} - sentFrom[key] = true const moderator = await ConsultancyEntry.getModerator(id) // TODO i18n TIME FORMAT @@ -197,9 +205,13 @@ consultancyAdmin.edit = async (req, res) => { const isPublished = entry.status === 'published' + const { slug, ...meta } = STATUS_META[entry.status] ?? STATUS_META.new + const sentFrom = req.query.sentFrom || slug + res.render('pages/consultancy/admin/edit', { id, - sentFrom: key, + sentFrom, + meta, entry: entry, allPrimaryDomains, moderator, @@ -392,14 +404,6 @@ async function consultancyRequest( } } - if (entry.timeCreated) { - const date = new Date(entry.timeCreated) - - entry.formattedTimeCreated = `${date.getDate()}. ${ - date.getMonth() + 1 - }. ${date.getFullYear()}` - } - return entry }) diff --git a/express/controllers/dictionaries.js b/express/controllers/dictionaries.js index 36b81e6..8ca1bc6 100644 --- a/express/controllers/dictionaries.js +++ b/express/controllers/dictionaries.js @@ -15,7 +15,10 @@ const { getExportFilesPath } = require('../models/helpers/dictionary') const { DEFAULT_HITS_PER_PAGE, DATA_FILES_PATH } = require('../config/settings') const { statusChangeCheckAndAct, - determineNewStatus + determineNewStatus, + resolveDictionarySort, + parseDictionaryListFilters, + DICTIONARY_STATUSES } = require('./helpers/dictionary') const SFDSuggestionImporter = require('./helpers/search-filter-data-suggestion-importer') const Extraction = require('../models/extraction') @@ -26,7 +29,7 @@ const importFileBodyParser = multer({ dest: `${DATA_FILES_PATH}/dict_import_temp`, limits: { fieldNameSize: 21, - fieldSize: 9, + fieldSize: 64, fields: 3, fileSize: 1000 * 1000 * 1000, // 1GB headerPairs: 500 @@ -99,11 +102,9 @@ dictionary.updateDescription = async (req, res) => { const { dictionaryId } = req.params const { body } = req - // TODO Consider using a transaction. await Promise.all([ Dictionary.updateDescription(dictionaryId, body), - Dictionary.deleteSecondaryDomains(dictionaryId, body), - Dictionary.updateSecondaryDomains(dictionaryId, body) + Dictionary.updateSecondaryDomainAssociations(dictionaryId, body) ]) res.redirect(303, 'back') @@ -205,11 +206,9 @@ dictionary.updateStructure = async (req, res) => { const { body } = req const { dictionaryId } = req.params - // TODO Consider using a transaction. await Promise.all([ Dictionary.updateStructure(dictionaryId, body), - Dictionary.deleteLanguages(dictionaryId), - Dictionary.updateLanguages(dictionaryId, body) + Dictionary.updateLanguageAssociations(dictionaryId, body) ]) res.redirect(303, 'back') } @@ -294,18 +293,57 @@ dictionary.showImportFromFileForm = async (req, res) => { dictionary.listAdminDictionaries = async (req, res) => { const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE + const page = +req.query.p > 0 ? +req.query.p : 1 + const { sortBy, sortDir } = resolveDictionarySort( + req.query.sort, + req.query.dir + ) + const filters = parseDictionaryListFilters(req.query) + const statusLabels = { + closed: req.t('zaprt'), + reviewed: req.t('v predogledu'), + published: req.t('odprt') + } - const { pages_total: numberOfAllPages, results } = - await Dictionary.fetchAllAdminDictionaries( + const [ + { pages_total: numberOfAllPages, results }, + allPrimaryDomains, + allSecondaryDomains, + allLanguages + ] = await Promise.all([ + Dictionary.fetchAllAdminDictionaries( req.determinedLanguage, resultsPerPage, - 1 - ) + page, + sortBy, + sortDir, + filters + ), + Dictionary.fetchAllPrimaryDomains(req.determinedLanguage), + Dictionary.fetchAllSecondaryDomainsUnfiltered(req.determinedLanguage), + Dictionary.fetchAllLanguages(req.determinedLanguage, false) + ]) + const allStatuses = DICTIONARY_STATUSES.map(value => ({ + value, + label: statusLabels[value] + })) res.render('pages/admin/dictionaries-list', { title: req.t('Seznam slovarjev'), numberOfAllPages, - results + results, + page, + sortBy, + sortDir, + q: filters.nameQuery, + pd: filters.primaryDomainIds || [], + sd: filters.secondaryDomainIds || [], + lang: filters.languageIds || [], + status: filters.statuses || [], + allPrimaryDomains, + allSecondaryDomains, + allLanguages, + allStatuses }) } @@ -335,6 +373,85 @@ dictionary.adminEditDescription = async (req, res) => { }) } +dictionary.listViewableDictionaries = async (req, res) => { + const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE + const page = +req.query.p > 0 ? +req.query.p : 1 + const { sortBy, sortDir } = resolveDictionarySort( + req.query.sort, + req.query.dir + ) + const filters = parseDictionaryListFilters(req.query) + const statusLabels = { + closed: req.t('zaprt'), + reviewed: req.t('v predogledu'), + published: req.t('odprt') + } + + const [ + { pages_total: numberOfAllPages, results }, + allPrimaryDomains, + allSecondaryDomains, + allLanguages + ] = await Promise.all([ + Dictionary.fetchAllAdminDictionaries( + req.determinedLanguage, + resultsPerPage, + page, + sortBy, + sortDir, + filters + ), + Dictionary.fetchAllPrimaryDomains(req.determinedLanguage), + Dictionary.fetchAllSecondaryDomainsUnfiltered(req.determinedLanguage), + Dictionary.fetchAllLanguages(req.determinedLanguage, false) + ]) + const allStatuses = DICTIONARY_STATUSES.map(value => ({ + value, + label: statusLabels[value] + })) + + res.render('pages/view-resources/list', { + title: req.t('Seznam slovarjev'), + numberOfAllPages, + results, + page, + sortBy, + sortDir, + q: filters.nameQuery, + pd: filters.primaryDomainIds || [], + sd: filters.secondaryDomainIds || [], + lang: filters.languageIds || [], + status: filters.statuses || [], + allPrimaryDomains, + allSecondaryDomains, + allLanguages, + allStatuses + }) +} + +dictionary.viewDictionaryDetails = async (req, res) => { + const { dictionaryId } = req.params + const [ + allPrimaryDomains, + dictionaryData, + associatedSecondaryDomains, + status + ] = await Promise.all([ + Dictionary.fetchAllPrimaryDomains(req.determinedLanguage), + Dictionary.fetchEditDescription(dictionaryId), + Dictionary.fetchSecondaryDomains(dictionaryId), + Dictionary.fetchStatus(dictionaryId) + ]) + + res.render('pages/view-resources/dictionary-details', { + title: req.t('Osnovni podatki'), + allPrimaryDomains, + dictionary: dictionaryData, + associatedSecondaryDomains, + status + }) +} + dictionary.updateAdminDescription = async (req, res) => { // TODO Due to reindexing of all of dictionary entries on status change, this operation might take a while. // TODO Stress test and consider either a notification to user or alteast a progress indicator while they wait. @@ -344,11 +461,9 @@ dictionary.updateAdminDescription = async (req, res) => { const oldDictStatus = await Dictionary.fetchStatus(dictionaryId) - // TODO Consider using a transaction. await Promise.all([ Dictionary.updateDescription(dictionaryId, body), - Dictionary.deleteSecondaryDomains(dictionaryId, body), - Dictionary.updateSecondaryDomains(dictionaryId, body), + Dictionary.updateSecondaryDomainAssociations(dictionaryId, body), Dictionary.updateStatus(dictionaryId, body) ]) @@ -674,6 +789,7 @@ dictionary.dictionaryDetails = async (req, res) => { } dictionary.importFromFile = async (req, res) => { + let jobId try { await parseImportFileBody(req, res) // TODO return JSON error response rather then delegate to express. @@ -684,7 +800,7 @@ dictionary.importFromFile = async (req, res) => { const importFilePath = req.file.path const { deleteExistingEntries, entryStatus, importFileFormat } = req.body - await Dictionary.openImportFileJob( + jobId = await Dictionary.openImportFileJob( dictionaryId, deleteExistingEntries, importFileFormat @@ -695,26 +811,41 @@ dictionary.importFromFile = async (req, res) => { await Entry.deleteAll(dictionaryId) } - await Dictionary.importFromFile( + const { totalCount, validCount } = await Dictionary.importFromFile( req.user.id, dictionaryId, importFilePath, - entryStatus + entryStatus, + importFileFormat ) // TODO Rather then waiting for success/failure, return immediately and continue processing in the background. // TODO Also add API endpoint for getting progress. + await Dictionary.closeImportFileJob( + jobId, + 'done', + validCount, + totalCount - validCount + ) + await Dictionary.indexIntoSearchEngine(dictionaryId) // TODO Error --> import job status: (indexing) error --> User manually triggers reindex. debug('IMPORT SUCCESSFUL') - const importProcessId = 'DUMMY ID' // TODO You'll get it from DB. - res.status(202).send(importProcessId) + res.status(202).send({ jobId }) } catch (error) { // TODO Consider writing a property on req and add an extra error handler for API errors. debug('IMPORT FAILED') debug(error) + if (jobId) { + try { + await Dictionary.closeImportFileJob(jobId, 'error', 0, 0) + } catch (closeError) { + debug('ERROR CLOSING IMPORT FILE JOB:') + debug(closeError) + } + } res.status(400).send(error) } finally { try { @@ -756,7 +887,7 @@ dictionary.exportDownload = [ ] function importFileFilter(req, file, cb) { - if (file.mimetype !== 'text/xml') { + if (!['text/xml', 'application/json'].includes(file.mimetype)) { const customError = Error('Invalid file type') customError.displayInProd = true return cb(customError) diff --git a/express/controllers/helpers/dictionary.js b/express/controllers/helpers/dictionary.js index aa9b555..e1814e7 100644 --- a/express/controllers/helpers/dictionary.js +++ b/express/controllers/helpers/dictionary.js @@ -1,6 +1,6 @@ /* global __ */ -const { getInstanceSetting } = require('../../models/helpers') +const { getInstanceSetting, intoDbArray } = require('../../models/helpers') const Dictionary = require('../../models/dictionary') const cache = require('../../models/cache') const { promisify } = require('util') @@ -194,6 +194,53 @@ exports.statusChangeCheckAndAct = { } } +// Whitelist of admin dictionary-list sortable columns, keeping req.query +// values from ever reaching raw SQL - see models/dictionary.js +// fetchAllAdminDictionaries. +const DICTIONARY_LIST_SORT_COLUMNS = [ + 'id', + 'name', + 'status', + 'timeCreated', + 'timeModified' +] + +// Resolves the admin dictionary-list sort params from a request query, +// defaulting to id/desc when absent or invalid. +exports.resolveDictionarySort = (querySort, queryDir) => ({ + sortBy: DICTIONARY_LIST_SORT_COLUMNS.includes(querySort) ? querySort : 'id', + sortDir: queryDir === 'asc' ? 'asc' : 'desc' +}) + +const DICTIONARY_STATUSES = ['closed', 'reviewed', 'published'] +exports.DICTIONARY_STATUSES = DICTIONARY_STATUSES + +// Keeps only numeric-looking id strings, matching the option values the +// admin filter selects render (real DB smallint ids) - drops anything else +// rather than letting it reach a ::smallint[] cast in SQL. +const toNumericIdArray = ids => { + if (!ids) return null + const numericIds = ids.filter(id => /^\d+$/.test(id)) + return numericIds.length > 0 ? numericIds : null +} + +// Parses/whitelists the admin dictionary-list search+filter params from a +// request query. A filter category left unselected resolves to null ("no +// filter"), never an empty array (which would match zero rows in SQL). +exports.parseDictionaryListFilters = query => { + const rawStatuses = intoDbArray(query.status) + const statuses = rawStatuses + ? rawStatuses.filter(value => DICTIONARY_STATUSES.includes(value)) + : null + return { + nameQuery: typeof query.q === 'string' ? query.q.trim() : '', + primaryDomainIds: toNumericIdArray(intoDbArray(query.pd)), + secondaryDomainIds: toNumericIdArray(intoDbArray(query.sd)), + languageIds: toNumericIdArray(intoDbArray(query.lang)), + statuses: statuses && statuses.length > 0 ? statuses : null + } +} + // Helper function used by statusChangeCheckAndAct methods. async function renderAndSendStatusChangeEmails( appRef, diff --git a/express/controllers/helpers/search-filter-data-suggestion-importer.js b/express/controllers/helpers/search-filter-data-suggestion-importer.js index 817d021..364b98f 100644 --- a/express/controllers/helpers/search-filter-data-suggestion-importer.js +++ b/express/controllers/helpers/search-filter-data-suggestion-importer.js @@ -18,7 +18,7 @@ helper.initialize = async determinedLanguage => { l => l.id !== 32 ) - initializers.allDictionaryNames = await Dictionary.fetchAll( + initializers.allDictionaryNames = await Dictionary.fetchAllPublished( determinedLanguage ) diff --git a/express/controllers/index.js b/express/controllers/index.js index b3ed712..4e3df7d 100644 --- a/express/controllers/index.js +++ b/express/controllers/index.js @@ -495,6 +495,10 @@ exports.deleteProfile = async (req, res) => { } exports.changePassword = async (req, res) => { + // SSO accounts have no local password to change - this page doesn't apply to them (the sidebar + // link is also hidden for them, but this covers direct navigation to the URL). + if (req.user.isSso) return res.redirect(303, '/moj-racun') + res.render('pages/profile/change-password', { title: req.t('Spremeni geslo') }) diff --git a/express/controllers/oidc.js b/express/controllers/oidc.js new file mode 100644 index 0000000..31b6c6f --- /dev/null +++ b/express/controllers/oidc.js @@ -0,0 +1,272 @@ +const { promisify } = require('util') +const bcrypt = require('bcrypt') +const passport = require('../middleware/auth') +const User = require('../models/user') +const { rememberMeCookieSettings } = require('../config/settings') +const universityDomainAbbreviations = require('../config/university-domains') + +const STRATEGY_NAME = 'oidc-uni-lj' + +const oidc = {} + +// Lazily discovers/registers the University of Ljubljana strategy on first use. Returns false +// (and has already flashed+redirected) if the IdP couldn't be reached - e.g. the dev Authentik +// stand-in isn't running. +async function ensureStrategyOrBail(req, res) { + try { + await passport.getUniLjStrategy() + return true + } catch (error) { + // eslint-disable-next-line no-console + console.error( + 'University of Ljubljana OIDC discovery/bootstrap failed:', + error + ) + req.flash( + 'info', + req.t( + 'Prijava prek Univerze v Ljubljani trenutno ni na voljo. Poskusite kasneje.' + ) + ) + res.redirect(303, '/') + return false + } +} + +async function issueRememberMe(res, user) { + const rememberMeToken = await User.generateRememberMeToken() + await User.saveRememberMeToken(user, rememberMeToken) + res.cookie('remember_me', rememberMeToken, rememberMeCookieSettings) +} + +// Derives the username used for both a brand-new SSO account and an SSO account conversion, from +// IdP-provided claims only. Shared by createProfileForm (display) and createProfileSubmit/ +// convertAccountSubmit (the authoritative value actually persisted) so the two never disagree. +function deriveSuggestedUsername({ givenName, familyName, preferredUsername, email }) { + const usernameLocalPart = + preferredUsername && preferredUsername.includes('@') + ? preferredUsername.slice(0, preferredUsername.indexOf('@')) + : null + const emailDomain = + email && email.includes('@') ? email.slice(email.indexOf('@') + 1) : null + const domainAbbreviation = emailDomain + ? universityDomainAbbreviations[emailDomain] || emailDomain + : null + + return givenName && familyName && usernameLocalPart && domainAbbreviation + ? `${givenName} ${familyName} (${usernameLocalPart}, ${domainAbbreviation})` + : preferredUsername +} + +// GET /users/oidc/login +oidc.login = async (req, res, next) => { + if (req.isAuthenticated()) return res.redirect(303, '/') + if (!(await ensureStrategyOrBail(req, res))) return + passport.authenticate(STRATEGY_NAME)(req, res, next) +} + +// GET /users/oidc/callback +oidc.callback = async (req, res, next) => { + if (!(await ensureStrategyOrBail(req, res))) return + + passport.authenticate(STRATEGY_NAME, async (err, user, info) => { + if (err) { + // Covers tampered/missing `state`, expired authorization code, IdP-side errors, etc. + // eslint-disable-next-line no-console + console.error('University of Ljubljana OIDC callback failed:', err) + req.flash( + 'info', + req.t('Prijava prek Univerze v Ljubljani ni uspela. Poskusite znova.') + ) + return res.redirect(303, '/') + } + + if (user) { + // Returning user with an already-linked external identity. + const loginAsync = promisify(req.login.bind(req)) + await loginAsync(user) + await issueRememberMe(res, user) + req.flash( + 'info', + req.t('Uspešno ste se prijavili prek Univerze v Ljubljani.') + ) + return res.redirect(303, '/') + } + + if (info && info.action === 'account-inactive') { + req.flash( + 'info', + req.t( + 'Vaš uporabniški račun ni aktiven. Za pomoč se obrnite na skrbnika portala.' + ) + ) + return res.redirect(303, '/') + } + + if (info && info.action === 'missing-required-data') { + // Nothing to review or overwrite with - there's no create/convert page to send them to. + req.flash( + 'info', + req.t( + 'Vaš račun pri Univerzi v Ljubljani ne vsebuje vseh podatkov (imena in priimka), potrebnih za ustvarjanje profila na portalu. Za pomoč se obrnite na skrbnika portala.' + ) + ) + return res.redirect(303, '/') + } + + if (info && info.action === 'convert') { + req.session.pendingOidcAuth = { + authProvider: 'uni_lj', + subject: info.subject, + claims: info.claims, + matchedUserId: info.matchedUserId + } + return res.redirect(303, '/users/convert-account') + } + + if (info && info.action === 'create-profile') { + req.session.pendingOidcAuth = { + authProvider: 'uni_lj', + subject: info.subject, + claims: info.claims + } + return res.redirect(303, '/users/create-profile') + } + + req.flash('info', req.t('Prijava prek Univerze v Ljubljani ni uspela.')) + res.redirect(303, '/') + })(req, res, next) +} + +// GET /users/create-profile +oidc.createProfileForm = (req, res) => { + if (req.isAuthenticated()) return res.redirect(303, '/') + const pending = req.session.pendingOidcAuth + if (!pending) return res.redirect(303, '/') + + res.render('pages/oidc/create-profile', { + title: req.t('Ustvarite svoj profil'), + claims: pending.claims, + suggestedUsername: deriveSuggestedUsername(pending.claims) + }) +} + +// POST /api/v1/users/create-profile (AJAX, mirrors register/reset-password's plain-text response +// convention). Every field is derived from the session-stored, server-side IdP claims - `req.body` +// is intentionally never read here, since the review page has no editable fields for the user to +// legitimately submit (this is what actually stops a tampered/direct API call from creating an +// account with attacker-chosen name/username - the disabled inputs in the view are only a UX +// signal, not the enforcement). +oidc.createProfileSubmit = async (req, res) => { + const pending = req.session.pendingOidcAuth + if (req.isAuthenticated() || !pending) { + const err = Error(req.t('Seja je potekla. Poskusite znova.')) + err.status = 400 + err.displayInProd = true + throw err + } + + const { givenName, familyName, email } = pending.claims + const username = deriveSuggestedUsername(pending.claims) + + const userId = await User.createFromExternalIdentity( + pending.authProvider, + pending.subject, + { + username, + firstName: givenName, + lastName: familyName, + email, + language: req.session.language + }, + req.t + ) + + delete req.session.pendingOidcAuth + delete req.session.language + + const loginAsync = promisify(req.login.bind(req)) + await loginAsync({ id: userId }) + await issueRememberMe(res, { id: userId }) + + res.send( + req.t( + 'Uspešno ste ustvarili račun prek Univerze v Ljubljani in se prijavili.' + ) + ) +} + +// GET /users/convert-account +oidc.convertAccountForm = async (req, res) => { + if (req.isAuthenticated()) return res.redirect(303, '/') + const pending = req.session.pendingOidcAuth + if (!pending || !pending.matchedUserId) return res.redirect(303, '/') + + const existingUser = await User.fetchByUsernameOrEmail(pending.claims.email) + + res.render('pages/oidc/convert-account', { + title: req.t('Pretvorite svoj račun'), + claims: pending.claims, + suggestedUsername: deriveSuggestedUsername(pending.claims), + existingUsername: existingUser?.username + }) +} + +// POST /api/v1/users/convert-account (AJAX). Password is the only field the client actually +// supplies and the only one that's meaningful to trust here - it confirms ownership of the +// matched local account. Every other written field (username/first/last name, and the removal of +// the local password) comes from the session-stored IdP claims, same as createProfileSubmit, +// never from `req.body`. +oidc.convertAccountSubmit = async (req, res) => { + const pending = req.session.pendingOidcAuth + if (req.isAuthenticated() || !pending || !pending.matchedUserId) { + const err = Error(req.t('Seja je potekla. Poskusite znova.')) + err.status = 400 + err.displayInProd = true + throw err + } + + const { password } = req.body + const existingUser = await User.fetchByUsernameOrEmail(pending.claims.email) + + const isValid = + existingUser && + existingUser.status === 'active' && + existingUser.bcrypt_hash && + (await bcrypt.compare(password || '', existingUser.bcrypt_hash)) + + if (!isValid) { + const err = Error(req.t('Nepravilno geslo.')) + err.status = 403 + err.displayInProd = true + throw err + } + + const { givenName, familyName } = pending.claims + + await User.convertToExternalIdentity( + pending.authProvider, + pending.subject, + existingUser.id, + { + username: deriveSuggestedUsername(pending.claims), + firstName: givenName, + lastName: familyName + }, + req.t + ) + + delete req.session.pendingOidcAuth + + const loginAsync = promisify(req.login.bind(req)) + await loginAsync({ id: existingUser.id }) + await issueRememberMe(res, { id: existingUser.id }) + + res.send( + req.t( + 'Vaš račun je bil uspešno pretvorjen v prijavo prek Univerze v Ljubljani. Odslej se lahko prijavite le še prek tega načina.' + ) + ) +} + +module.exports = oidc diff --git a/express/controllers/users.js b/express/controllers/users.js index 7133166..3032838 100644 --- a/express/controllers/users.js +++ b/express/controllers/users.js @@ -130,6 +130,16 @@ user.generateResetPasswordToken = async (req, res) => { ) } + if (!user.bcrypt_hash) { + return res + .status(400) + .send( + req.t( + 'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.' + ) + ) + } + const resetPasswordToken = (await RandomBytesAsync(32)).toString('hex') await User.saveResetPasswordToken(user.id, resetPasswordToken) const { email: userEmail, username } = user diff --git a/express/lib/passport-remember-me-extended/LICENSE b/express/lib/passport-remember-me-extended/LICENSE new file mode 100644 index 0000000..e33bd10 --- /dev/null +++ b/express/lib/passport-remember-me-extended/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/express/lib/passport-remember-me-extended/README.md b/express/lib/passport-remember-me-extended/README.md new file mode 100644 index 0000000..ad45685 --- /dev/null +++ b/express/lib/passport-remember-me-extended/README.md @@ -0,0 +1,28 @@ +# passport-remember-me-extended (vendored) + +This directory contains a vendored copy of the `passport-remember-me-extended` +Passport strategy by Derek Lakin. It provides a "remember me" cookie +authentication strategy with support for signed cookies, which the original +`passport-remember-me` package does not provide. + +## Why vendored? + +The package was originally published to npm as `passport-remember-me-extended` +version 0.0.3 by dereklakin. That version was later unpublished from npm, and +the package name was subsequently claimed by an unrelated author. +Rather than depending on the npm registry or a personal +GitHub fork that could also disappear, the source is vendored directly into +this repository. + +## Source + +Copied from commit +[`7493da87`](https://github.com/dereklakin/passport-remember-me/tree/7493da87e167060b6c846658d6fb6009331677d1). +Only `lib/strategy.js`, `lib/utils.js`, `lib/index.js` and +`LICENSE` were copied. The `require('pkginfo')(module, 'version')` call was +removed from `index.js` to avoid pulling in the `pkginfo` dependency, since +we never read the exposed version string. + +## License + +MIT. See `LICENSE`. diff --git a/express/lib/passport-remember-me-extended/index.js b/express/lib/passport-remember-me-extended/index.js new file mode 100644 index 0000000..cd5c29b --- /dev/null +++ b/express/lib/passport-remember-me-extended/index.js @@ -0,0 +1,10 @@ +/** + * Module dependencies. + */ +var Strategy = require('./strategy'); + + +/** + * Expose constructors. + */ +exports.Strategy = Strategy; diff --git a/express/lib/passport-remember-me-extended/strategy.js b/express/lib/passport-remember-me-extended/strategy.js new file mode 100644 index 0000000..014bf28 --- /dev/null +++ b/express/lib/passport-remember-me-extended/strategy.js @@ -0,0 +1,114 @@ +/** + * Module dependencies. + */ +var passport = require('passport') + , util = require('util') + , utils = require('./utils'); + + +/** + * `Strategy` constructor. + * + * @param {Object} options + * @api public + */ +function Strategy(options, verify, issue) { + if (typeof options == 'function') { + issue = verify; + verify = options; + options = {}; + } + if (!verify) throw new Error('remember me cookie authentication strategy requires a verify function'); + if (!issue) throw new Error('remember me cookie authentication strategy requires an issue function'); + + var opts = { path: '/', httpOnly: true, maxAge: 604800000 }; // maxAge: 7 days + this._key = options.key || 'remember_me'; + this._opts = utils.merge(opts, options.cookie); + + passport.Strategy.call(this); + this.name = 'remember-me'; + this._verify = verify; + this._issue = issue; + this._passReqToCallback = !!options.passReqToCallback; +} + +/** + * Inherit from `passport.Strategy`. + */ +util.inherits(Strategy, passport.Strategy); + +/** + * Authenticate request based on remember me cookie. + * + * @param {Object} req + * @api protected + */ +Strategy.prototype.authenticate = function(req, options) { + // The rememeber me cookie is only consumed if the request is not + // authenticated. This is in preference to the session, which is typically + // established at the same time the remember me cookie is issued. + if (req.isAuthenticated()) { return this.pass(); } + + var token = (this._opts !== undefined && this._opts.signed === true ? req.signedCookies[this._key] : req.cookies[this._key]); + + // Since the remember me cookie is primarily a convenience, the lack of one is + // not a failure. In this case, a response should be rendered indicating a + // logged out state, rather than denying the request. + if (!token) { return this.pass(); } + + var self = this; + + function verified(err, user, info) { + if (err) { return self.error(err); } + + // Express exposes the response to the request. We need the response to set + // a cookie, so we'll grab it this way. This breaks the encapsulation of + // Passport's Strategy API, but is acceptable for this strategy. + var res = req.res; + + if (!user) { + // The remember me cookie was not valid. However, because this + // authentication method is primarily a convenience, we don't want to + // deny the request. Instead we'll clear the invalid cookie and proceed + // to respond in a manner which indicates a logged out state. + // + // Note that a failure at this point may indicate a possible theft of the + // cookie. If handling this situation is a requirement, it is up to the + // application to encode the value in such a way that this can be detected. + // For a discussion on such matters, refer to: + // http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice/ + // http://jaspan.com/improved_persistent_login_cookie_best_practice + // http://web.archive.org/web/20130214051957/http://jaspan.com/improved_persistent_login_cookie_best_practice + // http://stackoverflow.com/questions/549/the-definitive-guide-to-forms-based-website-authentication + + res.clearCookie(self._key); + return self.pass(); + } + + // The remember me cookie was valid and consumed. For security reasons, + // the just-used token should have been invalidated by the application. + // A new token will be issued and set as the value of the remember me + // cookie. + function issued(err, val) { + if (err) { return self.error(err); } + res.cookie(self._key, val, self._opts); + return self.success(user, info); + } + + if (self._passReqToCallback) + self._issue(req, user, issued); + else + self._issue(user, issued); + } + + if (self._passReqToCallback) + self._verify(req, token, verified); + else + self._verify(token, verified); +} + + +/** + * Expose `Strategy`. + */ +module.exports = Strategy; diff --git a/express/lib/passport-remember-me-extended/utils.js b/express/lib/passport-remember-me-extended/utils.js new file mode 100644 index 0000000..dfec86c --- /dev/null +++ b/express/lib/passport-remember-me-extended/utils.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * utils.merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api private + */ + +exports.merge = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/express/middleware/auth.js b/express/middleware/auth.js index 5cd0fcc..4e89ea5 100644 --- a/express/middleware/auth.js +++ b/express/middleware/auth.js @@ -1,6 +1,8 @@ const passport = require('passport') const LocalStrategy = require('passport-local').Strategy -const RememberMeStrategy = require('passport-remember-me-extended').Strategy +const RememberMeStrategy = + require('../lib/passport-remember-me-extended').Strategy +const { Issuer, Strategy: OidcStrategy, custom } = require('openid-client') const bcrypt = require('bcrypt') const db = require('../models/db') const User = require('../models/user') @@ -8,6 +10,16 @@ const { rememberMeCookieSettings, REMEMBER_ME_DURATION_SQL } = require('../config/settings') +const { + oidcUniLjClientId, + oidcUniLjClientSecret, + oidcUniLjDiscoveryUrl, + oidcUniLjAuthorizationExternalOrigin, + origin +} = require('../config/keys') + +// Fail fast rather than hang a request indefinitely if the IdP is unreachable. +custom.setHttpOptionsDefaults({ timeout: 5000 }) passport.serializeUser((user, done) => { done(null, user.id) @@ -53,6 +65,14 @@ passport.use( }) } + if (!user.bcrypt_hash) { + return done(null, false, { + message: req.t( + 'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.' + ) + }) + } + const isCorrectPassword = await bcrypt.compare( password, user.bcrypt_hash @@ -114,4 +134,105 @@ passport.use( ) ) +let cachedUniLjStrategy = null + +// Lazily discovers + caches the University of Ljubljana OIDC client/Strategy. Deliberately NOT +// run at module load: `docker compose up` (default profile) never starts the dev Authentik +// stand-in (`--profile develop-idp`), and eager discovery here would hang/throw at express boot +// for every developer not touching SSO. Only ever called from an actual SSO login/callback +// request; failures are not cached, so the very next click retries (no restart needed once the +// IdP comes back up). +async function getUniLjStrategy() { + if (cachedUniLjStrategy) return cachedUniLjStrategy + + const internalIssuer = await Issuer.discover(oidcUniLjDiscoveryUrl) + const metadata = internalIssuer.metadata + + if (oidcUniLjAuthorizationExternalOrigin) { + const authUrl = new URL(metadata.authorization_endpoint) + const externalOrigin = new URL(oidcUniLjAuthorizationExternalOrigin) + authUrl.protocol = externalOrigin.protocol + authUrl.host = externalOrigin.host // includes port + metadata.authorization_endpoint = authUrl.href + } + + const issuer = new Issuer(metadata) + const redirectUri = new URL('/users/oidc/callback', origin).href + + const client = new issuer.Client({ + client_id: oidcUniLjClientId, + client_secret: oidcUniLjClientSecret, + redirect_uris: [redirectUri], + response_types: ['code'] + }) + + cachedUniLjStrategy = new OidcStrategy( + { + client, + params: { scope: 'openid email profile' }, + passReqToCallback: true + }, + verifyUniLj + ) + passport.use('oidc-uni-lj', cachedUniLjStrategy) + + return cachedUniLjStrategy +} + +// The ID token's `claims` never carries given_name/family_name on the real University of +// Ljubljana/Entra IdP - only the standard /userinfo response does. The 4-arg verify-callback +// signature is required to get openid-client's Strategy to auto-fetch userinfo (see +// node_modules/openid-client/lib/passport_strategy.js's `loadUserinfo` check, which triggers on a +// 4-arg callback) - `userinfo` is a real data source here, not a debugging aid. +async function verifyUniLj(req, tokenset, userinfo, done) { + try { + const claims = tokenset.claims() + + const subject = claims.sub + + const linkedUser = await User.fetchByExternalIdentity('uni_lj', subject) + if (linkedUser) { + if (linkedUser.status !== 'active') { + return done(null, false, { action: 'account-inactive' }) + } + return done(null, { id: linkedUser.id }) + } + + const parsedClaims = { + givenName: userinfo.given_name || '', + familyName: userinfo.family_name || '', + email: claims.email || '', + preferredUsername: claims.preferred_username || '' + } + + // Both the create and convert flows below need a name to show/store - there's nothing to + // review or overwrite with otherwise. This is checked before the email-match lookup since it + // blocks both outcomes equally. + if (!parsedClaims.givenName || !parsedClaims.familyName) { + return done(null, false, { action: 'missing-required-data' }) + } + + if (parsedClaims.email) { + const matchedUser = await User.fetchActiveByEmail(parsedClaims.email) + if (matchedUser) { + return done(null, false, { + action: 'convert', + claims: parsedClaims, + subject, + matchedUserId: matchedUser.id + }) + } + } + + done(null, false, { + action: 'create-profile', + claims: parsedClaims, + subject + }) + } catch (error) { + done(error) + } +} + module.exports = passport +module.exports.getUniLjStrategy = getUniLjStrategy diff --git a/express/middleware/index.js b/express/middleware/index.js index a35552b..380c215 100644 --- a/express/middleware/index.js +++ b/express/middleware/index.js @@ -15,7 +15,7 @@ exports.adjustHeaders = async (req, res, next) => { } exports.setDerivedDictionaryIdFromEntryId = async (req, res, next) => { - const { entryId } = req.query + const entryId = req.params.entryId || req.query.entryId const { dictionary_id: dictionaryId } = await Entry.fetch(entryId) req.derivedDictionaryId = dictionaryId diff --git a/express/models/consultancy-entry.js b/express/models/consultancy-entry.js index 3d03e4d..2bacdae 100644 --- a/express/models/consultancy-entry.js +++ b/express/models/consultancy-entry.js @@ -27,9 +27,7 @@ class ConsultancyEntry { domain_primary_id: domainPrimaryId, first_name: firstName, last_name: lastName, - is_moderator: isModerator, - formatted_time_created: formattedTimeCreated, - formatted_time_published: formattedTimePublished + is_moderator: isModerator }) { this.id = id this.idExternal = idExternal @@ -51,8 +49,6 @@ class ConsultancyEntry { this.firstName = firstName this.lastName = lastName this.isModerator = isModerator - this.formattedTimeCreated = formattedTimeCreated - this.formattedTimePublished = formattedTimePublished } // Fetch consultancy entry by ID @@ -65,7 +61,7 @@ class ConsultancyEntry { id, id_external, - to_char(time_created,'DD. MM. YYYY') time_created, + time_created, status, author_id, institution, @@ -73,7 +69,7 @@ class ConsultancyEntry { domain_primary_id_initial, existing_solutions, examples_of_use, - to_char(time_published,'DD. MM. YYYY') time_published, + time_published, title, question, answer, @@ -96,7 +92,7 @@ class ConsultancyEntry { id, id_external, - to_char(time_created, 'DD. MM. YYYY') time_created, + time_created, status, author_id, institution, @@ -104,7 +100,7 @@ class ConsultancyEntry { domain_primary_id_initial, existing_solutions, examples_of_use, - to_char(time_published,'DD. MM. YYYY') time_published, + time_published, title, question, answer, @@ -179,12 +175,12 @@ class ConsultancyEntry { static async fetchWithStatusById(status, id) { const sqlQuery = ` SELECT ce.id, - to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created, + time_created, author_id, institution, description, domain_primary_id_initial, - to_char(time_published, 'FMDD. FMMM. YYYY') time_published, + time_published, title, question, answer, @@ -245,12 +241,12 @@ class ConsultancyEntry { static async fetchAllByStatusWithAuthorData(status) { const sqlQuery = ` SELECT ce.id, - to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created, + time_created, author_id, institution, description, domain_primary_id_initial, - to_char(time_published, 'FMDD. FMMM. YYYY') time_published, + time_published, title, question, answer, @@ -303,12 +299,12 @@ class ConsultancyEntry { static async fetch5MostRecentPublished() { const sqlQuery = ` SELECT ce.id, - to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created, + time_created, author_id, institution, description, domain_primary_id_initial, - to_char(time_published, 'FMDD. FMMM. YYYY') time_published, + time_published, title, question, answer, diff --git a/express/models/dictionary.js b/express/models/dictionary.js index 574d0ab..b3de335 100644 --- a/express/models/dictionary.js +++ b/express/models/dictionary.js @@ -1,13 +1,19 @@ const { mkdir, open, unlink } = require('fs/promises') const Cursor = require('pg-cursor') const db = require('./db') -const { intoDbArray, getInstanceSetting } = require('./helpers') +const { + intoDbArray, + getInstanceSetting, + escapeLikePattern +} = require('./helpers') const { deserialize, bulkIndex, - getExportFilesPath + getExportFilesPath, + insertSuggestionEntry } = require('./helpers/dictionary') const { readFileIntoDb } = require('./helpers/dictionary/import-file') +const { readJsonFileIntoDb } = require('./helpers/dictionary/import-json-file') const { transformAndAppend } = require('./helpers/dictionary/export-file') const { origin } = require('../config/keys') // const debug = require('debug')('termPortal:models/dictionary') @@ -35,8 +41,8 @@ class Dictionary { this.countComments = countComments } - // Fetch all dictionaries from DB. - static async fetchAll(determinedLanguage) { + // Fetch all published dictionaries from DB. + static async fetchAllPublished(determinedLanguage) { // TODO Implement SQL stored procedures or functions. const { rows: fetchedDictionaries } = await db.query(` SELECT @@ -47,6 +53,7 @@ class Dictionary { count_entries, count_comments FROM dictionary + WHERE status = 'published' ORDER BY time_modified DESC`) const deserializedDictionaries = fetchedDictionaries.map( dictionary => new this(dictionary) @@ -129,6 +136,16 @@ class Dictionary { return deserializedDomains } + // Fetch all secondary domains from DB, approved or not (for admin filtering). + static async fetchAllSecondaryDomainsUnfiltered(determinedLanguage) { + const { rows: fetchedDomains } = await db.query(` + SELECT id, name_${determinedLanguage} name + FROM domain_secondary + ORDER BY name_${determinedLanguage}`) + + return fetchedDomains + } + // Fetch all languages from DB. static async fetchAllLanguages(determinedLanguage, excludeSlovene) { // TODO Implement SQL stored procedures or functions. @@ -223,6 +240,37 @@ class Dictionary { return deserializedSecondaryDomains } + // Soft-warning check: does any of the given (non-null) names collide with another own dictionary? + static async checkNameCollision({ + nameSl, + nameSlShort, + nameEn, + excludeDictionaryId + }) { + const values = [ + nameSl || null, + nameSlShort || null, + nameEn || null, + excludeDictionaryId || null + ] + const text = ` + SELECT id + FROM dictionary + WHERE + count_comments IS NOT NULL AND + ($4::int IS NULL OR id <> $4) AND + ( + ($1::varchar IS NOT NULL AND name_sl = $1) OR + ($2::varchar IS NOT NULL AND name_sl_short = $2) OR + ($3::varchar IS NOT NULL AND name_en = $3) + ) + LIMIT 1` + + const { rows } = await db.query(text, values) + + return rows.length > 0 + } + // Update single dictionary description in DB. static async updateDescription(dictionaryId, dictionary) { const values = [ @@ -254,7 +302,7 @@ class Dictionary { } // Delete secondary domain associations with a single dictionary from DB. - static async deleteSecondaryDomains(dictionaryId, dictionary) { + static async deleteSecondaryDomains(dictionaryId, dictionary, dbClient = db) { const value = [dictionaryId] const text = ` @@ -262,11 +310,11 @@ class Dictionary { dictionary_domain_secondary WHERE dictionary_id = $1` - await db.query(text, value) + await dbClient.query(text, value) } // Insert new secondary domain associations with a single dictionary into DB. - static async updateSecondaryDomains(dictionaryId, dictionary) { + static async updateSecondaryDomains(dictionaryId, dictionary, dbClient = db) { const updatedSecondaryDomains = intoDbArray( dictionary.domainSecondary, 'always' @@ -276,7 +324,15 @@ class Dictionary { const text = ` INSERT INTO dictionary_domain_secondary (dictionary_id, domain_secondary_id) VALUES ($1, UNNEST($2::smallint[]))` - await db.query(text, values) + await dbClient.query(text, values) + } + + // Replace a dictionary's secondary domain associations atomically. + static async updateSecondaryDomainAssociations(dictionaryId, dictionary) { + await db.transaction(async dbClient => { + await this.deleteSecondaryDomains(dictionaryId, dictionary, dbClient) + await this.updateSecondaryDomains(dictionaryId, dictionary, dbClient) + }) } // Fetch single dictionary data for editing users from DB. @@ -395,7 +451,7 @@ class Dictionary { d.id, d.name_${determinedLanguage} dictionarysl, d.count_entries, - to_char(d.time_modified,'YYYY-MM-DD') time_modified, + d.time_modified, d.issn, d.author, dp.name_${determinedLanguage} domain_primary, @@ -431,7 +487,7 @@ class Dictionary { distinct(d.id), ${lang} dictionarysl, d.count_entries, - to_char(d.time_modified,'YYYY-MM-DD') time_modified, + d.time_modified, d.issn, d.author, dp.name_sl domain_primary, @@ -452,73 +508,6 @@ class Dictionary { return rows } - // Fetch dictionary data for viewing details about it - static async fetchBasicInfoPerPageFiltered( - searchQuery, - domainQuery, - resultsPerPage, - page - ) { - let queryAppend = '' - if (domainQuery.length > 0) { - try { - queryAppend = domainQuery.reduce((acc, e, i) => { - if (i === 0) { - let retstring = `( dp.id=${parseInt(e)}` - - if (domainQuery.length - 1 === 0) { - // if contains only one item -> "AND (dp.id=XXX)" - retstring = `${retstring} )` - } - - // "AND [[( dp.id=XXX]]" - return acc + retstring - } - if (i === domainQuery.length - 1) { - return acc + ` OR dp.id=${parseInt(e)})` - } - - // "AND ( dp.id=XXX [[OR dp.id=YYY]]" - return acc + ` OR dp.id=${parseInt(e)}` - }, 'AND ') - } catch (e) { - queryAppend = '' - } - } - - const isInEnglish = false - const lang = isInEnglish ? 'name_en' : 'name_sl' - const text = ` - SELECT - distinct (d.id), - d.${lang} dictionarysl, - d.count_entries, - to_char(d.time_modified,'YYYY-MM-DD') time_modified, - d.issn, - d.author, - dp.name_sl domain_primary, - description, - lp.name portalnamesl, - lp.code portalcode - FROM - dictionary d - FULL JOIN dictionary_language dl ON dl.dictionary_id = d.id - INNER JOIN domain_primary dp ON d.domain_primary_id = dp.id - LEFT JOIN linked_dictionary ld ON ld.target_dictionary_id = d.id - LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id - WHERE d.name_sl LIKE '%' || $1 || '%' ${queryAppend} - LIMIT $2 - OFFSET $3` - - const { rows } = await db.query(text, [ - searchQuery, - resultsPerPage, - resultsPerPage * (page - 1) - ]) - - return rows - } - // Fetch dictionary data for viewing details about it static async fetchBasicInfoPerPageFilteredWithOrdering( searchQuery, @@ -529,6 +518,10 @@ class Dictionary { orderIndex, determinedLanguage ) { + // Escaped so literal %/_ in a search term are matched as themselves, + // not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js. + const escapedSearchQuery = escapeLikePattern(searchQuery) + let queryAppend = '' if (domainQuery.length > 0) { try { @@ -567,7 +560,7 @@ class Dictionary { d.name_${determinedLanguage} dictionarysl, d.count_entries, d.count_comments, - to_char(d.time_modified,'YYYY-MM-DD') time_modified, + d.time_modified, d.issn, d.author, dp.name_${determinedLanguage} domain_primary, @@ -586,7 +579,7 @@ class Dictionary { OFFSET $3` const { rows } = await db.query(text, [ - searchQuery, + escapedSearchQuery, resultsPerPage, resultsPerPage * (page - 1) ]) @@ -596,6 +589,10 @@ class Dictionary { // Fetch dictionary data for viewing details about it static async fetchFilteredCount(searchQuery, domainQuery) { + // Escaped so literal %/_ in a search term are matched as themselves, + // not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js. + const escapedSearchQuery = escapeLikePattern(searchQuery) + let queryAppend = '' if (domainQuery.length > 0) { try { @@ -635,7 +632,7 @@ class Dictionary { LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id WHERE d.status = 'published' AND d.name_sl LIKE '%' || $1 || '%' ${queryAppend}` - const { rows } = await db.query(text, [searchQuery]) + const { rows } = await db.query(text, [escapedSearchQuery]) return rows[0] } @@ -789,7 +786,7 @@ class Dictionary { } // Delete language associations with a single dictionary from DB. - static async deleteLanguages(dictionaryId) { + static async deleteLanguages(dictionaryId, dbClient = db) { const value = [dictionaryId] const text = ` @@ -797,11 +794,11 @@ class Dictionary { dictionary_language WHERE dictionary_id = $1` - await db.query(text, value) + await dbClient.query(text, value) } // Insert new language associations with a single dictionary into DB. - static async updateLanguages(dictionaryId, dictionary) { + static async updateLanguages(dictionaryId, dictionary, dbClient = db) { const updatedLanguages = intoDbArray(dictionary.language, 'always') const selectionOrder = updatedLanguages.map((language, index) => index + 1) const values = [dictionaryId, updatedLanguages, selectionOrder] @@ -809,15 +806,69 @@ class Dictionary { const text = ` INSERT INTO dictionary_language (dictionary_id, language_id, selection_order) VALUES ($1, UNNEST($2::smallint[]), UNNEST($3::smallint[]))` - await db.query(text, values) + await dbClient.query(text, values) + } + + // Replace a dictionary's language associations atomically. + static async updateLanguageAssociations(dictionaryId, dictionary) { + await db.transaction(async dbClient => { + await this.deleteLanguages(dictionaryId, dbClient) + await this.updateLanguages(dictionaryId, dictionary, dbClient) + }) } static async fetchAllAdminDictionaries( determinedLanguage, resultsPerPage, - page + page, + sortBy, + sortDir, + filters = {} ) { // TODO Implement SQL stored procedures or functions. + // sortBy/sortDir must already be whitelisted by the caller (see + // controllers/helpers/dictionary.js resolveDictionarySort) - this map is + // a defense-in-depth fallback, never interpolate req.query values directly. + const sortColumns = { + id: 'id', + name: `name_${determinedLanguage}`, + status: 'status', + timeCreated: 'time_created', + timeModified: 'time_modified' + } + const sortColumn = sortColumns[sortBy] || 'id' + const direction = sortDir === 'asc' ? 'ASC' : 'DESC' + + // A category left unselected must be passed as null (not []) so the + // "$n::type[] IS NULL" branch short-circuits it as "no filter" - an + // empty array would instead match zero rows via "= ANY('{}')". + const { + nameQuery = '', + primaryDomainIds = null, + secondaryDomainIds = null, + languageIds = null, + statuses = null + } = filters + + // Escaped so literal %/_ in a search term (e.g. a dictionary named + // "100%") are matched as themselves, not as LIKE wildcards - see + // escapeLikePattern in models/helpers/index.js for wildcard-search notes. + const escapedNameQuery = escapeLikePattern(nameQuery) + + const whereClause = ` + WHERE count_comments IS NOT NULL + AND ($3 = '' OR LOWER(name_${determinedLanguage}) LIKE '%' || LOWER($3) || '%') + AND ($4::smallint[] IS NULL OR domain_primary_id = ANY($4::smallint[])) + AND ($5::dictionary_status[] IS NULL OR status = ANY($5::dictionary_status[])) + AND ($6::smallint[] IS NULL OR EXISTS ( + SELECT 1 FROM dictionary_domain_secondary dds + WHERE dds.dictionary_id = dictionary.id AND dds.domain_secondary_id = ANY($6::smallint[]) + )) + AND ($7::smallint[] IS NULL OR EXISTS ( + SELECT 1 FROM dictionary_language dl + WHERE dl.dictionary_id = dictionary.id AND dl.language_id = ANY($7::smallint[]) + ))` + const { rows: [{ result }] } = await db.query( @@ -826,6 +877,7 @@ class Dictionary { 'pages_total', ( SELECT CEIL(COUNT(*) / $1::float) FROM dictionary + ${whereClause} ), 'results', ARRAY( SELECT jsonb_build_object( @@ -836,12 +888,21 @@ class Dictionary { 'status', status ) FROM dictionary - WHERE count_comments IS NOT NULL + ${whereClause} + ORDER BY ${sortColumn} ${direction}, id ${direction} LIMIT $1 OFFSET $2 ) ) result`, - [resultsPerPage, resultsPerPage * (page - 1)] + [ + resultsPerPage, + resultsPerPage * (page - 1), + escapedNameQuery, + primaryDomainIds, + statuses, + secondaryDomainIds, + languageIds + ] ) return result @@ -959,7 +1020,31 @@ class Dictionary { delete_existing_entries, file_format ) - VALUES ($1, $2, $3)` + VALUES ($1, $2, $3) + RETURNING id` + + const { + rows: [{ id }] + } = await db.query(text, values) + + return id + } + + // Update import file job in DB with its final status and entry counts. + static async closeImportFileJob( + jobId, + status, + countValidEntries, + countInvalidEntries + ) { + const values = [jobId, status, countValidEntries, countInvalidEntries] + const text = ` + UPDATE import_file_job + SET + status = $2, + count_valid_entries = $3, + count_invalid_entries = $4 + WHERE id = $1` await db.query(text, values) } @@ -969,20 +1054,30 @@ class Dictionary { userId, dictionaryId, importFilePath, - entryStatus + entryStatus, + importFileFormat ) { const dbClient = await db.getClient() try { await dbClient.query('BEGIN') - await readFileIntoDb( - userId, - dictionaryId, - importFilePath, - entryStatus, - dbClient - ) + const { totalCount, validCount } = + importFileFormat === 'json_term_candidates' + ? await readJsonFileIntoDb( + userId, + dictionaryId, + importFilePath, + dbClient + ) + : await readFileIntoDb( + userId, + dictionaryId, + importFilePath, + entryStatus, + dbClient + ) await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient) await dbClient.query('COMMIT') + return { totalCount, validCount } } catch (error) { await dbClient.query('ROLLBACK') throw error @@ -999,31 +1094,7 @@ class Dictionary { kanonicnaoblika: term, definicija: other } of termCandidates) { - const values = [ - dictionaryId, - false, - 'suggestion', - term || null, - userId, - null, - null, - null, - null, - [], - null, - null, - null, - [], - other || null, - [], - null, - null, - null - ] - - const text = `SELECT entry_new (${db.genParamStr(values)})` - - await dbClient.query(text, values) + await insertSuggestionEntry(dbClient, dictionaryId, userId, term, other) } await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient) @@ -1214,6 +1285,10 @@ class Dictionary { resultsPerPage, page ) { + // Escaped so literal %/_ in a search term are matched as themselves, + // not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js. + const escapedQuery = escapeLikePattern(query) + const { rows: [{ result }] } = await db.query( @@ -1237,7 +1312,7 @@ class Dictionary { OFFSET $4 ) ) result`, - [dictionaryId, query, resultsPerPage, resultsPerPage * (page - 1)] + [dictionaryId, escapedQuery, resultsPerPage, resultsPerPage * (page - 1)] ) return result @@ -1275,6 +1350,10 @@ class Dictionary { // Fetch filtered secondary domains from DB. static async fetchFilteredSecondaryDomains(query, resultsPerPage, page) { + // Escaped so literal %/_ in a search term are matched as themselves, + // not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js. + const escapedQuery = escapeLikePattern(query) + const { rows: [{ result }] } = await db.query( @@ -1299,7 +1378,7 @@ class Dictionary { OFFSET $3 ) ) result`, - [query, resultsPerPage, resultsPerPage * (page - 1)] + [escapedQuery, resultsPerPage, resultsPerPage * (page - 1)] ) return result @@ -1501,10 +1580,11 @@ class Dictionary { 'status', status, 'delete_existing_entries', delete_existing_entries, 'file_format', file_format, - 'count_valid_entries', count_valid_entries + 'count_entries', count_valid_entries + count_invalid_entries ) FROM import_file_job WHERE dictionary_id = $1 + ORDER BY id DESC LIMIT $2 OFFSET $3 ) @@ -1572,6 +1652,7 @@ class Dictionary { ) FROM dictionary_export WHERE dictionary_id = $1 + ORDER BY id DESC LIMIT $2 OFFSET $3 ) @@ -1590,9 +1671,10 @@ class Dictionary { is_terminology_reviewed_filter, is_language_reviewed_filter, status_filter, - export_file_format + export_file_format, + time_zone ) - VALUES ($1, $2, $3, $4, $5, $6, $7) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id ` @@ -1603,7 +1685,8 @@ class Dictionary { exportParams.isTerminologyReviewedFilter, exportParams.isLanguageReviewedFilter, exportParams.statusFilter, - exportParams.exportFileFormat + exportParams.exportFileFormat, + exportParams.timeZone ] const { @@ -1613,6 +1696,13 @@ class Dictionary { return id } + static async deleteExport(dictionaryId, exportId) { + await db.query( + 'DELETE FROM dictionary_export WHERE id = $1 AND dictionary_id = $2', + [exportId, dictionaryId] + ) + } + static async processExport(exportId) { const dbClient = await db.getClient() let exportFilePath @@ -1631,7 +1721,8 @@ class Dictionary { is_terminology_reviewed_filter, is_language_reviewed_filter, status_filter, - export_file_format + export_file_format, + COALESCE(time_zone, 'UTC') time_zone ` const exportQueryParams = [exportId] @@ -1645,7 +1736,8 @@ class Dictionary { is_terminology_reviewed_filter: isTerminologyReviewedFilter, is_language_reviewed_filter: isLanguageReviewedFilter, status_filter: statusFilter, - export_file_format: exportFileFormat + export_file_format: exportFileFormat, + time_zone: timeZone } ] } = await dbClient.query(exportQueryText, exportQueryParams) @@ -1865,17 +1957,17 @@ class Dictionary { name_sl, name_en, author, - to_char(time_modified, 'YYYY-MM-DD') modified_date_string, + to_char(time_modified AT TIME ZONE $3, 'YYYY-MM-DD') modified_date_string, status, ( - SELECT to_char(time_created, 'YYYY-MM-DD') + SELECT to_char(time_created AT TIME ZONE $3, 'YYYY-MM-DD') FROM dictionary_export de WHERE de.id = $1 ) export_date_string FROM dictionary WHERE id = $2 `, - [exportId, dictionaryId] + [exportId, dictionaryId, timeZone] ) const portalName = await getInstanceSetting('portal_name_sl') const authorsString = tbxMetadata.author?.join(', ') @@ -1947,7 +2039,9 @@ class Dictionary { "UPDATE dictionary_export SET status = 'failed', time_finished = NOW() WHERE id = $1", [exportId] ) - await unlink(exportFilePath) + if (exportFilePath) { + await unlink(exportFilePath).catch(() => {}) + } throw error } finally { dbClient.release() @@ -1964,7 +2058,7 @@ class Dictionary { e.status, e.dictionary_id, d.name_sl_short name_string, - to_char(e.time_created, 'YYYYMMDDHH24MISS') time_string, + to_char(e.time_created AT TIME ZONE COALESCE(e.time_zone, 'UTC'), 'YYYYMMDDHH24MISS') time_string, e.export_file_format FROM dictionary_export e LEFT JOIN dictionary d ON d.id = e.dictionary_id diff --git a/express/models/entry.js b/express/models/entry.js index fd8099c..5ec3c1a 100644 --- a/express/models/entry.js +++ b/express/models/entry.js @@ -140,6 +140,7 @@ Entry.fetchFull = async entryId => { ) FROM entry_version_history WHERE entry_id = e.id + ORDER BY version ) ) ) entry @@ -223,6 +224,7 @@ Entry.fetchFullWithOrderedForeignLanguages = async entryId => { ) FROM entry_version_history WHERE entry_id = e.id + ORDER BY version ) ) ) entry diff --git a/express/models/extraction.js b/express/models/extraction.js index 6dc2642..93b006b 100644 --- a/express/models/extraction.js +++ b/express/models/extraction.js @@ -14,6 +14,9 @@ const { } = require('./helpers/extraction') const { extractionApiOrigin } = require('../config/keys') +// Upper limit for each concordancer status-polling loop in Extraction.processOwn. +const CONCORDANCER_POLL_TIMEOUT_SECONDS = 5 * 60 + const Extraction = {} // Fetch all extractions for a specific user. @@ -434,19 +437,12 @@ Extraction.processOwn = async function (extractionId, extractionName) { ]) // Wait for creation of corpus. - while (true) { - console.log('SLEEP FOR 5 SECS') - await sleep(5) - const { - data: { status } - } = await axios.get( - `http://concordancer:5000/dashboard/corpus/${corpusId}` - ) - - if (status === 'Creating') continue - if (status === 'Active') break - throw Error('Error creating concorcander corpus') - } + await pollConcordancerStatus({ + url: `http://concordancer:5000/dashboard/corpus/${corpusId}`, + inProgressStatuses: ['Creating'], + label: `corpus ${corpusId}`, + errorMessage: 'Error creating concorcander corpus' + }) console.log('CORPUS CREATED') const inProgressStatusList = [ @@ -471,19 +467,12 @@ Extraction.processOwn = async function (extractionId, extractionName) { ) // Wait for text ingestion. - while (true) { - console.log('SLEEP FOR 5 SECS') - await sleep(5) - const { - data: { status } - } = await axios.get( - `http://concordancer:5000/dashboard/corpus/${corpusId}/text/${textId}` - ) - - if (inProgressStatusList.includes(status)) continue - if (status === 'Active') break - throw Error('Error importing concorcander text') - } + await pollConcordancerStatus({ + url: `http://concordancer:5000/dashboard/corpus/${corpusId}/text/${textId}`, + inProgressStatuses: inProgressStatusList, + label: `text ${textId}`, + errorMessage: 'Error importing concorcander text' + }) console.log('TEXT ADDED') } @@ -501,19 +490,12 @@ Extraction.processOwn = async function (extractionId, extractionName) { ) // Wait for term list ingestion. - while (true) { - console.log('SLEEP FOR 5 SECS') - await sleep(5) - const { - data: { status } - } = await axios.get( - `http://concordancer:5000/dashboard/corpus/${corpusId}/termList/${termListId}` - ) - - if (inProgressStatusList.includes(status)) continue - if (status === 'Active') break - throw Error('Error importing concorcander text') - } + await pollConcordancerStatus({ + url: `http://concordancer:5000/dashboard/corpus/${corpusId}/termList/${termListId}`, + inProgressStatuses: inProgressStatusList, + label: `termList ${termListId}`, + errorMessage: 'Error importing concorcander term list' + }) console.log('TERMS ADDED') await db.query( @@ -654,6 +636,52 @@ function sleep(seconds) { return new Promise(resolve => setTimeout(resolve, seconds * 1000)) } +// Polls a concordancer status endpoint every 5 seconds until it reports +// 'Active', up to CONCORDANCER_POLL_TIMEOUT_SECONDS in total. The +// concordancer can return HTTP 500 (XForbiddenException, thrown by its +// CurrentContextInitializationDecorator) from these GET endpoints while +// the entity isn't 'Active' yet, which is indistinguishable from "still +// in progress", so a 500 is treated as such and the loop keeps retrying +// until either the entity becomes 'Active' or the upper time limit is +// reached. +async function pollConcordancerStatus({ + url, + inProgressStatuses, + label, + errorMessage +}) { + const startTime = Date.now() + let attempt = 0 + /* eslint-disable no-console */ + while (true) { + const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000) + const remainingSeconds = CONCORDANCER_POLL_TIMEOUT_SECONDS - elapsedSeconds + if (remainingSeconds <= 0) { + throw Error( + `Timed out polling ${label} after ${attempt} attempt(s) and ${elapsedSeconds}s (limit: ${CONCORDANCER_POLL_TIMEOUT_SECONDS}s)` + ) + } + attempt++ + console.log( + `Polling ${label}: attempt ${attempt}, ${remainingSeconds}s left until timeout` + ) + await sleep(5) + let status + try { + ;({ + data: { status } + } = await axios.get(url)) + } catch (error) { + if (error.response?.status === 500) continue + throw error + } + if (inProgressStatuses.includes(status)) continue + if (status === 'Active') return + throw Error(errorMessage) + } + /* eslint-enable no-console */ +} + function logExtractionError(error, extractionId, jobType, filename) { // eslint-disable-next-line no-console console.error( diff --git a/express/models/helpers/dictionary/import-file.js b/express/models/helpers/dictionary/import-file.js index 0bf1d28..a56196e 100644 --- a/express/models/helpers/dictionary/import-file.js +++ b/express/models/helpers/dictionary/import-file.js @@ -193,7 +193,10 @@ function handleEntryXml( ) { debug(`TOTAL ENTRIES: ${progress.totalCount}`) debug(`VALID ENTRIES: ${progress.validCount}`) - resolve() + resolve({ + totalCount: progress.totalCount, + validCount: progress.validCount + }) } } } diff --git a/express/models/helpers/dictionary/import-json-file.js b/express/models/helpers/dictionary/import-json-file.js new file mode 100644 index 0000000..f7c9cc0 --- /dev/null +++ b/express/models/helpers/dictionary/import-json-file.js @@ -0,0 +1,26 @@ +const { readFile } = require('fs/promises') +const { insertSuggestionEntry } = require('./index') + +// Import given JSON export of extraction term candidates into given dictionary. +exports.readJsonFileIntoDb = async ( + userId, + dictionaryId, + importFilePath, + dbClient +) => { + const fileContent = await readFile(importFilePath, 'utf8') + const { terminoloski_kandidati: termCandidates } = JSON.parse(fileContent) + + if (!Array.isArray(termCandidates)) { + throw Error('Invalid term candidates JSON: terminoloski_kandidati is not an array') + } + + for (const { + kanonicnaoblika: term, + definicija: other + } of termCandidates) { + await insertSuggestionEntry(dbClient, dictionaryId, userId, term, other) + } + + return { totalCount: termCandidates.length, validCount: 0 } +} diff --git a/express/models/helpers/dictionary/index.js b/express/models/helpers/dictionary/index.js index 8c9ca61..3ecfb3b 100644 --- a/express/models/helpers/dictionary/index.js +++ b/express/models/helpers/dictionary/index.js @@ -1,4 +1,5 @@ const xss = require('xss') +const db = require('../../db') const { removeHtmlTags } = require('../../helpers') const { searchEngineClient, ENTRY_INDEX } = require('../../search-engine') const { DATA_FILES_PATH } = require('../../../config/settings') @@ -353,3 +354,35 @@ exports.sanitizeField = { return sanitize(string, markupFilter.mixedOther) } } + +// Insert a single 'suggestion' status entry (as produced by extraction term +// candidates, whether imported directly or from a JSON export of them). +exports.insertSuggestionEntry = async (dbClient, dictionaryId, userId, term, other) => { + term = term ? exports.sanitizeField.toText(term) : null + other = other ? exports.sanitizeField.toText(other) : null + + const values = [ + dictionaryId, + false, + 'suggestion', + term || null, + userId, + null, + null, + null, + null, + [], + null, + null, + null, + [], + other || null, + [], + null, + null, + null + ] + const text = `SELECT entry_new (${db.genParamStr(values)})` + + await dbClient.query(text, values) +} diff --git a/express/models/helpers/index.js b/express/models/helpers/index.js index 70610c3..ba90747 100644 --- a/express/models/helpers/index.js +++ b/express/models/helpers/index.js @@ -22,6 +22,19 @@ exports.removeHtmlTags = text => { return tagFilter.process(text) } +// Escapes Postgres LIKE metacharacters (\, %, _) in a raw search string so +// it's matched literally rather than as a LIKE pattern - e.g. a user +// searching for a dictionary literally named "100%" gets that dictionary, +// not every dictionary. Backslash must be escaped first, or the escapes +// added for % and _ below would themselves get re-escaped. +// +// Wildcard search (*, ?), if ever added: translate user-facing '*' -> '%' +// and '?' -> '_' AFTER calling this function, on its return value - that +// way literal %, _, and \ in the search text stay literal while the +// user's own * and ? become real SQL wildcards. +exports.escapeLikePattern = value => + value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_') + // Returns setting value by its name from table instance_settings. exports.getInstanceSetting = async settingName => { const settingCacheName = `${INSTANCE_SETTING_NAMESPACE}:${settingName}` diff --git a/express/models/helpers/user/index.js b/express/models/helpers/user/index.js index 885365d..021c778 100644 --- a/express/models/helpers/user/index.js +++ b/express/models/helpers/user/index.js @@ -9,6 +9,7 @@ exports.deserialize = { status: user.status, hitsPerPage: user.hits_per_page, language: user.language, + isSso: user.is_sso, userRoles: user.user_roles, assignedConsultancyEntries: user.assigned_consultancy_entries } @@ -34,7 +35,10 @@ exports.deserialize = { const deserializedRights = { id: userData.id, userName: userData.username, + firstName: userData.first_name, + lastName: userData.last_name, email: userData.email, + language: userData.language, hasAdministration: userData.administration, hasEditing: userData.editing, hasTerminologyReview: userData.terminology_review, diff --git a/express/models/user.js b/express/models/user.js index bd23b2c..1286387 100644 --- a/express/models/user.js +++ b/express/models/user.js @@ -26,6 +26,135 @@ User.isEmailAlreadyTaken = async email => { return isTaken } +// Check if a user with provided username already exists, optionally excluding one user id (used +// when re-checking a username against its own current owner, e.g. during account conversion). +User.isUsernameAlreadyTaken = async (username, excludeUserId) => { + const { rows } = await db.query( + `SELECT 1 FROM "user" WHERE username = $1 ${ + excludeUserId ? 'AND id <> $2' : '' + }`, + excludeUserId ? [username, excludeUserId] : [username] + ) + + return rows.length > 0 +} + +// Fetch the active user linked to a given external identity (auth_provider, subject), if any. +User.fetchByExternalIdentity = async (authProvider, subject) => { + const { + rows: [user] + } = await db.query( + `SELECT u.id, u.status + FROM user_external_identity uei + JOIN "user" u ON u.id = uei.user_id + WHERE uei.auth_provider = $1 AND uei.subject = $2`, + [authProvider, subject] + ) + + return user +} + +// Fetch an active local user by email. Used to detect whether an SSO login's email claim +// matches an existing local account, for the account-linking flow. +User.fetchActiveByEmail = async email => { + const { + rows: [user] + } = await db.query('SELECT id FROM "user" WHERE email = $1 AND status = $2', [ + email, + 'active' + ]) + + return user +} + +// Atomically create a brand-new SSO-only user (no bcrypt_hash) and link it to the given external +// identity. Used the first time someone signs in via an external IdP with no matching account. +User.createFromExternalIdentity = async (authProvider, subject, profile, t) => { + let userId + + await db.transaction(async dbClient => { + if (await User.isEmailAlreadyTaken(profile.email)) { + const err = Error(t('Elektronski naslov uporablja že drug uporabnik.')) + err.status = 400 + err.displayInProd = true + throw err + } + + if (await User.isUsernameAlreadyTaken(profile.username)) { + const err = Error( + t('Izbrano uporabniško ime uporablja že drug uporabnik.') + ) + err.status = 400 + err.displayInProd = true + throw err + } + + const values = [ + profile.username, + profile.firstName, + profile.lastName, + profile.email + ] + if (profile.language) values.push(profile.language) + + // bcrypt_hash/status/time_activated are appended as fixed literals (not bound params) after + // the dynamic column list, on both the column-list and VALUES-tuple side, so the two stay + // positionally aligned regardless of whether the optional `language` column is included. + const { + rows: [user] + } = await dbClient.query( + `INSERT INTO "user" ( + username, first_name, last_name, email ${ + profile.language ? ', language' : '' + }, + bcrypt_hash, status, time_activated + ) + VALUES (${db.genParamStr(values)}, NULL, 'active', NOW()) + RETURNING id`, + values + ) + + userId = user.id + + await dbClient.query( + 'INSERT INTO user_external_identity (auth_provider, subject, user_id) VALUES ($1, $2, $3)', + [authProvider, subject, userId] + ) + }) + + return userId +} + +// Permanently convert an existing local user into an SSO-only user: overwrite its +// username/first/last name with the IdP-derived profile, remove its local password (from then on +// it can only sign in via this external identity, exactly like a user created straight from the +// IdP via createFromExternalIdentity), and link the external identity. Used once the user has +// confirmed ownership of the matched local account (its password). +User.convertToExternalIdentity = async (authProvider, subject, userId, profile, t) => { + await db.transaction(async dbClient => { + if (await User.isUsernameAlreadyTaken(profile.username, userId)) { + const err = Error( + t('Izbrano uporabniško ime uporablja že drug uporabnik.') + ) + err.status = 400 + err.displayInProd = true + throw err + } + + await dbClient.query( + `UPDATE "user" + SET username = $1, first_name = $2, last_name = $3, bcrypt_hash = NULL + WHERE id = $4`, + [profile.username, profile.firstName, profile.lastName, userId] + ) + + await dbClient.query( + 'INSERT INTO user_external_identity (auth_provider, subject, user_id) VALUES ($1, $2, $3)', + [authProvider, subject, userId] + ) + }) +} + // Create new user in DB. User.create = async (user, t) => { const { @@ -208,10 +337,25 @@ User.resetPasswordWithToken = async (token, password, t) => { ;({ rows: [user] } = await dbClient.query( - 'UPDATE "user" SET bcrypt_hash = $1 WHERE id = $2 RETURNING id, username, email', + // Only ever overwrites an EXISTING local password - never sets an initial one for an + // SSO-only account (bcrypt_hash IS NULL). Also guarded earlier, at token-issuance time + // (generateResetPasswordToken); this is defense in depth for any already-issued token. + `UPDATE "user" SET bcrypt_hash = $1 WHERE id = $2 AND bcrypt_hash IS NOT NULL RETURNING id, username, email`, [bcryptHash, userId] )) + if (!user) { + const err = Error( + t( + 'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.' + ) + ) + err.status = 403 + err.displayInProd = true + + throw err + } + await dbClient.query( 'DELETE FROM user_token_reset_password WHERE token = $1', [token] @@ -298,6 +442,7 @@ User.fetchDeserializedDataById = async userId => { u.status, u.hits_per_page, u.language, + u.bcrypt_hash IS NULL AS is_sso, ARRAY( SELECT jsonb_build_object( 'roleName', r.role_name, @@ -540,7 +685,8 @@ User.fetchUserRoles = async userId => { User.fetchAllWithDictionaryRights = async dictionaryId => { const text = ` - SELECT u.username,u.email, u.id, r.administration, r.editing, r.terminology_review, r.language_review + SELECT u.username, u.email, u.id, u.first_name, u.last_name, u.language, + r.administration, r.editing, r.terminology_review, r.language_review FROM user_role r INNER JOIN "user" u ON u.id = r.user_id WHERE dictionary_id = $1 @@ -711,6 +857,18 @@ User.changePassword = async (userId, passwordOld, passwordNew, t) => { userId ]) + if (!bcryptHashOld) { + const err = Error( + t( + 'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.' + ) + ) + err.status = 403 + err.displayInProd = true + + throw err + } + const isOldPasswordCorrect = await bcrypt.compare( passwordOld, bcryptHashOld @@ -753,6 +911,7 @@ User.closeAccount = async userId => { first_name = $2, last_name = $3, email = $4, + bcrypt_hash = NULL, status = 'closed', time_closed = NOW() WHERE id = $5`, @@ -776,7 +935,15 @@ User.closeAccount = async userId => { ), dbClient.query('DELETE FROM user_token_change_email WHERE user_id = $1', [ userId - ]) + ]), + dbClient.query('DELETE FROM user_external_identity WHERE user_id = $1', [ + userId + ]), + dbClient.query('DELETE FROM user_role WHERE user_id = $1', [userId]), + dbClient.query( + 'DELETE FROM consultancy_entry_consultant WHERE user_id = $1', + [userId] + ) ]) }) } diff --git a/express/package-lock.json b/express/package-lock.json index 33120cf..345dce0 100644 --- a/express/package-lock.json +++ b/express/package-lock.json @@ -32,9 +32,9 @@ "needle": "^3.0.0", "nodemailer": "^6.7.2", "nodemailer-html-to-text": "^3.2.0", + "openid-client": "^5.7.1", "passport": "^0.5.1", "passport-local": "^1.0.0", - "passport-remember-me-extended": "^0.0.3", "pg": "^8.6.0", "pg-cursor": "^2.7.1", "pug": "^3.0.2", @@ -46,7 +46,8 @@ }, "devDependencies": { "express-debug": "^1.1.1", - "nodemon": "^2.0.12" + "nodemon": "^2.0.12", + "sass": "1.35.2" } }, "node_modules/@babel/helper-validator-identifier": { @@ -2006,6 +2007,15 @@ "jade": "bin/jade" } }, + "node_modules/jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-stringify": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/js-stringify/-/js-stringify-1.0.2.tgz", @@ -2480,6 +2490,24 @@ "node": ">=0.10.0" } }, + "node_modules/object-hash": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/oidc-token-hash": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", + "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==", + "license": "MIT", + "engines": { + "node": "^10.13.0 || >=12.0.0" + } + }, "node_modules/on-finished": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", @@ -2507,6 +2535,21 @@ "wrappy": "1" } }, + "node_modules/openid-client": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", + "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", + "license": "MIT", + "dependencies": { + "jose": "^4.15.9", + "lru-cache": "^6.0.0", + "object-hash": "^2.2.0", + "oidc-token-hash": "^5.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/p-cancelable": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", @@ -2588,30 +2631,6 @@ "node": ">= 0.4.0" } }, - "node_modules/passport-remember-me-extended": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/passport-remember-me-extended/-/passport-remember-me-extended-0.0.3.tgz", - "integrity": "sha1-6hp2IJQZ7T4qH8GEnf5NFkEonDQ=", - "dependencies": { - "passport": "0.3.x", - "pkginfo": "0.2.x" - }, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/passport-remember-me-extended/node_modules/passport": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/passport/-/passport-0.3.2.tgz", - "integrity": "sha1-ndAJ+RXo/glbASSgG4+C2gdRAQI=", - "dependencies": { - "passport-strategy": "1.x.x", - "pause": "0.0.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/passport-strategy": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", @@ -2737,14 +2756,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/pkginfo": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.2.3.tgz", - "integrity": "sha1-cjnEKl72wwuPMoQ52bn/cQQkkPg=", - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/postgres-array": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", @@ -3186,6 +3197,22 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "node_modules/sass": { + "version": "1.35.2", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.35.2.tgz", + "integrity": "sha512-jhO5KAR+AMxCEwIH3v+4zbB2WB0z67V1X0jbapfVwQQdjHZUGUyukpnoM6+iCMfsIUC016w9OPKQ5jrNOS9uXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": ">=3.0.0 <4.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=8.9.0" + } + }, "node_modules/sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", @@ -5325,6 +5352,11 @@ "transformers": "~1.8.0" } }, + "jose": { + "version": "4.15.9", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", + "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==" + }, "js-stringify": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/js-stringify/-/js-stringify-1.0.2.tgz", @@ -5692,6 +5724,16 @@ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" }, + "object-hash": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==" + }, + "oidc-token-hash": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", + "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==" + }, "on-finished": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", @@ -5713,6 +5755,17 @@ "wrappy": "1" } }, + "openid-client": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", + "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", + "requires": { + "jose": "^4.15.9", + "lru-cache": "^6.0.0", + "object-hash": "^2.2.0", + "oidc-token-hash": "^5.0.3" + } + }, "p-cancelable": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", @@ -5771,26 +5824,6 @@ "passport-strategy": "1.x.x" } }, - "passport-remember-me-extended": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/passport-remember-me-extended/-/passport-remember-me-extended-0.0.3.tgz", - "integrity": "sha1-6hp2IJQZ7T4qH8GEnf5NFkEonDQ=", - "requires": { - "passport": "0.3.x", - "pkginfo": "0.2.x" - }, - "dependencies": { - "passport": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/passport/-/passport-0.3.2.tgz", - "integrity": "sha1-ndAJ+RXo/glbASSgG4+C2gdRAQI=", - "requires": { - "passport-strategy": "1.x.x", - "pause": "0.0.1" - } - } - } - }, "passport-strategy": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", @@ -5883,11 +5916,6 @@ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true }, - "pkginfo": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.2.3.tgz", - "integrity": "sha1-cjnEKl72wwuPMoQ52bn/cQQkkPg=" - }, "postgres-array": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", @@ -6251,6 +6279,15 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "sass": { + "version": "1.35.2", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.35.2.tgz", + "integrity": "sha512-jhO5KAR+AMxCEwIH3v+4zbB2WB0z67V1X0jbapfVwQQdjHZUGUyukpnoM6+iCMfsIUC016w9OPKQ5jrNOS9uXw==", + "dev": true, + "requires": { + "chokidar": ">=3.0.0 <4.0.0" + } + }, "sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", diff --git a/express/package.json b/express/package.json index b22db6a..2063d8c 100644 --- a/express/package.json +++ b/express/package.json @@ -5,7 +5,10 @@ "scripts": { "start": "node ./bin/www", "devstart": "nodemon --ignore data_files/ --ignore public/locales/dev --inspect=0.0.0.0:9229 ./bin/www", - "devstart-wait": "nodemon --ignore data_files/ --ignore public/locales/dev --inspect-brk=0.0.0.0:9229 ./bin/www" + "devstart-wait": "nodemon --ignore data_files/ --ignore public/locales/dev --inspect-brk=0.0.0.0:9229 ./bin/www", + "sass:watch": "sass --watch public/sass:public/stylesheets", + "sass:build": "sass public/sass:public/stylesheets", + "sass:build:prod": "sass public/sass:public/stylesheets --no-source-map --style=compressed" }, "dependencies": { "@opensearch-project/opensearch": "^2.1.0", @@ -32,9 +35,9 @@ "needle": "^3.0.0", "nodemailer": "^6.7.2", "nodemailer-html-to-text": "^3.2.0", + "openid-client": "^5.7.1", "passport": "^0.5.1", "passport-local": "^1.0.0", - "passport-remember-me-extended": "^0.0.3", "pg": "^8.6.0", "pg-cursor": "^2.7.1", "pug": "^3.0.2", @@ -46,6 +49,7 @@ }, "devDependencies": { "express-debug": "^1.1.1", - "nodemon": "^2.0.12" + "nodemon": "^2.0.12", + "sass": "1.35.2" } } diff --git a/express/public/javascripts/admin.js b/express/public/javascripts/admin.js index 3230d80..807db3b 100644 --- a/express/public/javascripts/admin.js +++ b/express/public/javascripts/admin.js @@ -1,4 +1,4 @@ -/* global $, axios, bootstrap, currentPagePath, initPagination, removeAllChildNodes, unsavedData, replaceContainer, isI18nReady, i18next, validator */ +/* global $, axios, bootstrap, currentPagePath, initPagination, removeAllChildNodes, unsavedData, replaceContainer, isI18nReady, i18next, validator, enableButton, disableButton, captureFormBaseline, isFormDirty, updateSaveButtonState, warnOnNameCollisionThenSubmit */ // const currentPagePath = location.pathname @@ -113,11 +113,9 @@ function initAdmin() { if (currentPagePath === '/admin/uporabniki/portal') { ce.formAddUser = document.getElementById('form-add-user') - const userTable = document.getElementById('user-roles-table') const tableForm = document.getElementById('form-user-roles') - userTable.addEventListener('change', enableButton) + tableForm.addEventListener('input', () => updateSaveButtonState(tableForm)) ce.formAddUser.addEventListener('submit', addUser) - ce.formAddUser.addEventListener('input', enableButton) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(tableForm, dictSideMenu) async function addUser(event) { @@ -204,83 +202,7 @@ function initAdmin() { }) } - if (currentPagePath === '/admin/slovarji') { - const resultsListEl = document.getElementById('page-results') - - const updatePager = initPagination('pagination', onPageChange) - - async function onPageChange(newPage) { - try { - const { page, numberOfAllPages, results } = await getDataForPage( - newPage - ) - removeAllChildNodes(resultsListEl) - renderResults(results) - updatePager(page, numberOfAllPages) - } catch (error) { - let message = i18next.t('Prišlo je do napake.') - if (error.response?.data) { - message = error.response.data - } else if (error.request) { - message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') - } - alert(message) - updatePager() - } - } - - async function getDataForPage(page) { - const url = `/api/v1/dictionaries/listAllDictionaries?p=${page}` - const { data } = await axios.get(url) - return data - } - - function renderResults(results) { - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } - results.forEach(result => { - const rowEl = document.createElement('tr') - const td1 = document.createElement('td') - const td2 = document.createElement('td') - const td3 = document.createElement('td') - const td4 = document.createElement('td') - const td5 = document.createElement('td') - const td6 = document.createElement('td') - const aEl = document.createElement('a') - const imgEl = document.createElement('img') - const spanEl = document.createElement('span') - td1.textContent = result.id - td2.textContent = result.name - td3.textContent = result.status - const timeCreated = new Date(result.timeCreated).toLocaleDateString( - 'sl-SL', - localeOptions - ) - td4.textContent = timeCreated - const timeModified = new Date(result.timeModified).toLocaleDateString( - 'sl-SL', - localeOptions - ) - td5.textContent = timeModified - aEl.classList.add('image-link') - aEl.type = 'link' - aEl.href = `/admin/slovarji/${result.id}/podatki` - imgEl.src = '/images/u_edit-alt.svg' - imgEl.alt = i18next.t('Uredi') - spanEl.className = 'normal-gray ms-1' - spanEl.textContent = i18next.t('Uredi') - td6.append(aEl) - aEl.append(imgEl, spanEl) - rowEl.append(td1, td2, td3, td4, td5, td6) - resultsListEl.appendChild(rowEl) - }) - } - } + // /admin/slovarji sorting/pagination logic lives in dictionary-list-table.js. if ( /\/admin\/slovarji\/\d+\/podatki/.test(currentPagePath) || @@ -291,24 +213,32 @@ function initAdmin() { const inputNewAuthorEl = document.getElementById('input-new-author') const inputNewAreaEl = document.getElementById('input-new-area') const dictSideMenu = document.querySelector('.admin-nav-content') - $('.without-addition').on('change', enableButton) + $('.without-addition').on('change', () => updateSaveButtonState(formEl)) unsavedData(formEl, dictSideMenu) - formEl.addEventListener('input', enableButton) + formEl.addEventListener('input', () => updateSaveButtonState(formEl)) if (imgTrashIcon !== null) { imgTrashIcon.forEach(el => el.addEventListener('click', deleteInput)) } inputNewAuthorEl.addEventListener('click', () => { createNewAuthorInput(formEl) + updateSaveButtonState(formEl) }) inputNewAreaEl.addEventListener('click', () => { createNewAreaInput(formEl) + updateSaveButtonState(formEl) }) formEl.addEventListener('submit', event => { - checkform() + // checkform() // Stray call left over from consultancy pages' #select-cerif; this form has no such element. if (!event.target.checkValidity()) { event.preventDefault() + event.target.classList.add('was-validated') + return } + event.preventDefault() event.target.classList.add('was-validated') + warnOnNameCollisionThenSubmit(event.target, { + excludeDictionaryId: document.getElementById('dictionary-id').value + }) }) } @@ -322,13 +252,11 @@ function initAdmin() { ce.domainLabelsForm = document.getElementById('dictionary-domain-labels') ce.domainLabelsForm.addEventListener('submit', secondaryDomainsToDb) const formAreas = document.getElementById('dictionary-domain-labels') - formAreas.addEventListener('input', enableButton) + formAreas.addEventListener('input', updateSecondaryDomainsButtonState) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(formAreas, dictSideMenu, secondaryDomainsToDb) - const addAreaButtons = document.getElementById('add-area') - addAreaButtons.addEventListener('click', enableButton) const useBtn = document.getElementById('modal-use-btn') - useBtn.addEventListener('click', enableButton) + useBtn.addEventListener('click', updateSecondaryDomainsButtonState) async function secondaryDomainsToDb(event) { const data = secondaryDomainsForChange() @@ -423,9 +351,10 @@ function initAdmin() { ce.terminologyReviewCb = document.getElementById('terminology_review') ce.languageReviewCb = document.getElementById('language_review') ce.formDictUsers = document.getElementById('admin-dictionary-users') - ce.formDictUsers.addEventListener('input', enableButton) + ce.formDictUsers.addEventListener('input', () => + updateSaveButtonState(ce.formDictUsers) + ) ce.formAddUser = document.getElementById('form-add-user') - ce.formAddUser.addEventListener('input', enableButton) ce.formAddUser.addEventListener('submit', addUser) checkUserRightsCb() const dictSideMenu = document.querySelector('.admin-nav-content') @@ -436,8 +365,6 @@ function initAdmin() { const arrAdminEls = Array.from(adminEl) arrAdminEls.forEach(el => el.addEventListener('click', () => countAdmins())) countAdmins() - const publishSwitch = document.getElementById('publish-switch') - publishSwitch.addEventListener('input', enableButton) async function addUser(event) { event.preventDefault() @@ -457,19 +384,26 @@ function initAdmin() { if (/\/admin\/uporabniki\/\d+\/urejanje/.test(currentPagePath)) { const formEditUser = document.getElementById('form-edit-user') - formEditUser.addEventListener('input', enableButton) + captureFormBaseline(formEditUser) + formEditUser.addEventListener('input', () => + updateSaveButtonState(formEditUser) + ) } if (currentPagePath === '/admin/nastavitve/portal') { const formAdminPortal = document.getElementById('admin-portal-settings') - formAdminPortal.addEventListener('input', enableButton) + formAdminPortal.addEventListener('input', () => + updateSaveButtonState(formAdminPortal) + ) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(formAdminPortal, dictSideMenu) } if (currentPagePath === '/admin/nastavitve/slovarji') { const formAdminPortal = document.getElementById('admin-settings-dict') - formAdminPortal.addEventListener('input', enableButton) + formAdminPortal.addEventListener('input', () => + updateSaveButtonState(formAdminPortal) + ) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(formAdminPortal, dictSideMenu) } @@ -479,7 +413,9 @@ function initAdmin() { const { offsetMain } = window.adminElements offsetMain.addEventListener('click', handleClick) const formAdminPortal = document.getElementById('admin-settings-consult') - formAdminPortal.addEventListener('input', enableButton) + formAdminPortal.addEventListener('input', () => + updateSaveButtonState(formAdminPortal) + ) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(formAdminPortal, dictSideMenu) } @@ -687,21 +623,17 @@ function checkConsultancyBtns() { function deleteInput({ target }) { const element = target.closest('.added-field') + const form = element.closest('form') const alertModal = new bootstrap.Modal(document.getElementById('alert-modal')) alertModal.toggle() const modalUseBtn = document.getElementById('modal-use-btn') modalUseBtn.addEventListener('click', () => { element.remove() alertModal.hide() - enableButton() + updateSaveButtonState(form) }) } -function enableButton() { - const disabledBtn = document.getElementById('disabled-submit-btn') - disabledBtn.disabled = false -} - function handleAreasClick({ target }) { const editRow = target.closest('.edit-row-btn') const deleteRow = target.closest('.delete-row-btn') @@ -717,11 +649,12 @@ function handleAreasClick({ target }) { } } if (deleteUserRow) { - enableButton() const getRow = deleteUserRow.parentElement.parentElement + const form = getRow.closest('form') const modalUseBtn = document.getElementById('modal-use-btn') modalUseBtn.addEventListener('click', () => { getRow.remove() + updateSaveButtonState(form) }) } if (deleteRow) { @@ -832,6 +765,7 @@ function handleAreasClick({ target }) { type: 'addArea' } secondaryDomainsForChange(data) + updateSecondaryDomainsButtonState() } } } @@ -875,6 +809,7 @@ function saveChanges( secondaryDomainsForChange(changed) } visibilityEl.disabled = true + updateSecondaryDomainsButtonState() } function initSecondaryDomainsForChange() { @@ -888,6 +823,18 @@ function initSecondaryDomainsForChange() { const secondaryDomainsForChange = initSecondaryDomainsForChange() +// secondaryDomainsForChange tracks add/edit/delete of a row separately from +// the form's own fields (added rows have no submittable inputs of their +// own), so dirty-checking here needs both: the form itself, and this queue. +function updateSecondaryDomainsButtonState() { + const { domainLabelsForm } = window.adminElements + if (isFormDirty(domainLabelsForm) || secondaryDomainsForChange().length > 0) { + enableButton() + } else { + disableButton() + } +} + function initTempCounter() { let counter = 0 return function (el) { @@ -919,6 +866,7 @@ function abortEditing(btnGrp, oldButtons, areaEl, translationEl) { translationEl.style.display = 'table-cell' const visibilityEl = getRow.querySelector('.form-check') visibilityEl.disabled = true + updateSecondaryDomainsButtonState() } function mobileMoveContent() { @@ -1188,8 +1136,9 @@ $('.summernote').summernote({ const profileForm = document.getElementById('profileForm') if (profileForm) { - profileForm.addEventListener('input', e => { - enableButton() + captureFormBaseline(profileForm) + profileForm.addEventListener('input', () => { + updateSaveButtonState(profileForm) }) profileForm.addEventListener('submit', async e => { @@ -1216,7 +1165,11 @@ $('.summernote').summernote({ return } - if (data.passwordOld && data.passwordNew && data.passwordNewRepeat) { + if (data.passwordNew && data.passwordNewRepeat) { + // passwordOld is intentionally not required here (it may legitimately be blank, e.g. + // for an SSO-only account with no local password) - the server tells the user exactly + // why it rejected the change (wrong old password, or no local password to change at + // all), which is more useful than a generic "fill in all fields" notice. await handleUpdatePassword(data) } else if (location.pathname === '/spremeni-geslo') { // if missing the required data on endpoint /spremeni-geslo, notify! diff --git a/express/public/javascripts/comments.js b/express/public/javascripts/comments.js index 031cd9e..23340cd 100644 --- a/express/public/javascripts/comments.js +++ b/express/public/javascripts/comments.js @@ -1,6 +1,6 @@ // TODO Remove no-console ignore rule once things are out of rapid dev phase. /* eslint no-console: 0 */ -/* global axios, initPagination, i18next */ +/* global axios, initPagination, i18next, DateUtils */ const pageURL = location.pathname window.addEventListener('load', () => { @@ -10,9 +10,12 @@ window.addEventListener('load', () => { function initComments() { const ce = {} window.commentElements = ce - ce.updatePager = initPagination('pagination', onPageChange) ce.commentsCountEl = document.getElementById('comments-count') ce.commentsContainerEl = document.getElementById('comments-container') + if (!ce.commentsContainerEl) { + return + } + ce.updatePager = initPagination('pagination', onCommentsPageChange) ce.commentForm = document.getElementById('comment-form') ce.commentReplyForm = document.getElementById('comment-reply-form') ce.commentMessageInput = document.getElementById('comment-message-input') @@ -37,15 +40,6 @@ function initComments() { ce.commentReplyInput.addEventListener('input', autoGrow) // ce.commentMessageInput.addEventListener('keydown', normalizeTextAreaSize) - window.commentSetting = {} - window.commentSetting.localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } - if (ce.commentMessageInput && ce.commentReplyInput) { ce.commentMessageInput.originalHeight = window.getComputedStyle( ce.commentMessageInput @@ -154,7 +148,6 @@ function renderCommentCount(commentCount) { function appendComment(comment) { const { commentsContainerEl, commentDiv } = window.commentElements - const { localeOptions } = window.commentSetting const { message, @@ -164,9 +157,7 @@ function appendComment(comment) { quote } = comment - let tstamp = new Date(timeCreated).toLocaleTimeString('sl-SL', localeOptions) - - tstamp = `• ${tstamp}` + const tstamp = `• ${DateUtils.formatDateTime(timeCreated)}` const divText = document.createElement('div') const divTextComment = document.createElement('div') const divRow = document.createElement('div') @@ -230,12 +221,7 @@ function appendComment(comment) { timeCreated } = quote - let tstamp = new Date(timeCreated).toLocaleTimeString( - 'sl-SL', - localeOptions - ) - - tstamp = `• ${tstamp}` + const tstamp = `• ${DateUtils.formatDateTime(timeCreated)}` const quoteText = document.createElement('div') const imgQuotemarks = document.createElement('img') @@ -411,7 +397,6 @@ function prepareReplyForm(repliedCommentData) { window.scrollTo(0, document.body.scrollHeight) const { commentForm, commentReplyForm, commentQuoteId, replyFormContainer } = window.commentElements - const { localeOptions } = window.commentSetting commentQuoteId.value = quoteId @@ -439,12 +424,7 @@ function prepareReplyForm(repliedCommentData) { quoteAuthorLastNameEl.textContent = quoteAuthorLastName quotePreview.appendChild(quoteAuthorLastNameEl) - let tstamp = new Date(quotetimeCreated).toLocaleTimeString( - 'sl-SL', - localeOptions - ) - - tstamp = `• ${tstamp}` + const tstamp = `• ${DateUtils.formatDateTime(quotetimeCreated)}` const quotetimeCreatedEl = document.createElement('p') quotetimeCreatedEl.className = 'comment-quote-time-created' quotetimeCreatedEl.textContent = tstamp @@ -569,10 +549,10 @@ function checkButton(type) { } async function changeEntryCommentSection() { - await onPageChange() + await onCommentsPageChange() } -async function onPageChange(newPage) { +async function onCommentsPageChange(newPage) { const { updatePager } = window.commentElements try { let { page, numberOfAllPages } = await displayComments(newPage) diff --git a/express/public/javascripts/consultancy.js b/express/public/javascripts/consultancy.js index 143e9e0..f58f0ae 100644 --- a/express/public/javascripts/consultancy.js +++ b/express/public/javascripts/consultancy.js @@ -1,5 +1,5 @@ /* global $, bootstrap, handleDomainsClickForConsultancy, initPagination, inputFieldsChecker, currentPagePath, -axios, nthParent, tooltipListWOL, tooltipTriggerList, removeAllChildNodes, i18next */ +axios, nthParent, tooltipListWOL, tooltipTriggerList, removeAllChildNodes, i18next, DateUtils */ /* author: Miha Stele, 2022 @@ -463,10 +463,14 @@ const initialPage = +new URL(location).searchParams.get('p') || 1 let updatePager try { - updatePager = initPagination('pagination', onPageChange, initialPage) + updatePager = initPagination( + 'pagination', + onConsultancyEntriesPageChange, + initialPage + ) } catch (e) {} -async function onPageChange(newPage) { +async function onConsultancyEntriesPageChange(newPage) { const receivedPageNumber = await changePage(newPage) updateUrlAndHistory(receivedPageNumber) } @@ -541,6 +545,7 @@ function renderResults(resultsMarkup) { const wrapper = document.createElement('div') wrapper.innerHTML = resultsMarkup resultsListEl.appendChild(wrapper) + DateUtils.applyTimestamps(wrapper) } function updateUrlAndHistory(page) { diff --git a/express/public/javascripts/date-utils.js b/express/public/javascripts/date-utils.js new file mode 100644 index 0000000..0f4223b --- /dev/null +++ b/express/public/javascripts/date-utils.js @@ -0,0 +1,67 @@ +const dateLocaleByLang = { + sl: 'sl-SI', + en: 'en-GB' +} + +const dateOnlyOptions = { day: '2-digit', month: '2-digit', year: 'numeric' } +const timeOnlyOptions = { hour: '2-digit', minute: '2-digit' } +const dateTimeOptions = { ...dateOnlyOptions, ...timeOnlyOptions } + +function getDateLocale() { + const lang = document.documentElement.lang || 'sl' + return dateLocaleByLang[lang] || dateLocaleByLang.sl +} + +function toDateOrNull(value) { + const date = value instanceof Date ? value : new Date(value) + return isNaN(date.getTime()) ? null : date +} + +function formatDate(value) { + const date = toDateOrNull(value) + return date ? date.toLocaleDateString(getDateLocale(), dateOnlyOptions) : '' +} + +function formatTime(value) { + const date = toDateOrNull(value) + return date ? date.toLocaleTimeString(getDateLocale(), timeOnlyOptions) : '' +} + +function formatDateTime(value) { + const date = toDateOrNull(value) + return date ? date.toLocaleString(getDateLocale(), dateTimeOptions) : '' +} + +// Scans `root` (defaults to the whole document) for elements carrying a +// data-timestamp attribute and fills them in using the browser's own +// timezone. Call this again after injecting server-rendered HTML fragments +// (e.g. AJAX-paginated results), since it only runs automatically once on +// page load. +function applyTimestamps(root) { + const scope = root || document + scope.querySelectorAll('[data-timestamp]').forEach(el => { + const date = toDateOrNull(el.getAttribute('data-timestamp')) + if (!date) return + + const datePart = el.querySelector('[data-timestamp-part="date"]') + const timePart = el.querySelector('[data-timestamp-part="time"]') + + if (datePart || timePart) { + if (datePart) datePart.textContent = formatDate(date) + if (timePart) timePart.textContent = formatTime(date) + } else if (el.getAttribute('data-timestamp-format') === 'date') { + el.textContent = formatDate(date) + } else { + el.textContent = formatDateTime(date) + } + }) +} + +window.DateUtils = { + formatDate, + formatTime, + formatDateTime, + applyTimestamps +} + +window.addEventListener('load', () => applyTimestamps()) diff --git a/express/public/javascripts/dictionaries.js b/express/public/javascripts/dictionaries.js index 61aecb5..3b3d9e0 100644 --- a/express/public/javascripts/dictionaries.js +++ b/express/public/javascripts/dictionaries.js @@ -1,4 +1,4 @@ -/* global $, axios, bootstrap, currentPagePath, initPagination, removeAllChildNodes, unsavedData, replaceContainer, i18next */ +/* global $, axios, bootstrap, currentPagePath, initPagination, removeAllChildNodes, unsavedData, replaceContainer, i18next, DateUtils, captureFormBaseline, isFormDirty, updateSaveButtonState, enableButton, disableButton, warnOnNameCollisionThenSubmit */ // Temporary workaround (use of currentPagePath). @@ -11,6 +11,7 @@ let queryBattery = '' function initDictionaries() { const ce = {} window.dictionaryElements = ce + let confirmedVersionId = 'latest-version' ce.textDescription = document.getElementById('text-description') ce.headerTitle = document.getElementById('site-header-title') ce.fixedTopSection = document.getElementById('fixed-top-section') @@ -23,10 +24,7 @@ function initDictionaries() { mobileMoveContent() adjustOffsetBy() window.onscroll = hideAndShowHeader - if ( - /\/slovarji\/\d+\/podatki/.test(currentPagePath) || - currentPagePath === '/slovarji/nov' - ) { + if (currentPagePath === '/slovarji/nov') { ce.inputNewAuthor = document.getElementById('input-new-author') ce.inputNewArea = document.getElementById('input-new-area') } @@ -66,8 +64,12 @@ function initDictionaries() { checkLanguages() if (!event.target.checkValidity()) { event.preventDefault() + event.target.classList.add('was-validated') + return } + event.preventDefault() event.target.classList.add('was-validated') + warnOnNameCollisionThenSubmit(event.target) }) } @@ -78,6 +80,7 @@ function initDictionaries() { ce.dictionaryStructureForm = document.getElementById( 'form-dictionary-structure' ) + captureFormBaseline(ce.dictionaryStructureForm) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(ce.dictionaryStructureForm, dictSideMenu) ce.checkLanguageGroup = document.getElementById('language-group') @@ -92,10 +95,13 @@ function initDictionaries() { 'synonym-language-subgroup' ) - // jquery event listener for a select2 field - $('.multiple').on('change', enableButton) + $('#languages-input').on('select2:select select2:unselect', () => + updateSaveButtonState(ce.dictionaryStructureForm) + ) - ce.dictionaryStructureForm.addEventListener('input', enableButton) + ce.dictionaryStructureForm.addEventListener('input', () => + updateSaveButtonState(ce.dictionaryStructureForm) + ) ce.definitionCheckBox = document.getElementById('definition-check-box') ce.submitDictionaryBtn = document.getElementById('submit-dictionary-btn') ce.checkLanguageGroup.addEventListener('click', checkBoxLanguageChecker) @@ -111,54 +117,14 @@ function initDictionaries() { }) } - if (/\/slovarji\/\d+\/podatki/.test(currentPagePath)) { - ce.descriptionDictionaryForm = document.getElementById( - 'form-dictionary-description' - ) - ce.descriptionDictionaryForm.addEventListener('input', enableButton) - const dictSideMenu = document.querySelector('.admin-nav-content') - unsavedData(ce.descriptionDictionaryForm, dictSideMenu) - ce.inputElements = document.querySelectorAll('input') - ce.imgTrashIcon = document.querySelectorAll('.delete-author-btn') - ce.inputElements.forEach(el => el.addEventListener('input', enableButton)) - ce.inputElements.forEach(el => el.addEventListener('change', enableButton)) - ce.inputNewAuthor.addEventListener('click', () => { - addField(ce.descriptionDictionaryForm, ce.inputNewAuthor) - }) - ce.inputNewAuthor.addEventListener('click', enableButton) - ce.inputNewArea.addEventListener('click', () => { - createNewAreaInput(ce.descriptionDictionaryForm) - }) - ce.inputNewArea.addEventListener('click', enableButton) - if (ce.imgTrashIcon !== null) { - ce.imgTrashIcon.forEach(el => el.addEventListener('click', deleteField)) - ce.imgTrashIcon.forEach(el => el.addEventListener('click', enableButton)) - } - - // jquery event listener for select2 fields - $('.without-addition').on('change', enableButton) - $('.multiple').on('change', enableButton) - - // JQuery for summernote text editor - $('.summernote').on('summernote.change', enableButton) - - ce.descriptionDictionaryForm.addEventListener('submit', event => { - // checkform() - if (!event.target.checkValidity()) { - event.preventDefault() - } - event.target.classList.add('was-validated') - }) - } - if (/\/slovarji\/\d+\/uvoz\/datoteka/.test(currentPagePath)) { ce.fileUploadInput = document.getElementById('upload') const btnImportEl = document.getElementById('button-import') btnImportEl.addEventListener('click', () => ce.fileUploadInput.click()) const fileUploadInputValue = ce.fileUploadInput.value const chosenFile = document.getElementById('chosen-file') - const fileTypeSelectionContainer = document.getElementById( - 'file-type-selection' + const fileFormatSelectionContainer = document.getElementById( + 'file-format-selection' ) ce.fileImportForm = document.getElementById('file-import-form') @@ -173,10 +139,19 @@ function initDictionaries() { } }) - fileTypeSelectionContainer.addEventListener( - 'change', - updateAcceptedFileTypes - ) + fileFormatSelectionContainer.addEventListener('change', () => { + updateAcceptedFileTypes() + updateEntryStatusAvailability() + }) + updateEntryStatusAvailability() + + function updateEntryStatusAvailability() { + const isJsonFormat = + ce.fileImportForm.importFileFormat.value === 'json_term_candidates' + for (const radio of ce.fileImportForm.entryStatus) { + radio.disabled = isJsonFormat + } + } ce.fileImportForm.addEventListener('submit', submitFormMultipart) @@ -187,74 +162,25 @@ function initDictionaries() { await axios.post(event.target.action, payload) - alert(i18next.t('SLOVAR UVOŽEN')) + showImportResponseModal(i18next.t('SLOVAR UVOŽEN')) + onPageChange(1) } catch (error) { - alert(i18next.t('NAPAKA V UVOZU')) + showImportResponseModal(i18next.t('NAPAKA V UVOZU')) } } - { - const resultsListEl = document.getElementById('page-results') - const dictionaryId = document.getElementById('dictionary-id').value - - const updatePager = initPagination('pagination', onPageChange) - - async function onPageChange(newPage) { - try { - const { page, numberOfAllPages, results } = await getDataForPage( - newPage - ) - removeAllChildNodes(resultsListEl) - renderResults(results) - updatePager(page, numberOfAllPages) - } catch (error) { - let message = i18next.t('Prišlo je do napake.') - if (error.response?.data) { - message = error.response.data - } else if (error.request) { - message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') - } - alert(message) - updatePager() - } - } - - async function getDataForPage(page) { - const url = `/api/v1/dictionaries/${dictionaryId}/showImportFromFileForm?p=${page}` - const { data } = await axios.get(url) - return data - } - - function renderResults(results) { - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } - results.forEach(result => { - const rowEl = document.createElement('tr') - const td1 = document.createElement('td') - const td2 = document.createElement('td') - const td3 = document.createElement('td') - const td4 = document.createElement('td') - const date = new Date(result.time_started).toLocaleDateString( - 'sl-SL', - localeOptions - ) - td1.textContent = date - td2.textContent = result.file_format - td3.textContent = result.count_valid_entries - td4.textContent = result.status - rowEl.append(td1, td2, td3, td4) - resultsListEl.appendChild(rowEl) - }) - } + function showImportResponseModal(message) { + const modalEl = document.getElementById('import-response-modal') + modalEl.querySelector('#response-modal-text').textContent = message + new bootstrap.Modal(modalEl).toggle() + } + + const IMPORT_STATUS_KEYS = { + 'in progress': 'importStatusInProgress', + error: 'importStatusError', + done: 'importStatusDone' } - } - if (/\/slovarji\/\d+\/izvoz/.test(currentPagePath)) { const resultsListEl = document.getElementById('page-results') const dictionaryId = document.getElementById('dictionary-id').value @@ -281,44 +207,174 @@ function initDictionaries() { } async function getDataForPage(page) { - const url = `/api/v1/dictionaries/${dictionaryId}/showExportToFileForm?p=${page}` + const url = `/api/v1/dictionaries/${dictionaryId}/showImportFromFileForm?p=${page}` const { data } = await axios.get(url) return data } function renderResults(results) { - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } results.forEach(result => { const rowEl = document.createElement('tr') const td1 = document.createElement('td') const td2 = document.createElement('td') const td3 = document.createElement('td') const td4 = document.createElement('td') - const date = new Date(result.time_created).toLocaleDateString( - 'sl-SL', - localeOptions + td1.textContent = DateUtils.formatDateTime(result.time_started) + td2.textContent = result.file_format + td3.textContent = result.count_entries + td4.textContent = i18next.t(IMPORT_STATUS_KEYS[result.status]) + rowEl.append(td1, td2, td3, td4) + resultsListEl.appendChild(rowEl) + }) + } + } + + if (/\/slovarji\/\d+\/izvoz/.test(currentPagePath)) { + const EXPORT_POLL_INTERVAL_MS = 2000 + const EXPORT_POLL_MAX_ATTEMPTS = 150 // ~5 minutes, then give up quietly + + const exportForm = document.forms['dictionary-export'] + + exportForm.addEventListener('submit', async event => { + event.preventDefault() + + const payload = Object.fromEntries(new FormData(event.target)) + payload.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone + + try { + await axios.post(event.target.action, payload) + pollExportsUntilFinished() + } catch (error) { + let message = i18next.t('Prišlo je do napake.') + if (error.response) { + message = error.response.data + } else if (error.request) { + message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') + } + showExportResponseModal(message) + } + }) + + function showExportResponseModal(message) { + const modalEl = document.getElementById('export-response-modal') + modalEl.querySelector('#response-modal-text').textContent = message + new bootstrap.Modal(modalEl).toggle() + } + + async function pollExportsUntilFinished( + remainingAttempts = EXPORT_POLL_MAX_ATTEMPTS + ) { + if (remainingAttempts <= 0) return + const results = await onPageChange(1) + const stillProcessing = results?.some( + result => result.status === 'pending' || result.status === 'in progress' + ) + if (stillProcessing) { + setTimeout( + () => pollExportsUntilFinished(remainingAttempts - 1), + EXPORT_POLL_INTERVAL_MS ) - td1.textContent = date + } + } + + const EXPORT_STATUS_KEYS = { + pending: 'exportStatusPending', + 'in progress': 'exportStatusInProgress', + failed: 'exportStatusFailed' + } + + const resultsListEl = document.getElementById('page-results') + const dictionaryId = document.getElementById('dictionary-id').value + + const updatePager = initPagination('pagination', onPageChange) + + async function onPageChange(newPage) { + try { + const { page, numberOfAllPages, results } = await getDataForPage( + newPage + ) + removeAllChildNodes(resultsListEl) + renderResults(results) + updatePager(page, numberOfAllPages) + return results + } catch (error) { + let message = i18next.t('Prišlo je do napake.') + if (error.response?.data) { + message = error.response.data + } else if (error.request) { + message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') + } + alert(message) + updatePager() + } + } + + async function getDataForPage(page) { + const url = `/api/v1/dictionaries/${dictionaryId}/showExportToFileForm?p=${page}` + const { data } = await axios.get(url) + return data + } + + function renderResults(results) { + results.forEach(result => { + const rowEl = document.createElement('tr') + const td1 = document.createElement('td') + const td2 = document.createElement('td') + const td3 = document.createElement('td') + const td4 = document.createElement('td') + td1.textContent = DateUtils.formatDateTime(result.time_created) td2.textContent = result.export_file_format td3.textContent = result.entry_count if (result.status === 'finished') { + const wrapperEl = document.createElement('div') + wrapperEl.className = 'd-flex align-items-center' + const aEl = document.createElement('a') aEl.href = `/slovarji/export-download/${result.id}` aEl.textContent = i18next.t('Shrani') aEl.className = 'btn btn-primary' - td4.append(aEl) - } else td4.textContent = '' + wrapperEl.append(aEl) + + const deleteImgEl = document.createElement('img') + deleteImgEl.src = '/images/red-trash-icon.svg' + deleteImgEl.alt = i18next.t('Izbriši') + const deleteBtnEl = document.createElement('button') + deleteBtnEl.type = 'button' + deleteBtnEl.className = 'p-0 table-button-grp delete-row-btn ms-3' + deleteBtnEl.setAttribute('data-bs-target', '#alert-modal') + deleteBtnEl.setAttribute('data-bs-toggle', 'modal') + deleteBtnEl.dataset.exportId = result.id + deleteBtnEl.append(deleteImgEl) + wrapperEl.append(deleteBtnEl) + + td4.append(wrapperEl) + } else td4.textContent = i18next.t(EXPORT_STATUS_KEYS[result.status]) rowEl.append(td1, td2, td3, td4) resultsListEl.appendChild(rowEl) }) } + + resultsListEl.addEventListener('click', handleExportResultsClick) + + function handleExportResultsClick({ target }) { + const deleteBtn = target.closest('.delete-row-btn') + if (!deleteBtn) return + + const rowEl = deleteBtn.closest('tr') + const exportId = deleteBtn.dataset.exportId + + document.getElementById('modal-use-btn').onclick = async () => { + try { + await axios.delete( + `/api/v1/dictionaries/${dictionaryId}/export/${exportId}` + ) + rowEl.remove() + } catch { + showExportResponseModal(i18next.t('Prišlo je do napake.')) + } + } + } } if (/\/slovarji\/\d+\/vsebina/.test(currentPagePath)) { @@ -340,7 +396,7 @@ function initDictionaries() { ce.selectAllDates = document.querySelectorAll('input[name=date]') ce.classicOverview = document.getElementById('classic-overview') // ce.selectedOverview = document.getElementById('selected-date-overview') - ce.btnSaveIcon = document.getElementById('btn-save-icon') + ce.btnSaveIcon = document.getElementById('disabled-submit-btn') ce.filterCheckBoxes = document.querySelectorAll('.indeterminate-cbox') ce.showFilterBtn = document.getElementById('show-filter') ce.explanationField = document.getElementById('explanation-field') @@ -363,7 +419,10 @@ function initDictionaries() { ce.clearSearchInput = document.querySelector('.clear-search-input') ce.collapsablePart = document.querySelectorAll('.collapsable-entry-part') ce.scrollEl = document.querySelector('.content-nav-content') - $('.multiple').on('select2:select', enableButton) + $('.multiple, .without-dropdown').on( + 'select2:select select2:unselect', + onFormEdited + ) ce.collapsablePart.forEach(el => { el.addEventListener('hide.bs.collapse', () => changePageContent('collapse-hidden') @@ -415,16 +474,16 @@ function initDictionaries() { ce.showDates.addEventListener('click', () => changePageContent(ce.showDates.id) ) - ce.selectAllDates.forEach(el => - el.addEventListener('click', () => showSelectedDateData(el)) - ) ce.filterCheckBoxes.forEach(el => el.addEventListener('click', () => indeterminateTheBox(el)) ) ce.showFilterBtn.addEventListener('click', () => changePageContent(ce.showFilterBtn.getAttribute('aria-expanded')) ) - ce.formEditContent.addEventListener('input', enableButton) + ce.formEditContent.addEventListener('input', onFormEdited) + document + .getElementById('alert-modal') + .addEventListener('hidden.bs.modal', onFormEdited) ce.resizeFields = document.querySelectorAll('.explanation-field') if (ce.resizeFields.length) { ce.resizeFields.forEach(el => @@ -436,26 +495,30 @@ function initDictionaries() { ce.resizeFields.forEach(el => el.dispatchEvent(eventText)) const mcBtnsGrp = document.querySelectorAll('.mc-buttons-group') if (mcBtnsGrp.length) { - mcBtnsGrp.forEach(e => e.addEventListener('click', enableButton)) + mcBtnsGrp.forEach(e => e.addEventListener('click', onFormEdited)) } if (ce.newHeadwordGroupBtn) ce.newHeadwordGroupBtn.addEventListener('click', createHeadword) if (ce.newConnectionBtn) - ce.newConnectionBtn.addEventListener('click', () => + ce.newConnectionBtn.addEventListener('click', () => { addConnectionField(ce.formEditContent, ce.newConnectionBtn) - ) + onFormEdited() + }) if (ce.newImageBtn) - ce.newImageBtn.addEventListener('click', () => + ce.newImageBtn.addEventListener('click', () => { addField(ce.formEditContent, ce.newImageBtn) - ) + onFormEdited() + }) if (ce.newAudioBtn) - ce.newAudioBtn.addEventListener('click', () => + ce.newAudioBtn.addEventListener('click', () => { addField(ce.formEditContent, ce.newAudioBtn) - ) + onFormEdited() + }) if (ce.newVideoBtn) - ce.newVideoBtn.addEventListener('click', () => + ce.newVideoBtn.addEventListener('click', () => { addField(ce.formEditContent, ce.newVideoBtn) - ) + onFormEdited() + }) ce.statusEditEl.addEventListener('change', () => checkIfValid()) ce.termInputField.addEventListener('input', () => checkIfValid()) if (ce.definitionField !== null) @@ -532,7 +595,6 @@ function initDictionaries() { } } - let unsaved = false ce.deleteEntryBtn.addEventListener('click', handleClick) // Ajax render entry data const messageContainer = document.querySelectorAll('.message-container') @@ -549,7 +611,7 @@ function initDictionaries() { const versionEl = target.closest('.date-element') const deleteEntryEl = target.closest('#delete-entry') if (term) { - if (unsaved) { + if (isFormDirty(window.dictionaryElements.formEditContent)) { const modalUseBtn = document.getElementById('modal-use-btn') const modalCnclBtn = document.getElementById('modal-cancel-btn') const modalMain = document.getElementById('alert-text') @@ -571,7 +633,6 @@ function initDictionaries() { updateEntry(event, termId) renderTermData(termId, event) activateMe(term) - disableButton() term.classList.add('selected-term-btn') modalUseBtn.textContent = okBtnText modalCnclBtn.textContent = cnclBtnTxt @@ -581,7 +642,6 @@ function initDictionaries() { const termId = term.getAttribute('data-term-id') renderTermData(termId, event) activateMe(term) - disableButton() term.classList.add('selected-term-btn') modalUseBtn.textContent = okBtnText modalCnclBtn.textContent = cnclBtnTxt @@ -591,7 +651,6 @@ function initDictionaries() { const termId = term.getAttribute('data-term-id') renderTermData(termId, event) activateMe(term) - disableButton() term.classList.add('selected-term-btn') } } @@ -637,9 +696,16 @@ function initDictionaries() { const info = new FormData(formEditContent) info.append('isPublishedEl', isPublishedEl) loadPreview(info) + updateSaveButtonState(formEditContent) + showSelectedDateData() + confirmedVersionId = versionId } catch (error) { console.log(error) alert('Prišlo je do napake.') + const confirmedRadio = document.querySelector( + `input[name="date"][value="${confirmedVersionId}"]` + ) + if (confirmedRadio) confirmedRadio.checked = true } } @@ -666,7 +732,7 @@ function initDictionaries() { loadPreview(info) changeVersionList(data.entry.versions) setLatestVersion(data.entry) - ce.formEditContent.addEventListener('input', () => (unsaved = true)) + confirmedVersionId = 'latest-version' formEditContent.dataset.entryId = entryId formEditContent.action = '/api/v1/entries/update' previewBtnEl.disabled = false @@ -679,9 +745,18 @@ function initDictionaries() { deleteEntry.disabled = false changeCollapsedContent() checkIfValid() - unsaved = false + captureFormBaseline(formEditContent) + if (!ce.btnSaveIcon.classList.contains('saved-entry-btn')) { + disableButton() + ce.btnSaveIcon.textContent = i18next.t('Shrani') + } } catch (error) { console.log(error) + alert('Prišlo je do napake.') + const confirmedRadio = document.querySelector( + `input[name="date"][value="${confirmedVersionId}"]` + ) + if (confirmedRadio) confirmedRadio.checked = true } finally { resizeFields.forEach(el => autoResize(el)) window.scrollTo({ top: 0, behavior: 'smooth' }) @@ -690,11 +765,6 @@ function initDictionaries() { function insertTermData(entryId, data, vAuthor) { const { newConnectionBtn } = window.dictionaryElements - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric' - } const termName = document.getElementById('term-name') const domainsSecondary = $('#domain-secondary') const label = document.getElementById('explanation-field') @@ -733,10 +803,9 @@ function initDictionaries() { linkRow ) if (data.entry.time_modified) { - const dateModified = new Date( + latestVersionLabel.textContent = DateUtils.formatDate( data.entry.time_modified - ).toLocaleDateString('sl-SL', localeOptions) - latestVersionLabel.textContent = dateModified + ) } if (entryId) for (let i = 0; i < termIdText.length; i++) { @@ -798,7 +867,7 @@ function initDictionaries() { } }) } - if (data.entry.links) { + if (data.entry.links && linkRow) { data.entry.links.forEach((el, index) => { if (index > 0) { addConnectionField(ce.formEditContent, newConnectionBtn, el) @@ -902,10 +971,13 @@ function initDictionaries() { payload.set('entryId', entryId) try { saveBtn.textContent = i18next.t('Shranjujem ...') + saveBtn.disabled = true await axios.post(ce.formEditContent.action, payload) spinnerEl.classList.remove('d-none') saveBtn.classList.add('saved-entry-btn') + saveBtn.disabled = false saveBtn.textContent = i18next.t('Shranjeno') + captureFormBaseline(ce.formEditContent) if (id != null) entryId = id ajaxSideMenu(entryId) } catch (error) { @@ -916,16 +988,21 @@ function initDictionaries() { message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') } messageContainer.textContent = message + updateSaveButtonState(ce.formEditContent) + saveBtn.textContent = i18next.t('Shrani') } } else { event.preventDefault() const payload = new URLSearchParams(new FormData(ce.formEditContent)) try { saveBtn.textContent = i18next.t('Shranjujem ...') + saveBtn.disabled = true const res = await axios.post(ce.formEditContent.action, payload) spinnerEl.classList.remove('d-none') saveBtn.classList.add('saved-entry-btn') + saveBtn.disabled = false saveBtn.textContent = i18next.t('Shranjeno') + captureFormBaseline(ce.formEditContent) let entryId = res.data.entryId if (id != null) entryId = id ajaxSideMenu(entryId) @@ -937,6 +1014,8 @@ function initDictionaries() { message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') } messageContainer.textContent = message + updateSaveButtonState(ce.formEditContent) + saveBtn.textContent = i18next.t('Shrani') } finally { changePageContent('first') } @@ -1069,11 +1148,10 @@ function initDictionaries() { ce.domainLabelsForm.addEventListener('submit', domainLabelsToDb) const addAreaBtn = document.getElementById('add-area') addAreaBtn.addEventListener('click', () => subareasContent(noSubareas)) - addAreaBtn.addEventListener('click', enableButton) const formLabes = document.getElementById('dictionary-domain-labels') - formLabes.addEventListener('input', enableButton) + formLabes.addEventListener('input', updateDomainLabelsButtonState) const useBtn = document.getElementById('modal-use-btn') - useBtn.addEventListener('click', enableButton) + useBtn.addEventListener('click', updateDomainLabelsButtonState) const dictSideMenu = document.querySelector('.admin-nav-content') unsavedData(ce.domainLabelsForm, dictSideMenu, domainLabelsToDb) async function domainLabelsToDb(event) { @@ -1305,6 +1383,9 @@ function adjustOffsetBy() { function hideAndShowHeader() { const { textDescription, headerTitle } = window.dictionaryElements + // Pages without the side-menu structure (e.g. /slovarji, /svetovanje) + // don't have #site-header-title/#text-description - nothing to show/hide. + if (!textDescription || !headerTitle) return if (!/\/slovarji\/\d+\/vsebina/.test(currentPagePath)) { if (document.documentElement.scrollTop < 50) { textDescription.style.display = 'block' @@ -1323,11 +1404,22 @@ function mobileMoveContent() { const secondaryButton = document.querySelector('.header-btn-secondary') const primaryButton = document.querySelector('.header-btn') const siteHeading = document.getElementById('site-heading') - const siteHeadingTextContent = siteHeading.textContent const navTitle = document.getElementById('nav-title') const headerContainerRight = document.querySelector( '.header-container-divider-right' ) + // Pages without the side-menu structure (e.g. /slovarji, /svetovanje) + // don't have these elements - nothing to reposition/show-hide there. + if ( + !adminNavMobileEl || + !mobileRightHolder || + !siteHeading || + !navTitle || + !headerContainerRight + ) { + return + } + const siteHeadingTextContent = siteHeading.textContent if (document.body.clientWidth <= 1200) { if (secondaryButton) { mobileRightHolder.appendChild(secondaryButton) @@ -1552,6 +1644,9 @@ function checkBoxLanguageChecker() { synonymLanguageSubgroup.classList.add('disabled-input') definitionCheckBox.classList.add('disabled-input') } + + const { dictionaryStructureForm } = window.dictionaryElements + if (dictionaryStructureForm) updateSaveButtonState(dictionaryStructureForm) } function checkBoxDefinitionChecker() { @@ -1566,22 +1661,9 @@ function checkBoxDefinitionChecker() { } } -function enableButton() { - const disabledBtn = document.getElementById('disabled-submit-btn') - disabledBtn.disabled = false - if (disabledBtn.classList.contains('saved-entry-btn')) { - disabledBtn.classList.remove('saved-entry-btn') - disabledBtn.textContent = 'Shrani' - } -} - -function disableButton() { - const disabledBtn = document.getElementById('disabled-submit-btn') - disabledBtn.disabled = true - if (disabledBtn.classList.contains('saved-entry-btn')) { - disabledBtn.classList.remove('saved-entry-btn') - disabledBtn.textContent = 'Shrani' - } +function onFormEdited() { + updateSaveButtonState(window.dictionaryElements.formEditContent) + window.dictionaryElements.btnSaveIcon.textContent = i18next.t('Shrani') } function changePageContent(el) { @@ -1680,9 +1762,6 @@ function changePageContent(el) { selectAllDates.forEach(el => (el.checked = false)) showDates.firstChild.src = '/images/fi_blue-calendar.svg' showDates.id = 'show-dates' - btnSaveIcon.firstChild.src = '/images/fi_save.svg' - btnSaveIcon.children[1].textContent = 'Shrani' - btnSaveIcon.id = 'btn-save-icon' break case 'new-entry-btn': { // formEditContent.reset() @@ -1728,13 +1807,16 @@ function changePageContent(el) { const messageContainer = document.querySelectorAll('.message-container') messageContainer.forEach(el => el.classList.add('d-none')) window.scrollTo({ top: 0, behavior: 'smooth' }) - selectedEntry.classList.remove('selected-term-btn') + if (selectedEntry) selectedEntry.classList.remove('selected-term-btn') $('.multiple').val(null).trigger('change') $('.without-dropdown').val(null).trigger('change') // editBtnEl.click() // termInputField.addEventListener('focus', () => // showMCButtons(termInputField, 'link') // ) + captureFormBaseline(formEditContent) + disableButton() + btnSaveIcon.textContent = i18next.t('Shrani') termInputField.focus() termInputField.click() @@ -1786,7 +1868,7 @@ function changePageContent(el) { editBtnEl.click() termInputField.focus() window.scrollTo({ top: 0, behavior: 'smooth' }) - selectedEntry.classList.remove('selected-term-btn') + if (selectedEntry) selectedEntry.classList.remove('selected-term-btn') editBtnEl.click() responseModal.toggle() duplicateEntry.disabled = true @@ -1977,7 +2059,7 @@ function loadPreview(info) { } } else changeClasses(previewLinkedTerms, 'hide') - if (foreignTerm) { + if (foreignTerm.length) { listForeignTerm.forEach(el => (el.textContent = '')) foreignTerm.forEach(el => { if (listForeignTerm.length) { @@ -1997,7 +2079,7 @@ function loadPreview(info) { else changeClasses(el.parentElement.parentElement, 'hide') }) } - if (foreignDef) { + if (foreignDef.length) { listForeignDefinitions.forEach(el => (el.textContent = '')) foreignDef.forEach(el => { if (listForeignDefinitions.length) { @@ -2015,7 +2097,7 @@ function loadPreview(info) { }) } - if (foreignSyn) { + if (foreignSyn.length) { listForeignSynonyms.forEach(el => (el.textContent = '')) foreignSyn.forEach(el => { if (listForeignSynonyms.length) { @@ -2038,7 +2120,7 @@ function loadPreview(info) { const languageContainers = document.querySelectorAll('.preview-one-language') const langLine = document.querySelector('.start-line') - if (languageContainers) { + if (languageContainers.length) { const arrLang = Array.from(languageContainers) arrLang.forEach(el => { const arrChildren = Array.from(el.children) @@ -2046,12 +2128,14 @@ function loadPreview(info) { el.classList.add('d-none') } else el.classList.remove('d-none') }) - if ( - arrLang.filter(el => el.classList.contains('d-none')).length >= - arrLang.length - ) { - langLine.classList.add('d-none') - } else langLine.classList.remove('d-none') + if (langLine) { + if ( + arrLang.filter(el => el.classList.contains('d-none')).length >= + arrLang.length + ) { + langLine.classList.add('d-none') + } else langLine.classList.remove('d-none') + } } changeCollapsedContent() } @@ -2080,11 +2164,6 @@ function changeVersionList(versions) { el.remove() } }) - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric' - } if (versions.length) { versions .slice() @@ -2100,11 +2179,7 @@ function changeVersionList(versions) { dateLabel.dataset.bsPlacement = 'bottom' dateLabel.dataset.bsToggle = 'tooltip' dateLabel.dataset.bsHtml = 'true' - const date = new Date(el.version_time).toLocaleDateString( - 'sl-SL', - localeOptions - ) - dateLabel.textContent = date + dateLabel.textContent = DateUtils.formatDate(el.version_time) dateRadio.id = `date${el.version}` dateRadio.value = `${el.version}` dateLabel.htmlFor = `date${el.version}` @@ -2150,15 +2225,14 @@ function setLatestVersion(data) { } function removeOldMedia(images, audio, video) { - if (images !== null || audio !== null || video !== null) { - const media = [images, audio, video] - media.forEach(el => { - const arrChildren = Array.from(el.childNodes) - arrChildren.forEach(el => { - el.remove() - }) + const media = [images, audio, video] + media.forEach(el => { + if (!el) return + const arrChildren = Array.from(el.childNodes) + arrChildren.forEach(el => { + el.remove() }) - } + }) } function changeClasses(el, elClass) { @@ -2199,14 +2273,9 @@ function letsScroll(btn) { } } -function showSelectedDateData(date) { +function showSelectedDateData() { const { btnSaveIcon } = window.dictionaryElements - - // classicOverview.classList.add('d-none') - // selectedOverview.classList.remove('d-none') - btnSaveIcon.firstChild.src = '/images/u_redo.svg' - btnSaveIcon.children[1].textContent = i18next.t('Obnovi') - btnSaveIcon.id = 'redo-action' + btnSaveIcon.textContent = i18next.t('Obnovi') } function indeterminateTheBox(checkbox) { @@ -2615,6 +2684,7 @@ function handleAreasClick({ target }) { type: 'addArea' } domainLabelsForChange(data) + updateDomainLabelsButtonState() } } } @@ -2746,6 +2816,7 @@ function abortEditing(btnGrp, oldButtons, areaEl) { areaEl.style.display = 'table-cell' const visibilityEl = getRow.querySelector('.form-check') visibilityEl.disabled = true + updateDomainLabelsButtonState() } function saveChanges(btnGrp, inputArea, oldButtons, tDataArea) { @@ -2774,6 +2845,7 @@ function saveChanges(btnGrp, inputArea, oldButtons, tDataArea) { domainLabelsForChange(changed) } visibilityEl.disabled = true + updateDomainLabelsButtonState() } function initDomainLabelsForChange() { @@ -2787,6 +2859,18 @@ function initDomainLabelsForChange() { const domainLabelsForChange = initDomainLabelsForChange() +// domainLabelsForChange tracks add/edit/delete of a row separately from the +// form's own fields (added rows have no submittable inputs of their own), +// so dirty-checking here needs both: the form itself, and this queue. +function updateDomainLabelsButtonState() { + const { domainLabelsForm } = window.dictionaryElements + if (isFormDirty(domainLabelsForm) || domainLabelsForChange().length > 0) { + enableButton() + } else { + disableButton() + } +} + function initTempCounter() { let counter = 0 return function (el) { @@ -2810,14 +2894,16 @@ function deleteContentData( ) { const addedFields = document.querySelectorAll('.added-field') if (addedFields.length) addedFields.forEach(el => el.remove()) - if (domainLabels) domainLabels.val(null).trigger('change') - if (domainLabels) domainLabels.empty().trigger('change') - if (synonym) synonym.val(null).trigger('change') - if (synonym) synonym.empty().trigger('change') - if (listForeignTerms) $('.foreign-term-el').val(null).trigger('change') - if (listForeignTerms) $('.foreign-term-el').empty().trigger('change') - if (listForeignSynonyms) $('.foreign-synonym-el').val(null).trigger('change') - if (listForeignSynonyms) $('.foreign-synonym-el').empty().trigger('change') + if (domainLabels.length) domainLabels.val(null).trigger('change') + if (domainLabels.length) domainLabels.empty().trigger('change') + if (synonym.length) synonym.val(null).trigger('change') + if (synonym.length) synonym.empty().trigger('change') + if (listForeignTerms.length) $('.foreign-term-el').val(null).trigger('change') + if (listForeignTerms.length) $('.foreign-term-el').empty().trigger('change') + if (listForeignSynonyms.length) + $('.foreign-synonym-el').val(null).trigger('change') + if (listForeignSynonyms.length) + $('.foreign-synonym-el').empty().trigger('change') if (images) images.value = '' if (audio) audio.value = '' if (video) video.value = '' @@ -2827,7 +2913,7 @@ function deleteContentData( linkType.value = 'related' linkText.value = '' } - if (listForeignDefinitions) { + if (listForeignDefinitions.length) { const foreignDefinitionsFields = document.querySelectorAll( '.foreign-definition-el' ) @@ -2923,8 +3009,10 @@ $('.summernote').summernote({ function updateAcceptedFileTypes() { const { fileImportForm, fileUploadInput } = window.dictionaryElements - const selectedFileFormat = fileImportForm.importFileFormat.value - fileUploadInput.accept = `.${selectedFileFormat}` + const selectedFileFormatRadio = fileImportForm.querySelector( + 'input[name="importFileFormat"]:checked' + ) + fileUploadInput.accept = `.${selectedFileFormatRadio.dataset.extension}` } // Activate BS5 tooltips diff --git a/express/public/javascripts/dictionary-export.js b/express/public/javascripts/dictionary-export.js deleted file mode 100644 index 9f16590..0000000 --- a/express/public/javascripts/dictionary-export.js +++ /dev/null @@ -1,24 +0,0 @@ -/* globals axios, i18next */ - -const exportForm = document.forms['dictionary-export'] - -exportForm.addEventListener('submit', async event => { - event.preventDefault() - - const payload = Object.fromEntries(new FormData(event.target)) - - try { - await axios.post(event.target.action, payload) - // TODO This (page refresh) is a temporary hack. Replace with proper UI updating logic. - location.reload() - } catch (error) { - let message = i18next.t('Prišlo je do napake.') - if (error.response) { - message = error.response.data - } else if (error.request) { - message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') - } - - alert(message) - } -}) diff --git a/express/public/javascripts/dictionary-list-table.js b/express/public/javascripts/dictionary-list-table.js new file mode 100644 index 0000000..2b02140 --- /dev/null +++ b/express/public/javascripts/dictionary-list-table.js @@ -0,0 +1,291 @@ +/* global $, axios, i18next, isI18nReady, initSelect2, initPagination, removeAllChildNodes, currentPagePath, DateUtils, bindKeys, setVisibleAdvancedSearch */ +// eslint-disable-next-line no-unused-vars +/* global isAdvancedSearchButtonPressedOddTimes:writable */ + +// Sorting, pagination, searching and filtering shared by /admin/slovarji and /ogled-virov. +const PAGE_CONFIG = { + '/admin/slovarji': { + apiUrl: '/api/v1/dictionaries/listAllDictionaries', + rowActionHref: id => `/admin/slovarji/${id}/podatki`, + rowActionIcon: '/images/u_edit-alt.svg', + rowActionLabelKey: 'Uredi' + }, + '/ogled-virov': { + apiUrl: '/api/v1/dictionaries/listAllViewableDictionaries', + rowActionHref: id => `/ogled-virov/${id}/podatki`, + rowActionIcon: '/images/eye.svg', + rowActionLabelKey: 'Podatki' + } +} + +const pageConfig = PAGE_CONFIG[currentPagePath] + +if (pageConfig) { + ;(function () { + const SORT_COLUMNS = [ + 'id', + 'name', + 'status', + 'timeCreated', + 'timeModified' + ] + + const resultsListEl = document.getElementById('page-results') + const headerButtons = { + id: document.getElementById('sortById'), + name: document.getElementById('sortByName'), + status: document.getElementById('sortByStatus'), + timeCreated: document.getElementById('sortByTimeCreated'), + timeModified: document.getElementById('sortByTimeModified') + } + const headerIcons = { + id: document.getElementById('idImg'), + name: document.getElementById('nameImg'), + status: document.getElementById('statusImg'), + timeCreated: document.getElementById('timeCreatedImg'), + timeModified: document.getElementById('timeModifiedImg') + } + + const searchInput = document.getElementById('dict-name-search') + const searchBtn = document.getElementById('search-dictionaries') + const applyFiltersBtn = document.getElementById('apply-filters') + const clearFiltersBtn = document.getElementById('clear-filters') + + const initialParams = new URL(location).searchParams + let currentPage = +initialParams.get('p') > 0 ? +initialParams.get('p') : 1 + let sortBy = SORT_COLUMNS.includes(initialParams.get('sort')) + ? initialParams.get('sort') + : 'id' + let sortDir = initialParams.get('dir') === 'asc' ? 'asc' : 'desc' + let nameQuery = initialParams.get('q') || '' + let primaryDomainIds = initialParams.getAll('pd') + let secondaryDomainIds = initialParams.getAll('sd') + let languageIds = initialParams.getAll('lang') + let statuses = initialParams.getAll('status') + let latestRequestId = 0 + + const updatePager = initPagination('pagination', onPageChange, currentPage) + + bindSortHeaderListeners() + bindFilterListeners() + initFilterSelect2() + bindKeys('#dict-name-search') + if ( + primaryDomainIds.length || + secondaryDomainIds.length || + languageIds.length || + statuses.length + ) { + // scripts.js unconditionally force-closes the panel on every page load + // (setVisibleAdvancedSearch(false), run once #advanced-search exists), + // which would otherwise override the server-rendered "open" state from + // the Pug `class` condition on #admin-dict-filter-panel. Explicitly + // reopen it here (this file loads after scripts.js) and keep the + // shared open/close counter in sync so the *next* click closes it. + isAdvancedSearchButtonPressedOddTimes = true + setVisibleAdvancedSearch(true) + } + window.addEventListener('popstate', onPopState) + + function bindSortHeaderListeners() { + SORT_COLUMNS.forEach(column => { + headerButtons[column].addEventListener('click', () => + onSortClick(column) + ) + }) + } + + async function onSortClick(column) { + if (sortBy === column) { + sortDir = sortDir === 'asc' ? 'desc' : 'asc' + } else { + sortBy = column + sortDir = 'asc' + } + currentPage = 1 + updateSortIndicators() + await fetchAndRender() + } + + function updateSortIndicators() { + SORT_COLUMNS.forEach(column => { + const icon = headerIcons[column] + if (column === sortBy) { + icon.classList.remove('invisible') + icon.src = + sortDir === 'asc' + ? '/images/arrow_drop_up.svg' + : '/images/arrow_drop_down.svg' + } else { + icon.classList.add('invisible') + } + }) + } + + async function onPageChange(newPage) { + currentPage = newPage + await fetchAndRender() + } + + function initFilterSelect2() { + isI18nReady.then(t => { + initSelect2('.select-admin-domain-primary', t('Področje')) + initSelect2('.select-admin-domain-secondary', t('Podpodročje')) + initSelect2('.select-admin-language', t('Jezik')) + initSelect2('.select-admin-status', t('Status')) + }) + } + + function bindFilterListeners() { + // Opening/closing #admin-dict-filter-panel itself is handled globally + // by scripts.js (initAdvancedSearch('#advanced-search')), since the + // panel reuses the #advanced-search id and .advanced-search-root class + // from /slovarji's advanced-search dropdown. + searchBtn.addEventListener('click', onApplyFilters) + searchInput.addEventListener('keydown', event => { + if (event.key === 'Enter') { + event.preventDefault() + onApplyFilters() + } + }) + applyFiltersBtn.addEventListener('click', onApplyFilters) + clearFiltersBtn.addEventListener('click', onClearFilters) + } + + async function onApplyFilters() { + nameQuery = searchInput.value.trim() + primaryDomainIds = $('#filter-domain-primary').val() || [] + secondaryDomainIds = $('#filter-domain-secondary').val() || [] + languageIds = $('#filter-language').val() || [] + statuses = $('#filter-status').val() || [] + currentPage = 1 + await fetchAndRender() + } + + async function onClearFilters() { + nameQuery = '' + primaryDomainIds = [] + secondaryDomainIds = [] + languageIds = [] + statuses = [] + syncFilterControls() + currentPage = 1 + await fetchAndRender() + } + + function syncFilterControls() { + searchInput.value = nameQuery + $('#filter-domain-primary').val(primaryDomainIds).trigger('change') + $('#filter-domain-secondary').val(secondaryDomainIds).trigger('change') + $('#filter-language').val(languageIds).trigger('change') + $('#filter-status').val(statuses).trigger('change') + } + + async function fetchAndRender(updateHistory = true) { + // Guards against out-of-order responses: if a newer request has been + // issued (e.g. rapid sort-click then back-navigation) by the time this + // one resolves, its response is stale and must not overwrite the UI. + const requestId = ++latestRequestId + try { + const { page, numberOfAllPages, results } = await getData( + currentPage + ) + if (requestId !== latestRequestId) return + currentPage = page + removeAllChildNodes(resultsListEl) + renderResults(results) + updatePager(page, numberOfAllPages) + if (updateHistory) updateUrlAndHistory() + } catch (error) { + if (requestId !== latestRequestId) return + let message = i18next.t('Prišlo je do napake.') + if (error.response?.data) { + message = error.response.data + } else if (error.request) { + message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') + } + alert(message) + updatePager() + } + } + + function buildQueryParams(page) { + const params = new URLSearchParams() + params.set('p', page) + params.set('sort', sortBy) + params.set('dir', sortDir) + if (nameQuery) params.set('q', nameQuery) + primaryDomainIds.forEach(id => params.append('pd', id)) + secondaryDomainIds.forEach(id => params.append('sd', id)) + languageIds.forEach(id => params.append('lang', id)) + statuses.forEach(value => params.append('status', value)) + return params + } + + async function getData(page) { + const url = `${pageConfig.apiUrl}?${buildQueryParams(page)}` + const { data } = await axios.get(url) + return data + } + + function renderResults(results) { + results.forEach(result => { + const rowEl = document.createElement('tr') + const td1 = document.createElement('td') + const td2 = document.createElement('td') + const td3 = document.createElement('td') + const td4 = document.createElement('td') + const td5 = document.createElement('td') + const td6 = document.createElement('td') + const aEl = document.createElement('a') + const imgEl = document.createElement('img') + const spanEl = document.createElement('span') + td1.textContent = result.id + td2.textContent = result.name + td3.textContent = statusLabel(result.status) + td4.textContent = DateUtils.formatDateTime(result.timeCreated) + td5.textContent = DateUtils.formatDateTime(result.timeModified) + aEl.classList.add('image-link') + aEl.type = 'link' + aEl.href = pageConfig.rowActionHref(result.id) + imgEl.src = pageConfig.rowActionIcon + imgEl.alt = i18next.t(pageConfig.rowActionLabelKey) + spanEl.className = 'normal-gray ms-1' + spanEl.textContent = i18next.t(pageConfig.rowActionLabelKey) + td6.append(aEl) + aEl.append(imgEl, spanEl) + rowEl.append(td1, td2, td3, td4, td5, td6) + resultsListEl.appendChild(rowEl) + }) + } + + function statusLabel(status) { + if (status === 'closed') return i18next.t('zaprt') + if (status === 'reviewed') return i18next.t('v predogledu') + return i18next.t('odprt') + } + + function updateUrlAndHistory() { + const newUrl = new URL(location) + newUrl.search = buildQueryParams(currentPage).toString() + history.pushState(null, '', newUrl) + } + + function onPopState() { + const params = new URL(location).searchParams + currentPage = +params.get('p') > 0 ? +params.get('p') : 1 + sortBy = SORT_COLUMNS.includes(params.get('sort')) + ? params.get('sort') + : 'id' + sortDir = params.get('dir') === 'asc' ? 'asc' : 'desc' + nameQuery = params.get('q') || '' + primaryDomainIds = params.getAll('pd') + secondaryDomainIds = params.getAll('sd') + languageIds = params.getAll('lang') + statuses = params.getAll('status') + updateSortIndicators() + syncFilterControls() + fetchAndRender(false) + } + })() +} diff --git a/express/public/javascripts/extraction-edit-own.js b/express/public/javascripts/extraction-edit-own.js index aad3c8c..c62d1df 100644 --- a/express/public/javascripts/extraction-edit-own.js +++ b/express/public/javascripts/extraction-edit-own.js @@ -1,7 +1,22 @@ +/* global captureFormBaseline, isFormDirty */ + +const nameForm = document.getElementById('extraction-name') +captureFormBaseline(nameForm) + const nameEl = document.getElementById('name') -nameEl.addEventListener('input', enableButton) +nameEl.addEventListener('input', updateButtonState) + +function updateButtonState() { + if (isFormDirty(nameForm)) enableButton() + else disableButton() +} function enableButton() { const disabledBtn = document.getElementById('mpbtn') disabledBtn.classList.remove('disabled') } + +function disableButton() { + const disabledBtn = document.getElementById('mpbtn') + disabledBtn.classList.add('disabled') +} diff --git a/express/public/javascripts/extraction-files-edit.js b/express/public/javascripts/extraction-files-edit.js index d159ced..a41c23e 100644 --- a/express/public/javascripts/extraction-files-edit.js +++ b/express/public/javascripts/extraction-files-edit.js @@ -1,4 +1,4 @@ -/* global axios, removeAllChildNodes, bootstrap, i18next */ +/* global axios, removeAllChildNodes, bootstrap, i18next, DateUtils */ const fileUploadContainerEl = document.getElementById('upload-files-container') const fileUploadForm = document.forms['upload-files'] @@ -180,10 +180,7 @@ function updateFileListEl(fileListEl, { status, fileStats, index }) { sizeEl.textContent = fileStats.size const dateEl = fileListEl.querySelector('.file-date-modified') - const formattedDate = new Date(fileStats.timeModified).toLocaleDateString( - 'sl-SL' - ) - dateEl.textContent = formattedDate + dateEl.textContent = DateUtils.formatDate(fileStats.timeModified) const successImgEl = document.createElement('img') successImgEl.src = '/images/valid.svg' diff --git a/express/public/javascripts/extraction-oss-edit.js b/express/public/javascripts/extraction-oss-edit.js index af8d63e..f7d0460 100644 --- a/express/public/javascripts/extraction-oss-edit.js +++ b/express/public/javascripts/extraction-oss-edit.js @@ -1,8 +1,9 @@ -/* global $, axios, bootstrap, i18next */ +/* global $, axios, bootstrap, i18next, exactTagMatcher */ $('.pick-multiple').select2() $('.enter-multiple').select2({ - tags: true + tags: true, + matcher: exactTagMatcher }) const editStopTermsLink = document.getElementById('edit-stop-terms') diff --git a/express/public/javascripts/offset-header.js b/express/public/javascripts/offset-header.js new file mode 100644 index 0000000..330581c --- /dev/null +++ b/express/public/javascripts/offset-header.js @@ -0,0 +1,22 @@ +// Clears the fixed #offset-padding header out of the way of the page content +// below it, for pages with no side menu (mirrors the same logic each +// page-specific script - admin.js, dictionaries.js, help.js, etc. - already +// duplicates for its own page). + +window.addEventListener('load', adjustOffsetBy) +window.addEventListener('resize', adjustOffsetBy) + +function adjustOffsetBy() { + const fixedTopSection = document.getElementById('fixed-top-section') + const offsetMain = document.getElementById('offset-main') + const offsetHeaderPadding = document.getElementById('offset-padding') + if (!fixedTopSection || !offsetMain) return + + if (document.body.clientWidth < 1200) { + if (offsetHeaderPadding !== null) offsetMain.style.paddingTop = `0px` + } else if (offsetHeaderPadding !== null) { + const referenceHeight = fixedTopSection.offsetHeight + const offsetHeaderHeight = offsetHeaderPadding.offsetHeight + offsetMain.style.paddingTop = `${referenceHeight + offsetHeaderHeight}px` + } +} diff --git a/express/public/javascripts/oidc-forms.js b/express/public/javascripts/oidc-forms.js new file mode 100644 index 0000000..bcc4198 --- /dev/null +++ b/express/public/javascripts/oidc-forms.js @@ -0,0 +1,38 @@ +/* global axios, i18next */ + +function displayError(errorElementId, error) { + let message = i18next.t('Prišlo je do napake.') + if (error.response) { + message = error.response.data + } else if (error.request) { + message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.') + } + + const errorElement = document.querySelector(`#${errorElementId}`) + errorElement.textContent = message + errorElement.style.visibility = 'visible' +} + +function bindAjaxForm(formId, errorElementId) { + const form = document.querySelector(`#${formId}`) + if (!form) return + + form.addEventListener('submit', async event => { + event.preventDefault() + + const data = {} + new FormData(form).forEach((value, key) => { + data[key] = value + }) + + try { + await axios.post(form.action, data) + window.location = '/' + } catch (error) { + displayError(errorElementId, error) + } + }) +} + +bindAjaxForm('create-profile-form', 'create-profile-error') +bindAjaxForm('convert-account-form', 'convert-account-error') diff --git a/express/public/javascripts/query-focus-handler.js b/express/public/javascripts/query-focus-handler.js index 5602956..9621cf2 100644 --- a/express/public/javascripts/query-focus-handler.js +++ b/express/public/javascripts/query-focus-handler.js @@ -1,9 +1,4 @@ -// Note to myself: please optimize and remove the redundacy of the code written in multiple classes to achieve the same result as this - -const focusOnCompletePromtBase = queryInput => { - queryInput.focus() - queryInput.select() -} +/* global focusOnCompletePromtBase */ // Tradeoff: Declare a variable for the element to reduce duplication? const inputQuery = document.querySelector('#search-query') diff --git a/express/public/javascripts/scripts.js b/express/public/javascripts/scripts.js index 41e467d..165768e 100644 --- a/express/public/javascripts/scripts.js +++ b/express/public/javascripts/scripts.js @@ -898,14 +898,47 @@ if (registerSwithcButton) { } { - let unsaved = false + const formBaselines = new WeakMap() + + function serializeFormState(form) { + return new URLSearchParams(new FormData(form)).toString() + } + + function captureFormBaseline(form) { + formBaselines.set(form, serializeFormState(form)) + } + + function isFormDirty(form) { + const baseline = formBaselines.get(form) + if (baseline == null) return false + return serializeFormState(form) !== baseline + } + + function enableButton() { + const disabledBtn = document.getElementById('disabled-submit-btn') + disabledBtn.disabled = false + if (disabledBtn.classList.contains('saved-entry-btn')) { + disabledBtn.classList.remove('saved-entry-btn') + disabledBtn.textContent = 'Shrani' + } + } + + function disableButton() { + const disabledBtn = document.getElementById('disabled-submit-btn') + disabledBtn.disabled = true + if (disabledBtn.classList.contains('saved-entry-btn')) { + disabledBtn.classList.remove('saved-entry-btn') + disabledBtn.textContent = 'Shrani' + } + } + + function updateSaveButtonState(form) { + if (isFormDirty(form)) enableButton() + else disableButton() + } + function unsavedData(form, sideMenu, ajaxFunction) { - form.addEventListener('input', () => { - unsaved = true - }) - $('.without-addition').on('change.select2', () => { - unsaved = true - }) + captureFormBaseline(form) sideMenu.addEventListener('click', () => handleMenuClick(form, event, ajaxFunction) ) @@ -914,7 +947,7 @@ if (registerSwithcButton) { /* SELECT 2 */ function evaluateAlerModalTarget(pf, form, ajaxFunction) { - if (unsaved) { + if (isFormDirty(form)) { event.preventDefault() openUnsavedMixin(form, pf, ajaxFunction) } @@ -950,8 +983,64 @@ if (registerSwithcButton) { ) } + function warnOnNameCollisionThenSubmit(form, { excludeDictionaryId } = {}) { + const fieldNames = ['nameSl', 'nameSlShort', 'nameEn'] + const params = {} + let anyChanged = false + + fieldNames.forEach(name => { + const input = form.querySelector(`[name="${name}"]`) + if (!input) return + const changed = input.value !== input.defaultValue + if (changed) anyChanged = true + if (input.value && (!excludeDictionaryId || changed)) { + params[name] = input.value + } + }) + + if (excludeDictionaryId && !anyChanged) { + form.submit() + return + } + if (excludeDictionaryId) params.excludeDictionaryId = excludeDictionaryId + + axios + .get('/api/v1/dictionaries/check-name-collision', { params }) + .then(({ data }) => { + if (!data.collision) { + form.submit() + return + } + const modal = new bootstrap.Modal( + document.getElementById('name-collision-warning') + ) + modal.show() + const acceptBtnId = excludeDictionaryId + ? 'modal-rename-btn' + : 'modal-create-btn' + document + .getElementById(acceptBtnId) + .addEventListener('click', () => form.submit(), { once: true }) + }) + } + /* SELECT 2 */ + // select2's default matcher does substring + diacritic-insensitive comparison, + // which blocks entering tags like "scar" after "scarf" or "gloš" after "glos". + // Use exact comparison instead for free-text tag fields. + function exactTagMatcher(params, data) { + if ($.trim(params.term) === '') { + return data + } + + if (typeof data.text === 'undefined') { + return null + } + + return data.text.toUpperCase() === params.term.toUpperCase() ? data : null + } + function initSelect2(querySelector, placeholder) { $(querySelector).select2({ // allowClear: true, @@ -1042,7 +1131,8 @@ if (registerSwithcButton) { $('.multiple').select2({ minimumResultsForSearch: Infinity, - tags: true + tags: true, + matcher: exactTagMatcher }) $('.without-addition').select2({ @@ -1065,7 +1155,8 @@ if (registerSwithcButton) { $('.without-dropdown').select2({ minimumResultsForSearch: Infinity, tags: true, - dropdownCssClass: 'hide-dropdown' + dropdownCssClass: 'hide-dropdown', + matcher: exactTagMatcher }) } catch (e) { // console.log(e) diff --git a/express/public/javascripts/view-resources-details.js b/express/public/javascripts/view-resources-details.js new file mode 100644 index 0000000..b0d059d --- /dev/null +++ b/express/public/javascripts/view-resources-details.js @@ -0,0 +1,28 @@ +/* global axios, bootstrap */ + +const contactAuthorsForm = document.querySelector('#contact-authors-form') + +if (contactAuthorsForm) { + contactAuthorsForm.addEventListener('submit', async event => { + event.preventDefault() + if (!contactAuthorsForm.checkValidity()) { + event.stopPropagation() + contactAuthorsForm.classList.add('was-validated') + return + } + + const payload = Object.fromEntries(new FormData(event.target)) + const res = await axios.post(event.target.action, payload) + + if (res.status === 201) { + contactAuthorsForm.reset() + contactAuthorsForm.classList.remove('was-validated') + + const infoModal = document.getElementById('contact-authors-response') + if (infoModal) { + const responseModal = new bootstrap.Modal(infoModal) + responseModal.toggle() + } + } + }) +} diff --git a/express/public/locales/en/core.json b/express/public/locales/en/core.json index f1b2671..4353a18 100644 --- a/express/public/locales/en/core.json +++ b/express/public/locales/en/core.json @@ -20,9 +20,11 @@ "ANGLEŠKI OPIS PORTALA": "PORTAL DESCRIPTION IN ENGLISH", "ANGLEŠKO IME PORTALA": "PORTAL NAME IN ENGLISH", "Angleško ime terminološkega portala.": "English name of the terminology portal.", + "Angleški naslov slovarja": "English dictionary title", "Avtor": "Author", "AVTOR": "AUTHOR", "AVTOR SLOVARJA": "DICTIONARY AUTHOR", + "Avtor slovarja": "Dictionary author", "Avtor:": "Author:", "Avtorja": "Authors", "Avtorji": "Authors", @@ -145,6 +147,7 @@ "Iskanje po vseh": "Search all", "ISSN": "ISSN", "ISSN OZNAKA": "ISSN CODE", + "ISSN oznaka": "ISSN code", "ISSN oznaka.": "ISSN code.", "Italijanščina": "Italian", "IZBERI": "SELECT", @@ -180,6 +183,7 @@ "IZVOZI": "EXPORT", "Izvozi termine od številke": "Export entries between the numbers", "je že v tabeli.": "is already in the table.", + "Jezik": "Language", "Jeziki": "Languages", "Jeziki iskanja": "Search languages", "Jezikovni pregled": "Language review", @@ -189,6 +193,7 @@ "Ko bo luščenje uspešno zaključeno, boste na svoj elektronski naslov, ki ste ga navedli ob registraciji, prejeli obvestilo.": "After the extraction is successfully completed, you will receive a notification to the email address that you provided during registration.", "Ko boste končali z urejanjem svojega terminološkega slovarja, lahko objavite vse slovarske sestavke, ki bodo postali vidni vsem uporabnikom. Vaše dejanje mora potrditi še administrator portala.": "After you finish editing your terminology dictionary, you can publish all the dictionary entries, which will become visible to all users. Your action must be approved by the portal administrator.", "komentar": "comment", + "Kontaktiraj avtorje": "Contact the authors", "komentarja": "comments", "komentarjev": "comments", "komentarji": "comments", @@ -253,14 +258,17 @@ "Naprej": "Next", "Naslednje datoteke niso bile naložene zaradi navedenih razlogov:": "The following files were not uploaded due to the following reasons:", "Naslov": "Address", - "NASLOV": "ADDRESS", + "NASLOV": "TITLE", "NASLOV SLOVARJA *": "DICTIONARY TITLE *", + "Naslov slovarja": "Dictionary title", + "Nastavi parametre luščenja": "Set extraction parameters", "Nastavitve": "Settings", "Nastavitve portala": "Portal settings", "Nastavitve računa": "Account settings", "Nastavitve slovarjev": "Dictionaries settings", "Nastavitve svetovalnice": "Consultancy settings", "Nazaj": "Back", + "Nazaj na nastavitve parametrov": "Back to parameter settings", "Nazaj na prijavo": "Back to login", "Nazaj na zadetke": "Back to results", "Ne": "No", @@ -277,6 +285,7 @@ "Neveljavni": "Invalid", "Neveljavni elektronski naslov.": "Invalid e-mail address", "Ni področja": "No domain", + "Ni še dodanih izvozov.": "No exports have been added.", "Ni še dodanih uvozov.": "No imports have been added.", "Ni še povezanih portalov": "No portals have been connected", "Ni slovarskih sestavkov za urejanje.": "There are no dictionary entries to edit.", @@ -295,6 +304,7 @@ "Niste vpisali naslova slovarja.": "Dictionary title missing.", "Niste vpisali opisa terminološkega problema.": "Terminology problem description missing.", "Niste vpisali priimka.": "Last name missing.", + "Niste vpisali sporočila.": "Message missing.", "Niste vpisali tujih jezikov.": "Foreign languages missing.", "Nov": "New", "Nov avtor": "New author", @@ -333,7 +343,6 @@ "Objavljeno": "Published", "Oblike": "Forms", "Oblike, naglasi, izgovor": "Forms, accents, pronunciation", - "Obljavljeno": "Published", "Obnovi": "Restore", "Obstoječe poimenovalne rešitve": "Existing naming solutions", "OBSTOJEČE POIMENOVALNE REŠITVE": "EXISTING NAMING SOLUTIONS", @@ -346,9 +355,11 @@ "odprt": "published", "Odprt": "Published", "Odstrani": "Remove", + "Ogled virov na portalu": "View portal resources", "Omogočeno": "Enabled", "OPIS PORTALA": "PORTAL DESCRIPTION", "OPIS SLOVARJA": "DICTIONARY DESCRIPTION", + "Opis slovarja": "Dictionary description", "Opis terminološkega problema": "Description of the terminology problem", "OPIS TERMINOLOŠKEGA PROBLEMA": "DESCRIPTION OF THE TERMINOLOGY PROBLEM", "Opis terminološkega problema:": "Description of the terminology problem:", @@ -359,8 +370,10 @@ "Oznaka portala": "Portal label", "OZNAKA PORTALA *": "PORTAL LABEL *", "Po koncu urejanja vseh slovarskih sestavkov lahko slovar objavite in ga tako prikažete na javnem delu terminološkega portala.": "After all dictionary entires are edited, you can publish the dictionary to make it available on the public part of the terminology portal.", + "Po urejanju nabora datotek se s klikom vrnemo na stran z nastavitvami parametrov luščenja.": "After editing the file set, click to return to the page with the extraction parameter settings.", "Počisti filtre": "Remove filters", "POČISTI FILTRE": "REMOVE FILTERS", + "Podatki": "Details", "Podnaslov": "Subtitle", "Podpodročja": "Secondary domains", "Podpodročja so namenjena podrobnejšemu razvrščanju terminoloških slovarjev. Administrator mora vsa novo predlagana podpodročja potrditi, preden jih lahko na seznamu vidijo tudi drugi uporabniki portala.": "Secondary domains are used for more detailed classification of terminology dictionaries. All new suggested secondary domains must be approved by the Portal Administrator before other portal users can see them on the list.", @@ -412,11 +425,14 @@ "Pozabljeno geslo": "Forgoten password", "Pozdravljeni ": "Hello ", "Pozor": "Attention", + "Pozor, slovar s tem imenom že obstaja. Ali res želite izdelati slovar s tem imenom?": "Warning, a dictionary with this name already exists. Do you really want to create a dictionary with this name?", + "Pozor, slovar s tem imenom že obstaja. Ali res želite slovar preimenovati v ime, ki že obstaja?": "Warning, a dictionary with this name already exists. Do you really want to rename this dictionary to a name that already exists?", "Prazno obvezno polje": "Mandatory field is empty", "Preden naložite besedila, jih shranite v besedilni obliki (končnica .txt).": "Before uploading texts, save them in text format (.txt file).", "Predlog": "Suggestion", "Predogled": "Preview", "Pregledani": "Reviewed", + "Preimenuj": "Rename", "Prekinjen": "Interrupted", "Prekliči": "Cancel", "Preverite, če ste pravilno vpisali uporabniško ime. Bodite pozorni na velike in male črke.": "Check if you entered the username correctly. Pay attention to capital letters.", @@ -453,6 +469,8 @@ "rezultati": "results", "Rezultati: ": "Results: ", "rezultatov": "results", + "S klikom se vrnete na stran, kjer lahko zaženete postopek luščenja.": "Clicking returns you to the page where you can start the extraction process.", + "S klikom shranite spremembe parametrov.": "Clicking saves your parameter changes.", "S ključnimi besedami, ki so vključene v večino znanstvenih in strokovnih, lahko bolj natančno izberete besedila, ki jih želite uporabiti za luščenje terminoloških kandidatov.": "Most of the scientific and specialized texts have keywords you can use for a more precise selection of texts from which to extract term candidates.", "S prijavo pridobite možnost uporabe vseh funkcij terminološkega portala.": "By registering, you get access to all functions of the terminology portal.", "S tem dejanjem boste izbrisali vse slovarske sestavke v slovarju in vse metapodatke. Dejanja ni mogoče razveljaviti.": "This action will delete all dictionary entries in the dictionary and all metadata. The action cannot be undone.", @@ -489,6 +507,7 @@ "SINONIMI": "SYNONYMS", "Širši": "Broad", "SKRAJŠANI NASLOV SLOVARJA": "SHORT DICTIONARY TITLE", + "Skrajšani naslov slovarja": "Short dictionary title", "Skrbnik portala": "Portal administrator", "Skrbnik slovarjev": "Dictionary administrator", "Skrbnik svetovalnice": "Consultancy administrator", @@ -516,6 +535,8 @@ "Slovenščina": "Slovenian", "Soglašam s politiko zasebnosti": "I agree with the Privacy policy", "Sorodni": "Similar", + "Sporočilo je bilo poslano avtorjem slovarja.": "The message has been sent to the dictionary's authors.", + "Sporočilo o slovarju \"{{name}}\"": "Message about the dictionary \"{{name}}\"", "Sprememba stanja slovarja": "Dictionary status change", "Spremeni geslo": "Change password", "SPREMENJEN": "CHANGED", @@ -587,6 +608,7 @@ "UPORABNIŠKO IME": "USERNAME", "Uporabniško ime ali elektronski naslov": "Username or e-mail address", "Uporabniško ime že obstaja": "Username already exists", + "Upoštevaj filtre": "Apply filters", "Uredi": "Edit", "UREDI": "EDIT", "Uredi lastnosti": "Edit properties", @@ -686,6 +708,7 @@ "Zadnji objavljeni slovarji": "Recent published dictionaries", "Zadnji odgovori na vprašanja": "Recent answers to questions", "Zadnji uvozi": "Recent imports", + "Zaključi nastavljanje parametrov": "Finish setting parameters", "Zapomni si prijavo": "Remember my login", "Zaporedje:": "Sequence:", "Zapri": "Close", @@ -710,6 +733,12 @@ "userStatusactive": "active", "userStatusinactive": "inactive", "userStatusclosed": "closed", + "importStatusInProgress": "in progress", + "importStatusError": "error", + "importStatusDone": "imported", + "exportStatusPending": "pending", + "exportStatusInProgress": "in progress", + "exportStatusFailed": "failed", "Nepravilno uporabniško ime ali elektronski naslov.": "Invalid user name or e-mail address.", "Ponastavitev gesla": "Password reset", "Uspešna ponastavitev gesla": "Password successfully reset", @@ -735,5 +764,26 @@ "Število slovarskih sestavkov": "Number of dictionary entries", "VPRAŠANJE": "QUESTION", "MNENJE": "OPINION", - "ANGLEŠKI PREVOD": "ENGLISH TRANSLATION" + "ANGLEŠKI PREVOD": "ENGLISH TRANSLATION", + "Univerza v Ljubljani": "University of Ljubljana", + "ali": "or", + "Ustvarite svoj profil": "Create your profile", + "Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in bodo uporabljeni za ustvarjanje vašega računa. Tukaj jih ni mogoče spreminjati.": "The details below come from your University of Ljubljana sign-in and will be used to create your account. They cannot be changed here.", + "Pretvorite svoj račun": "Convert your account", + "Elektronski naslov, prijavljen prek Univerze v Ljubljani, se ujema z obstoječim računom na portalu z uporabniškim imenom ": "The email address signed in via the University of Ljubljana matches an existing portal account with the username ", + ". Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in jih ni mogoče spreminjati. Z vnosom gesla obstoječega računa in potrditvijo boste ta račun trajno pretvorili: uporabniško ime, ime in priimek bodo nadomeščeni s podatki spodaj, geslo pa bo odstranjeno - odslej se boste lahko prijavili le še prek gumba za prijavo z Univerzo v Ljubljani.": ". The details below come from your University of Ljubljana sign-in and cannot be changed. Entering that account's password and confirming will permanently convert it: the username, first and last name will be replaced with the data below, and the password will be removed - from then on you'll only be able to sign in via the University of Ljubljana sign-in button.", + "POTRDI PRETVORBO": "CONFIRM CONVERSION", + "Vaš uporabniški račun ni aktiven. Za pomoč se obrnite na skrbnika portala.": "Your user account is not active. Please contact the portal administrator for help.", + "Vaš račun pri Univerzi v Ljubljani ne vsebuje vseh podatkov (imena in priimka), potrebnih za ustvarjanje profila na portalu. Za pomoč se obrnite na skrbnika portala.": "Your University of Ljubljana account doesn't include all the data (first and last name) needed to create a profile on the portal. Please contact the portal administrator for help.", + "Nepravilno geslo.": "Incorrect password.", + "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.": "This account was created via University of Ljubljana sign-in and has no password. Please sign in using the University of Ljubljana sign-in button.", + "Prijava prek Univerze v Ljubljani trenutno ni na voljo. Poskusite kasneje.": "Sign-in via the University of Ljubljana is currently unavailable. Please try again later.", + "Prijava prek Univerze v Ljubljani ni uspela. Poskusite znova.": "Sign-in via the University of Ljubljana failed. Please try again.", + "Prijava prek Univerze v Ljubljani ni uspela.": "Sign-in via the University of Ljubljana failed.", + "Uspešno ste se prijavili prek Univerze v Ljubljani.": "You have successfully signed in via the University of Ljubljana.", + "Uspešno ste ustvarili račun prek Univerze v Ljubljani in se prijavili.": "You have successfully created your account via the University of Ljubljana and signed in.", + "Vaš račun je bil uspešno pretvorjen v prijavo prek Univerze v Ljubljani. Odslej se lahko prijavite le še prek tega načina.": "Your account has been successfully converted to sign in via the University of Ljubljana. From now on you can only sign in this way.", + "Seja je potekla. Poskusite znova.": "Your session has expired. Please try again.", + "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani, zato osebnih podatkov ni mogoče spreminjati na portalu.": "This account was created via University of Ljubljana sign-in, so personal data cannot be changed on the portal.", + "Ta račun je bil ustvarjen s prijavo prek Univerze v Ljubljani, zato osebnih podatkov (ime, priimek, uporabniško ime, e-poštni naslov) tukaj ni mogoče spreminjati.": "This account was created via University of Ljubljana sign-in, so personal data (first name, last name, username, email address) cannot be changed here." } diff --git a/express/public/locales/sl/core.json b/express/public/locales/sl/core.json index 7cb3ad1..c026d24 100644 --- a/express/public/locales/sl/core.json +++ b/express/public/locales/sl/core.json @@ -20,9 +20,11 @@ "ANGLEŠKI OPIS PORTALA": "ANGLEŠKI OPIS PORTALA", "ANGLEŠKO IME PORTALA": "ANGLEŠKO IME PORTALA", "Angleško ime terminološkega portala.": "Angleško ime terminološkega portala.", + "Angleški naslov slovarja": "Angleški naslov slovarja", "Avtor": "Avtor", "AVTOR": "AVTOR", "AVTOR SLOVARJA": "AVTOR SLOVARJA", + "Avtor slovarja": "Avtor slovarja", "Avtor:": "Avtor:", "Avtorja": "Avtorja", "Avtorji": "Avtorji", @@ -145,6 +147,7 @@ "Iskanje po vseh": "Iskanje po vseh", "ISSN": "ISSN", "ISSN OZNAKA": "ISSN OZNAKA", + "ISSN oznaka": "ISSN oznaka", "ISSN oznaka.": "ISSN oznaka.", "Italijanščina": "Italijanščina", "IZBERI": "IZBERI", @@ -180,6 +183,7 @@ "IZVOZI": "IZVOZI", "Izvozi termine od številke": "Izvozi termine od številke", "je že v tabeli.": "je že v tabeli.", + "Jezik": "Jezik", "Jeziki": "Jeziki", "Jeziki iskanja": "Jeziki iskanja", "Jezikovni pregled": "Jezikovni pregled", @@ -189,6 +193,7 @@ "Ko bo luščenje uspešno zaključeno, boste na svoj elektronski naslov, ki ste ga navedli ob registraciji, prejeli obvestilo.": "Ko bo luščenje uspešno zaključeno, boste na svoj elektronski naslov, ki ste ga navedli ob registraciji, prejeli obvestilo.", "Ko boste končali z urejanjem svojega terminološkega slovarja, lahko objavite vse slovarske sestavke, ki bodo postali vidni vsem uporabnikom. Vaše dejanje mora potrditi še administrator portala.": "Ko boste končali z urejanjem svojega terminološkega slovarja, lahko objavite vse slovarske sestavke, ki bodo postali vidni vsem uporabnikom. Vaše dejanje mora potrditi še administrator portala.", "komentar": "komentar", + "Kontaktiraj avtorje": "Kontaktiraj avtorje", "komentarja": "komentarja", "komentarjev": "komentarjev", "komentarji": "komentarji", @@ -255,12 +260,15 @@ "Naslov": "Naslov", "NASLOV": "NASLOV", "NASLOV SLOVARJA *": "NASLOV SLOVARJA *", + "Naslov slovarja": "Naslov slovarja", + "Nastavi parametre luščenja": "Nastavi parametre luščenja", "Nastavitve": "Nastavitve", "Nastavitve portala": "Nastavitve portala", "Nastavitve računa": "Nastavitve računa", "Nastavitve slovarjev": "Nastavitve slovarjev", "Nastavitve svetovalnice": "Nastavitve svetovalnice", "Nazaj": "Nazaj", + "Nazaj na nastavitve parametrov": "Nazaj na nastavitve parametrov", "Nazaj na prijavo": "Nazaj na prijavo", "Nazaj na zadetke": "Nazaj na zadetke", "Ne": "Ne", @@ -277,6 +285,7 @@ "Neveljavni": "Neveljavni", "Neveljavni elektronski naslov.": "Neveljavni elektronski naslov.", "Ni področja": "Ni področja", + "Ni še dodanih izvozov.": "Ni še dodanih izvozov.", "Ni še dodanih uvozov.": "Ni še dodanih uvozov.", "Ni še povezanih portalov": "Ni še povezanih portalov", "Ni slovarskih sestavkov za urejanje.": "Ni slovarskih sestavkov za urejanje.", @@ -295,6 +304,7 @@ "Niste vpisali naslova slovarja.": "Niste vpisali naslova slovarja.", "Niste vpisali opisa terminološkega problema.": "Niste vpisali opisa terminološkega problema.", "Niste vpisali priimka.": "Niste vpisali priimka.", + "Niste vpisali sporočila.": "Niste vpisali sporočila.", "Niste vpisali tujih jezikov.": "Niste vpisali tujih jezikov.", "Nov": "Nov", "Nov avtor": "Nov avtor", @@ -333,7 +343,6 @@ "Objavljeno": "Objavljeno", "Oblike": "Oblike", "Oblike, naglasi, izgovor": "Oblike, naglasi, izgovor", - "Obljavljeno": "Obljavljeno", "Obnovi": "Obnovi", "Obstoječe poimenovalne rešitve": "Obstoječe poimenovalne rešitve", "OBSTOJEČE POIMENOVALNE REŠITVE": "OBSTOJEČE POIMENOVALNE REŠITVE", @@ -346,9 +355,11 @@ "odprt": "odprt", "Odprt": "Odprt", "Odstrani": "Odstrani", + "Ogled virov na portalu": "Ogled virov na portalu", "Omogočeno": "Omogočeno", "OPIS PORTALA": "OPIS PORTALA", "OPIS SLOVARJA": "OPIS SLOVARJA", + "Opis slovarja": "Opis slovarja", "Opis terminološkega problema": "Opis terminološkega problema", "OPIS TERMINOLOŠKEGA PROBLEMA": "OPIS TERMINOLOŠKEGA PROBLEMA", "Opis terminološkega problema:": "Opis terminološkega problema:", @@ -359,8 +370,10 @@ "Oznaka portala": "Oznaka portala", "OZNAKA PORTALA *": "OZNAKA PORTALA *", "Po koncu urejanja vseh slovarskih sestavkov lahko slovar objavite in ga tako prikažete na javnem delu terminološkega portala.": "Po koncu urejanja vseh slovarskih sestavkov lahko slovar objavite in ga tako prikažete na javnem delu terminološkega portala.", + "Po urejanju nabora datotek se s klikom vrnemo na stran z nastavitvami parametrov luščenja.": "Po urejanju nabora datotek se s klikom vrnemo na stran z nastavitvami parametrov luščenja.", "Počisti filtre": "Počisti filtre", "POČISTI FILTRE": "POČISTI FILTRE", + "Podatki": "Podatki", "Podnaslov": "Podnaslov", "Podpodročja": "Podpodročja", "Podpodročja so namenjena podrobnejšemu razvrščanju terminoloških slovarjev. Administrator mora vsa novo predlagana podpodročja potrditi, preden jih lahko na seznamu vidijo tudi drugi uporabniki portala.": "Podpodročja so namenjena podrobnejšemu razvrščanju terminoloških slovarjev. Administrator mora vsa novo predlagana podpodročja potrditi, preden jih lahko na seznamu vidijo tudi drugi uporabniki portala.", @@ -412,11 +425,14 @@ "Pozabljeno geslo": "Pozabljeno geslo", "Pozdravljeni ": "Pozdravljeni ", "Pozor": "Pozor", + "Pozor, slovar s tem imenom že obstaja. Ali res želite izdelati slovar s tem imenom?": "Pozor, slovar s tem imenom že obstaja. Ali res želite izdelati slovar s tem imenom?", + "Pozor, slovar s tem imenom že obstaja. Ali res želite slovar preimenovati v ime, ki že obstaja?": "Pozor, slovar s tem imenom že obstaja. Ali res želite slovar preimenovati v ime, ki že obstaja?", "Prazno obvezno polje": "Prazno obvezno polje", "Preden naložite besedila, jih shranite v besedilni obliki (končnica .txt).": "Preden naložite besedila, jih shranite v besedilni obliki (končnica .txt).", "Predlog": "Predlog", "Predogled": "Predogled", "Pregledani": "Pregledani", + "Preimenuj": "Preimenuj", "Prekinjen": "Prekinjen", "Prekliči": "Prekliči", "Preverite, če ste pravilno vpisali uporabniško ime. Bodite pozorni na velike in male črke.": "Preverite, če ste pravilno vpisali uporabniško ime. Bodite pozorni na velike in male črke.", @@ -453,6 +469,8 @@ "rezultati": "rezultati", "Rezultati: ": "Rezultati: ", "rezultatov": "rezultatov", + "S klikom se vrnete na stran, kjer lahko zaženete postopek luščenja.": "S klikom se vrnete na stran, kjer lahko zaženete postopek luščenja.", + "S klikom shranite spremembe parametrov.": "S klikom shranite spremembe parametrov.", "S ključnimi besedami, ki so vključene v večino znanstvenih in strokovnih, lahko bolj natančno izberete besedila, ki jih želite uporabiti za luščenje terminoloških kandidatov.": "S ključnimi besedami, ki so vključene v večino znanstvenih in strokovnih, lahko bolj natančno izberete besedila, ki jih želite uporabiti za luščenje terminoloških kandidatov.", "S prijavo pridobite možnost uporabe vseh funkcij terminološkega portala.": "S prijavo pridobite možnost uporabe vseh funkcij terminološkega portala.", "S tem dejanjem boste izbrisali vse slovarske sestavke v slovarju in vse metapodatke. Dejanja ni mogoče razveljaviti.": "S tem dejanjem boste izbrisali vse slovarske sestavke v slovarju in vse metapodatke. Dejanja ni mogoče razveljaviti.", @@ -489,6 +507,7 @@ "SINONIMI": "SINONIMI", "Širši": "Širši", "SKRAJŠANI NASLOV SLOVARJA": "SKRAJŠANI NASLOV SLOVARJA", + "Skrajšani naslov slovarja": "Skrajšani naslov slovarja", "Skrbnik portala": "Skrbnik portala", "Skrbnik slovarjev": "Skrbnik slovarjev", "Skrbnik svetovalnice": "Skrbnik svetovalnice", @@ -516,6 +535,8 @@ "Slovenščina": "Slovenščina", "Soglašam s politiko zasebnosti": "Soglašam s politiko zasebnosti", "Sorodni": "Sorodni", + "Sporočilo je bilo poslano avtorjem slovarja.": "Sporočilo je bilo poslano avtorjem slovarja.", + "Sporočilo o slovarju \"{{name}}\"": "Sporočilo o slovarju \"{{name}}\"", "Sprememba stanja slovarja": "Sprememba stanja slovarja", "Spremeni geslo": "Spremeni geslo", "SPREMENJEN": "SPREMENJEN", @@ -587,6 +608,7 @@ "UPORABNIŠKO IME": "UPORABNIŠKO IME", "Uporabniško ime ali elektronski naslov": "Uporabniško ime ali elektronski naslov", "Uporabniško ime že obstaja": "Uporabniško ime že obstaja", + "Upoštevaj filtre": "Upoštevaj filtre", "Uredi": "Uredi", "UREDI": "UREDI", "Uredi lastnosti": "Uredi lastnosti", @@ -686,6 +708,7 @@ "Zadnji objavljeni slovarji": "Zadnji objavljeni slovarji", "Zadnji odgovori na vprašanja": "Zadnji odgovori na vprašanja", "Zadnji uvozi": "Zadnji uvozi", + "Zaključi nastavljanje parametrov": "Zaključi nastavljanje parametrov", "Zapomni si prijavo": "Zapomni si prijavo", "Zaporedje:": "Zaporedje:", "Zapri": "Zapri", @@ -710,6 +733,12 @@ "userStatusactive": "aktiven", "userStatusinactive": "neaktiven", "userStatusclosed": "zaprt", + "importStatusInProgress": "v teku", + "importStatusError": "napaka", + "importStatusDone": "uvožen", + "exportStatusPending": "čaka", + "exportStatusInProgress": "v teku", + "exportStatusFailed": "neuspešno", "Nepravilno uporabniško ime ali elektronski naslov.": "Nepravilno uporabniško ime ali elektronski naslov.", "Ponastavitev gesla": "Ponastavitev gesla", "Uspešna ponastavitev gesla": "Uspešna ponastavitev gesla", @@ -735,5 +764,26 @@ "Število slovarskih sestavkov": "Število slovarskih sestavkov", "VPRAŠANJE": "VPRAŠANJE", "MNENJE": "MNENJE", - "ANGLEŠKI PREVOD": "ANGLEŠKI PREVOD" + "ANGLEŠKI PREVOD": "ANGLEŠKI PREVOD", + "Univerza v Ljubljani": "Univerza v Ljubljani", + "ali": "ali", + "Ustvarite svoj profil": "Ustvarite svoj profil", + "Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in bodo uporabljeni za ustvarjanje vašega računa. Tukaj jih ni mogoče spreminjati.": "Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in bodo uporabljeni za ustvarjanje vašega računa. Tukaj jih ni mogoče spreminjati.", + "Pretvorite svoj račun": "Pretvorite svoj račun", + "Elektronski naslov, prijavljen prek Univerze v Ljubljani, se ujema z obstoječim računom na portalu z uporabniškim imenom ": "Elektronski naslov, prijavljen prek Univerze v Ljubljani, se ujema z obstoječim računom na portalu z uporabniškim imenom ", + ". Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in jih ni mogoče spreminjati. Z vnosom gesla obstoječega računa in potrditvijo boste ta račun trajno pretvorili: uporabniško ime, ime in priimek bodo nadomeščeni s podatki spodaj, geslo pa bo odstranjeno - odslej se boste lahko prijavili le še prek gumba za prijavo z Univerzo v Ljubljani.": ". Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in jih ni mogoče spreminjati. Z vnosom gesla obstoječega računa in potrditvijo boste ta račun trajno pretvorili: uporabniško ime, ime in priimek bodo nadomeščeni s podatki spodaj, geslo pa bo odstranjeno - odslej se boste lahko prijavili le še prek gumba za prijavo z Univerzo v Ljubljani.", + "POTRDI PRETVORBO": "POTRDI PRETVORBO", + "Vaš uporabniški račun ni aktiven. Za pomoč se obrnite na skrbnika portala.": "Vaš uporabniški račun ni aktiven. Za pomoč se obrnite na skrbnika portala.", + "Vaš račun pri Univerzi v Ljubljani ne vsebuje vseh podatkov (imena in priimka), potrebnih za ustvarjanje profila na portalu. Za pomoč se obrnite na skrbnika portala.": "Vaš račun pri Univerzi v Ljubljani ne vsebuje vseh podatkov (imena in priimka), potrebnih za ustvarjanje profila na portalu. Za pomoč se obrnite na skrbnika portala.", + "Nepravilno geslo.": "Nepravilno geslo.", + "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.": "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.", + "Prijava prek Univerze v Ljubljani trenutno ni na voljo. Poskusite kasneje.": "Prijava prek Univerze v Ljubljani trenutno ni na voljo. Poskusite kasneje.", + "Prijava prek Univerze v Ljubljani ni uspela. Poskusite znova.": "Prijava prek Univerze v Ljubljani ni uspela. Poskusite znova.", + "Prijava prek Univerze v Ljubljani ni uspela.": "Prijava prek Univerze v Ljubljani ni uspela.", + "Uspešno ste se prijavili prek Univerze v Ljubljani.": "Uspešno ste se prijavili prek Univerze v Ljubljani.", + "Uspešno ste ustvarili račun prek Univerze v Ljubljani in se prijavili.": "Uspešno ste ustvarili račun prek Univerze v Ljubljani in se prijavili.", + "Vaš račun je bil uspešno pretvorjen v prijavo prek Univerze v Ljubljani. Odslej se lahko prijavite le še prek tega načina.": "Vaš račun je bil uspešno pretvorjen v prijavo prek Univerze v Ljubljani. Odslej se lahko prijavite le še prek tega načina.", + "Seja je potekla. Poskusite znova.": "Seja je potekla. Poskusite znova.", + "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani, zato osebnih podatkov ni mogoče spreminjati na portalu.": "Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani, zato osebnih podatkov ni mogoče spreminjati na portalu.", + "Ta račun je bil ustvarjen s prijavo prek Univerze v Ljubljani, zato osebnih podatkov (ime, priimek, uporabniško ime, e-poštni naslov) tukaj ni mogoče spreminjati.": "Ta račun je bil ustvarjen s prijavo prek Univerze v Ljubljani, zato osebnih podatkov (ime, priimek, uporabniško ime, e-poštni naslov) tukaj ni mogoče spreminjati." } diff --git a/express/public/sass/components/_admin-dictionaries-filter.scss b/express/public/sass/components/_admin-dictionaries-filter.scss new file mode 100644 index 0000000..bb27088 --- /dev/null +++ b/express/public/sass/components/_admin-dictionaries-filter.scss @@ -0,0 +1,7 @@ +.admin-dict-filter-root { + max-width: 100%; + // The pager sits beside this on wide screens but wraps below it on narrow + // ones (.flex-wrap adds no gutter of its own) - without this, the search + // bar/filter panel and the pager controls touch with zero gap. + margin-bottom: 16px; +} diff --git a/express/public/sass/components/_extraction-main.scss b/express/public/sass/components/_extraction-main.scss index 9983d90..667816d 100644 --- a/express/public/sass/components/_extraction-main.scss +++ b/express/public/sass/components/_extraction-main.scss @@ -41,6 +41,25 @@ height: 32px; } +.form-actions { + .btn { + height: auto; + } + + // .btn-primary has no border, .border-header has a 1px border top and + // bottom; padding is split accordingly so both buttons are 40px tall + // on a single line despite the differing border widths. + .btn-primary { + padding-top: 9.5px; + padding-bottom: 9.5px; + } + + .border-header { + padding-top: 8.5px; + padding-bottom: 8.5px; + } +} + // List .task { diff --git a/express/public/sass/components/_header-section.scss b/express/public/sass/components/_header-section.scss index 17379b0..16f60a9 100644 --- a/express/public/sass/components/_header-section.scss +++ b/express/public/sass/components/_header-section.scss @@ -272,6 +272,12 @@ overflow: hidden; text-overflow: ellipsis; } + th button { + // Buttons (e.g. sortable column headers) don't inherit color/weight + // from their parent th by default - restore the plain-text th look. + font: inherit; + color: inherit; + } #thead { background-color: inherit !important; } diff --git a/express/public/sass/login-signup/_login-signup.scss b/express/public/sass/login-signup/_login-signup.scss index f44c297..a158c23 100644 --- a/express/public/sass/login-signup/_login-signup.scss +++ b/express/public/sass/login-signup/_login-signup.scss @@ -25,6 +25,10 @@ $modal-padding: 48px; width: 151px !important; } +.h-auto { + height: auto !important; +} + .no-bg-and-borders { border: none; background: none; @@ -255,3 +259,41 @@ form#register-form { } } } + +.sso-login-section { + padding-bottom: 1rem; + + #sso-login-btn { + display: flex; + align-items: center; + justify-content: center; + text-decoration: none; + + .sso-login-icon { + width: 24px; + height: 24px; + margin-right: 12px; + // White, to match .btn-primary's white text. + filter: brightness(0) invert(1); + } + } + + .sso-divider { + display: flex; + align-items: center; + text-align: center; + color: v.$header-title-gray; + margin: 1.25rem 0 0; + + &::before, + &::after { + content: ""; + flex: 1; + border-bottom: 1px solid v.$gray-C4; + } + + span { + padding: 0 1rem; + } + } +} diff --git a/express/public/sass/style.scss b/express/public/sass/style.scss index 4d471c4..a761e7b 100644 --- a/express/public/sass/style.scss +++ b/express/public/sass/style.scss @@ -14,6 +14,7 @@ @use "components/search-filter/result-detail"; @use "components/admin-main"; @use "components/admin-side-menu"; +@use "components/admin-dictionaries-filter"; @use "components/comments-main"; @use "components/content-main"; @use "components/content-side-menu"; diff --git a/express/routes/api/v1/dictionaries.js b/express/routes/api/v1/dictionaries.js index 8cb5d71..d90ad7c 100644 --- a/express/routes/api/v1/dictionaries.js +++ b/express/routes/api/v1/dictionaries.js @@ -27,6 +27,27 @@ router.get( dictionaries.listDictionaries ) +// Change page in pagination (read-only "Ogled virov" list, any logged-in user). +router.get( + '/listAllViewableDictionaries', + user.isAuthenticated, + dictionaries.listDictionaries +) + +// Soft-warning check: does a candidate dictionary name collide with another own dictionary? +router.get( + '/check-name-collision', + user.isAuthenticated, + dictionaries.checkNameCollision +) + +// Send a message to all users with a role on the given dictionary. +router.post( + '/:dictionaryId/contact-authors', + user.isAuthenticated, + dictionaries.contactDictionaryAuthors +) + // Change page in pagination router.get( '/:dictionaryId/listDomainLabels', @@ -76,6 +97,13 @@ router.post( dictionaries.exportBegin ) +// Delete a specific dictionary export. +router.delete( + '/:dictionaryId/export/:exportId', + user.canContentEdit, + dictionaries.deleteExport +) + router.get( '/:dictionaryId/domainLabels', user.canContentEdit, diff --git a/express/routes/api/v1/entries.js b/express/routes/api/v1/entries.js index 7fd1b4e..430a281 100644 --- a/express/routes/api/v1/entries.js +++ b/express/routes/api/v1/entries.js @@ -17,6 +17,7 @@ const { // All further routes are only available to authenticated users with dictionary content editing rights. router.use(user.isAuthenticated) router.use('/delete-entry', setDerivedDictionaryIdFromEntryId) +router.use('/:entryId/version-snapshots', setDerivedDictionaryIdFromEntryId) router.use(user.canContentEdit) // Render entry data for the selected entry diff --git a/express/routes/api/v1/users.js b/express/routes/api/v1/users.js index bfd447a..02395fd 100644 --- a/express/routes/api/v1/users.js +++ b/express/routes/api/v1/users.js @@ -2,6 +2,7 @@ const router = require('express-promise-router')() const user = require('../../../controllers/users') const users = require('../../../controllers/api/v1/users') const userAuth = require('../../../middleware/user') +const oidc = require('../../../controllers/oidc') // Validate and create a new user. router.post('/register', user.register) @@ -15,6 +16,13 @@ router.post('/reset-password-init', user.generateResetPasswordToken) // Validate new passwords, change if successful and sign the user in. router.post('/reset-password-submit', user.changePassword) +// Create a brand-new SSO account from the session-stored IdP claims, and sign the user in. +router.post('/create-profile', oidc.createProfileSubmit) + +// Confirm the matched local account's password, then permanently convert it into an SSO-only +// account (IdP-derived name/username, local password removed). +router.post('/convert-account', oidc.convertAccountSubmit) + // Find user by username or email in dictionary or admin console. router.get( '/addUser', @@ -41,6 +49,11 @@ router.post('/basic-data', users.updateBasicData) router.post('/password', users.updatePassword) // Delete user profile of the requesting user. +// TODO This route has no explicit isAuthenticated middleware, unlike the admin-only routes above +// - it relies entirely on req.user.id throwing inside the controller when req.user is undefined, +// which surfaces as an unhandled 500 rather than a clean 401/403 (see the general API-auth TODO +// in routes/api/index.js). Since this endpoint permanently destroys account data, it deserves an +// explicit auth check of its own rather than an implicit crash-as-guard. router.delete('/current', users.deleteCurrent) module.exports = router diff --git a/express/routes/index.js b/express/routes/index.js index d423da1..cc65194 100644 --- a/express/routes/index.js +++ b/express/routes/index.js @@ -2,6 +2,7 @@ const router = require('express-promise-router')() const { isAuthenticated: isUserAuthenticated } = require('../middleware/user') const index = require('../controllers/index') const user = require('../controllers/users') +const oidc = require('../controllers/oidc') // TODO Some of these endpoints might need authorization protection. Review and clean up at a later point. @@ -37,6 +38,14 @@ router.get('/slovarji/xml-schema', (req, res) => { // Activate user account. router.get('/users/activate', user.activateAccount) +// SSO/OIDC (University of Ljubljana) login. +router.get('/users/oidc/login', oidc.login) +// Fixed by the already-configured Authentik/University of Ljubljana redirect URI - path must not +// change. +router.get('/users/oidc/callback', oidc.callback) +router.get('/users/create-profile', oidc.createProfileForm) +router.get('/users/convert-account', oidc.convertAccountForm) + // Render privacy policy page router.get('/politika-zasebnosti', (req, res) => { res.render(`pages/privacy-policy_${req.language}`, { diff --git a/express/routes/view-resources.js b/express/routes/view-resources.js new file mode 100644 index 0000000..8ebb4b5 --- /dev/null +++ b/express/routes/view-resources.js @@ -0,0 +1,19 @@ +const router = require('express-promise-router')() +const dictionary = require('../controllers/dictionaries') + +// All routes require an authenticated user. Redirect to the site root, not +// req.baseUrl - unlike routes/dictionaries.js this router's own root ('/') +// is itself gated, so redirecting to req.baseUrl (== '/ogled-virov') would +// send an anonymous visitor straight back into the same check, looping. +router.use((req, res, next) => { + if (req.isAuthenticated()) return next() + res.redirect(303, '/') +}) + +// Show a read-only list of all dictionaries on the portal, regardless of status. +router.get('/', dictionary.listViewableDictionaries) + +// Show read-only details for a specific dictionary. +router.get('/:dictionaryId/podatki', dictionary.viewDictionaryDetails) + +module.exports = router diff --git a/express/views/components/consultancy/admin/consultancy-item-admin.pug b/express/views/components/consultancy/admin/consultancy-item-admin.pug index 019caeb..ff7a090 100644 --- a/express/views/components/consultancy/admin/consultancy-item-admin.pug +++ b/express/views/components/consultancy/admin/consultancy-item-admin.pug @@ -32,7 +32,7 @@ mixin consultancyItem(data, section) .circle.ms-1.align-items-center.justify-content-center.d-flex span.pt-0.question-asked-time.text-p625rem #{ data.sharedAuthors.length } span.d-inline-block.pt-0.ps-1.question-asked-time.text-p875rem.ms-2.me-1 • - span.d-inline-block.pt-0.ps-1.question-asked-time.text-p875rem= `${data.formattedTimeCreated}` + span.d-inline-block.pt-0.ps-1.question-asked-time.text-p875rem: time(data-timestamp=data.timeCreated data-timestamp-format="date") if (data.title) .row.mt-2.mb-2 .col diff --git a/express/views/components/consultancy/consultancy-item.pug b/express/views/components/consultancy/consultancy-item.pug index 79a7da7..7b013b0 100644 --- a/express/views/components/consultancy/consultancy-item.pug +++ b/express/views/components/consultancy/consultancy-item.pug @@ -4,8 +4,9 @@ mixin consultancyItem(entry) .row.mt-4.mb-2 .col.d-flex.justify-content-start //- 9. 11. 2021 --> questionDateDMYformat - //- span.question-asked-time.text-p875rem= `Vprašanje poslano: ${entry.formattedTimeCreated}` - span.question-asked-time.text-p875rem= t('Vprašanje poslano:') + `${entry.formattedTimeCreated}` + span.question-asked-time.text-p875rem + = t('Vprašanje poslano:') + time(data-timestamp=entry.timeCreated data-timestamp-format="date") .row.mb-2 .col h5.pb-0.title-cons diff --git a/express/views/components/dictionary/dictionary-list-table-mixin.pug b/express/views/components/dictionary/dictionary-list-table-mixin.pug new file mode 100644 index 0000000..716825c --- /dev/null +++ b/express/views/components/dictionary/dictionary-list-table-mixin.pug @@ -0,0 +1,119 @@ +mixin dictionaryListTable(data) + .d-flex.justify-content-between.flex-wrap + #admin-dict-filter-root.admin-dict-filter-root + .search-root-mobile-only.ps-0.pe-0 + #searchbar-main.text-center + .search-bar.height-46p(tabindex="0") + button.searchbar-icon-container#search-dictionaries(type="button") + img.search_icon(src="/images/search.svg" alt="OK") + input#dict-name-search.search-input( + type="text" + placeholder=t('Ime slovarja') + value=data.q + ) + button#keyboard.search-button-keyboard + span + img.keyboard(src="/images/keyboard.svg" alt="Keys") + button#advanced-search.dropdown-btn + img(src="/images/dropdown.svg" alt="Opt") + #admin-dict-filter-panel.advanced-search-root( + class=(data.pd.length || data.sd.length || data.lang.length || data.status.length) ? '' : 'd-none-weak' + ) + .advanced-search-filter-section + .advanced-search-filter-division + span + .d-flex.w-100 + label.d-flex.flex-grow-1.align-items-end + select#filter-domain-primary.select-admin-domain-primary( + multiple="multiple" + ) + each domain in data.allPrimaryDomains + option( + value=domain.id + selected=data.pd.includes(String(domain.id)) + )= domain.name + span + .d-flex.w-100 + label.d-flex.flex-grow-1.align-items-end + select#filter-domain-secondary.select-admin-domain-secondary( + multiple="multiple" + ) + each domain in data.allSecondaryDomains + option( + value=domain.id + selected=data.sd.includes(String(domain.id)) + )= domain.name + .advanced-search-filter-division + span + .d-flex.w-100 + label.d-flex.flex-grow-1.align-items-end + select#filter-language.select-admin-language( + multiple="multiple" + ) + each language in data.allLanguages + option( + value=language.id + selected=data.lang.includes(String(language.id)) + )= language.name + span + .d-flex.w-100 + label.d-flex.flex-grow-1.align-items-end + select#filter-status.select-admin-status(multiple="multiple") + each s in data.allStatuses + option(value=s.value selected=data.status.includes(s.value))= s.label + .advanced-search-final-options + span + button#clear-filters.btn.clear-f(type="button")= t('Počisti filtre') + button#apply-filters.btn.search-btn-a(type="button")= t('Upoštevaj filtre') + include /utilities/keyboard + +keyboard() + .d-flex + include /utilities/pager + +pager(data.page) + + .table-responsive + table.styled-table + thead + tr#thead + - const arrowSrc = data.sortDir === 'asc' ? '/images/arrow_drop_up.svg' : '/images/arrow_drop_down.svg' + th + button#sortById.no-bg.no-border.text-decoration-none(type="button") + span= 'ID' + img#idImg(class=data.sortBy === 'id' ? '' : 'invisible' src=arrowSrc alt="") + th + button#sortByName.no-bg.no-border.text-decoration-none(type="button") + span= t('NASLOV') + img#nameImg(class=data.sortBy === 'name' ? '' : 'invisible' src=arrowSrc alt="") + th + button#sortByStatus.no-bg.no-border.text-decoration-none(type="button") + span= t('STATUS') + img#statusImg(class=data.sortBy === 'status' ? '' : 'invisible' src=arrowSrc alt="") + th + button#sortByTimeCreated.no-bg.no-border.text-decoration-none(type="button") + span= t('USTVARJEN') + img#timeCreatedImg(class=data.sortBy === 'timeCreated' ? '' : 'invisible' src=arrowSrc alt="") + th + button#sortByTimeModified.no-bg.no-border.text-decoration-none(type="button") + span= t('SPREMENJEN') + img#timeModifiedImg(class=data.sortBy === 'timeModified' ? '' : 'invisible' src=arrowSrc alt="") + th= '' + tbody#page-results + each result in data.results + tr + td= result.id + td= result.name + if result.status === 'closed' + td= t('zaprt') + else if result.status ==='reviewed' + td= t('v predogledu') + else + td= t('odprt') + td: time(data-timestamp=result.timeCreated data-timestamp-format="datetime") + td: time(data-timestamp=result.timeModified data-timestamp-format="datetime") + td + a.image-link( + type="link" + href=data.rowAction.hrefBuilder(result.id) + ) + img(src=data.rowAction.icon alt=data.rowAction.label) + span.normal-gray.ms-1= data.rowAction.label diff --git a/express/views/components/login-signup/login-signup.pug b/express/views/components/login-signup/login-signup.pug index d73bdc0..336bfc1 100644 --- a/express/views/components/login-signup/login-signup.pug +++ b/express/views/components/login-signup/login-signup.pug @@ -31,6 +31,14 @@ method="post" autocomplete="off" ) + .sso-login-section + a#sso-login-btn.btn.btn-primary.h41.w-100( + href="/users/oidc/login" + ) + img.sso-login-icon(src="/images/icon-user-x.svg" alt="") + span= t('Univerza v Ljubljani') + .sso-divider + span= t('ali') .row .col-2.d-flex.align-items-center.justify-content-center.pe-4 img(src="/images/user.svg" alt="") diff --git a/express/views/components/navigation/main-navigation-right-mixin.pug b/express/views/components/navigation/main-navigation-right-mixin.pug index 1364337..fe8f5ee 100644 --- a/express/views/components/navigation/main-navigation-right-mixin.pug +++ b/express/views/components/navigation/main-navigation-right-mixin.pug @@ -32,6 +32,9 @@ mixin main-navigation-right(languageToolbarPresent=false, menuTextPresent=false, if user && (user.hasRole('portal admin') || user.hasRole('dictionaries admin')) li a.dropdown-item(href="/admin")= t('Administracija') + if user && dictionariesEnabled + li + a.dropdown-item(href="/ogled-virov")= t('Ogled virov na portalu') li a.dropdown-item(href="/pomoc")= t('Pomoč') diff --git a/express/views/email/dictionary-contact-authors_en.pug b/express/views/email/dictionary-contact-authors_en.pug new file mode 100644 index 0000000..2ff5432 --- /dev/null +++ b/express/views/email/dictionary-contact-authors_en.pug @@ -0,0 +1,3 @@ +p Dear user, +p #[b #{ senderName }] (#{ senderEmail }) has sent you a message via the Slovenian Terminology Portal regarding the dictionary #[b #{ dictionaryName }]: +p #{ message } diff --git a/express/views/email/dictionary-contact-authors_sl.pug b/express/views/email/dictionary-contact-authors_sl.pug new file mode 100644 index 0000000..f46edec --- /dev/null +++ b/express/views/email/dictionary-contact-authors_sl.pug @@ -0,0 +1,3 @@ +p Pozdravljeni, +p uporabnik #[b #{ senderName }] (#{ senderEmail }) vam je preko Slovenskega terminološkega portala poslal sporočilo v zvezi s slovarjem #[b #{ dictionaryName }]: +p #{ message } diff --git a/express/views/layout.pug b/express/views/layout.pug index b085dc0..29745d6 100644 --- a/express/views/layout.pug +++ b/express/views/layout.pug @@ -109,6 +109,7 @@ html(lang=language) if inDevEnv script(nonce=cspNonce) window.inDevEnv = true + script(nonce=cspNonce src="/javascripts/date-utils.js") script(nonce=cspNonce src="/javascripts/globals.js") script(nonce=cspNonce src="/javascripts/scripts.js") script(nonce=cspNonce src="/javascripts/main-sreach-utils.js") diff --git a/express/views/pages/admin/dictionaries-list.pug b/express/views/pages/admin/dictionaries-list.pug index 5f437b5..a6c2112 100644 --- a/express/views/pages/admin/dictionaries-list.pug +++ b/express/views/pages/admin/dictionaries-list.pug @@ -2,6 +2,7 @@ extends /layout block pageSpecificScipts script(nonce=cspNonce src="/javascripts/admin.js") + script(nonce=cspNonce src="/javascripts/dictionary-list-table.js") block body section#fixed-top-section @@ -16,50 +17,26 @@ block body +mainHeader(c) .content-hold-prerequisites #offset-main.main-container.mt-3 - .d-flex.justify-content-end - .d-flex - include /utilities/pager - +pager - - - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit', - } - - .table-responsive - table.styled-table - thead - tr#thead - th= 'ID' - th= t('NASLOV') - th= t('STATUS') - th= t('USTVARJEN') - th= t('SPREMENJEN') - th= '' - tbody#page-results - each result in results - tr - td= result.id - td= result.name - if result.status === 'closed' - td= t('zaprt') - else if result.status ==='reviewed' - td= t('v predogledu') - else - td= t('odprt') - - const dateC = new Date(result.timeCreated).toLocaleDateString('sl-SL', localeOptions) - - const dateM = new Date(result.timeModified).toLocaleDateString('sl-SL', localeOptions) - td= dateC - td= dateM - td - a.image-link( - type="link" - href=`/admin/slovarji/${result.id}/podatki` - ) - img(src="/images/u_edit-alt.svg" alt=t('Uredi')) - span.normal-gray.ms-1= t('Uredi') + include /components/dictionary/dictionary-list-table-mixin + +dictionaryListTable({ + results, + page, + sortBy, + sortDir, + q, + pd, + sd, + lang, + status, + allPrimaryDomains, + allSecondaryDomains, + allLanguages, + allStatuses, + rowAction: { + hrefBuilder: id => `/admin/slovarji/${id}/podatki`, + icon: '/images/u_edit-alt.svg', + label: t('Uredi') + } + }) include /common/footer diff --git a/express/views/pages/admin/dictionary-description.pug b/express/views/pages/admin/dictionary-description.pug index 4e2f4ca..0b5941d 100644 --- a/express/views/pages/admin/dictionary-description.pug +++ b/express/views/pages/admin/dictionary-description.pug @@ -19,3 +19,4 @@ block body include /utilities/modal-alert include /utilities/modal-alert-mixin +alertModal('unsaved-data', t('Shrani'), t('Ne'), 'modal-save-btn', 'modal-dont-save-btn', t('Imate neshranjene spremembe. Ali jih želite shraniti?')) + +alertModal('name-collision-warning', t('Preimenuj'), t('Prekliči'), 'modal-rename-btn', 'modal-cancel-rename-btn', t('Pozor, slovar s tem imenom že obstaja. Ali res želite slovar preimenovati v ime, ki že obstaja?')) diff --git a/express/views/pages/admin/dictionary-export.pug b/express/views/pages/admin/dictionary-export.pug index d281b46..d1c4658 100644 --- a/express/views/pages/admin/dictionary-export.pug +++ b/express/views/pages/admin/dictionary-export.pug @@ -1,7 +1,6 @@ extends /layout block pageSpecificScipts script(nonce=cspNonce src="/javascripts/dictionaries.js") - script(nonce=cspNonce src="/javascripts/dictionary-export.js") block body section#fixed-top-section diff --git a/express/views/pages/consultancy/admin/edit.pug b/express/views/pages/consultancy/admin/edit.pug index 95397ca..64a1447 100644 --- a/express/views/pages/consultancy/admin/edit.pug +++ b/express/views/pages/consultancy/admin/edit.pug @@ -18,7 +18,7 @@ block body include /common/main-navigation +main-navigation(false) block config - - const pageTypeObject = sentFrom + - const pageTypeObject = meta - const subHeading = t('Urejanje') - const description = t('Dodajte terminološki odgovor in ga utemeljite.') @@ -35,11 +35,16 @@ block body #offset-main.main-container.offset-correction .row.mt-4.mx-0 .col.g-0 - p.text-header-description-gray.mb-2 #{ t('Datum vprašanja:') } #{ entry.timeCreated } + p.text-header-description-gray.mb-2 + != `${t('Datum vprašanja:')}` + time(data-timestamp=entry.timeCreated data-timestamp-format="date") p.text-header-description-gray.mt-2.mb-0 #{ t('Uporabnik') }: #{ author.firstName } p.text-header-description-gray.mt-1 #{ t('E-pošta') }: #{ author.email } hr - p.text-header-description-gray.mb-2 #{ t('Datum objave/spremembe') }: #{ entry.timePublished } + p.text-header-description-gray.mb-2 + != `${t('Datum objave/spremembe')}:` + if entry.timePublished + time(data-timestamp=entry.timePublished data-timestamp-format="date") p.text-header-description-gray.mt-2.mb-0 #{ t('Avtorji mnenja:') } span.text-header-description-gray= ` ${entry.answerAuthors ? entry.answerAuthors.join(`, `) : ''}` p.text-header-description-gray.mt-1 #{ t('URL povezava do mnenja:') } #{ isPublished?`${urlPrefix}/svetovanje/vprasanje/${id}`:'' } diff --git a/express/views/pages/consultancy/item-details.pug b/express/views/pages/consultancy/item-details.pug index 8a3e1f3..748ab9c 100644 --- a/express/views/pages/consultancy/item-details.pug +++ b/express/views/pages/consultancy/item-details.pug @@ -31,7 +31,9 @@ block body .consultancy-item-detailed .row .col-6.d-flex.justify-content-start - span Vprašanje poslano: #{ entry.timeCreated } + span + | Vprašanje poslano: + time(data-timestamp=entry.timeCreated data-timestamp-format="date") //- .col-6.d-flex.justify-content-end button.me-3.bg-transparent.no-border img.i1p5rx1p5r(src="/images/copy.svg") diff --git a/express/views/pages/dictionaries/description.pug b/express/views/pages/dictionaries/description.pug index 8f82357..3c52d8f 100644 --- a/express/views/pages/dictionaries/description.pug +++ b/express/views/pages/dictionaries/description.pug @@ -19,3 +19,4 @@ block body include /utilities/modal-alert include /utilities/modal-alert-mixin +alertModal('unsaved-data', t('Shrani'), t('Ne'), 'modal-save-btn', 'modal-dont-save-btn', t('Imate neshranjene spremembe. Ali jih želite shraniti?')) + +alertModal('name-collision-warning', t('Preimenuj'), t('Prekliči'), 'modal-rename-btn', 'modal-cancel-rename-btn', t('Pozor, slovar s tem imenom že obstaja. Ali res želite slovar preimenovati v ime, ki že obstaja?')) diff --git a/express/views/pages/dictionaries/export.pug b/express/views/pages/dictionaries/export.pug index be6dbb5..95a3cbd 100644 --- a/express/views/pages/dictionaries/export.pug +++ b/express/views/pages/dictionaries/export.pug @@ -2,7 +2,6 @@ extends /layout block pageSpecificScipts script(nonce=cspNonce src="/javascripts/dictionaries.js") - script(nonce=cspNonce src="/javascripts/dictionary-export.js") block body section#fixed-top-section diff --git a/express/views/pages/dictionaries/list.pug b/express/views/pages/dictionaries/list.pug index 383ff5e..e353e90 100644 --- a/express/views/pages/dictionaries/list.pug +++ b/express/views/pages/dictionaries/list.pug @@ -16,12 +16,6 @@ block body .content-hold-prerequisites #offset-main.ps-3.pe-3 if dictionaries.length - - - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric' - } each dictionary, index in dictionaries div( class=index ? 'container-fluid dictionary-content mt-4 pb-2 pt-1' : 'container-fluid dictionary-content mt-3 pb-2 pt-1' @@ -37,7 +31,7 @@ block body span.dictionary-value.me-5= dictionary.countEntries .d-sm-flex.mt-2 span.dictionary-attributes.me-3.ms-xl-5.text-nowrap= t('Zadnja sprememba') - span.dictionary-value.me-md-5.me-2.d-block= dictionary.timeModified.toLocaleDateString('sl-SL', localeOptions) + span.dictionary-value.me-md-5.me-2.d-block: time(data-timestamp=dictionary.timeModified.toISOString() data-timestamp-format="date") .d-lg-flex .d-sm-flex.mt-2 span.dictionary-attributes.me-3.ms-xl-5.d-inline= t('Status') diff --git a/express/views/pages/dictionaries/new.pug b/express/views/pages/dictionaries/new.pug index edad5cb..94fbdd0 100644 --- a/express/views/pages/dictionaries/new.pug +++ b/express/views/pages/dictionaries/new.pug @@ -18,4 +18,6 @@ block body include /utilities/dictionary-main-input +dictionaryMainInput({ formId: 'form-dictionary-new', hasStructure: true}) include /utilities/modal-alert + include /utilities/modal-alert-mixin + +alertModal('name-collision-warning', t('Ustvari'), t('Prekliči'), 'modal-create-btn', 'modal-cancel-create-btn', t('Pozor, slovar s tem imenom že obstaja. Ali res želite izdelati slovar s tem imenom?')) include /common/footer diff --git a/express/views/pages/extraction/docs-edit.pug b/express/views/pages/extraction/docs-edit.pug index 3f5272a..5c6a68f 100644 --- a/express/views/pages/extraction/docs-edit.pug +++ b/express/views/pages/extraction/docs-edit.pug @@ -11,7 +11,7 @@ block body include /common/side-menu-fake +sideNavigationFake include /utilities/dictionaries-main-panel-header - - const c = { noSidebar: false, hrefurl: '.', h2: t('Luščenje iz lastnih besedil | dodaj opravilo '), h1: t('Uporabnikovi dokumenti'), description: t('Uporabnik na tem mestu izdela specializirani korpus iz besedil, ki jih je zbral in shranil sam. Besedila naj bodo izbrana po načelih tvorjenja specializiranih korpusov. Za uspešno luščenje priporočamo najmanj 10 besedil. Vsa besedila naj bodo shranjena v besedilnem formatu (.txt). Luščenje podpira tudi formate .docx in .pdf, vendar so rezultati slabši.'), buttons: [{ type: 'cancel', content: t('Naprej'), classAtr: 'btn border-header header-btn-secondary link-back' }] } + - const c = { noSidebar: false, hrefurl: '.', h2: t('Luščenje iz lastnih besedil | dodaj opravilo '), h1: t('Uporabnikovi dokumenti'), description: t('Uporabnik na tem mestu izdela specializirani korpus iz besedil, ki jih je zbral in shranil sam. Besedila naj bodo izbrana po načelih tvorjenja specializiranih korpusov. Za uspešno luščenje priporočamo najmanj 10 besedil. Vsa besedila naj bodo shranjena v besedilnem formatu (.txt). Luščenje podpira tudi formate .docx in .pdf, vendar so rezultati slabši.') } +mainHeader(c) .content-hold-prerequisites.mt-2 #offset-main @@ -31,7 +31,7 @@ block body td.file-index= index + 1 td.file-name= document.filename td.file-size= document.size - td.file-date-modified= new Date(document.timeModified).toLocaleDateString('sl-SL') + td.file-date-modified: time(data-timestamp=new Date(document.timeModified).toISOString() data-timestamp-format="date") td.file-last-cell button.p-0.delete-file.delete-btn-table img(src="/images/red-trash-icon.svg" alt="") @@ -54,6 +54,11 @@ block body ) .col.d-flex.align-items-center.ms-md-3 span.gray-info= t('Dodaj besedilo za luščenje terminoloških kandidatov iz lastnega specializiranega korpusa. Ko boste dodali vsa besedila, ki ste jih izbrali, morate izbiro shraniti.') + .form-actions.row.ms-2.me-2.align-items-center.mt-4 + .col-sm-5 + a.btn.border-header(href=`/luscenje/${id}`)= t('Nazaj na nastavitve parametrov') + .col.d-flex.align-items-center.ms-md-3 + span.gray-info= t('Po urejanju nabora datotek se s klikom vrnemo na stran z nastavitvami parametrov luščenja.') //- include /utilities/modal-spinner include /utilities/modal-alert include /common/footer diff --git a/express/views/pages/extraction/edit-own.pug b/express/views/pages/extraction/edit-own.pug index a3e40bc..5f1a3c8 100644 --- a/express/views/pages/extraction/edit-own.pug +++ b/express/views/pages/extraction/edit-own.pug @@ -11,24 +11,11 @@ block body include /common/side-menu-fake +sideNavigationFake include /utilities/dictionaries-main-panel-header - - const c = { noSidebar: false, hrefurl: '/luscenje', h2: t('Luščenje iz lastnih besedil'), h1: t('Dodaj opravilo'), description: t('Luščenje terminoloških kandidatov iz besedil, ki jih uporabnik namensko izbere, je najučinkovitejše. Primerno izbrano ime opravila, vam omogoča, da lahko sledite, katera luščenja ste že opravili. Ko vnesete podatke, morate vse spremembe shraniti. Zaradi omejenega prostora za shranjevanje lahko shranite največ pet zadnjih luščenj. '), buttons: [{ type: 'cancel', url:'/luscenje', content: t('Naprej'), classAtr:"btn border-header header-btn-secondary" }, { type: 'button', content: t('Shrani'), classAtr:'btn btn-primary disabled header-btn', form: 'extraction-name' }] } + - const c = { noSidebar: false, hrefurl: '/luscenje', h2: t('Luščenje iz lastnih besedil'), h1: t('Nastavi parametre luščenja'), description: t('Luščenje terminoloških kandidatov iz besedil, ki jih uporabnik namensko izbere, je najučinkovitejše. Primerno izbrano ime opravila, vam omogoča, da lahko sledite, katera luščenja ste že opravili. Ko vnesete podatke, morate vse spremembe shraniti. Zaradi omejenega prostora za shranjevanje lahko shranite največ pet zadnjih luščenj. ') } +mainHeader(c) .root-container .content-hold-prerequisites.mt-2 #offset-main - form#extraction-name(method="post") - .subject-name - label.smaller-black-uppercase(for="name")= t('IME') - .row.pe-0 - .col-sm-6.pe-0 - input#name.name-input.form-control.d-inline( - type="text" - name="name" - value=extraction.name - ) - .col-sm.d-flex.align-items-center.ms-sm-4.ps-sm-0.mt-1.mt-sm-0 - span.d-md-inline.d-block.smaller-gray-info= t('Izberite takšno ime, ki vam bo pomagalo slediti rezultatom, če boste luščenje besedil opravili večkrat.') - .table-documents.mt-4.d-sm-flex .col-sm-6.d-flex.flex-column .personal-documents.justify-content-between.d-flex.align-items-center @@ -67,4 +54,34 @@ block body .col-sm.d-flex.ms-sm-4.mt-1.mt-sm-0 .d-md-inline.d-block.smaller-gray-info!= t('Dodate lahko seznam besed, ki jih v seznam terminoloških kandidatov ne želite vključiti. Seznam naj bo shranjen v formatu .txt. Vse spremembe morate shraniti. Več...') + form#extraction-name.mt-4(method="post") + .subject-name + label.smaller-black-uppercase(for="name")= t('IME') + .row.pe-0 + .col-sm-6.pe-0 + input#name.name-input.form-control.d-inline( + type="text" + name="name" + value=extraction.name + ) + .col-sm.d-flex.align-items-center.ms-sm-4.ps-sm-0.mt-1.mt-sm-0 + span.d-md-inline.d-block.smaller-gray-info= t('Izberite takšno ime, ki vam bo pomagalo slediti rezultatom, če boste luščenje besedil opravili večkrat.') + + .form-actions.mt-4 + .row.pe-0.align-items-center + .col-sm-6.pe-0 + button#mpbtn.btn.btn-primary.disabled( + form="extraction-name" + )= t('Shrani') + .col-sm.d-flex.align-items-center.ms-sm-4.ps-sm-0.mt-1.mt-sm-0 + span.d-md-inline.d-block.smaller-gray-info= t('S klikom shranite spremembe parametrov.') + .row.pe-0.align-items-center.mt-3 + .col-sm-6.pe-0 + a.btn.border-header( + type="link" + href="/luscenje" + )= t('Zaključi nastavljanje parametrov') + .col-sm.d-flex.align-items-center.ms-sm-4.ps-sm-0.mt-1.mt-sm-0 + span.d-md-inline.d-block.smaller-gray-info= t('S klikom se vrnete na stran, kjer lahko zaženete postopek luščenja.') + include /common/footer diff --git a/express/views/pages/extraction/list.pug b/express/views/pages/extraction/list.pug index e780ffd..339ad0c 100644 --- a/express/views/pages/extraction/list.pug +++ b/express/views/pages/extraction/list.pug @@ -14,18 +14,6 @@ block body include /utilities/dictionaries-main-panel-header - const c = { sideMenu: false, h2: t('Luščenje'), h1: t('Seznam luščenj'), description: t('Nabor vseh luščenj, s katerimi lahko uporabnik iz izbranih besedil pridobi sezname terminoloških kandidatov. Posamezne terminološke kandidate lahko preveri tudi v konkordančniku.') } +mainHeader(c) - - - const localeDayOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric' - } - - - - const localeHourOptions = { - hour: '2-digit', - minute: '2-digit', - } .content-hold-prerequisites #offset-main.mt-2 if extractions.length >= 5 @@ -92,9 +80,9 @@ block body .d-flex.align-items-center img.me-1(src="/images/fi_calendar.svg") span.smaller-gray-uppercase.align-items-center= t('Začetek') - .d-grid.ms-4.align-items-center - span.bold-weight-black= el.timeStarted.toLocaleString('sl-SI', localeDayOptions) - span.normal-gray= el.timeStarted.toLocaleString('sl-SI', localeHourOptions) + .d-grid.ms-4.align-items-center(data-timestamp=el.timeStarted.toISOString()) + span.bold-weight-black(data-timestamp-part="date") + span.normal-gray(data-timestamp-part="time") hr.mt-2.mb-3 .d-flex.justify-content-between .d-sm-flex.align-items-center.mb-0.flex-grow-1 @@ -113,17 +101,17 @@ block body .d-sm-flex.align-items-center img.me-1(src="/images/fi_calendar.svg") span.smaller-gray-uppercase.align-items-center= t('Začetek') - .d-grid.ms-2.ms-sm-4.align-items-center - span.bold-weight-black= el.timeStarted.toLocaleString('sl-SI', localeDayOptions) - span.normal-gray= el.timeStarted.toLocaleString('sl-SI', localeHourOptions) + .d-grid.ms-2.ms-sm-4.align-items-center(data-timestamp=el.timeStarted.toISOString()) + span.bold-weight-black(data-timestamp-part="date") + span.normal-gray(data-timestamp-part="time") .d-md-flex.start-date.ms-sm-5.ms-2.mt-2.mt-md-0 .d-md-grid.ms-md-1.align-items-center .d-md-flex.align-items-center img.me-1(src="/images/fi_calendar.svg") span.smaller-gray-uppercase.align-items-center= t('Konec') - .d-grid.ms-4.align-items-center - span.bold-weight-black= el.timeFinished.toLocaleString('sl-SI', localeDayOptions) - span.normal-gray= el.timeFinished.toLocaleString('sl-SI', localeHourOptions) + .d-grid.ms-4.align-items-center(data-timestamp=el.timeFinished.toISOString()) + span.bold-weight-black(data-timestamp-part="date") + span.normal-gray(data-timestamp-part="time") //- TODO: Once duplication is implemented remove ".invisible" class .d-flex.align-items-center.justify-content-lg-end.mt-2.mt-sm-0.ms-2.ms-md-0.invisible @@ -158,17 +146,17 @@ block body .d-sm-flex.align-items-center img.me-1(src="/images/fi_calendar.svg") span.smaller-gray-uppercase.align-items-center= t('Začetek') - .d-grid.ms-2.ms-sm-4.align-items-center - span.bold-weight-black= el.timeStarted.toLocaleString('sl-SI', localeDayOptions) - span.normal-gray= el.timeStarted.toLocaleString('sl-SI', localeHourOptions) + .d-grid.ms-2.ms-sm-4.align-items-center(data-timestamp=el.timeStarted.toISOString()) + span.bold-weight-black(data-timestamp-part="date") + span.normal-gray(data-timestamp-part="time") .d-md-flex.start-date.ms-sm-5.ms-2.mt-2.mt-md-0 .d-md-grid.ms-md-1.align-items-center .d-md-flex.align-items-center img.me-1(src="/images/fi_calendar.svg") span.smaller-gray-uppercase.align-items-center= t('Konec') - .d-grid.ms-4.align-items-center - span.bold-weight-black= el.timeFinished.toLocaleString('sl-SI', localeDayOptions) - span.normal-gray= el.timeFinished.toLocaleString('sl-SI', localeHourOptions) + .d-grid.ms-4.align-items-center(data-timestamp=el.timeFinished.toISOString()) + span.bold-weight-black(data-timestamp-part="date") + span.normal-gray(data-timestamp-part="time") .d-flex.align-items-center.ms-2.ms-sm-auto.mt-2.mt-md-0 img(src="/images/fi_check-circle.svg") diff --git a/express/views/pages/extraction/stop-terms-edit.pug b/express/views/pages/extraction/stop-terms-edit.pug index f023005..5980bb4 100644 --- a/express/views/pages/extraction/stop-terms-edit.pug +++ b/express/views/pages/extraction/stop-terms-edit.pug @@ -11,7 +11,7 @@ block body include /common/side-menu-fake +sideNavigationFake include /utilities/dictionaries-main-panel-header - - const c = { noSidebar: false, hrefurl: '.', h2: t('Luščenje | dodaj opravilo'), h1: t('Seznam neželenih terminov'), description: t('Seznam terminoloških kandidatov bo natančnejši, če boste dodali tudi seznam neželenih besed, ki naj jih luščilnik izloči iz seznama. Seznam lahko vsebuje splošne termine, npr. tabela, kazalnik, ali pogoste slovnične besede, zlasti veznike, pomožne glagole.'), buttons: [{ type: 'cancel', content: t('Naprej'), classAtr: 'btn border-header header-btn-secondary link-back' }] } + - const c = { noSidebar: false, hrefurl: '.', h2: t('Luščenje | dodaj opravilo'), h1: t('Seznam neželenih terminov'), description: t('Seznam terminoloških kandidatov bo natančnejši, če boste dodali tudi seznam neželenih besed, ki naj jih luščilnik izloči iz seznama. Seznam lahko vsebuje splošne termine, npr. tabela, kazalnik, ali pogoste slovnične besede, zlasti veznike, pomožne glagole.') } +mainHeader(c) .content-hold-prerequisites.mt-2 #offset-main @@ -31,7 +31,7 @@ block body td.file-index= index + 1 td.file-name= document.filename td.file-size= document.size - td.file-date-modified= new Date(document.timeModified).toLocaleDateString('sl-SL') + td.file-date-modified: time(data-timestamp=new Date(document.timeModified).toISOString() data-timestamp-format="date") td.file-last-cell button.p-0.delete-file.delete-btn-table img(src="/images/red-trash-icon.svg" alt="") @@ -54,6 +54,11 @@ block body ) .col.d-flex.align-items-center.ms-md-3 span.gray-info!= t('Dodate lahko seznam besed, ki jih v seznam terminoloških kandidatov ne želite vključiti. Seznam naj bo shranjen v formatu .txt. Na koncu morate spremembe shraniti. Več ...') + .form-actions.row.ms-2.me-2.align-items-center.mt-4 + .col-sm-5 + a.btn.border-header(href=`/luscenje/${id}`)= t('Nazaj na nastavitve parametrov') + .col.d-flex.align-items-center.ms-md-3 + span.gray-info= t('Po urejanju nabora datotek se s klikom vrnemo na stran z nastavitvami parametrov luščenja.') //- include /utilities/modal-spinner include /utilities/modal-alert include /common/footer diff --git a/express/views/pages/index.pug b/express/views/pages/index.pug index 7687f38..05ef26a 100644 --- a/express/views/pages/index.pug +++ b/express/views/pages/index.pug @@ -11,8 +11,7 @@ block body .index-nav ul.nav li.nav-item - a(href="https://www.slovenscina.eu/") - img.logo(src="/images/logo.png" alt="Logo") + img.logo(src="/images/logo.png" alt="Logo") include ../components/navigation/main-navigation-right-mixin diff --git a/express/views/pages/oidc/convert-account.pug b/express/views/pages/oidc/convert-account.pug new file mode 100644 index 0000000..cb261d2 --- /dev/null +++ b/express/views/pages/oidc/convert-account.pug @@ -0,0 +1,65 @@ +extends /layout + +block pageSpecificScipts + script(nonce=cspNonce src="/javascripts/oidc-forms.js") + script(nonce=cspNonce src="/javascripts/offset-header.js") + +block body + section#fixed-top-section + include /common/main-navigation + +main-navigation(false) + include /utilities/generic-main-panel-header + - const c = { h1: t('Pretvorite svoj račun'), description: t('Elektronski naslov, prijavljen prek Univerze v Ljubljani, se ujema z obstoječim računom na portalu z uporabniškim imenom ') + existingUsername + t('. Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in jih ni mogoče spreminjati. Z vnosom gesla obstoječega računa in potrditvijo boste ta račun trajno pretvorili: uporabniško ime, ime in priimek bodo nadomeščeni s podatki spodaj, geslo pa bo odstranjeno - odslej se boste lahko prijavili le še prek gumba za prijavo z Univerzo v Ljubljani.') } + +mainHeader(c) + .content-hold-prerequisites.ps-3.pe-3 + #offset-main.container-fluid.mt-4.px-0 + .p-squeeze-lg + .rpm-corr + form#convert-account-form( + action="/api/v1/users/convert-account" + method="POST" + autocomplete="off" + ) + .subject-name + label.input-name-txt(for="ca-username") #{ t('UPORABNIK') } + input#ca-username.name-input.form-control.d-block.w-100( + type="text" + value=suggestedUsername + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="ca-first-name") #{ t('IME') } + input#ca-first-name.name-input.form-control.d-block.w-100( + type="text" + value=claims.givenName + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="ca-last-name") #{ t('PRIIMEK') } + input#ca-last-name.name-input.form-control.d-block.w-100( + type="text" + value=claims.familyName + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="ca-email") #{ t('ELEKTRONSKI NASLOV') } + input#ca-email.name-input.form-control.d-block.w-100( + type="text" + value=claims.email + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="ca-password") #{ t('GESLO') } + input#ca-password.name-input.form-control.d-block.w-100( + name="password" + type="password" + ) + p#convert-account-error.error-text.pt-3.mb-1 + .row.pt-3 + .col + button#convert-account-btn.btn.btn-primary.h-auto(type="submit")= t('POTRDI PRETVORBO') + include /common/footer diff --git a/express/views/pages/oidc/create-profile.pug b/express/views/pages/oidc/create-profile.pug new file mode 100644 index 0000000..b014e54 --- /dev/null +++ b/express/views/pages/oidc/create-profile.pug @@ -0,0 +1,60 @@ +extends /layout + +block pageSpecificScipts + script(nonce=cspNonce src="/javascripts/oidc-forms.js") + script(nonce=cspNonce src="/javascripts/offset-header.js") + +block body + section#fixed-top-section + include /common/main-navigation + +main-navigation(false) + include /utilities/generic-main-panel-header + - const c = { h1: t('Ustvarite svoj profil'), description: t('Spodnji podatki prihajajo iz vaše prijave pri Univerzi v Ljubljani in bodo uporabljeni za ustvarjanje vašega računa. Tukaj jih ni mogoče spreminjati.') } + +mainHeader(c) + .content-hold-prerequisites.ps-3.pe-3 + #offset-main.container-fluid.mt-4.px-0 + .p-squeeze-lg + .rpm-corr + form#create-profile-form( + action="/api/v1/users/create-profile" + method="POST" + autocomplete="off" + ) + .subject-name + label.input-name-txt(for="cp-username") #{ t('UPORABNIK') } + input#cp-username.name-input.form-control.d-block.w-100( + type="text" + value=suggestedUsername + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="cp-first-name") #{ t('IME') } + input#cp-first-name.name-input.form-control.d-block.w-100( + type="text" + value=claims.givenName + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="cp-last-name") #{ t('PRIIMEK') } + input#cp-last-name.name-input.form-control.d-block.w-100( + type="text" + value=claims.familyName + disabled + ) + .mt-4 + .subject-name + label.input-name-txt(for="cp-email") #{ t('ELEKTRONSKI NASLOV') } + input#cp-email.name-input.form-control.d-block.w-100( + type="text" + value=claims.email + disabled + ) + p#create-profile-error.error-text.pt-3.mb-1 + .row.pt-3 + .col + button#create-profile-btn.btn.btn-primary.h-auto( + type="submit" + )= t('POTRDI') + include /common/footer diff --git a/express/views/pages/profile/my-profile-side-menu-mixin.pug b/express/views/pages/profile/my-profile-side-menu-mixin.pug index ee8f9a3..cfa8cd7 100644 --- a/express/views/pages/profile/my-profile-side-menu-mixin.pug +++ b/express/views/pages/profile/my-profile-side-menu-mixin.pug @@ -17,12 +17,13 @@ mixin sideNavigation(sideNavigationData) a.p-2.active(href="/moj-racun") img(src="/images/user-gray.svg" alt=t('Basic')) p #{ t('Osnovni podatki') } - li.p-0( - class=sideNavigationData.selection === 'change-profile-password' ? 'focused-menu' : 'admin-nav-item' - ) - a.p-2.active(href="/spremeni-geslo") - img(src="/images/lock-gray.svg" alt=t('Settings')) - p #{ t('Spremeni geslo') } + if !user.isSso + li.p-0( + class=sideNavigationData.selection === 'change-profile-password' ? 'focused-menu' : 'admin-nav-item' + ) + a.p-2.active(href="/spremeni-geslo") + img(src="/images/lock-gray.svg" alt=t('Settings')) + p #{ t('Spremeni geslo') } li.p-0( class=sideNavigationData.selection === 'change-profile-settings' ? 'focused-menu' : 'admin-nav-item' ) diff --git a/express/views/pages/profile/my-profile.pug b/express/views/pages/profile/my-profile.pug index 01c7a4e..6625314 100644 --- a/express/views/pages/profile/my-profile.pug +++ b/express/views/pages/profile/my-profile.pug @@ -11,7 +11,8 @@ block body - const d = { selection: 'change-profile-data' } +sideNavigation(d) include /utilities/dictionaries-main-panel-header - - const c = { sideMenu: true, h1: title, description: t('Tukaj lahko spremenite ime, priimek in elektronski naslov uporabnika.'), buttons: [{ type: 'disabled', content: t('Shrani'), form: 'profileForm' }] } + - const ssoDescription = t('Ta račun je bil ustvarjen s prijavo prek Univerze v Ljubljani, zato osebnih podatkov (ime, priimek, uporabniško ime, e-poštni naslov) tukaj ni mogoče spreminjati.') + - const c = { sideMenu: true, h1: title, description: user.isSso ? ssoDescription : t('Tukaj lahko spremenite ime, priimek in elektronski naslov uporabnika.'), buttons: user.isSso ? [] : [{ type: 'disabled', content: t('Shrani'), form: 'profileForm' }] } +mainHeader(c) .content-hold-prerequisites @@ -43,6 +44,7 @@ block body name="firstName" minLength="1" value=user.firstName + disabled=user.isSso ) .invalid-feedback #{ t('Niste vpisali imena') } @@ -59,6 +61,7 @@ block body name="lastName" minLength="1" value=user.lastName + disabled=user.isSso ) .invalid-feedback #{ t('Niste vpisali priimka.') } @@ -75,6 +78,7 @@ block body name="email" minLength="1" value=user.email + disabled=user.isSso ) .invalid-feedback #{ t('Neveljavni elektronski naslov.') } diff --git a/express/views/pages/reset-password/reset-password.pug b/express/views/pages/reset-password/reset-password.pug index 87267e4..2333993 100644 --- a/express/views/pages/reset-password/reset-password.pug +++ b/express/views/pages/reset-password/reset-password.pug @@ -2,6 +2,7 @@ extends /layout block pageSpecificScipts script(nonce=cspNonce src="/javascripts/reset-password.js") + script(nonce=cspNonce src="/javascripts/offset-header.js") block body section#fixed-top-section @@ -16,7 +17,7 @@ block body +mainHeader(c) .content-hold-prerequisites.ps-3.pe-3 - #offset-main.container-fluid.mt-4.errc.px-0 + #offset-main.container-fluid.mt-4.px-0 .p-squeeze-lg .rpm-corr if (isTokenValid) diff --git a/express/views/pages/view-resources/dictionary-details.pug b/express/views/pages/view-resources/dictionary-details.pug new file mode 100644 index 0000000..108d893 --- /dev/null +++ b/express/views/pages/view-resources/dictionary-details.pug @@ -0,0 +1,51 @@ +extends /layout + +block pageSpecificScipts + script(nonce=cspNonce src="/javascripts/offset-header.js") + script(nonce=cspNonce src="/javascripts/view-resources-details.js") + +block body + section#fixed-top-section + include /common/main-navigation + +main-navigation(false) + + #offset-padding.header-section-root.no-side-menu.p-squeeze-lg + #chevrons-left.d-flex + a#btn-chevrons.no-text-decoration.btn-chevrons-left.pt-0.h-24.d-flex( + type="link" + href="/ogled-virov" + ) + img.align-middle(src="/images/chevrons-left.svg") + span.ms-2.text-header-description-gray.fw-700= t('Nazaj') + .d-flex.justify-content-between.flex-md-nowrap.flex-wrap + .header-container-left-side.d-flex + .header-container-divider-left + h2#site-header-title= dictionary[`name${capitalize(determinedLanguage)}`] + h1#site-heading= t('Osnovni podatki') + hr#header-row.mt-1.mb-0 + + include /utilities/dictionary-description-readonly-mixin + +dictionaryDescriptionReadonly({ dictionary, allPrimaryDomains, associatedSecondaryDomains, status, determinedLanguage }) + + .content-hold-prerequisites + #offset-main.ps-3.pe-3.mt-4 + .p-squeeze-lg + h5.navigation-text-color= t('Kontaktiraj avtorje') + form#contact-authors-form.needs-validation.mt-3( + action=`/api/v1/dictionaries/${dictionary.id}/contact-authors` + method="post" + novalidate + ) + textarea#contact-authors-message.form-control( + name="message" + rows="10" + style="resize: vertical" + required + ) + .invalid-feedback= t('Niste vpisali sporočila.') + button.btn.btn-primary.mt-3(type="submit")= t('Pošlji') + + include /utilities/modal-response + +responseModal("contact-authors-response", t('Razumem'), "contact-authors-understand-btn", t('Sporočilo je bilo poslano avtorjem slovarja.')) + + include /common/footer diff --git a/express/views/pages/view-resources/list.pug b/express/views/pages/view-resources/list.pug new file mode 100644 index 0000000..e0e0883 --- /dev/null +++ b/express/views/pages/view-resources/list.pug @@ -0,0 +1,51 @@ +extends /layout + +block pageSpecificScipts + script(nonce=cspNonce src="/javascripts/offset-header.js") + script(nonce=cspNonce src="/javascripts/dictionary-list-table.js") + +block body + section#fixed-top-section + include /common/main-navigation + +main-navigation(false) + + #offset-padding.header-section-root.no-side-menu + #chevrons-left.d-flex + a#btn-chevrons.no-text-decoration.btn-chevrons-left.pt-0.h-24.d-flex( + type="link" + href="/" + ) + img.align-middle(src="/images/chevrons-left.svg") + span.ms-2.text-header-description-gray.fw-700= t('Nazaj') + .d-flex.justify-content-between.flex-md-nowrap.flex-wrap + .header-container-left-side.d-flex + .header-container-divider-left + h1#site-heading= t('Seznam slovarjev') + span#text-description.pe-xl-5.page-description= t('Seznam vseh slovarjev, ki jih uredniki, sicer registrirani uporabniki, urejajo na tem portalu.') + hr#header-row.mt-1.mb-0 + + .content-hold-prerequisites + #offset-main.ps-3.pe-3.mt-3 + include /components/dictionary/dictionary-list-table-mixin + +dictionaryListTable({ + results, + page, + sortBy, + sortDir, + q, + pd, + sd, + lang, + status, + allPrimaryDomains, + allSecondaryDomains, + allLanguages, + allStatuses, + rowAction: { + hrefBuilder: id => `/ogled-virov/${id}/podatki`, + icon: '/images/eye.svg', + label: t('Podatki') + } + }) + + include /common/footer diff --git a/express/views/utilities/comments-new.pug b/express/views/utilities/comments-new.pug index cc2a776..df70652 100644 --- a/express/views/utilities/comments-new.pug +++ b/express/views/utilities/comments-new.pug @@ -1,20 +1,14 @@ -- - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit'} if comments each comment in comments - - const date = new Date(comment.timeCreated).toLocaleDateString('sl-SL', localeOptions) .comment(class=comment.status === 'hidden' ? 'comment-white-text' : '') .row .comment-initials-container span.test= `${comment.author.firstName[0]}${comment.author.lastName[0]}` .comment-col.col span.comment-author-name= `${comment.author.firstName} ${comment.author.lastName}` - span.comment-date= `• ${date}` + span.comment-date + | • + time(data-timestamp=comment.timeCreated data-timestamp-format="datetime") if (comment.showEye) if comment.status === 'visible' button.comment-seen-btn.me-2 @@ -28,10 +22,11 @@ if comments .comment-text if comment.quote .comment-text-2 - - const quoteDate = new Date(comment.quote.timeCreated).toLocaleDateString('sl-SL', localeOptions) img(src="/images/quote-marks.svg") span.comment-quotename= `${comment.quote.author.firstName} ${comment.quote.author.lastName}` - span.comment-quotedate= `• ${quoteDate}` + span.comment-quotedate + | • + time(data-timestamp=comment.quote.timeCreated data-timestamp-format="datetime") .comment-quotedtext= comment.quote.message hr.comment-quotehr .comment-text-2= comment.message diff --git a/express/views/utilities/content-side-menu.pug b/express/views/utilities/content-side-menu.pug index fdfcbf6..2aaadca 100644 --- a/express/views/utilities/content-side-menu.pug +++ b/express/views/utilities/content-side-menu.pug @@ -71,7 +71,7 @@ type="checkbox" name="isPublished" ) - label.form-check-label(for="published")= t('Obljavljeno') + label.form-check-label(for="published")= t('Objavljeno') .form-check.d-flex.align-items-center input#comments.form-check-input.indeterminate-cbox( diff --git a/express/views/utilities/dictionary-description-mixin.pug b/express/views/utilities/dictionary-description-mixin.pug index 3181e00..bce38e9 100644 --- a/express/views/utilities/dictionary-description-mixin.pug +++ b/express/views/utilities/dictionary-description-mixin.pug @@ -1,6 +1,7 @@ mixin dictionary-description(dictionaryId) .content-hold-prerequisites #offset-main.main-container.mt-1 + input#dictionary-id(hidden value=dictionary.id) if dictionaryId .title .subject-name diff --git a/express/views/utilities/dictionary-description-readonly-mixin.pug b/express/views/utilities/dictionary-description-readonly-mixin.pug new file mode 100644 index 0000000..e507744 --- /dev/null +++ b/express/views/utilities/dictionary-description-readonly-mixin.pug @@ -0,0 +1,68 @@ +mixin dictionaryDescriptionReadonly(data) + .content-hold-prerequisites + #offset-main.ps-3.pe-3.mt-1 + .p-squeeze-lg + .title + .subject-name + label.input-name-txt= t('ID Slovarja') + span.page-title-header= data.dictionary.id + + .mt-4 + .subject-name + label.input-name-txt= t('Naslov slovarja') + span.normal-gray= data.dictionary.nameSl + + .mt-4 + .subject-name + label.input-name-txt= t('Angleški naslov slovarja') + span.normal-gray= data.dictionary.nameEn + + if data.dictionary.nameSlShort + .mt-4 + .subject-name + label.input-name-txt= t('Skrajšani naslov slovarja') + span.normal-gray= data.dictionary.nameSlShort + + .mt-4 + .subject-name + label.input-name-txt= t('Avtor slovarja') + if data.dictionary.author && data.dictionary.author.length + each author in data.dictionary.author + span.normal-gray.d-block= author + else + span.normal-gray   + + .mt-4 + .subject-name + label.input-name-txt= t('STATUS') + if data.status === 'closed' + span.normal-gray= t('Zaprt') + else if data.status === 'reviewed' + span.normal-gray= t('V odpiranju') + else + span.normal-gray= t('Odprt') + + .mt-4 + .subject-name + label.input-name-txt= t('Področje') + - const primaryDomain = data.allPrimaryDomains.find(domain => domain.id === data.dictionary.domainPrimary) + span.normal-gray= primaryDomain ? primaryDomain.name : '' + + .mt-4 + .subject-name + label.input-name-txt= t('Podpodročje') + if data.associatedSecondaryDomains && data.associatedSecondaryDomains.length + span.normal-gray= data.associatedSecondaryDomains.map(domain => domain[`name${capitalize(data.determinedLanguage)}`]).join(', ') + else + span.normal-gray   + + .mt-4 + .subject-name + label.input-name-txt= t('Opis slovarja') + span!= data.dictionary.description ? data.dictionary.description : t('Ta slovar nima opisa') + + if data.dictionary.issn + .mt-4 + .subject-name + label.input-name-txt= t('ISSN oznaka') + span.normal-gray= data.dictionary.issn diff --git a/express/views/utilities/dictionary-export-content-mixin.pug b/express/views/utilities/dictionary-export-content-mixin.pug index cdadffb..8d33a80 100644 --- a/express/views/utilities/dictionary-export-content-mixin.pug +++ b/express/views/utilities/dictionary-export-content-mixin.pug @@ -245,37 +245,45 @@ mixin dictionary-export-content(dictionaryId) include /utilities/pager +pager - - - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } - if results.length - .table-responsive - table.styled-table - thead - tr#thead - th= t('DATUM') - th= t('VRSTA') - th= t('ŠT. GESEL') - th= t('STATUS') - tbody#page-results + - const exportStatusKeys = { pending: 'exportStatusPending', 'in progress': 'exportStatusInProgress', failed: 'exportStatusFailed' } + .table-responsive + table.styled-table + thead + tr#thead + th= t('DATUM') + th= t('VRSTA') + th= t('ŠT. GESEL') + th= t('STATUS') + tbody#page-results + if results.length each result in results tr - - const date = new Date(result.time_created).toLocaleDateString('sl-SL', localeOptions) - td= date + td: time(data-timestamp=result.time_created data-timestamp-format="datetime") td= result.export_file_format td= result.entry_count td if (result.status === 'finished') - a.btn.btn-primary( - href=`/slovarji/export-download/${result.id}` - )= t('Shrani') + .d-flex.align-items-center + a.btn.btn-primary( + href=`/slovarji/export-download/${result.id}` + )= t('Shrani') + button.p-0.table-button-grp.delete-row-btn.ms-3( + type="button" + data-bs-target="#alert-modal" + data-bs-toggle="modal" + data-export-id=result.id + ) + img(src="/images/red-trash-icon.svg" alt=t('Izbriši')) + else + = t(exportStatusKeys[result.status]) + else + tr + td(colspan="4")= t('Ni še dodanih izvozov.') .mt-3 p!= t('Shemo za format xml si prenesete tukaj.') + include /utilities/modal-response + +responseModal("export-response-modal") + include /utilities/modal-alert include /common/footer //- .d-block.w-100 //- include /utilities/table-mixin diff --git a/express/views/utilities/dictionary-import-mixin.pug b/express/views/utilities/dictionary-import-mixin.pug index 58d1bba..251c0c1 100644 --- a/express/views/utilities/dictionary-import-mixin.pug +++ b/express/views/utilities/dictionary-import-mixin.pug @@ -4,6 +4,48 @@ mixin dictionary-import(dictionaryId) .import-container.mt-3.ms-1 form#file-import-form(method="post" enctype="multipart/form-data") .file-type + span.new-user-info= t('FORMAT ZAPISA') + #file-format-selection.file-types + .row + .col-sm-6.ms-2.text-nowrap + .form-check.radio-button.ms-0.ps-3 + input#file-format-xml.form-check-input( + type="radio" + name="importFileFormat" + value="xml" + data-extension="xml" + checked + ) + label.form-check-label.ms-0(for="file-format-xml") XML + .form-check.radio-button.ms-2 + input#file-format-csv.form-check-input( + disabled + type="radio" + name="importFileFormat" + value="csv" + data-extension="csv" + ) + label.form-check-label.ms-0(for="file-format-csv") CSV + .form-check.radio-button.ms-2 + input#file-format-tsv.form-check-input( + disabled + type="radio" + name="importFileFormat" + value="tsv" + data-extension="tsv" + ) + label.form-check-label.ms-0(for="file-format-tsv") TSV + .form-check.radio-button.ms-2 + input#file-format-json.form-check-input( + type="radio" + name="importFileFormat" + value="json_term_candidates" + data-extension="json" + ) + label.form-check-label.ms-0(for="file-format-json") JSON (#{t('Terminološki kandidati')}) + .col + span.name-info-txt= t('Izberite format datoteke, v kateri je slovar shranjen na vašem računalniku.') + .file-type.mt-4 span.new-user-info= t('DATOTEKA') .row .col-md-6.ms-2.white-border-background.p-4.d-flex.align-items-center.justify-content-between.me-2 @@ -35,7 +77,7 @@ mixin dictionary-import(dictionaryId) span.name-info-txt= t('Če izberete to možnost, se bodo vsi doslejšnji slovarski sestavki ob uvozu nove datoteke izbrisali.') .file-type.mt-4 span.new-user-info= t('FAZA UREJANJA') - #file-type-selection.file-types + #entry-status-selection.file-types .row .col-sm-6.ms-2 .form-check.radio-button.ms-0.ps-3 @@ -57,37 +99,6 @@ mixin dictionary-import(dictionaryId) = t('Urejeno') .col span.name-info-txt= t('Z izbiro te možnosti boste pobrisali samo slovarske sestavke, ki so v določeni fazi urejanja.') - .file-type.mt-4 - span.new-user-info= t('FORMAT ZAPISA') - #file-type-selection.file-types - .row - .col-sm-6.ms-2.text-nowrap - .form-check.radio-button.ms-0.ps-3 - input#file-format-xml.form-check-input( - type="radio" - name="importFileFormat" - value="xml" - checked - ) - label.form-check-label.ms-0(for="file-format-xml") XML - .form-check.radio-button.ms-2 - input#file-format-csv.form-check-input( - disabled - type="radio" - name="importFileFormat" - value="csv" - ) - label.form-check-label.ms-0(for="file-format-csv") CSV - .form-check.radio-button.ms-2 - input#file-format-tsv.form-check-input( - disabled - type="radio" - name="importFileFormat" - value="tsv" - ) - label.form-check-label.ms-0(for="file-format-tsv") TSV - .col - span.name-info-txt= t('Izberite format datoteke, v kateri je slovar shranjen na vašem računalniku.') .file-type.mt-4 button.btn.btn-primary.mt-4= t('UVOZI') .latest-uploads.mt-4 @@ -99,34 +110,28 @@ mixin dictionary-import(dictionaryId) include /utilities/pager +pager - - - const localeOptions = { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit' - } - - if results.length - .table-responsive - table.styled-table - thead - tr#thead - th= t('DATUM') - th= t('VRSTA') - th= t('ŠT. GESEL') - th= t('STATUS') - tbody#page-results + - const importStatusKeys = { 'in progress': 'importStatusInProgress', error: 'importStatusError', done: 'importStatusDone' } + .table-responsive + table.styled-table + thead + tr#thead + th= t('DATUM') + th= t('VRSTA') + th= t('ŠT. GESEL') + th= t('STATUS') + tbody#page-results + if results.length each result in results tr - - const date = new Date(result.time_started).toLocaleDateString('sl-SL', localeOptions) - td= date + td: time(data-timestamp=result.time_started data-timestamp-format="datetime") td= result.file_format - td= result.count_valid_entries - td= result.status - else - p= t('Ni še dodanih uvozov.') + td= result.count_entries + td= t(importStatusKeys[result.status]) + else + tr + td(colspan="4")= t('Ni še dodanih uvozov.') .mt-4 p!= t('Shemo za format xml si prenesete tukaj.') + include /utilities/modal-response + +responseModal("import-response-modal") include /common/footer diff --git a/express/views/utilities/dictionary-structure-input.pug b/express/views/utilities/dictionary-structure-input.pug index 76a3552..90d02df 100644 --- a/express/views/utilities/dictionary-structure-input.pug +++ b/express/views/utilities/dictionary-structure-input.pug @@ -1,3 +1,19 @@ +mixin structureCheckbox(id, name, label, checked, extraLabelClass) + .form-switch.d-flex + input.form-check-input(id=id type="checkbox" name=name checked=checked) + label.form-check-label(for=id class=extraLabelClass)= t(label) + +mixin structureForeignSubgroup(id, labelId, name, label, disabledInput, checked) + .form-switch.d-flex + input.form-check-input( + id=id + class=disabledInput ? 'disabled-input' : undefined + type="checkbox" + name=name + checked=checked + ) + label.form-check-label.language-subgroups(id=labelId for=id)= t(label) + block input-structure .switches .subject-name.mt-2 @@ -11,322 +27,41 @@ block input-structure input.form-check-input(type="checkbox" disabled checked) label.form-check-label(for="Termin")= t('Termin') - //- .form-switch.d-flex - //- input.form-check-input(type="checkbox" disabled checked) - //- label.form-check-label(for="headword-ele") Oblike, naglasi, izgovor + - + const hasForeignLanguages = dictionary ? dictionary.hasForeignLanguages : true + const hasDict = !!dictionary + const primaryCheckboxes = [ + { id: 'domain-labels', name: 'hasDomainLabels', label: 'Področna oznaka', defaultChecked: false, labelClass: 'text-nowrap' }, + { id: 'label-checkbox', name: 'hasLabel', label: 'Pojasnilo', defaultChecked: false }, + { id: 'definition-check-box', name: 'hasDefinition', label: 'Definicija', defaultChecked: true }, + { id: 'synonyms', name: 'hasSynonyms', label: 'Sinonim', defaultChecked: false }, + { id: 'links', name: 'hasLinks', label: 'Povezani termin', defaultChecked: false }, + { id: 'other', name: 'hasOther', label: 'Drugo', defaultChecked: false }, + { id: 'language-group', name: 'hasForeignLanguages', label: 'Tuji jezik', defaultChecked: true, labelClass: 'text-nowrap' } + ] + const foreignSubgroups = [ + { id: 'termin-language-subgroup', labelId: 'termin-subgroup-label', name: undefined, dictKey: undefined, label: 'Termin', alwaysDisabled: true }, + { id: 'definition-language-subgroup', labelId: 'definition-subgroup-label', name: 'hasForeignDefinitions', dictKey: 'hasForeignDefinitions', label: 'Definicija', alwaysDisabled: false }, + { id: 'synonym-language-subgroup', labelId: 'synonym-subgroup-label', name: 'hasForeignSynonyms', dictKey: 'hasForeignSynonyms', label: 'Sinonim', alwaysDisabled: false } + ] + const mediaCheckboxes = [ + { id: 'images', name: 'hasImages', label: 'Slika', defaultChecked: false }, + { id: 'audio', name: 'hasAudio', label: 'Zvok', defaultChecked: false }, + { id: 'video', name: 'hasVideos', dictKey: 'hasVideo', label: 'Video', defaultChecked: false } + ] - if dictionary - if dictionary.hasDomainLabels - .form-switch.d-flex - input#domain-labels.form-check-input( - type="checkbox" - name="hasDomainLabels" - checked - ) - label.form-check-label.text-nowrap(for="domain-labels")= t('Področna oznaka') - else - .form-switch.d-flex - input#domain-labels.form-check-input( - type="checkbox" - name="hasDomainLabels" - ) - label.form-check-label.text-nowrap(for="domain-labels")= t('Področna oznaka') - else - .form-switch.d-flex - input#domain-labels.form-check-input( - type="checkbox" - name="hasDomainLabels" - ) - label.form-check-label.text-nowrap(for="domain-labels")= t('Področna oznaka') + each field in primaryCheckboxes + - const checked = dictionary ? dictionary[field.dictKey || field.name] : field.defaultChecked + +structureCheckbox(field.id, field.name, field.label, checked, field.labelClass) - if dictionary - if dictionary.hasLabel - .form-switch.d-flex - input#label-checkbox.form-check-input( - type="checkbox" - name="hasLabel" - checked - ) - label.form-check-label(for="label-checkbox")= t('Pojasnilo') - else - .form-switch.d-flex - input#label-checkbox.form-check-input( - type="checkbox" - name="hasLabel" - ) - label.form-check-label(for="label-checkbox")= t('Pojasnilo') + each field in foreignSubgroups + - const disabledInput = field.alwaysDisabled || (hasDict ? !hasForeignLanguages : false) + - const subgroupChecked = field.dictKey ? hasDict && hasForeignLanguages && dictionary[field.dictKey] : hasForeignLanguages + +structureForeignSubgroup(field.id, field.labelId, field.name, field.label, disabledInput, subgroupChecked) - else - .form-switch.d-flex - input#label-checkbox.form-check-input( - type="checkbox" - name="hasLabel" - ) - label.form-check-label(for="label-checkbox")= t('Pojasnilo') - - .form-switch.d-flex - input#definition-check-box.form-check-input( - type="checkbox" - name="hasDefinition" - checked - ) - label.form-check-label(for="definition-check-box")= t('Definicija') - - if dictionary - if dictionary.hasSynonyms - .form-switch.d-flex - input#synonyms.form-check-input( - type="checkbox" - name="hasSynonyms" - checked - ) - label.form-check-label(for="synonyms")= t('Sinonim') - else - .form-switch.d-flex - input#synonyms.form-check-input( - type="checkbox" - name="hasSynonyms" - ) - label.form-check-label(for="synonyms")= t('Sinonim') - else - .form-switch.d-flex - input#synonyms.form-check-input( - type="checkbox" - name="hasSynonyms" - ) - label.form-check-label(for="synonyms")= t('Sinonim') - - if dictionary - if dictionary.hasLinks - .form-switch.d-flex - input#links.form-check-input( - type="checkbox" - name="hasLinks" - checked - ) - label.form-check-label(for="links")= t('Povezani termin') - else - .form-switch.d-flex - input#links.form-check-input(type="checkbox" name="hasLinks") - label.form-check-label(for="links")= t('Povezani termin') - - else - .form-switch.d-flex - input#links.form-check-input(type="checkbox" name="hasLinks") - label.form-check-label(for="links")= t('Povezani termin') - - //- .form-switch.d-flex - //- input#other.form-check-input(type="checkbox" name="hasOther") - //- label.form-check-label(for="other") Drugo - - if dictionary - if dictionary.hasOther - .form-switch.d-flex - input#other.form-check-input( - type="checkbox" - name="hasOther" - checked - ) - label.form-check-label(for="other")= t('Drugo') - else - .form-switch.d-flex - input#other.form-check-input(type="checkbox" name="hasOther") - label.form-check-label(for="other")= t('Drugo') - else - .form-switch.d-flex - input#other.form-check-input(type="checkbox" name="hasOther") - label.form-check-label(for="other")= t('Drugo') - - if dictionary - if dictionary.hasForeignLanguages - .form-switch.d-flex - input#language-group.form-check-input( - type="checkbox" - name="hasForeignLanguages" - checked - ) - label.form-check-label.text-nowrap(for="language-group")= t('Tuji jezik') - else - .form-switch.d-flex - input#language-group.form-check-input( - type="checkbox" - name="hasForeignLanguages" - ) - label.form-check-label.text-nowrap(for="language-group")= t('Tuji jezik') - else - .form-switch.d-flex - input#language-group.form-check-input( - type="checkbox" - name="hasForeignLanguages" - checked - ) - label.form-check-label.text-nowrap(for="language-group")= t('Tuji jezik') - - if dictionary - if !dictionary.hasForeignLanguages - .form-switch.d-flex - input#termin-language-subgroup.form-check-input.disabled-input( - type="checkbox" - ) - label#termin-subgroup-label.form-check-label.language-subgroups( - for="termin-language-subgroup" - )= t('Termin') - else - .form-switch.d-flex - input#termin-language-subgroup.form-check-input.disabled-input( - type="checkbox" - checked - ) - label#termin-subgroup-label.form-check-label.language-subgroups( - for="termin-language-subgroup" - )= t('Termin') - else - .form-switch.d-flex - input#termin-language-subgroup.form-check-input.disabled-input( - type="checkbox" - checked - ) - label#termin-subgroup-label.form-check-label.language-subgroups( - for="termin-language-subgroup" - )= t('Termin') - - if dictionary - if !dictionary.hasForeignLanguages - .form-switch.d-flex - input#definition-language-subgroup.form-check-input.disabled-input( - type="checkbox" - name="hasForeignDefinitions" - ) - label#definition-subgroup-label.form-check-label.language-subgroups( - for="definition-language-subgroup" - )= t('Definicija') - else if dictionary.hasForeignDefinitions - .form-switch.d-flex - input#definition-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignDefinitions" - checked - ) - label#definition-subgroup-label.form-check-label.language-subgroups( - for="definition-language-subgroup" - )= t('Definicija') - else - .form-switch.d-flex - input#definition-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignDefinitions" - ) - label#definition-subgroup-label.form-check-label.language-subgroups( - for="definition-language-subgroup" - )= t('Definicija') - else - .form-switch.d-flex - input#definition-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignDefinitions" - ) - label#definition-subgroup-label.form-check-label.language-subgroups( - for="definition-language-subgroup" - )= t('Definicija') - - if dictionary - if !dictionary.hasForeignLanguages - .form-switch.d-flex - input#synonym-language-subgroup.form-check-input.disabled-input( - type="checkbox" - name="hasForeignSynonyms" - ) - label#synonym-subgroup-label.form-check-label.language-subgroups( - for="synonym-language-subgroup" - )= t('Sinonim') - else if dictionary.hasForeignSynonyms - .form-switch.d-flex - input#synonym-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignSynonyms" - checked - ) - label#synonym-subgroup-label.form-check-label.language-subgroups( - for="synonym-language-subgroup" - )= t('Sinonim') - else - .form-switch.d-flex - input#synonym-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignSynonyms" - ) - label#synonym-subgroup-label.form-check-label.language-subgroups( - for="synonym-language-subgroup" - )= t('Sinonim') - else - .form-switch.d-flex - input#synonym-language-subgroup.form-check-input( - type="checkbox" - name="hasForeignSynonyms" - ) - label#synonym-subgroup-label.form-check-label.language-subgroups( - for="synonym-language-subgroup" - )= t('Sinonim') - - if dictionary - if dictionary.hasImages - .form-switch.d-flex - input#images.form-check-input( - type="checkbox" - name="hasImages" - checked - ) - label.form-check-label(for="images")= t('Slika') - else - .form-switch.d-flex - input#images.form-check-input( - type="checkbox" - name="hasImages" - ) - label.form-check-label(for="images")= t('Slika') - else - .form-switch.d-flex - input#images.form-check-input(type="checkbox" name="hasImages") - label.form-check-label(for="images")= t('Slika') - - if dictionary - if dictionary.hasAudio - .form-switch.d-flex - input#audio.form-check-input( - type="checkbox" - name="hasAudio" - checked - ) - label.form-check-label(for="audio")= t('Zvok') - else - .form-switch.d-flex - input#audio.form-check-input(type="checkbox" name="hasAudio") - label.form-check-label(for="audio")= t('Zvok') - else - .form-switch.d-flex - input#audio.form-check-input(type="checkbox" name="hasAudio") - label.form-check-label(for="audio")= t('Zvok') - - if dictionary - if dictionary.hasVideo - .form-switch.d-flex - input#video.form-check-input( - type="checkbox" - name="hasVideos" - checked - ) - label.form-check-label(for="video")= t('Video') - else - .form-switch.d-flex - input#video.form-check-input( - type="checkbox" - name="hasVideos" - ) - label.form-check-label(for="video")= t('Video') - else - .form-switch.d-flex - input#video.form-check-input(type="checkbox" name="hasVideos") - label.form-check-label(for="video")= t('Video') + each field in mediaCheckboxes + - const checked = dictionary ? dictionary[field.dictKey || field.name] : field.defaultChecked + +structureCheckbox(field.id, field.name, field.label, checked, field.labelClass) .ms-2.ms-md-5.flex-grow-1 include /utilities/entry-preview diff --git a/express/views/utilities/result-detail-side-menu.pug b/express/views/utilities/result-detail-side-menu.pug index 59946a8..cc6f559 100644 --- a/express/views/utilities/result-detail-side-menu.pug +++ b/express/views/utilities/result-detail-side-menu.pug @@ -44,7 +44,7 @@ mixin result_detail(data) .text-header-description-gray.fw-400= data.languages if data.time_modified li.text-gray-1.fw-500 #{ t('Spremenjen') } - .text-header-description-gray.fw-400= data.time_modified + .text-header-description-gray.fw-400: time(data-timestamp=data.time_modified.toISOString() data-timestamp-format="date") if data.count_entries li.text-gray-1.fw-500 #{ t('Število slovarskih sestavkov') } .text-header-description-gray.fw-400= data.count_entries diff --git a/opensearch/Dockerfile b/opensearch/Dockerfile index d3a8caa..bd7a2ce 100644 --- a/opensearch/Dockerfile +++ b/opensearch/Dockerfile @@ -1,3 +1,4 @@ +# syntax=docker/dockerfile:1 FROM opensearchproject/opensearch:2.3.0 # Install analysis-icu plugin for collation support. diff --git a/package-lock.json b/package-lock.json index 6d3d63f..14f8f87 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,60 +1,84 @@ { "name": "terminoloski-portal-project", "version": "0.0.0", - "lockfileVersion": 1, + "lockfileVersion": 3, "requires": true, - "dependencies": { - "@babel/code-frame": { + "packages": { + "": { + "name": "terminoloski-portal-project", + "version": "0.0.0", + "devDependencies": { + "@prettier/plugin-pug": "1.16.1", + "eslint": "~7.30.0", + "eslint-config-prettier": "~8.3.0", + "eslint-config-standard": "~16.0.3", + "eslint-plugin-import": "~2.23.4", + "eslint-plugin-node": "~11.1.0", + "eslint-plugin-promise": "~5.1.0", + "prettier": "2.3.2" + } + }, + "node_modules/@babel/code-frame": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", "dev": true, - "requires": { + "dependencies": { "@babel/highlight": "^7.10.4" } }, - "@babel/helper-validator-identifier": { + "node_modules/@babel/helper-validator-identifier": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.5.tgz", "integrity": "sha512-5lsetuxCLilmVGyiLEfoHBRX8UCFD+1m2x3Rj97WrW3V7H3u4RWRXA4evMjImCsin2J2YT0QaVDGf+z8ondbAg==", - "dev": true + "dev": true, + "engines": { + "node": ">=6.9.0" + } }, - "@babel/highlight": { + "node_modules/@babel/highlight": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", "dev": true, - "requires": { + "dependencies": { "@babel/helper-validator-identifier": "^7.14.5", "chalk": "^2.0.0", "js-tokens": "^4.0.0" }, - "dependencies": { - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - } + "engines": { + "node": ">=6.9.0" } }, - "@eslint/eslintrc": { + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@eslint/eslintrc": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.2.tgz", "integrity": "sha512-8nmGq/4ycLpIwzvhI4tNDmQztZ8sp+hI7cyG8i1nQDhkAbRzHpXPidRAHlNvCZQpJTKw5ItIpMw9RSToGF00mg==", "dev": true, - "requires": { + "dependencies": { "ajv": "^6.12.4", "debug": "^4.1.1", "espree": "^7.3.0", @@ -64,346 +88,398 @@ "js-yaml": "^3.13.1", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" } }, - "@humanwhocodes/config-array": { + "node_modules/@humanwhocodes/config-array": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", + "deprecated": "Use @eslint/config-array instead", "dev": true, - "requires": { + "dependencies": { "@humanwhocodes/object-schema": "^1.2.0", "debug": "^4.1.1", "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=10.10.0" } }, - "@humanwhocodes/object-schema": { + "node_modules/@humanwhocodes/object-schema": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", + "deprecated": "Use @eslint/object-schema instead", "dev": true }, - "@prettier/plugin-pug": { + "node_modules/@prettier/plugin-pug": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/@prettier/plugin-pug/-/plugin-pug-1.16.1.tgz", "integrity": "sha512-Fh3GfZUmyZSRQVXAk2V7ZYx17yHDHN3sqYSQ+hM5m2X2wBN/g/Eza5KMA4loBpylGJ0z2IT3NAljnYebPNY5OA==", "dev": true, - "requires": { + "dependencies": { "pug-lexer": "^5.0.0" + }, + "peerDependencies": { + "prettier": "^2.1.0" } }, - "acorn": { + "node_modules/acorn": { "version": "7.4.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } }, - "acorn-jsx": { + "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } }, - "ajv": { + "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, - "requires": { + "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" } }, - "ansi-colors": { + "node_modules/ansi-colors": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", - "dev": true + "dev": true, + "engines": { + "node": ">=6" + } }, - "ansi-regex": { + "node_modules/ansi-regex": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + } }, - "ansi-styles": { + "node_modules/ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, - "requires": { + "dependencies": { "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" } }, - "anymatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", - "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", - "dev": true, - "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - } - }, - "argparse": { + "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, - "requires": { + "dependencies": { "sprintf-js": "~1.0.2" } }, - "array-includes": { + "node_modules/array-includes": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz", "integrity": "sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.2", "get-intrinsic": "^1.1.1", "is-string": "^1.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "array.prototype.flat": { + "node_modules/array.prototype.flat": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.4.tgz", "integrity": "sha512-4470Xi3GAPAjZqFcljX2xzckv1qeKPizoNkiS0+O4IoPR2ZNpcjE0pkhdihlDouK+x6QOast26B4Q/O9DJnwSg==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.0", "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "astral-regex": { + "node_modules/astral-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + } }, - "balanced-match": { + "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, - "binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", - "dev": true - }, - "brace-expansion": { + "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "requires": { + "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, - "braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, - "requires": { - "fill-range": "^7.0.1" - } - }, - "call-bind": { + "node_modules/call-bind": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, - "requires": { + "dependencies": { "function-bind": "^1.1.1", "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "callsites": { + "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=6" + } }, - "chalk": { + "node_modules/chalk": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.1.tgz", "integrity": "sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==", "dev": true, - "requires": { + "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" }, - "dependencies": { - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "character-parser": { + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/chalk/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/chalk/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/character-parser": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/character-parser/-/character-parser-2.2.0.tgz", "integrity": "sha1-x84o821LzZdE5f/CxfzeHHMmH8A=", "dev": true, - "requires": { + "dependencies": { "is-regex": "^1.0.3" } }, - "chokidar": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz", - "integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==", - "dev": true, - "requires": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "fsevents": "~2.3.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - } - }, - "color-convert": { + "node_modules/color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, - "requires": { + "dependencies": { "color-name": "1.1.3" } }, - "color-name": { + "node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, - "concat-map": { + "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, - "cross-spawn": { + "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, - "requires": { + "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" } }, - "debug": { + "node_modules/debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, - "requires": { + "dependencies": { "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "deep-is": { + "node_modules/deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", "dev": true }, - "define-properties": { + "node_modules/define-properties": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", "dev": true, - "requires": { + "dependencies": { "object-keys": "^1.0.12" + }, + "engines": { + "node": ">= 0.4" } }, - "doctrine": { + "node_modules/doctrine": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", "dev": true, - "requires": { + "dependencies": { "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" } }, - "emoji-regex": { + "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, - "enquirer": { + "node_modules/enquirer": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", "dev": true, - "requires": { + "dependencies": { "ansi-colors": "^4.1.1" + }, + "engines": { + "node": ">=8.6" } }, - "error-ex": { + "node_modules/error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "dev": true, - "requires": { + "dependencies": { "is-arrayish": "^0.2.1" } }, - "es-abstract": { + "node_modules/es-abstract": { "version": "1.18.3", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.3.tgz", "integrity": "sha512-nQIr12dxV7SSxE6r6f1l3DtAeEYdsGpps13dR0TwJg1S8gyp4ZPgy3FZcHBgbiQqnoqSTb+oC+kO4UQ0C/J8vw==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", @@ -420,31 +496,50 @@ "string.prototype.trimend": "^1.0.4", "string.prototype.trimstart": "^1.0.4", "unbox-primitive": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "es-to-primitive": { + "node_modules/es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", "dev": true, - "requires": { + "dependencies": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "escape-string-regexp": { + "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "eslint": { + "node_modules/eslint": { "version": "7.30.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.30.0.tgz", "integrity": "sha512-VLqz80i3as3NdloY44BQSJpFw534L9Oh+6zJOUaViV4JPd+DaHwutqP7tcpkW3YiXbK6s05RZl7yl7cQn+lijg==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, - "requires": { + "dependencies": { "@babel/code-frame": "7.12.11", "@eslint/eslintrc": "^0.4.2", "@humanwhocodes/config-array": "^0.5.0", @@ -485,84 +580,127 @@ "table": "^6.0.9", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "eslint-config-prettier": { + "node_modules/eslint-config-prettier": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz", "integrity": "sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew==", - "dev": true + "dev": true, + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } }, - "eslint-config-standard": { + "node_modules/eslint-config-standard": { "version": "16.0.3", "resolved": "https://registry.npmjs.org/eslint-config-standard/-/eslint-config-standard-16.0.3.tgz", "integrity": "sha512-x4fmJL5hGqNJKGHSjnLdgA6U6h1YW/G2dW9fA+cyVur4SK6lyue8+UgNKWlZtUDTXvgKDD/Oa3GQjmB5kjtVvg==", - "dev": true + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "peerDependencies": { + "eslint": "^7.12.1", + "eslint-plugin-import": "^2.22.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1 || ^5.0.0" + } }, - "eslint-import-resolver-node": { + "node_modules/eslint-import-resolver-node": { "version": "0.3.4", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz", "integrity": "sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA==", "dev": true, - "requires": { + "dependencies": { "debug": "^2.6.9", "resolve": "^1.13.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } } }, - "eslint-module-utils": { + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/eslint-module-utils": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.1.tgz", "integrity": "sha512-ZXI9B8cxAJIH4nfkhTwcRTEAnrVfobYqwjWy/QMCZ8rHkZHFjf9yO4BzpiF9kCSfNlMG54eKigISHpX0+AaT4A==", "dev": true, - "requires": { + "dependencies": { "debug": "^3.2.7", "pkg-dir": "^2.0.0" }, - "dependencies": { - "debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "requires": { - "ms": "^2.1.1" - } - } + "engines": { + "node": ">=4" } }, - "eslint-plugin-es": { + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-es": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz", "integrity": "sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ==", "dev": true, - "requires": { + "dependencies": { "eslint-utils": "^2.0.0", "regexpp": "^3.0.0" + }, + "engines": { + "node": ">=8.10.0" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": ">=4.19.1" } }, - "eslint-plugin-import": { + "node_modules/eslint-plugin-import": { "version": "2.23.4", "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.23.4.tgz", "integrity": "sha512-6/wP8zZRsnQFiR3iaPFgh5ImVRM1WN5NUWfTIRqwOdeiGJlBcSk82o1FEVq8yXmy4lkIzTo7YhHCIxlU/2HyEQ==", "dev": true, - "requires": { + "dependencies": { "array-includes": "^3.1.3", "array.prototype.flat": "^1.2.4", "debug": "^2.6.9", @@ -579,39 +717,46 @@ "resolve": "^1.20.0", "tsconfig-paths": "^3.9.0" }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0" } }, - "eslint-plugin-node": { + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/eslint-plugin-node": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", "integrity": "sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g==", "dev": true, - "requires": { + "dependencies": { "eslint-plugin-es": "^3.0.0", "eslint-utils": "^2.0.0", "ignore": "^5.1.1", @@ -619,1076 +764,1365 @@ "resolve": "^1.10.1", "semver": "^6.1.0" }, - "dependencies": { - "ignore": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", - "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", - "dev": true - }, - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } + "engines": { + "node": ">=8.10.0" + }, + "peerDependencies": { + "eslint": ">=5.16.0" } }, - "eslint-plugin-promise": { + "node_modules/eslint-plugin-node/node_modules/ignore": { + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", + "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint-plugin-node/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-promise": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-5.1.0.tgz", "integrity": "sha512-NGmI6BH5L12pl7ScQHbg7tvtk4wPxxj8yPHH47NvSmMtFneC077PSeY3huFj06ZWZvtbfxSPt3RuOQD5XcR4ng==", - "dev": true + "dev": true, + "engines": { + "node": "^10.12.0 || >=12.0.0" + }, + "peerDependencies": { + "eslint": "^7.0.0" + } }, - "eslint-scope": { + "node_modules/eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, - "requires": { + "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" } }, - "eslint-utils": { + "node_modules/eslint-utils": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", "dev": true, - "requires": { + "dependencies": { "eslint-visitor-keys": "^1.1.0" }, - "dependencies": { - "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true - } + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" } }, - "eslint-visitor-keys": { + "node_modules/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint-visitor-keys": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true + "dev": true, + "engines": { + "node": ">=10" + } }, - "espree": { + "node_modules/espree": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", "dev": true, - "requires": { + "dependencies": { "acorn": "^7.4.0", "acorn-jsx": "^5.3.1", "eslint-visitor-keys": "^1.3.0" }, - "dependencies": { - "eslint-visitor-keys": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", - "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", - "dev": true - } + "engines": { + "node": "^10.12.0 || >=12.0.0" } }, - "esprima": { + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } }, - "esquery": { + "node_modules/esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", "dev": true, - "requires": { + "dependencies": { "estraverse": "^5.1.0" }, - "dependencies": { - "estraverse": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true - } + "engines": { + "node": ">=0.10" } }, - "esrecurse": { + "node_modules/esquery/node_modules/estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, - "requires": { + "dependencies": { "estraverse": "^5.2.0" }, - "dependencies": { - "estraverse": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", - "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", - "dev": true - } + "engines": { + "node": ">=4.0" } }, - "estraverse": { + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true + "dev": true, + "engines": { + "node": ">=4.0" + } }, - "esutils": { + "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "fast-deep-equal": { + "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, - "fast-json-stable-stringify": { + "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, - "fast-levenshtein": { + "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, - "file-entry-cache": { + "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, - "requires": { + "dependencies": { "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" } }, - "fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, - "requires": { - "to-regex-range": "^5.0.1" - } - }, - "find-up": { + "node_modules/find-up": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", "dev": true, - "requires": { + "dependencies": { "locate-path": "^2.0.0" + }, + "engines": { + "node": ">=4" } }, - "flat-cache": { + "node_modules/flat-cache": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", "dev": true, - "requires": { + "dependencies": { "flatted": "^3.1.0", "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" } }, - "flatted": { + "node_modules/flatted": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.1.tgz", "integrity": "sha512-OMQjaErSFHmHqZe+PSidH5n8j3O0F2DdnVh8JB4j4eUQ2k6KvB0qGfrKIhapvez5JerBbmWkaLYUYWISaESoXg==", "dev": true }, - "fs.realpath": { + "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "optional": true - }, - "function-bind": { + "node_modules/function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, - "functional-red-black-tree": { + "node_modules/functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", "dev": true }, - "get-intrinsic": { + "node_modules/get-intrinsic": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", "dev": true, - "requires": { + "dependencies": { "function-bind": "^1.1.1", "has": "^1.0.3", "has-symbols": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "glob": { + "node_modules/glob": { "version": "7.1.7", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", "dev": true, - "requires": { + "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "glob-parent": { + "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, - "requires": { + "dependencies": { "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" } }, - "globals": { + "node_modules/globals": { "version": "13.10.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.10.0.tgz", "integrity": "sha512-piHC3blgLGFjvOuMmWZX60f+na1lXFDhQXBf1UYp2fXPXqvEUbOhNwi6BsQ0bQishwedgnjkwv1d9zKf+MWw3g==", "dev": true, - "requires": { + "dependencies": { "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "graceful-fs": { + "node_modules/graceful-fs": { "version": "4.2.6", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==", "dev": true }, - "has": { + "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, - "requires": { + "dependencies": { "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" } }, - "has-bigints": { + "node_modules/has-bigints": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", - "dev": true + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "has-flag": { + "node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "has-symbols": { + "node_modules/has-symbols": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "hosted-git-info": { + "node_modules/hosted-git-info": { "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", "dev": true }, - "ignore": { + "node_modules/ignore": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", - "dev": true + "dev": true, + "engines": { + "node": ">= 4" + } }, - "import-fresh": { + "node_modules/import-fresh": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, - "requires": { + "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "imurmurhash": { + "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true + "dev": true, + "engines": { + "node": ">=0.8.19" + } }, - "inflight": { + "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, - "requires": { + "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, - "inherits": { + "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, - "is-arrayish": { + "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, - "is-bigint": { + "node_modules/is-bigint": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", "integrity": "sha512-0JV5+SOCQkIdzjBK9buARcV804Ddu7A0Qet6sHi3FimE9ne6m4BGQZfRn+NZiXbBk4F4XmHfDZIipLj9pX8dSA==", - "dev": true - }, - "is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, - "requires": { - "binary-extensions": "^2.0.0" + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "is-boolean-object": { + "node_modules/is-boolean-object": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", "integrity": "sha512-bXdQWkECBUIAcCkeH1unwJLIpZYaa5VvuygSyS/c2lf719mTKZDU5UdDRlpd01UjADgmW8RfqaP+mRaVPdr/Ng==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "is-callable": { + "node_modules/is-callable": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "is-core-module": { + "node_modules/is-core-module": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz", "integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==", "dev": true, - "requires": { + "dependencies": { "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "is-date-object": { + "node_modules/is-date-object": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.4.tgz", "integrity": "sha512-/b4ZVsG7Z5XVtIxs/h9W8nvfLgSAyKYdtGWQLbqy6jA1icmgjf8WCoTKgeS4wy5tYaPePouzFMANbnj94c2Z+A==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "is-expression": { + "node_modules/is-expression": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-expression/-/is-expression-4.0.0.tgz", "integrity": "sha512-zMIXX63sxzG3XrkHkrAPvm/OVZVSCPNkwMHU8oTX7/U3AL78I0QXCEICXUM13BIa8TYGZ68PiTKfQz3yaTNr4A==", "dev": true, - "requires": { + "dependencies": { "acorn": "^7.1.1", "object-assign": "^4.1.1" } }, - "is-extglob": { + "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "is-fullwidth-code-point": { + "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + } }, - "is-glob": { + "node_modules/is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", "dev": true, - "requires": { + "dependencies": { "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" } }, - "is-negative-zero": { + "node_modules/is-negative-zero": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true - }, - "is-number-object": { + "node_modules/is-number-object": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.5.tgz", "integrity": "sha512-RU0lI/n95pMoUKu9v1BZP5MBcZuNSVJkMkAG2dJqC4z2GlkGUNeH68SuHuBKBD/XFe+LHZ+f9BKkLET60Niedw==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "is-regex": { + "node_modules/is-regex": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "is-string": { + "node_modules/is-string": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", "integrity": "sha512-2gdzbKUuqtQ3lYNrUTQYoClPhm7oQu4UdpSZMp1/DGgkHBT8E2Z1l0yMdb6D4zNAxwDiMv8MdulKROJGNl0Q0w==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "is-symbol": { + "node_modules/is-symbol": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", "dev": true, - "requires": { + "dependencies": { "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "isexe": { + "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, - "js-tokens": { + "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true }, - "js-yaml": { + "node_modules/js-yaml": { "version": "3.14.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", "dev": true, - "requires": { + "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" } }, - "json-parse-better-errors": { + "node_modules/json-parse-better-errors": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", "dev": true }, - "json-schema-traverse": { + "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, - "json-stable-stringify-without-jsonify": { + "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", "dev": true }, - "json5": { + "node_modules/json5": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", "dev": true, - "requires": { + "dependencies": { "minimist": "^1.2.5" + }, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" } }, - "levn": { + "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, - "requires": { + "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" } }, - "load-json-file": { + "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", "dev": true, - "requires": { + "dependencies": { "graceful-fs": "^4.1.2", "parse-json": "^4.0.0", "pify": "^3.0.0", "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "locate-path": { + "node_modules/locate-path": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", "dev": true, - "requires": { + "dependencies": { "p-locate": "^2.0.0", "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "lodash.clonedeep": { + "node_modules/lodash.clonedeep": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", "dev": true }, - "lodash.merge": { + "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, - "lodash.truncate": { + "node_modules/lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", "dev": true }, - "lru-cache": { + "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, - "requires": { + "dependencies": { "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, - "minimatch": { + "node_modules/minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, - "requires": { + "dependencies": { "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" } }, - "minimist": { + "node_modules/minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "dev": true }, - "ms": { + "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true }, - "natural-compare": { + "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, - "normalize-package-data": { + "node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, - "requires": { + "dependencies": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "dev": true - } } }, - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true + "node_modules/normalize-package-data/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } }, - "object-assign": { + "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "object-inspect": { + "node_modules/object-inspect": { "version": "1.10.3", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", - "dev": true + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, - "object-keys": { + "node_modules/object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.4" + } }, - "object.assign": { + "node_modules/object.assign": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.0", "define-properties": "^1.1.3", "has-symbols": "^1.0.1", "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "object.values": { + "node_modules/object.values": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.4.tgz", "integrity": "sha512-TnGo7j4XSnKQoK3MfvkzqKCi0nVe/D9I9IjwTNYdb/fxYHpjrluHVOgw0AF6jrRFGMPHdfuidR09tIDiIvnaSg==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3", "es-abstract": "^1.18.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "once": { + "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, - "requires": { + "dependencies": { "wrappy": "1" } }, - "optionator": { + "node_modules/optionator": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", "dev": true, - "requires": { + "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.3" + }, + "engines": { + "node": ">= 0.8.0" } }, - "p-limit": { + "node_modules/p-limit": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", "dev": true, - "requires": { + "dependencies": { "p-try": "^1.0.0" + }, + "engines": { + "node": ">=4" } }, - "p-locate": { + "node_modules/p-locate": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", "dev": true, - "requires": { + "dependencies": { "p-limit": "^1.1.0" + }, + "engines": { + "node": ">=4" } }, - "p-try": { + "node_modules/p-try": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "parent-module": { + "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, - "requires": { + "dependencies": { "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" } }, - "parse-json": { + "node_modules/parse-json": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", "dev": true, - "requires": { + "dependencies": { "error-ex": "^1.3.1", "json-parse-better-errors": "^1.0.1" + }, + "engines": { + "node": ">=4" } }, - "path-exists": { + "node_modules/path-exists": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "path-is-absolute": { + "node_modules/path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "path-key": { + "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + } }, - "path-parse": { + "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, - "path-type": { + "node_modules/path-type": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", "dev": true, - "requires": { + "dependencies": { "pify": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "picomatch": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", - "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", - "dev": true - }, - "pify": { + "node_modules/pify": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "pkg-dir": { + "node_modules/pkg-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", "dev": true, - "requires": { + "dependencies": { "find-up": "^2.1.0" + }, + "engines": { + "node": ">=4" } }, - "pkg-up": { + "node_modules/pkg-up": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-2.0.0.tgz", "integrity": "sha1-yBmscoBZpGHKscOImivjxJoATX8=", "dev": true, - "requires": { + "dependencies": { "find-up": "^2.1.0" + }, + "engines": { + "node": ">=4" } }, - "prelude-ls": { + "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.8.0" + } }, - "prettier": { + "node_modules/prettier": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.3.2.tgz", "integrity": "sha512-lnJzDfJ66zkMy58OL5/NY5zp70S7Nz6KqcKkXYzn2tMVrNxvbqaBpg7H3qHaLxCJ5lNMsGuM8+ohS7cZrthdLQ==", - "dev": true + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + } }, - "progress": { + "node_modules/progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", - "dev": true + "dev": true, + "engines": { + "node": ">=0.4.0" + } }, - "pug-error": { + "node_modules/pug-error": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pug-error/-/pug-error-2.0.0.tgz", "integrity": "sha512-sjiUsi9M4RAGHktC1drQfCr5C5eriu24Lfbt4s+7SykztEOwVZtbFk1RRq0tzLxcMxMYTBR+zMQaG07J/btayQ==", "dev": true }, - "pug-lexer": { + "node_modules/pug-lexer": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/pug-lexer/-/pug-lexer-5.0.1.tgz", "integrity": "sha512-0I6C62+keXlZPZkOJeVam9aBLVP2EnbeDw3An+k0/QlqdwH6rv8284nko14Na7c0TtqtogfWXcRoFE4O4Ff20w==", "dev": true, - "requires": { + "dependencies": { "character-parser": "^2.2.0", "is-expression": "^4.0.0", "pug-error": "^2.0.0" } }, - "punycode": { + "node_modules/punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true + "dev": true, + "engines": { + "node": ">=6" + } }, - "read-pkg": { + "node_modules/read-pkg": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", "dev": true, - "requires": { + "dependencies": { "load-json-file": "^4.0.0", "normalize-package-data": "^2.3.2", "path-type": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "read-pkg-up": { + "node_modules/read-pkg-up": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-3.0.0.tgz", "integrity": "sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc=", "dev": true, - "requires": { + "dependencies": { "find-up": "^2.0.0", "read-pkg": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "requires": { - "picomatch": "^2.2.1" - } - }, - "regexpp": { + "node_modules/regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + } }, - "require-from-string": { + "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "resolve": { + "node_modules/resolve": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", "dev": true, - "requires": { + "dependencies": { "is-core-module": "^2.2.0", "path-parse": "^1.0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "resolve-from": { + "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "rimraf": { + "node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, - "requires": { + "dependencies": { "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "sass": { - "version": "1.35.2", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.35.2.tgz", - "integrity": "sha512-jhO5KAR+AMxCEwIH3v+4zbB2WB0z67V1X0jbapfVwQQdjHZUGUyukpnoM6+iCMfsIUC016w9OPKQ5jrNOS9uXw==", - "dev": true, - "requires": { - "chokidar": ">=3.0.0 <4.0.0" - } - }, - "semver": { + "node_modules/semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, - "requires": { + "dependencies": { "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, - "shebang-command": { + "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, - "requires": { + "dependencies": { "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" } }, - "shebang-regex": { + "node_modules/shebang-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + } }, - "slice-ansi": { + "node_modules/slice-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", "dev": true, - "requires": { + "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", "is-fullwidth-code-point": "^3.0.0" }, - "dependencies": { - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - } + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "spdx-correct": { + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/slice-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/spdx-correct": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", "dev": true, - "requires": { + "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" } }, - "spdx-exceptions": { + "node_modules/spdx-exceptions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", "dev": true }, - "spdx-expression-parse": { + "node_modules/spdx-expression-parse": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", "dev": true, - "requires": { + "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, - "spdx-license-ids": { + "node_modules/spdx-license-ids": { "version": "3.0.9", "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.9.tgz", "integrity": "sha512-Ki212dKK4ogX+xDo4CtOZBVIwhsKBEfsEEcwmJfLQzirgc2jIWdzg40Unxz/HzEUqM1WFzVlQSMF9kZZ2HboLQ==", "dev": true }, - "sprintf-js": { + "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, - "string-width": { + "node_modules/string-width": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", "dev": true, - "requires": { + "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" } }, - "string.prototype.trimend": { + "node_modules/string.prototype.trimend": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "string.prototype.trimstart": { + "node_modules/string.prototype.trimstart": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", "dev": true, - "requires": { + "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "strip-ansi": { + "node_modules/strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, - "requires": { + "dependencies": { "ansi-regex": "^5.0.0" + }, + "engines": { + "node": ">=8" } }, - "strip-bom": { + "node_modules/strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true + "dev": true, + "engines": { + "node": ">=4" + } }, - "strip-json-comments": { + "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "supports-color": { + "node_modules/supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, - "requires": { + "dependencies": { "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" } }, - "table": { + "node_modules/table": { "version": "6.7.1", "resolved": "https://registry.npmjs.org/table/-/table-6.7.1.tgz", "integrity": "sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg==", "dev": true, - "requires": { + "dependencies": { "ajv": "^8.0.1", "lodash.clonedeep": "^4.5.0", "lodash.truncate": "^4.4.2", @@ -1696,140 +2130,160 @@ "string-width": "^4.2.0", "strip-ansi": "^6.0.0" }, - "dependencies": { - "ajv": { - "version": "8.6.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.1.tgz", - "integrity": "sha512-42VLtQUOLefAvKFAQIxIZDaThq6om/PrfP0CYk3/vn+y4BMNkKnbli8ON2QCiHov4KkzOSJ/xSoBJdayiiYvVQ==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - } - }, - "json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true - } + "engines": { + "node": ">=10.0.0" } }, - "text-table": { + "node_modules/table/node_modules/ajv": { + "version": "8.6.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.1.tgz", + "integrity": "sha512-42VLtQUOLefAvKFAQIxIZDaThq6om/PrfP0CYk3/vn+y4BMNkKnbli8ON2QCiHov4KkzOSJ/xSoBJdayiiYvVQ==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/table/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, - "to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "requires": { - "is-number": "^7.0.0" - } - }, - "tsconfig-paths": { + "node_modules/tsconfig-paths": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.10.1.tgz", "integrity": "sha512-rETidPDgCpltxF7MjBZlAFPUHv5aHH2MymyPvh+vEyWAED4Eb/WeMbsnD/JDr4OKPOA1TssDHgIcpTN5Kh0p6Q==", "dev": true, - "requires": { + "dependencies": { "json5": "^2.2.0", "minimist": "^1.2.0", "strip-bom": "^3.0.0" } }, - "type-check": { + "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, - "requires": { + "dependencies": { "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" } }, - "type-fest": { + "node_modules/type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, - "unbox-primitive": { + "node_modules/unbox-primitive": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", "dev": true, - "requires": { + "dependencies": { "function-bind": "^1.1.1", "has-bigints": "^1.0.1", "has-symbols": "^1.0.2", "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "uri-js": { + "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, - "requires": { + "dependencies": { "punycode": "^2.1.0" } }, - "v8-compile-cache": { + "node_modules/v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", "dev": true }, - "validate-npm-package-license": { + "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", "dev": true, - "requires": { + "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" } }, - "which": { + "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, - "requires": { + "dependencies": { "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" } }, - "which-boxed-primitive": { + "node_modules/which-boxed-primitive": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", "dev": true, - "requires": { + "dependencies": { "is-bigint": "^1.0.1", "is-boolean-object": "^1.1.0", "is-number-object": "^1.0.4", "is-string": "^1.0.5", "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "word-wrap": { + "node_modules/word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "wrappy": { + "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, - "yallist": { + "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", diff --git a/package.json b/package.json index a0f1dc9..02e1aab 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ "prettier": "prettier . express/bin/www --check", "prettier:fix": "npm run prettier -- --write", "format": "npm run prettier:fix && npm run lint:fix", - "sass:watch": "sass --watch express/public/sass:express/public/stylesheets" + "sass:watch": "npm --prefix express run sass:watch", + "sass:build": "npm --prefix express run sass:build", + "sass:build:prod": "npm --prefix express run sass:build:prod" }, "devDependencies": { "@prettier/plugin-pug": "1.16.1", @@ -18,7 +20,6 @@ "eslint-plugin-import": "~2.23.4", "eslint-plugin-node": "~11.1.0", "eslint-plugin-promise": "~5.1.0", - "prettier": "2.3.2", - "sass": "^1.35.2" + "prettier": "2.3.2" } } diff --git a/postgres/Dockerfile.debug.alpine b/postgres/Dockerfile.debug.alpine index b583dc9..e6089ae 100644 --- a/postgres/Dockerfile.debug.alpine +++ b/postgres/Dockerfile.debug.alpine @@ -1,3 +1,4 @@ +# syntax=docker/dockerfile:1 FROM postgres:13-alpine AS base FROM base AS builder diff --git a/postgres/Dockerfile.debug.debian b/postgres/Dockerfile.debug.debian index 9c28671..df94f3e 100644 --- a/postgres/Dockerfile.debug.debian +++ b/postgres/Dockerfile.debug.debian @@ -1,3 +1,4 @@ +# syntax=docker/dockerfile:1 FROM postgres:13 ENV PG_MAJOR 13 diff --git a/postgres/init/001_structure.sql b/postgres/init/001_structure.sql index c4d42fd..44b1f71 100644 --- a/postgres/init/001_structure.sql +++ b/postgres/init/001_structure.sql @@ -48,7 +48,7 @@ CREATE TABLE dictionary ( time_published TIMESTAMPTZ, status dictionary_status NOT NULL DEFAULT 'closed', count_entries INT NOT NULL DEFAULT 0, -- This one is updated manually and not through triggers. - count_comments INT, + count_comments INT, -- Indicator of own dictionaries: NULL means synced in from a linked/federated portal. description VARCHAR, entries_have_domain_labels BOOL NOT NULL DEFAULT FALSE, entries_have_label BOOL NOT NULL DEFAULT FALSE, diff --git a/postgres/init/002_data-domain-primary.sql b/postgres/init/002_data-domain-primary.sql index 58b1ec9..62e3e16 100644 --- a/postgres/init/002_data-domain-primary.sql +++ b/postgres/init/002_data-domain-primary.sql @@ -66,5 +66,4 @@ VALUES ('Zgodovina', 'History', '93/94', 'Zgodovina in umetnost', 'H 003', 'Humanities', '3611'), ('Zoologija', 'Zoology', '59', 'Zoologija', 'B 005', 'Natural and applied sciences', '3606'), ('Zootehnika in veterina', 'Zootechnics and veterinary medicine', '636', 'Zootehnika, živinoreja, vzreja', 'B 400', 'Health', '2841'), - ('Živilstvo in kulinarika', 'Food industry and culinary', '641', 'Tehnologija hrane in pijač', 'T 430', 'Foodstuff', '6026'), - ('Neopredeljeno', 'Undefined', '', '', '', '', ''); + ('Živilstvo in kulinarika', 'Food industry and culinary', '641', 'Tehnologija hrane in pijač', 'T 430', 'Foodstuff', '6026'); diff --git a/postgres/init/007_entry.sql b/postgres/init/007_entry.sql index 7dadb13..a84aba5 100644 --- a/postgres/init/007_entry.sql +++ b/postgres/init/007_entry.sql @@ -87,7 +87,7 @@ CREATE TABLE process ( report VARCHAR ); -CREATE TYPE import_file_format AS ENUM ('xml', 'csv', 'tsv'); +CREATE TYPE import_file_format AS ENUM ('xml', 'csv', 'tsv', 'json_term_candidates'); CREATE TYPE import_file_status AS ENUM ('in progress', 'error', 'done'); diff --git a/postgres/init/010_function_dictionary_new.sql b/postgres/init/010_function_dictionary_new.sql index 6cc7236..a01ce0d 100644 --- a/postgres/init/010_function_dictionary_new.sql +++ b/postgres/init/010_function_dictionary_new.sql @@ -31,21 +31,6 @@ DECLARE _secondary_domain_id domain_secondary.id%type; BEGIN - -- Check uniqueness of names within own dictionaries. - IF EXISTS ( - SELECT 1 - FROM dictionary - WHERE - count_comments IS NOT NULL AND -- Indicator of own dictionaries. - ( - name_sl = _name_sl OR - name_sl_short = _name_sl_short OR - name_en = _name_en - ) - ) THEN - RAISE EXCEPTION 'One of dictionary names not unique among own dictionaries.'; - END IF; - -- Create new dictionary. INSERT INTO dictionary ( name_sl, diff --git a/postgres/init/022_dictionary_export_time_zone.sql b/postgres/init/022_dictionary_export_time_zone.sql new file mode 100644 index 0000000..5135860 --- /dev/null +++ b/postgres/init/022_dictionary_export_time_zone.sql @@ -0,0 +1,5 @@ +-- Client-supplied IANA time zone (e.g. 'Europe/Ljubljana'), captured when the +-- export is started, used to render dates embedded in the exported file +-- content and the download filename in the requesting browser's local time +-- instead of the server's. +ALTER TABLE dictionary_export ADD COLUMN time_zone TEXT; diff --git a/postgres/init/023_external_identity.sql b/postgres/init/023_external_identity.sql new file mode 100644 index 0000000..3a2d8b9 --- /dev/null +++ b/postgres/init/023_external_identity.sql @@ -0,0 +1,18 @@ +-- Adds support for federated/SSO login (OIDC) alongside local username+password accounts. Only +-- one external identity provider is modeled today: the University of Ljubljana (backed by +-- Microsoft Entra ID in production; a throwaway local Authentik instance stands in for it in dev +-- - see dev/authentik/). The auth_provider enum intentionally has just these two values. + +CREATE TYPE auth_provider AS ENUM ('local', 'uni_lj'); + +-- SSO-only users are authenticated entirely by the external IdP and never set a local password. +ALTER TABLE "user" ALTER COLUMN bcrypt_hash DROP NOT NULL; + +CREATE TABLE user_external_identity ( + auth_provider auth_provider NOT NULL, + subject VARCHAR NOT NULL, + user_id INT NOT NULL REFERENCES "user", + time_linked TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (auth_provider, subject), + UNIQUE (user_id, auth_provider) +); diff --git a/postgres/manual-scripts/2026-08-27_add_oidc_sso_support.sql b/postgres/manual-scripts/2026-08-27_add_oidc_sso_support.sql new file mode 100644 index 0000000..30b9ac5 --- /dev/null +++ b/postgres/manual-scripts/2026-08-27_add_oidc_sso_support.sql @@ -0,0 +1,26 @@ +-- Companion DDL for postgres/init/023_external_identity.sql, for databases that already exist +-- (dev/staging/prod) and therefore never re-run postgres/init/*.sql. Run manually once per +-- environment, e.g.: +-- docker compose exec postgres psql -U postgres -d term_portal -f /path/to/this/file.sql + +BEGIN; + +CREATE TYPE auth_provider AS ENUM ('local', 'uni_lj'); + +ALTER TABLE "user" ALTER COLUMN bcrypt_hash DROP NOT NULL; + +CREATE TABLE user_external_identity ( + auth_provider auth_provider NOT NULL, + subject VARCHAR NOT NULL, + user_id INT NOT NULL REFERENCES "user", + time_linked TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (auth_provider, subject), + UNIQUE (user_id, auth_provider) +); + +-- postgres/init/500_init_user.sql's blanket GRANT ALL ... TO express only runs once, at fresh-DB +-- provisioning time (before this table ever existed there) - it does not retroactively apply to +-- tables created later against an already-provisioned DB, so this table needs its own grant here. +GRANT ALL PRIVILEGES ON TABLE user_external_identity TO express; + +COMMIT; diff --git a/postgres/manual-scripts/remove_neopredeljeno_domain.sql b/postgres/manual-scripts/remove_neopredeljeno_domain.sql new file mode 100644 index 0000000..bc00f04 --- /dev/null +++ b/postgres/manual-scripts/remove_neopredeljeno_domain.sql @@ -0,0 +1,56 @@ +-- Script to remove the "Neopredeljeno" (Undefined) catch-all row from domain_primary. +-- Run manually against each environment's Postgres (dev/staging/prod) - the +-- postgres/init/*.sql seed scripts only run once, on first container init, so this +-- change does not otherwise propagate to already-initialized databases. +-- +-- Safe to re-run: if the row is already gone, it's a no-op. If any dictionary or +-- consultancy_entry still references it, the delete is aborted (nothing is changed) +-- and the offending rows are listed below for manual reassignment. + +-- Informational: list anything currently pointing at "Neopredeljeno", if it still exists. +SELECT 'dictionary' AS table_name, d.id, d.name_sl AS label, d.status::text AS status +FROM dictionary d +JOIN domain_primary dp ON dp.id = d.domain_primary_id +WHERE dp.name_sl = 'Neopredeljeno' +UNION ALL +SELECT 'consultancy_entry.domain_primary_id', ce.id, ce.title, ce.status::text +FROM consultancy_entry ce +JOIN domain_primary dp ON dp.id = ce.domain_primary_id +WHERE dp.name_sl = 'Neopredeljeno' +UNION ALL +SELECT 'consultancy_entry.domain_primary_id_initial', ce.id, ce.title, ce.status::text +FROM consultancy_entry ce +JOIN domain_primary dp ON dp.id = ce.domain_primary_id_initial +WHERE dp.name_sl = 'Neopredeljeno'; + +BEGIN; + +DO $$ +DECLARE + target_id smallint; + dict_count integer; + cons_count integer; + cons_initial_count integer; +BEGIN + SELECT id INTO target_id FROM domain_primary WHERE name_sl = 'Neopredeljeno'; + + IF target_id IS NULL THEN + RAISE NOTICE 'Row "Neopredeljeno" not found in domain_primary - nothing to do.'; + RETURN; + END IF; + + SELECT count(*) INTO dict_count FROM dictionary WHERE domain_primary_id = target_id; + SELECT count(*) INTO cons_count FROM consultancy_entry WHERE domain_primary_id = target_id; + SELECT count(*) INTO cons_initial_count FROM consultancy_entry WHERE domain_primary_id_initial = target_id; + + IF dict_count > 0 OR cons_count > 0 OR cons_initial_count > 0 THEN + RAISE EXCEPTION + 'Cannot remove "Neopredeljeno" (id=%): still referenced by % dictionary row(s), % consultancy_entry.domain_primary_id row(s), % consultancy_entry.domain_primary_id_initial row(s). Reassign these manually (see the SELECT above), then re-run this script.', + target_id, dict_count, cons_count, cons_initial_count; + END IF; + + DELETE FROM domain_primary WHERE id = target_id; + RAISE NOTICE 'Removed domain_primary id=% ("Neopredeljeno").', target_id; +END $$; + +COMMIT; diff --git a/run-prod.sh b/run-prod.sh new file mode 100755 index 0000000..ff3d071 --- /dev/null +++ b/run-prod.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Thin wrapper around `docker compose` for the production stack. +# Guarantees docker-compose.prod.override.yml (host-specific, gitignored, not part of this repo) +# is always layered in when present, so environment-specific tweaks can never be forgotten. +# Forwards all arguments, e.g.: +# ./run-prod.sh --profile concordancer-manager up -d --build +# ./run-prod.sh logs -f express +# ./run-prod.sh config +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" + +files=(-f docker-compose.prod.yml) +if [[ -f docker-compose.prod.override.yml ]]; then + files+=(-f docker-compose.prod.override.yml) +fi + +echo "+ docker compose ${files[*]} $*" >&2 +exec docker compose "${files[@]}" "$@"