CJVT updates August and September 2026

This commit is contained in:
Luka Romih
2026-10-01 00:49:26 +02:00
parent fd02e25719
commit 83f73aeb58
135 changed files with 6146 additions and 1970 deletions
-24
View File
@@ -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
+63
View File
@@ -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-<short>, 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
+32
View File
@@ -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
+54
View File
@@ -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-<short> 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
+2
View File
@@ -1,6 +1,8 @@
node_modules/
.vscode
/.env
/docker-compose.prod.override.yml
.idea
.playwright-cli
express/public/stylesheets
/draft/
+8
View File
@@ -0,0 +1,8 @@
{
"browser": {
"browserName": "chromium",
"launchOptions": {
"channel": "chromium"
}
}
}
+101 -9
View File
@@ -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 <CONCORDANCER_LISTEN_PORT> 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-<short>` → 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=<gitea-host>/<owner>` 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 <gitea-host>` 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="<runner-ip>",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-<short>` 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.
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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
+48
View File
@@ -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/<tenant-id>/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 <gitea-host>/<owner-lowercase>, 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"
+157
View File
@@ -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=<Graph API constant>` | **(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=<Graph API constant>` | **(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.
@@ -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 "<family_name>, <given_name>" (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 "<lastname><first-letter-of-firstname>@<domain>" 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!"
+352
View File
@@ -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 <url> --token <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/<owner>/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`.
- **`<owner>` 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/<owner>/<repo>.git "$DEPLOY_DIR"
# Username: <your-gitea-user>
# Password: <the read PAT> -> 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/<owner-lowercase>)
# 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 <your-gitea-user> # 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:<owner>/<repo>.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="<source>",`:
```
from="<source>",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="<source>"` — 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 <IP> …`.
- `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 <IP> 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-<short>` 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).
+31
View File
@@ -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
+44
View File
@@ -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="<runner-ip>",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
+32
View File
@@ -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"
+18
View File
@@ -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
+61
View File
@@ -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
+46
View File
@@ -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
+24 -14
View File
@@ -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
+105 -11
View File
@@ -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:<port>/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:
+8
View File
@@ -0,0 +1,8 @@
node_modules
npm-debug.log
.env
.env.*
Dockerfile*
.dockerignore
public/locales/dev
data_files
+7 -4
View File
@@ -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"]
+16 -2
View File
@@ -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 && \
+2
View File
@@ -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)
+1 -1
View File
@@ -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:'],
+16 -1
View File
@@ -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
}
+32
View File
@@ -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'
}
@@ -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
})
+84 -3
View File
@@ -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)
+17
View File
@@ -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()
+16 -12
View File
@@ -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
})
+153 -22
View File
@@ -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)
+48 -1
View File
@@ -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,
@@ -18,7 +18,7 @@ helper.initialize = async determinedLanguage => {
l => l.id !== 32
)
initializers.allDictionaryNames = await Dictionary.fetchAll(
initializers.allDictionaryNames = await Dictionary.fetchAllPublished(
determinedLanguage
)
+4
View File
@@ -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')
})
+272
View File
@@ -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
+10
View File
@@ -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
@@ -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.
@@ -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`.
@@ -0,0 +1,10 @@
/**
* Module dependencies.
*/
var Strategy = require('./strategy');
/**
* Expose constructors.
*/
exports.Strategy = Strategy;
@@ -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;
@@ -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;
};
+122 -1
View File
@@ -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
+1 -1
View File
@@ -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
+11 -15
View File
@@ -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,
+228 -134
View File
@@ -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
+2
View File
@@ -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
+67 -39
View File
@@ -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(
@@ -193,7 +193,10 @@ function handleEntryXml(
) {
debug(`TOTAL ENTRIES: ${progress.totalCount}`)
debug(`VALID ENTRIES: ${progress.validCount}`)
resolve()
resolve({
totalCount: progress.totalCount,
validCount: progress.validCount
})
}
}
}
@@ -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 }
}
@@ -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)
}
+13
View File
@@ -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}`
+4
View File
@@ -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,
+170 -3
View File
@@ -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]
)
])
})
}
+96 -59
View File
@@ -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",
+7 -3
View File
@@ -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"
}
}
+59 -106
View File
@@ -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!
+10 -30
View File
@@ -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)
+8 -3
View File
@@ -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) {
+67
View File
@@ -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())
+320 -232
View File
@@ -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
@@ -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)
}
})
@@ -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)
}
})()
}
@@ -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')
}
@@ -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'
@@ -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')
@@ -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`
}
}
+38
View File
@@ -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')
@@ -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')
+101 -10
View File
@@ -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)
@@ -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()
}
}
})
}
+53 -3
View File
@@ -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 <a target=\"_blank\" href=\"/politika-zasebnosti\">politiko zasebnosti</a>": "I agree with the <a target=\"_blank\" href=\"/politika-zasebnosti\">Privacy policy</a>",
"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."
}
+52 -2
View File
@@ -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 <a target=\"_blank\" href=\"/politika-zasebnosti\">politiko zasebnosti</a>": "Soglašam s <a target=\"_blank\" href=\"/politika-zasebnosti\">politiko zasebnosti</a>",
"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."
}
@@ -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;
}
@@ -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 {
@@ -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;
}
@@ -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;
}
}
}
+1
View File
@@ -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";
+28
View File
@@ -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,
+1
View File
@@ -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
+13
View File
@@ -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
+9
View File
@@ -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}`, {
+19
View File
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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="")
@@ -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č')
@@ -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 }
@@ -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 }
+1
View File
@@ -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")
+22 -45
View File
@@ -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
@@ -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?'))
@@ -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
@@ -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 <b>#{ t('Datum vprašanja:') }</b> #{ entry.timeCreated }
p.text-header-description-gray.mb-2
!= `<b>${t('Datum vprašanja:')}</b>`
time(data-timestamp=entry.timeCreated data-timestamp-format="date")
p.text-header-description-gray.mt-2.mb-0 <b>#{ t('Uporabnik') }:</b> #{ author.firstName }
p.text-header-description-gray.mt-1 <b>#{ t('E-pošta') }:</b> #{ author.email }
hr
p.text-header-description-gray.mb-2 <b>#{ t('Datum objave/spremembe') }:</b> #{ entry.timePublished }
p.text-header-description-gray.mb-2
!= `<b>${t('Datum objave/spremembe')}:</b>`
if entry.timePublished
time(data-timestamp=entry.timePublished data-timestamp-format="date")
p.text-header-description-gray.mt-2.mb-0 <b>#{ t('Avtorji mnenja:') }</b>
span.text-header-description-gray= ` ${entry.answerAuthors ? entry.answerAuthors.join(`, `) : ''}`
p.text-header-description-gray.mt-1 <b>#{ t('URL povezava do mnenja:') }</b> #{ isPublished?`${urlPrefix}/svetovanje/vprasanje/${id}`:'' }
@@ -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")
@@ -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?'))
@@ -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
+1 -7
View File
@@ -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')

Some files were not shown because too many files have changed in this diff Show More