feat: Authentik OIDC SSO, allow/deny RBAC, admin console & Gitea CI
All checks were successful
build-and-push / build (push) Successful in 15m15s
All checks were successful
build-and-push / build (push) Successful in 15m15s
Authentication & RBAC
- Add confidential OIDC client (Authentik) with /auth/oidc/login +
/auth/oidc/callback: discovery, code exchange, id_token verify (go-oidc),
groups claim → role (Archivum-admin → admin, else user). Sessions carry groups.
- Rework ACL into an allow/deny model (new `effect` column + migration).
db.EffectiveAccess resolves user + all groups over the path and its ancestors:
default deny, explicit deny always beats allow.
- Enforce ACL for ALL non-admin users (not just guest) across list/read/save/
delete/move/create/history/diff/images/upload. Admins bypass.
- Seed built-in Archivum-admin / Archivum-reader groups; login allow-list on
users & groups; public (guest) user access is ACL-configurable.
Admin API & UI
- New GraphQL ops: oidcConfig/updateOidcConfig, group CRUD, membership,
setUserRole/setUserLogin/setGroupLogin, userGroups, loginOptions.
- Rebuilt AdminView: SSO config, user/group management + membership, login
toggles, and an allow/deny access-control matrix per path.
- LoginView: "Sign in with Authentik" + public-user option; OIDC callback route.
Rendering/editor
- Fix bug where inline marks (bold/italic/code/strike/link) were dropped on
TipTap→AsciiDoc save. Add RENDERING_IMPROVEMENTS.md with proposals.
CI / build
- .gitea/workflows/build.yaml: build on the Pi5 runner, push
localhost:5000/archivum:{latest,<sha>}. Add .dockerignore; bump Go image to 1.25.
- Docs: ARCHITECTURE.md, README.md, docs/AUTHENTIK_SETUP.md.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
35
.dockerignore
Normal file
35
.dockerignore
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Keep the build context small and reproducible. The Dockerfile builds the
|
||||||
|
# frontend from source (npm install + vite) and the backend from Go sources, so
|
||||||
|
# none of the following belong in the context.
|
||||||
|
.git
|
||||||
|
.gitea
|
||||||
|
.github
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
|
||||||
|
# Frontend build artefacts / deps (rebuilt inside the image)
|
||||||
|
frontend/node_modules
|
||||||
|
frontend/dist
|
||||||
|
frontend/.env
|
||||||
|
frontend/.env.local
|
||||||
|
|
||||||
|
# Backend local dev artefacts
|
||||||
|
backend/archivum
|
||||||
|
backend/*.exe
|
||||||
|
backend/*.test
|
||||||
|
backend/vendor
|
||||||
|
|
||||||
|
# Local state, databases and example data (never build into the image)
|
||||||
|
**/*.db
|
||||||
|
config.json
|
||||||
|
exempel.data
|
||||||
|
exempel.db
|
||||||
|
docker/data
|
||||||
|
|
||||||
|
# Docs / misc
|
||||||
|
*.md
|
||||||
|
*.pdf
|
||||||
|
LICENSE
|
||||||
|
repl.txt
|
||||||
|
backend/chunk.txt
|
||||||
|
backend/test_db.go
|
||||||
35
.gitea/workflows/build.yaml
Normal file
35
.gitea/workflows/build.yaml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
name: build-and-push
|
||||||
|
|
||||||
|
# Bygger Archivum-imagen på Pi5-runnern (arm64, nativt) och pushar till den lokala
|
||||||
|
# registryn. Ett enda multi-stage-bygge (frontend -> backend -> runtime), så
|
||||||
|
# build-context måste vara repo-roten (Dockerfile COPY:ar frontend/, backend/ och
|
||||||
|
# docker/entrypoint.sh). localhost:5000 trustas automatiskt av Docker på Pi5
|
||||||
|
# (ingen insecure-registry-config behövs där).
|
||||||
|
#
|
||||||
|
# Pull:a på Pi5 med localhost:5000/archivum:latest (t.ex. i dockge-stacken).
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, master]
|
||||||
|
paths:
|
||||||
|
- "backend/**"
|
||||||
|
- "frontend/**"
|
||||||
|
- "docker/**"
|
||||||
|
- ".gitea/workflows/build.yaml"
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Build & push image
|
||||||
|
run: |
|
||||||
|
docker build --progress=plain \
|
||||||
|
-f docker/Dockerfile \
|
||||||
|
-t localhost:5000/archivum:latest \
|
||||||
|
-t "localhost:5000/archivum:${GITHUB_SHA::12}" \
|
||||||
|
.
|
||||||
|
docker push localhost:5000/archivum:latest
|
||||||
|
docker push "localhost:5000/archivum:${GITHUB_SHA::12}"
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -40,3 +40,7 @@ node_modules/
|
|||||||
testdata/
|
testdata/
|
||||||
test_data/
|
test_data/
|
||||||
tests/data/
|
tests/data/
|
||||||
|
|
||||||
|
# Local example data (not part of the app)
|
||||||
|
exempel.data/
|
||||||
|
exempel.db/
|
||||||
|
|||||||
@@ -45,7 +45,8 @@ Webbläsare
|
|||||||
| PWA | vite-plugin-pwa (Service Worker, manifest) |
|
| PWA | vite-plugin-pwa (Service Worker, manifest) |
|
||||||
| Backend | Go 1.22, HTTP-standardbibliotek |
|
| Backend | Go 1.22, HTTP-standardbibliotek |
|
||||||
| Databas | SQLite via modernc.org/sqlite (CGO-fri, multi-arch) |
|
| Databas | SQLite via modernc.org/sqlite (CGO-fri, multi-arch) |
|
||||||
| Autentisering| Lokala konton (bcrypt) + LDAP, JWT-liknande sessions-tokens |
|
| Autentisering| OIDC/SSO (Authentik) + lokala konton (bcrypt) + LDAP, sessions-tokens i minnet |
|
||||||
|
| RBAC / ACL | Roll via OIDC-grupper; allow/deny-ACL per sökväg för användare & grupper |
|
||||||
| Versionshantering | Git via `os/exec` |
|
| Versionshantering | Git via `os/exec` |
|
||||||
| Containerisering | Docker (multi-stage, multi-arch: amd64 + arm64) |
|
| Containerisering | Docker (multi-stage, multi-arch: amd64 + arm64) |
|
||||||
|
|
||||||
@@ -175,9 +176,33 @@ En inbyggd `guest`-användare skapas automatiskt vid installation och vid server
|
|||||||
- Kan som standard inte se något
|
- Kan som standard inte se något
|
||||||
- Admin ger tillgång per dokument eller mapp via ACL-panelen
|
- Admin ger tillgång per dokument eller mapp via ACL-panelen
|
||||||
|
|
||||||
### Åtkomstkontroll (ACL)
|
### Autentisering via OIDC (Authentik)
|
||||||
|
|
||||||
ACL-poster lagras i SQLite-tabellen `acl`. Varje post kopplar en sökväg (slug eller mappnamn) till ett subjekt (användare eller grupp) och sju boolean-flaggor:
|
Archivum är en confidential OIDC-klient mot Authentik. Flödet är rent
|
||||||
|
browser-redirect och ligger utanför GraphQL (två HTTP-endpoints):
|
||||||
|
|
||||||
|
```
|
||||||
|
Login-sida → GET /auth/oidc/login
|
||||||
|
→ 302 till Authentik (authorize, scope: openid profile email groups, state)
|
||||||
|
→ användaren autentiseras (Authentik → OpenLDAP)
|
||||||
|
→ 302 tillbaka GET /auth/oidc/callback?code&state
|
||||||
|
├─ validerar state (CSRF), byter code→token (backend↔Authentik, TLS)
|
||||||
|
├─ verifierar id_token (JWKS via go-oidc), läser preferred_username + groups
|
||||||
|
├─ mappar grupp → roll: Archivum-admin → admin, annars user
|
||||||
|
├─ speglar användare + grupper till SQLite (för admin-UI + ACL-mål)
|
||||||
|
├─ login-grind: användare/grupp måste vara tillåten
|
||||||
|
└─ 302 till /oidc/callback#token=… (SPA:n läser token ur fragmentet)
|
||||||
|
```
|
||||||
|
|
||||||
|
Konfiguration ligger i `config.oidc` (issuer, client_id/secret, grupp-mappning)
|
||||||
|
och sätts i admin-panelen. Discovery körs i bakgrunden vid start/ändring så att
|
||||||
|
en otillgänglig IdP inte blockerar servern. Se `docs/AUTHENTIK_SETUP.md`.
|
||||||
|
|
||||||
|
### Åtkomstkontroll (allow/deny-ACL)
|
||||||
|
|
||||||
|
ACL-poster lagras i SQLite-tabellen `acl`. Varje post kopplar en **sökväg** (slug
|
||||||
|
eller mappnamn) till ett **subjekt** (användare eller grupp), en **effekt**
|
||||||
|
(`allow`/`deny`) och sju rättighetsflaggor:
|
||||||
|
|
||||||
| Flagga | Innebär |
|
| Flagga | Innebär |
|
||||||
|------------|----------------------------------------|
|
|------------|----------------------------------------|
|
||||||
@@ -189,9 +214,25 @@ ACL-poster lagras i SQLite-tabellen `acl`. Varje post kopplar en sökväg (slug
|
|||||||
| canDelete | Kan radera |
|
| canDelete | Kan radera |
|
||||||
| canMove | Kan flytta/byta namn |
|
| canMove | Kan flytta/byta namn |
|
||||||
|
|
||||||
Sökvägar är hierarkiska: om admin ger gästen tillgång till mappen `docs` räcker det för alla dokument under `docs/`.
|
**Effektiv rättighet** (`db.EffectiveAccess`) beräknas för (användare, sökväg,
|
||||||
|
handling) genom att kombinera **alla** poster som gäller subjektet — användaren
|
||||||
|
själv **plus alla dess grupper** (från OIDC-claimet eller lokalt medlemskap) —
|
||||||
|
över sökvägen **och alla dess överliggande mappar**:
|
||||||
|
|
||||||
Enforcement sker i `handleDocuments` och `handleFolders` — gästanvändare filtreras mot ACL. Admin-användare kringgår alltid ACL-kontroller.
|
1. Standard = **deny**.
|
||||||
|
2. En `allow` på handlingen ger tillgång.
|
||||||
|
3. En `deny` på handlingen **vinner alltid** över allow.
|
||||||
|
|
||||||
|
Alltså: tillgång ges bara om någon post tillåter och ingen post nekar. Sökvägar
|
||||||
|
är hierarkiska (en `allow` på mappen `docs` gäller allt under `docs/`).
|
||||||
|
|
||||||
|
Enforcement sker för **alla icke-admins** (inloggade användare, `Archivum-reader`
|
||||||
|
och den publika/gäst-användaren) i alla operationer — listning, läsning, spara,
|
||||||
|
radera, flytta, skapa, historik/diff och bilduppladdning. **Admin kringgår ACL.**
|
||||||
|
|
||||||
|
> **Känd begränsning:** `/media/<bild>` serveras utan ACL eftersom bilder laddas
|
||||||
|
> via `<img>` utan Authorization-header. Skydda känsliga bilder på annat sätt
|
||||||
|
> (t.ex. signerade URL:er) om det behövs.
|
||||||
|
|
||||||
### Setup-detektion — `needsSetup`
|
### Setup-detektion — `needsSetup`
|
||||||
|
|
||||||
@@ -220,7 +261,13 @@ resolveDBPath(configPath):
|
|||||||
- `db_path` — sökväg till SQLite-fil
|
- `db_path` — sökväg till SQLite-fil
|
||||||
- `jwt_secret` — används för session-token generation (ej JWT i klassisk mening)
|
- `jwt_secret` — används för session-token generation (ej JWT i klassisk mening)
|
||||||
- `listen_addr` — TCP-adress att lyssna på, t.ex. `:4000`
|
- `listen_addr` — TCP-adress att lyssna på, t.ex. `:4000`
|
||||||
- `ldap` — valfri LDAP-konfiguration:
|
- `public_url` — extern bas-URL (t.ex. `https://archivum.brasse-pc.eu`), används
|
||||||
|
för att härleda OIDC-redirect-URI
|
||||||
|
- `oidc` — valfri OIDC/SSO-konfiguration (Authentik):
|
||||||
|
- `enabled`, `issuer`, `client_id`, `client_secret`, `redirect_url`
|
||||||
|
- `groups_claim` (default `groups`), `username_claim` (default `preferred_username`)
|
||||||
|
- `admin_group` (default `Archivum-admin`), `reader_group` (default `Archivum-reader`)
|
||||||
|
- `ldap` — valfri LDAP-konfiguration (direkt bind, äldre alternativ):
|
||||||
- `url` — LDAP-server URL, t.ex. `ldap://openldap:389`
|
- `url` — LDAP-server URL, t.ex. `ldap://openldap:389`
|
||||||
- `base_dn` — rot-DN att söka ifrån, t.ex. `dc=example,dc=com`
|
- `base_dn` — rot-DN att söka ifrån, t.ex. `dc=example,dc=com`
|
||||||
- `admin_user` — tjänstekonto DN för uppslag (valfritt)
|
- `admin_user` — tjänstekonto DN för uppslag (valfritt)
|
||||||
|
|||||||
31
README.md
31
README.md
@@ -162,6 +162,37 @@ Konfigurationen lagras i `config.json`. Filen skapas automatiskt av installation
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Autentisering & behörigheter
|
||||||
|
|
||||||
|
Archivum stöder tre inloggningssätt:
|
||||||
|
|
||||||
|
- **SSO via Authentik (OIDC)** — rekommenderat. Användare loggar in genom
|
||||||
|
Authentik (som i sin tur autentiserar mot LDAP). Grupp-medlemskap avgör roll
|
||||||
|
och åtkomst. Se [`docs/AUTHENTIK_SETUP.md`](docs/AUTHENTIK_SETUP.md).
|
||||||
|
- **Lokala konton** — skapas i setup-guiden och i admin-panelen (bcrypt).
|
||||||
|
- **Publik användare** — anonym, väljs på login-sidan; ser bara det admin delat.
|
||||||
|
|
||||||
|
**Roller:** medlemmar i gruppen `Archivum-admin` är administratörer (ser/gör allt,
|
||||||
|
administrerar sidan). Alla andra styrs av åtkomstreglerna.
|
||||||
|
|
||||||
|
**Åtkomstmodell:** per sökväg (dokument eller mapp) tilldelar admin `allow`/`deny`
|
||||||
|
till användare och grupper. Standard är **deny**; en `allow` ger tillgång, en
|
||||||
|
`deny` vinner alltid. Reglerna kombineras över användarens alla grupper och
|
||||||
|
överliggande mappar. Hanteras under **Admin Settings → Access Control**.
|
||||||
|
|
||||||
|
## Automatiskt bygge (Gitea Actions)
|
||||||
|
|
||||||
|
Vid push till `main` bygger den självhostade Gitea-runnern (arm64, på Pi5)
|
||||||
|
imagen och pushar den till registryn:
|
||||||
|
|
||||||
|
```
|
||||||
|
localhost:5000/archivum:latest
|
||||||
|
localhost:5000/archivum:<commit-sha>
|
||||||
|
```
|
||||||
|
|
||||||
|
Workflow: [`.gitea/workflows/build.yaml`](.gitea/workflows/build.yaml). Deploya
|
||||||
|
sedan `localhost:5000/archivum:latest` från din compose-stack på Pi5.
|
||||||
|
|
||||||
## Dokumentformat
|
## Dokumentformat
|
||||||
|
|
||||||
Alla dokument skrivs i [AsciiDoc](https://asciidoc.org/). Exempeldokument:
|
Alla dokument skrivs i [AsciiDoc](https://asciidoc.org/). Exempeldokument:
|
||||||
|
|||||||
120
RENDERING_IMPROVEMENTS.md
Normal file
120
RENDERING_IMPROVEMENTS.md
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
# Förbättringsförslag — rendering & editor
|
||||||
|
|
||||||
|
Genomgång av renderings- och editorlagret (`frontend/src/bridge/*`,
|
||||||
|
`components/editor/*`) med konkreta, prioriterade förslag. En bekräftad bugg är
|
||||||
|
redan åtgärdad i denna gren (se punkt 0).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. ÅTGÄRDAD bugg: inline-formatering tappades vid sparning
|
||||||
|
|
||||||
|
I `asciidoc-bridge.ts → renderTextNodes` byggdes den markerade strängen
|
||||||
|
(`*fet*`, `_kursiv_`, `` `kod` ``, länkar) men **lades aldrig till utdata** — i
|
||||||
|
stället lades den *omarkerade* texten till i ett andra `if`-block. Följd: all
|
||||||
|
inline-formatering försvann tyst varje gång ett dokument sparades från den
|
||||||
|
visuella editorn. Nu appliceras och skrivs marks korrekt (en enda gång).
|
||||||
|
|
||||||
|
> Rekommendation: lägg ett litet round-trip-test (`adoc → toTipTap → fromTipTap`)
|
||||||
|
> som CI-steg så att den här klassen av regressioner fångas automatiskt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Round-trip-modellen är den största risken
|
||||||
|
|
||||||
|
Idag är flödet vid varje sparning:
|
||||||
|
|
||||||
|
```
|
||||||
|
.adoc ──asciidoctor.convert──▶ HTML ──generateJSON──▶ TipTap-JSON
|
||||||
|
▲ │
|
||||||
|
└─────────── fromTipTap (handskriven) ◀──────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
Två lossy konverteringar i rad. Allt som TipTap-schemat inte känner till
|
||||||
|
(attribut, `ifdef`/`ifeval`, `:attribut:`-definitioner, block-roller, kommentarer,
|
||||||
|
tabellformat, korsreferenser) går förlorat så fort man öppnar och sparar i den
|
||||||
|
visuella vyn.
|
||||||
|
|
||||||
|
**Förslag (välj en):**
|
||||||
|
- **A. Källan är sanningen.** Behandla `.adoc` som master. Visuella editorn får
|
||||||
|
bara redigera dokument som är "rena" (kan round-trippa förlustfritt), annars
|
||||||
|
öppnas källeditorn. Visa en varning "det här dokumentet innehåller avancerad
|
||||||
|
AsciiDoc — redigera i källvyn".
|
||||||
|
- **B. Patch-baserad sparning.** Spara bara de block som faktiskt ändrats i den
|
||||||
|
visuella vyn i stället för att reserialisera hela dokumentet.
|
||||||
|
- **C. Byt serialisering.** Använd en riktig AST (t.ex. `downdoc`/`@asciidoctor`
|
||||||
|
reducer) i stället för den handskrivna `TipTapToAsciidoc`-klassen.
|
||||||
|
|
||||||
|
Minst arbete/störst nytta på kort sikt: **A** + en tydlig indikator i UI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Konkreta serialiseringsluckor i `fromTipTap`
|
||||||
|
|
||||||
|
| Nod / mark | Problem | Förslag |
|
||||||
|
|------------|---------|---------|
|
||||||
|
| Kombinerade marks (fet+kursiv) | Ger `*_text_*` — bräckligt intill andra tecken | Använd oконstruerad syntax (`**`, `__`) vid behov |
|
||||||
|
| Tabeller (`convertTable`) | Ingen header-rad (`[%header]`), inga kolumn-specar, colspan/align tappas | Detektera `tableHeader`, skriv `[options="header"]`, `cols=` |
|
||||||
|
| Listor (`convertListItem`) | Blandning av stycke + nästlad lista i samma item blir fel; principallista använder nivå-räkning som spretar | Rendera item-innehåll block för block med `+`-continuation för flerstycke |
|
||||||
|
| `blockquote` | Attribution/citat-källa tappas | Stöd `[quote, author, source]` |
|
||||||
|
| `admonition` | Bara 5 typer, alltid versalt block-format | Bevara ursprunglig form (inline `NOTE:` vs `[NOTE]`-block) |
|
||||||
|
| Bild | `role`/alignment/`link=` tappas | Utöka `AsciidocImage`-attribut och serialisering |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Renderingspipelinen (adoc → HTML)
|
||||||
|
|
||||||
|
- **Regex-omskrivning av admonitions** (`htmlContent.replace(/<div class="admonitionblock…`)
|
||||||
|
är känslig för nästlat innehåll och flera stycken. En admonition med en lista
|
||||||
|
eller ett kodblock inuti går sönder. → Rendera i stället admonitions via en
|
||||||
|
Asciidoctor-**converter/extension** i stället för att patcha HTML i efterhand.
|
||||||
|
- **`include::`** hanteras med regex och blir en platshållare. Riktiga includes
|
||||||
|
(t.ex. återanvändbara fragment) renderas aldrig. → Implementera en
|
||||||
|
include-resolver på backend (den har redan fil-I/O) och rendera server-side,
|
||||||
|
eller hämta fragmentet via API innan `convert`.
|
||||||
|
- **Passthrough (`+++`)**: fotnötter injiceras som rå-HTML före parsing. Fungerar,
|
||||||
|
men kringgår sanering. Låg risk internt, men värt en `DOMPurify` på
|
||||||
|
renderad HTML om publika/gäst-användare någonsin ska se opålitligt innehåll.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Prestanda / bundle
|
||||||
|
|
||||||
|
`DocumentView`-chunken är **~2,8 MB** (880 kB gzip). Två tunga poster:
|
||||||
|
|
||||||
|
- **`lowlight` med `all`** (`createLowlight(all)`) drar in *alla* språkgrammatiker.
|
||||||
|
→ Byt till `common` eller registrera bara de språk ni faktiskt använder
|
||||||
|
(go, js, ts, bash, python, yaml…). Sparar hundratals kB.
|
||||||
|
- **`asciidoctor.js`** är stort och laddas i varje dokumentvy. → Lazy-load
|
||||||
|
(`import()` först när ett dokument öppnas) — delvis redan gjort via
|
||||||
|
route-splitting, men Asciidoctor kan brytas ut ytterligare. Överväg
|
||||||
|
server-side-rendering av HTML (backend har redan Go; ett litet
|
||||||
|
`asciidoctor`-anrop eller cache av renderad HTML per commit-hash skulle ta bort
|
||||||
|
klientkostnaden helt och göra läsvyn snabb även på Pi5/mobil).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Editor-UX (presentation)
|
||||||
|
|
||||||
|
- **Synk mellan Visual och Source.** Gör "source of truth"-valet (punkt 1)
|
||||||
|
synligt: en toggle med en varningsikon när dokumentet inte kan round-trippa.
|
||||||
|
- **Live-förhandsvisning i källeditorn.** CodeMirror till vänster, renderad HTML
|
||||||
|
till höger (delad vy) — vanligt och uppskattat för teknisk dokumentation.
|
||||||
|
- **Innehållsförteckning / rubriknavigering.** Generera en TOC från rubrikerna
|
||||||
|
(finns redan `id` på `CustomHeading`) och visa i sidopanelen.
|
||||||
|
- **Bildhantering.** Uppladdning finns; lägg till drag-and-drop och inklistring
|
||||||
|
från urklipp direkt i editorn.
|
||||||
|
- **Autospar / utkast.** Spara utkast lokalt (IndexedDB) så inget tappas vid
|
||||||
|
session-timeout (sessioner ligger bara i minnet på servern).
|
||||||
|
- **Diff-vy i redigering.** `HistoryPanel`/`DiffViewer` finns — koppla en
|
||||||
|
"jämför med sparad version"-knapp direkt i editorn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prioriteringsordning (rekommenderad)
|
||||||
|
|
||||||
|
1. ✅ Fixa marks-buggen (klar).
|
||||||
|
2. Lägg round-trip-test i CI.
|
||||||
|
3. Byt `lowlight` `all` → `common`/whitelist (snabb, stor bundle-vinst).
|
||||||
|
4. Inför "source of truth"-indikator + öppna källvyn för avancerade dokument.
|
||||||
|
5. Server-side- eller cachead HTML-rendering (störst läs-prestandavinst).
|
||||||
|
6. Robustare tabell-/list-serialisering.
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
module github.com/brasse-b/archivum
|
module github.com/brasse-b/archivum
|
||||||
|
|
||||||
go 1.22
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/coreos/go-oidc/v3 v3.19.0
|
||||||
github.com/go-ldap/ldap/v3 v3.4.8
|
github.com/go-ldap/ldap/v3 v3.4.8
|
||||||
golang.org/x/crypto v0.21.0
|
golang.org/x/crypto v0.21.0
|
||||||
|
golang.org/x/oauth2 v0.36.0
|
||||||
modernc.org/sqlite v1.30.0
|
modernc.org/sqlite v1.30.0
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -12,6 +14,7 @@ require (
|
|||||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+
|
|||||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
|
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
|
||||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@@ -9,6 +11,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
|||||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
||||||
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||||
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
||||||
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
||||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||||
@@ -71,6 +75,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
|||||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
|
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
|
||||||
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||||
|
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||||
|
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ type Session struct {
|
|||||||
Username string
|
Username string
|
||||||
Token string
|
Token string
|
||||||
Role string
|
Role string
|
||||||
|
Groups []string // group names (from OIDC claim or local membership)
|
||||||
ExpiresAt time.Time
|
ExpiresAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,9 +60,10 @@ func CheckPassword(hashedPassword, password string) error {
|
|||||||
// Returns the session token, the user's role, and any error.
|
// Returns the session token, the user's role, and any error.
|
||||||
// password is a SHA-256 hash (for local accounts); ldapPassword is plaintext (for LDAP bind).
|
// password is a SHA-256 hash (for local accounts); ldapPassword is plaintext (for LDAP bind).
|
||||||
func (m *Manager) Login(database *db.DB, username, password, ldapPassword string) (token, role string, err error) {
|
func (m *Manager) Login(database *db.DB, username, password, ldapPassword string) (token, role string, err error) {
|
||||||
// Guest login — no password required.
|
// Guest / public login — no password required.
|
||||||
if username == "guest" {
|
if username == "guest" {
|
||||||
tok, err := m.createSession("guest", "guest")
|
groups, _ := database.GetUserGroupNames("guest")
|
||||||
|
tok, err := m.createSession("guest", "guest", groups)
|
||||||
return tok, "guest", err
|
return tok, "guest", err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +76,8 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
|
|||||||
if bcrypt.CompareHashAndPassword([]byte(user.PassHash), []byte(password)) != nil {
|
if bcrypt.CompareHashAndPassword([]byte(user.PassHash), []byte(password)) != nil {
|
||||||
return "", "", errors.New("invalid credentials")
|
return "", "", errors.New("invalid credentials")
|
||||||
}
|
}
|
||||||
tok, err := m.createSession(username, user.Role)
|
groups, _ := database.GetUserGroupNames(username)
|
||||||
|
tok, err := m.createSession(username, user.Role, groups)
|
||||||
return tok, user.Role, err
|
return tok, user.Role, err
|
||||||
}
|
}
|
||||||
// No local password — must be an LDAP-only account.
|
// No local password — must be an LDAP-only account.
|
||||||
@@ -92,7 +95,8 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
|
|||||||
if err := ldapUserBind(cfg, username, ldapPwd); err != nil {
|
if err := ldapUserBind(cfg, username, ldapPwd); err != nil {
|
||||||
return "", "", errors.New("invalid credentials")
|
return "", "", errors.New("invalid credentials")
|
||||||
}
|
}
|
||||||
tok, err := m.createSession(username, user.Role)
|
groups, _ := database.GetUserGroupNames(username)
|
||||||
|
tok, err := m.createSession(username, user.Role, groups)
|
||||||
return tok, user.Role, err
|
return tok, user.Role, err
|
||||||
}
|
}
|
||||||
// In DB but no password and not LDAP — refuse.
|
// In DB but no password and not LDAP — refuse.
|
||||||
@@ -116,10 +120,60 @@ func (m *Manager) Login(database *db.DB, username, password, ldapPassword string
|
|||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
tok, err := m.createSession(username, "user")
|
tok, err := m.createSession(username, "user", nil)
|
||||||
return tok, "user", err
|
return tok, "user", err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LoginOIDC establishes a session from a verified OIDC identity. It maps the
|
||||||
|
// group claim to a role (admin group → admin, otherwise user), mirrors the
|
||||||
|
// user and groups into the local DB (for the admin UI and ACL targeting), and
|
||||||
|
// enforces the login allow-list. Returns an error if the account is not
|
||||||
|
// permitted to sign in.
|
||||||
|
func (m *Manager) LoginOIDC(database *db.DB, u *OIDCUser) (token, role string, err error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
cfg := m.cfg
|
||||||
|
m.mu.RUnlock()
|
||||||
|
|
||||||
|
adminGroup, readerGroup := "Archivum-admin", "Archivum-reader"
|
||||||
|
if cfg != nil {
|
||||||
|
oc := cfg.OIDC
|
||||||
|
oc.Normalize()
|
||||||
|
adminGroup, readerGroup = oc.AdminGroup, oc.ReaderGroup
|
||||||
|
}
|
||||||
|
_ = readerGroup // reader currently maps to the ACL-gated "user" role
|
||||||
|
|
||||||
|
// Mirror the token's groups locally so ACLs can target them and the admin
|
||||||
|
// UI can list them.
|
||||||
|
for _, g := range u.Groups {
|
||||||
|
_ = database.CreateOrUpdateGroup(g, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
allowed := database.LoginAllowed(u.Username, u.Groups)
|
||||||
|
|
||||||
|
role = "user"
|
||||||
|
for _, g := range u.Groups {
|
||||||
|
if g == adminGroup {
|
||||||
|
role = "admin"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provision / refresh the user record and its group mirror. allow_login is
|
||||||
|
// seeded from the gate result on first insert and preserved afterwards.
|
||||||
|
_ = database.CreateOrUpdateExternalUser(u.Username, role, allowed)
|
||||||
|
if role == "admin" {
|
||||||
|
_ = database.SetUserRole(u.Username, "admin")
|
||||||
|
}
|
||||||
|
_ = database.SyncUserGroups(u.Username, u.Groups)
|
||||||
|
|
||||||
|
if !allowed {
|
||||||
|
return "", "", errors.New("this account is not permitted to sign in to Archivum")
|
||||||
|
}
|
||||||
|
|
||||||
|
tok, err := m.createSession(u.Username, role, u.Groups)
|
||||||
|
return tok, role, err
|
||||||
|
}
|
||||||
|
|
||||||
// UserAuthType returns "guest", "ldap", or "local" for the given username.
|
// UserAuthType returns "guest", "ldap", or "local" for the given username.
|
||||||
// A user with a non-empty pass_hash is always "local", regardless of is_ldap,
|
// A user with a non-empty pass_hash is always "local", regardless of is_ldap,
|
||||||
// so that the frontend hashes the password before sending it.
|
// so that the frontend hashes the password before sending it.
|
||||||
@@ -246,7 +300,7 @@ func BrowseLDAP(url, baseDN, adminUser, adminPassword string) ([]string, []strin
|
|||||||
return users, groups, nil
|
return users, groups, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Manager) createSession(username, role string) (string, error) {
|
func (m *Manager) createSession(username, role string, groups []string) (string, error) {
|
||||||
token, err := generateToken()
|
token, err := generateToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -256,6 +310,7 @@ func (m *Manager) createSession(username, role string) (string, error) {
|
|||||||
Username: username,
|
Username: username,
|
||||||
Token: token,
|
Token: token,
|
||||||
Role: role,
|
Role: role,
|
||||||
|
Groups: groups,
|
||||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||||
}
|
}
|
||||||
m.mu.Unlock()
|
m.mu.Unlock()
|
||||||
|
|||||||
231
backend/internal/auth/oidc.go
Normal file
231
backend/internal/auth/oidc.go
Normal file
@@ -0,0 +1,231 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/brasse-b/archivum/internal/config"
|
||||||
|
"github.com/coreos/go-oidc/v3/oidc"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OIDCUser is the identity extracted from a verified id_token / userinfo.
|
||||||
|
type OIDCUser struct {
|
||||||
|
Username string
|
||||||
|
Email string
|
||||||
|
Groups []string
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrOIDCNotConfigured = errors.New("OIDC not configured")
|
||||||
|
|
||||||
|
type oidcState struct {
|
||||||
|
expiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// OIDCProvider wraps an OpenID Connect provider and OAuth2 client and manages
|
||||||
|
// the short-lived CSRF state values used during the auth-code flow. It can be
|
||||||
|
// reconfigured at runtime (after an admin changes the OIDC settings).
|
||||||
|
type OIDCProvider struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
cfg config.OIDCConfig
|
||||||
|
redirect string
|
||||||
|
oauth *oauth2.Config
|
||||||
|
provider *oidc.Provider
|
||||||
|
verifier *oidc.IDTokenVerifier
|
||||||
|
ready bool
|
||||||
|
states map[string]oidcState
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewOIDCProvider() *OIDCProvider {
|
||||||
|
return &OIDCProvider{states: make(map[string]oidcState)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure (re)initialises the provider from config. It performs OIDC
|
||||||
|
// discovery against the issuer, which requires network access to the IdP.
|
||||||
|
// Returns an error if discovery fails; the provider is then left disabled.
|
||||||
|
func (p *OIDCProvider) Configure(ctx context.Context, cfg config.OIDCConfig, redirectURL string) error {
|
||||||
|
cfg.Normalize()
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
p.cfg = cfg
|
||||||
|
p.redirect = redirectURL
|
||||||
|
p.ready = false
|
||||||
|
p.provider = nil
|
||||||
|
p.verifier = nil
|
||||||
|
p.oauth = nil
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
if !cfg.Enabled || cfg.Issuer == "" || cfg.ClientID == "" || redirectURL == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
provider, err := oidc.NewProvider(ctx, strings.TrimRight(cfg.Issuer, "/"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
oauthCfg := &oauth2.Config{
|
||||||
|
ClientID: cfg.ClientID,
|
||||||
|
ClientSecret: cfg.ClientSecret,
|
||||||
|
Endpoint: provider.Endpoint(),
|
||||||
|
RedirectURL: redirectURL,
|
||||||
|
Scopes: []string{oidc.ScopeOpenID, "profile", "email", cfg.GroupsClaim},
|
||||||
|
}
|
||||||
|
verifier := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID})
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
p.provider = provider
|
||||||
|
p.oauth = oauthCfg
|
||||||
|
p.verifier = verifier
|
||||||
|
p.ready = true
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enabled reports whether the provider is configured and ready.
|
||||||
|
func (p *OIDCProvider) Enabled() bool {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return p.ready
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthURL creates a fresh state value and returns the authorization URL to
|
||||||
|
// redirect the browser to.
|
||||||
|
func (p *OIDCProvider) AuthURL() (string, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if !p.ready {
|
||||||
|
return "", ErrOIDCNotConfigured
|
||||||
|
}
|
||||||
|
state := randToken()
|
||||||
|
p.states[state] = oidcState{expiresAt: time.Now().Add(10 * time.Minute)}
|
||||||
|
p.gcStatesLocked()
|
||||||
|
return p.oauth.AuthCodeURL(state), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange validates the state, swaps the code for tokens, verifies the
|
||||||
|
// id_token and returns the resulting identity (with groups). If the id_token
|
||||||
|
// carries no groups claim it falls back to the userinfo endpoint.
|
||||||
|
func (p *OIDCProvider) Exchange(ctx context.Context, state, code string) (*OIDCUser, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
if !p.ready {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil, ErrOIDCNotConfigured
|
||||||
|
}
|
||||||
|
st, ok := p.states[state]
|
||||||
|
if ok {
|
||||||
|
delete(p.states, state)
|
||||||
|
}
|
||||||
|
oauthCfg := p.oauth
|
||||||
|
verifier := p.verifier
|
||||||
|
provider := p.provider
|
||||||
|
cfg := p.cfg
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
if !ok || time.Now().After(st.expiresAt) {
|
||||||
|
return nil, errors.New("invalid or expired state")
|
||||||
|
}
|
||||||
|
|
||||||
|
tok, err := oauthCfg.Exchange(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rawID, ok := tok.Extra("id_token").(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("no id_token in token response")
|
||||||
|
}
|
||||||
|
idTok, err := verifier.Verify(ctx, rawID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var claims map[string]interface{}
|
||||||
|
if err := idTok.Claims(&claims); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
user := &OIDCUser{
|
||||||
|
Username: claimString(claims, cfg.UsernameClaim),
|
||||||
|
Email: claimString(claims, "email"),
|
||||||
|
Groups: claimStrings(claims, cfg.GroupsClaim),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Some providers only expose groups via userinfo — fall back to it.
|
||||||
|
if len(user.Groups) == 0 && provider != nil {
|
||||||
|
if ui, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(tok)); err == nil {
|
||||||
|
var uiClaims map[string]interface{}
|
||||||
|
if err := ui.Claims(&uiClaims); err == nil {
|
||||||
|
user.Groups = claimStrings(uiClaims, cfg.GroupsClaim)
|
||||||
|
if user.Username == "" {
|
||||||
|
user.Username = claimString(uiClaims, cfg.UsernameClaim)
|
||||||
|
}
|
||||||
|
if user.Email == "" {
|
||||||
|
user.Email = claimString(uiClaims, "email")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Username == "" {
|
||||||
|
user.Username = user.Email
|
||||||
|
}
|
||||||
|
if user.Username == "" {
|
||||||
|
user.Username = idTok.Subject
|
||||||
|
}
|
||||||
|
if user.Username == "" {
|
||||||
|
return nil, errors.New("could not determine username from OIDC claims")
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *OIDCProvider) gcStatesLocked() {
|
||||||
|
now := time.Now()
|
||||||
|
for k, v := range p.states {
|
||||||
|
if now.After(v.expiresAt) {
|
||||||
|
delete(p.states, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func claimString(claims map[string]interface{}, key string) string {
|
||||||
|
if v, ok := claims[key].(string); ok {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func claimStrings(claims map[string]interface{}, key string) []string {
|
||||||
|
raw, ok := claims[key]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch v := raw.(type) {
|
||||||
|
case []interface{}:
|
||||||
|
out := make([]string, 0, len(v))
|
||||||
|
for _, item := range v {
|
||||||
|
if s, ok := item.(string); ok && s != "" {
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
case []string:
|
||||||
|
return v
|
||||||
|
case string:
|
||||||
|
if v == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []string{v}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func randToken() string {
|
||||||
|
b := make([]byte, 32)
|
||||||
|
_, _ = rand.Read(b)
|
||||||
|
return hex.EncodeToString(b)
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config holds all backend runtime configuration.
|
// Config holds all backend runtime configuration.
|
||||||
@@ -11,8 +12,13 @@ type Config struct {
|
|||||||
StoragePath string `json:"storage_path"`
|
StoragePath string `json:"storage_path"`
|
||||||
DBPath string `json:"db_path"`
|
DBPath string `json:"db_path"`
|
||||||
LDAP LDAPConfig `json:"ldap"`
|
LDAP LDAPConfig `json:"ldap"`
|
||||||
|
OIDC OIDCConfig `json:"oidc"`
|
||||||
JWTSecret string `json:"jwt_secret"`
|
JWTSecret string `json:"jwt_secret"`
|
||||||
ListenAddr string `json:"listen_addr"`
|
ListenAddr string `json:"listen_addr"`
|
||||||
|
// PublicURL is the externally reachable base URL of Archivum
|
||||||
|
// (e.g. https://archivum.brasse-pc.eu). Used to build the OIDC
|
||||||
|
// redirect URL when one is not set explicitly.
|
||||||
|
PublicURL string `json:"public_url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LDAPConfig struct {
|
type LDAPConfig struct {
|
||||||
@@ -22,6 +28,50 @@ type LDAPConfig struct {
|
|||||||
AdminPass string `json:"admin_pass"`
|
AdminPass string `json:"admin_pass"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OIDCConfig configures Single-Sign-On via an OpenID Connect provider
|
||||||
|
// (Authentik in this deployment). The provider authenticates the user and
|
||||||
|
// returns their group membership in the groups claim.
|
||||||
|
type OIDCConfig struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
Issuer string `json:"issuer"` // e.g. https://authentik.brasse-pc.eu/application/o/archivum/
|
||||||
|
ClientID string `json:"client_id"`
|
||||||
|
ClientSecret string `json:"client_secret"`
|
||||||
|
RedirectURL string `json:"redirect_url"` // optional; derived from PublicURL when empty
|
||||||
|
// Claim/group mapping. Sensible defaults are applied in Normalize().
|
||||||
|
GroupsClaim string `json:"groups_claim"` // default "groups"
|
||||||
|
UsernameClaim string `json:"username_claim"` // default "preferred_username"
|
||||||
|
AdminGroup string `json:"admin_group"` // default "Archivum-admin"
|
||||||
|
ReaderGroup string `json:"reader_group"` // default "Archivum-reader"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize fills in defaults for optional OIDC fields.
|
||||||
|
func (o *OIDCConfig) Normalize() {
|
||||||
|
if o.GroupsClaim == "" {
|
||||||
|
o.GroupsClaim = "groups"
|
||||||
|
}
|
||||||
|
if o.UsernameClaim == "" {
|
||||||
|
o.UsernameClaim = "preferred_username"
|
||||||
|
}
|
||||||
|
if o.AdminGroup == "" {
|
||||||
|
o.AdminGroup = "Archivum-admin"
|
||||||
|
}
|
||||||
|
if o.ReaderGroup == "" {
|
||||||
|
o.ReaderGroup = "Archivum-reader"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolvedRedirectURL returns the OIDC callback URL, deriving it from
|
||||||
|
// PublicURL when RedirectURL is not set.
|
||||||
|
func (c *Config) ResolvedRedirectURL() string {
|
||||||
|
if c.OIDC.RedirectURL != "" {
|
||||||
|
return c.OIDC.RedirectURL
|
||||||
|
}
|
||||||
|
if c.PublicURL != "" {
|
||||||
|
return strings.TrimRight(c.PublicURL, "/") + "/auth/oidc/callback"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// ErrRequireSetup is returned when config is missing or empty,
|
// ErrRequireSetup is returned when config is missing or empty,
|
||||||
// signalling that the frontend should start the Setup Wizard.
|
// signalling that the frontend should start the Setup Wizard.
|
||||||
var ErrRequireSetup = errors.New("REQUIRE_SETUP")
|
var ErrRequireSetup = errors.New("REQUIRE_SETUP")
|
||||||
@@ -54,6 +104,8 @@ func Load(path string) (*Config, error) {
|
|||||||
cfg.DBPath = "/data/db/archivum.db"
|
cfg.DBPath = "/data/db/archivum.db"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg.OIDC.Normalize()
|
||||||
|
|
||||||
return &cfg, nil
|
return &cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package db
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -12,16 +13,33 @@ import (
|
|||||||
var ErrUserNotFound = errors.New("user not found")
|
var ErrUserNotFound = errors.New("user not found")
|
||||||
var ErrUserExists = errors.New("username already exists")
|
var ErrUserExists = errors.New("username already exists")
|
||||||
|
|
||||||
// User represents a local account stored in SQLite.
|
// Built-in group names that map to application roles. They are seeded on
|
||||||
|
// startup and are what OIDC group claims are matched against.
|
||||||
|
const (
|
||||||
|
GroupAdmin = "Archivum-admin"
|
||||||
|
GroupReader = "Archivum-reader"
|
||||||
|
)
|
||||||
|
|
||||||
|
// User represents an account stored in SQLite (local or externally
|
||||||
|
// provisioned via OIDC/LDAP).
|
||||||
type User struct {
|
type User struct {
|
||||||
ID int64
|
ID int64
|
||||||
Username string
|
Username string
|
||||||
PassHash string
|
PassHash string
|
||||||
Role string
|
Role string
|
||||||
IsLDAP bool
|
IsLDAP bool
|
||||||
|
AllowLogin bool
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Group represents a group stored in SQLite.
|
||||||
|
type Group struct {
|
||||||
|
ID int64
|
||||||
|
Name string
|
||||||
|
IsLDAP bool
|
||||||
|
AllowLogin bool
|
||||||
|
}
|
||||||
|
|
||||||
// DB wraps the SQLite connection.
|
// DB wraps the SQLite connection.
|
||||||
type DB struct {
|
type DB struct {
|
||||||
sql *sql.DB
|
sql *sql.DB
|
||||||
@@ -29,7 +47,7 @@ type DB struct {
|
|||||||
|
|
||||||
// New opens (or creates) the SQLite database at path and runs migrations.
|
// New opens (or creates) the SQLite database at path and runs migrations.
|
||||||
func New(path string) (*DB, error) {
|
func New(path string) (*DB, error) {
|
||||||
sqldb, err := sql.Open("sqlite", path+"?_journal=WAL&_timeout=5000")
|
sqldb, err := sql.Open("sqlite", path+"?_journal=WAL&_timeout=5000&_pragma=foreign_keys(1)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -53,12 +71,14 @@ func (d *DB) init() error {
|
|||||||
pass_hash TEXT NOT NULL,
|
pass_hash TEXT NOT NULL,
|
||||||
role TEXT NOT NULL DEFAULT 'user',
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
is_ldap BOOLEAN NOT NULL DEFAULT 0,
|
is_ldap BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
allow_login BOOLEAN NOT NULL DEFAULT 1,
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS groups (
|
CREATE TABLE IF NOT EXISTS groups (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
name TEXT NOT NULL UNIQUE,
|
name TEXT NOT NULL UNIQUE,
|
||||||
is_ldap BOOLEAN NOT NULL DEFAULT 0,
|
is_ldap BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
allow_login BOOLEAN NOT NULL DEFAULT 0,
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS user_groups (
|
CREATE TABLE IF NOT EXISTS user_groups (
|
||||||
@@ -73,6 +93,7 @@ func (d *DB) init() error {
|
|||||||
path TEXT NOT NULL,
|
path TEXT NOT NULL,
|
||||||
subject_type TEXT NOT NULL CHECK(subject_type IN ('user', 'group')),
|
subject_type TEXT NOT NULL CHECK(subject_type IN ('user', 'group')),
|
||||||
subject_id INTEGER NOT NULL,
|
subject_id INTEGER NOT NULL,
|
||||||
|
effect TEXT NOT NULL DEFAULT 'allow' CHECK(effect IN ('allow','deny')),
|
||||||
can_search BOOLEAN NOT NULL DEFAULT 0,
|
can_search BOOLEAN NOT NULL DEFAULT 0,
|
||||||
can_view BOOLEAN NOT NULL DEFAULT 0,
|
can_view BOOLEAN NOT NULL DEFAULT 0,
|
||||||
can_read BOOLEAN NOT NULL DEFAULT 0,
|
can_read BOOLEAN NOT NULL DEFAULT 0,
|
||||||
@@ -80,23 +101,110 @@ func (d *DB) init() error {
|
|||||||
can_create BOOLEAN NOT NULL DEFAULT 0,
|
can_create BOOLEAN NOT NULL DEFAULT 0,
|
||||||
can_delete BOOLEAN NOT NULL DEFAULT 0,
|
can_delete BOOLEAN NOT NULL DEFAULT 0,
|
||||||
can_move BOOLEAN NOT NULL DEFAULT 0,
|
can_move BOOLEAN NOT NULL DEFAULT 0,
|
||||||
UNIQUE(path, subject_type, subject_id)
|
UNIQUE(path, subject_type, subject_id, effect)
|
||||||
);
|
);
|
||||||
`)
|
`)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
}
|
||||||
|
return d.migrate()
|
||||||
}
|
}
|
||||||
|
|
||||||
// HasUsers returns true if at least one user account exists.
|
// migrate brings older databases (created before allow/deny ACLs and the
|
||||||
|
// allow_login flags) up to the current schema. All steps are idempotent.
|
||||||
|
func (d *DB) migrate() error {
|
||||||
|
// users.allow_login
|
||||||
|
if ok, err := d.columnExists("users", "allow_login"); err != nil {
|
||||||
|
return err
|
||||||
|
} else if !ok {
|
||||||
|
if _, err := d.sql.Exec(`ALTER TABLE users ADD COLUMN allow_login BOOLEAN NOT NULL DEFAULT 1`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// groups.allow_login
|
||||||
|
if ok, err := d.columnExists("groups", "allow_login"); err != nil {
|
||||||
|
return err
|
||||||
|
} else if !ok {
|
||||||
|
if _, err := d.sql.Exec(`ALTER TABLE groups ADD COLUMN allow_login BOOLEAN NOT NULL DEFAULT 0`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// acl.effect — requires a table rebuild because the UNIQUE constraint changes.
|
||||||
|
if ok, err := d.columnExists("acl", "effect"); err != nil {
|
||||||
|
return err
|
||||||
|
} else if !ok {
|
||||||
|
tx, err := d.sql.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
stmts := []string{
|
||||||
|
`ALTER TABLE acl RENAME TO acl_old`,
|
||||||
|
`CREATE TABLE acl (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
subject_type TEXT NOT NULL CHECK(subject_type IN ('user', 'group')),
|
||||||
|
subject_id INTEGER NOT NULL,
|
||||||
|
effect TEXT NOT NULL DEFAULT 'allow' CHECK(effect IN ('allow','deny')),
|
||||||
|
can_search BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_view BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_read BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_edit BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_create BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_delete BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
can_move BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
UNIQUE(path, subject_type, subject_id, effect)
|
||||||
|
)`,
|
||||||
|
`INSERT INTO acl (path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
|
||||||
|
SELECT path, subject_type, subject_id, 'allow', can_search, can_view, can_read, can_edit, can_create, can_delete, can_move FROM acl_old`,
|
||||||
|
`DROP TABLE acl_old`,
|
||||||
|
}
|
||||||
|
for _, s := range stmts {
|
||||||
|
if _, err := tx.Exec(s); err != nil {
|
||||||
|
return fmt.Errorf("acl migration: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) columnExists(table, column string) (bool, error) {
|
||||||
|
rows, err := d.sql.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var cid int
|
||||||
|
var name, ctype string
|
||||||
|
var notnull, pk int
|
||||||
|
var dflt sql.NullString
|
||||||
|
if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if name == column {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasUsers returns true if at least one non-guest user account exists.
|
||||||
func (d *DB) HasUsers() bool {
|
func (d *DB) HasUsers() bool {
|
||||||
var n int
|
var n int
|
||||||
d.sql.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
d.sql.QueryRow(`SELECT COUNT(*) FROM users WHERE username != 'guest'`).Scan(&n)
|
||||||
return n > 0
|
return n > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateUser inserts a new user. Returns ErrUserExists if the username is taken.
|
// ── Users ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// CreateUser inserts a new local user. Returns ErrUserExists if taken.
|
||||||
func (d *DB) CreateUser(username, passHash, role string) error {
|
func (d *DB) CreateUser(username, passHash, role string) error {
|
||||||
_, err := d.sql.Exec(
|
_, err := d.sql.Exec(
|
||||||
`INSERT INTO users (username, pass_hash, role) VALUES (?, ?, ?)`,
|
`INSERT INTO users (username, pass_hash, role, allow_login) VALUES (?, ?, ?, 1)`,
|
||||||
username, passHash, role,
|
username, passHash, role,
|
||||||
)
|
)
|
||||||
if err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") {
|
if err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") {
|
||||||
@@ -108,12 +216,12 @@ func (d *DB) CreateUser(username, passHash, role string) error {
|
|||||||
// GetUser fetches a single user by username.
|
// GetUser fetches a single user by username.
|
||||||
func (d *DB) GetUser(username string) (*User, error) {
|
func (d *DB) GetUser(username string) (*User, error) {
|
||||||
row := d.sql.QueryRow(
|
row := d.sql.QueryRow(
|
||||||
`SELECT id, username, pass_hash, role, is_ldap, created_at FROM users WHERE username = ?`,
|
`SELECT id, username, pass_hash, role, is_ldap, allow_login, created_at FROM users WHERE username = ?`,
|
||||||
username,
|
username,
|
||||||
)
|
)
|
||||||
u := &User{}
|
u := &User{}
|
||||||
var createdAt string
|
var createdAt string
|
||||||
err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.IsLDAP, &createdAt)
|
err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.IsLDAP, &u.AllowLogin, &createdAt)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, ErrUserNotFound
|
return nil, ErrUserNotFound
|
||||||
}
|
}
|
||||||
@@ -127,7 +235,7 @@ func (d *DB) GetUser(username string) (*User, error) {
|
|||||||
// ListUsers returns all users ordered by id.
|
// ListUsers returns all users ordered by id.
|
||||||
func (d *DB) ListUsers() ([]*User, error) {
|
func (d *DB) ListUsers() ([]*User, error) {
|
||||||
rows, err := d.sql.Query(
|
rows, err := d.sql.Query(
|
||||||
`SELECT id, username, role, is_ldap, created_at FROM users ORDER BY id`,
|
`SELECT id, username, role, is_ldap, allow_login, created_at FROM users ORDER BY id`,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -138,7 +246,7 @@ func (d *DB) ListUsers() ([]*User, error) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
u := &User{}
|
u := &User{}
|
||||||
var createdAt string
|
var createdAt string
|
||||||
if err := rows.Scan(&u.ID, &u.Username, &u.Role, &u.IsLDAP, &createdAt); err != nil {
|
if err := rows.Scan(&u.ID, &u.Username, &u.Role, &u.IsLDAP, &u.AllowLogin, &createdAt); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
u.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
u.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||||
@@ -176,49 +284,253 @@ func (d *DB) UpdatePassword(username, passHash string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserCount returns the total number of local accounts.
|
// SetUserRole updates a user's role (admin/user/guest).
|
||||||
|
func (d *DB) SetUserRole(username, role string) error {
|
||||||
|
_, err := d.sql.Exec(`UPDATE users SET role = ? WHERE username = ?`, role, username)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUserLogin toggles whether a user is permitted to sign in.
|
||||||
|
func (d *DB) SetUserLogin(username string, allow bool) error {
|
||||||
|
_, err := d.sql.Exec(`UPDATE users SET allow_login = ? WHERE username = ?`, boolInt(allow), username)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserCount returns the total number of accounts.
|
||||||
func (d *DB) UserCount() (int, error) {
|
func (d *DB) UserCount() (int, error) {
|
||||||
var n int
|
var n int
|
||||||
err := d.sql.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
err := d.sql.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- LDAP & Roles ---
|
// ── LDAP / OIDC provisioning ─────────────────────────────────────────────────
|
||||||
|
|
||||||
// CreateOrUpdateLDAPUser inserts or updates an LDAP user (without password, role='user').
|
// CreateOrUpdateExternalUser inserts or updates an externally-authenticated
|
||||||
// Existing accounts with a non-empty pass_hash are never overwritten so that
|
// user (OIDC/LDAP; no local password). On first insert allow_login is set to
|
||||||
// a local admin cannot be accidentally converted to an LDAP-only account.
|
// allowLogin; on subsequent logins the stored allow_login is preserved so an
|
||||||
func (d *DB) CreateOrUpdateLDAPUser(username string) error {
|
// admin's manual toggle sticks. Existing accounts with a non-empty pass_hash
|
||||||
|
// (local admins) keep their role — they are never downgraded.
|
||||||
|
func (d *DB) CreateOrUpdateExternalUser(username, role string, allowLogin bool) error {
|
||||||
|
if role == "" {
|
||||||
|
role = "user"
|
||||||
|
}
|
||||||
_, err := d.sql.Exec(`
|
_, err := d.sql.Exec(`
|
||||||
INSERT INTO users (username, pass_hash, role, is_ldap)
|
INSERT INTO users (username, pass_hash, role, is_ldap, allow_login)
|
||||||
VALUES (?, '', 'user', 1)
|
VALUES (?, '', ?, 1, ?)
|
||||||
ON CONFLICT(username) DO UPDATE SET is_ldap=1
|
ON CONFLICT(username) DO UPDATE SET is_ldap=1, role=excluded.role
|
||||||
WHERE excluded.pass_hash = '' AND pass_hash = '';
|
WHERE users.pass_hash = '';
|
||||||
`, username)
|
`, username, role, boolInt(allowLogin))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateOrUpdateGroup inserts or updates a group (local or LDAP).
|
// CreateOrUpdateGroup inserts or updates a group (local or external).
|
||||||
func (d *DB) CreateOrUpdateGroup(name string, isLdap bool) error {
|
func (d *DB) CreateOrUpdateGroup(name string, isLdap bool) error {
|
||||||
ldVal := 0
|
|
||||||
if isLdap {
|
|
||||||
ldVal = 1
|
|
||||||
}
|
|
||||||
_, err := d.sql.Exec(`
|
_, err := d.sql.Exec(`
|
||||||
INSERT INTO groups (name, is_ldap)
|
INSERT INTO groups (name, is_ldap)
|
||||||
VALUES (?, ?)
|
VALUES (?, ?)
|
||||||
ON CONFLICT(name) DO UPDATE SET is_ldap=excluded.is_ldap;
|
ON CONFLICT(name) DO UPDATE SET is_ldap=excluded.is_ldap;
|
||||||
`, name, ldVal)
|
`, name, boolInt(isLdap))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- ACL Methods ---
|
// DeleteGroup removes a group and its memberships/ACLs cascade via FK / manual cleanup.
|
||||||
|
func (d *DB) DeleteGroup(name string) error {
|
||||||
|
g, err := d.GetGroup(name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx, err := d.sql.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err := tx.Exec(`DELETE FROM acl WHERE subject_type='group' AND subject_id=?`, g.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(`DELETE FROM groups WHERE id=?`, g.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetGroupLogin toggles whether members of a group are permitted to sign in.
|
||||||
|
func (d *DB) SetGroupLogin(name string, allow bool) error {
|
||||||
|
_, err := d.sql.Exec(`UPDATE groups SET allow_login = ? WHERE name = ?`, boolInt(allow), name)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetGroup fetches a group by name.
|
||||||
|
func (d *DB) GetGroup(name string) (*Group, error) {
|
||||||
|
row := d.sql.QueryRow(`SELECT id, name, is_ldap, allow_login FROM groups WHERE name = ?`, name)
|
||||||
|
g := &Group{}
|
||||||
|
if err := row.Scan(&g.ID, &g.Name, &g.IsLDAP, &g.AllowLogin); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrUserNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return g, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListGroups returns all groups ordered by name.
|
||||||
|
func (d *DB) ListGroups() ([]*Group, error) {
|
||||||
|
rows, err := d.sql.Query(`SELECT id, name, is_ldap, allow_login FROM groups ORDER BY name`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var groups []*Group
|
||||||
|
for rows.Next() {
|
||||||
|
g := &Group{}
|
||||||
|
if err := rows.Scan(&g.ID, &g.Name, &g.IsLDAP, &g.AllowLogin); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
groups = append(groups, g)
|
||||||
|
}
|
||||||
|
return groups, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureBuiltinGroups creates the Archivum-admin / Archivum-reader groups that
|
||||||
|
// map to application roles. They are marked external (synced from the IdP) and
|
||||||
|
// login-enabled.
|
||||||
|
func (d *DB) EnsureBuiltinGroups() error {
|
||||||
|
for _, name := range []string{GroupAdmin, GroupReader} {
|
||||||
|
if _, err := d.sql.Exec(`
|
||||||
|
INSERT INTO groups (name, is_ldap, allow_login) VALUES (?, 1, 1)
|
||||||
|
ON CONFLICT(name) DO UPDATE SET allow_login=1;
|
||||||
|
`, name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureGuestUser creates the built-in public/guest account if missing.
|
||||||
|
func (d *DB) EnsureGuestUser() error {
|
||||||
|
_, err := d.sql.Exec(`
|
||||||
|
INSERT INTO users (username, pass_hash, role, allow_login) VALUES ('guest', '', 'guest', 1)
|
||||||
|
ON CONFLICT(username) DO NOTHING;
|
||||||
|
`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Group membership ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// AddUserToGroup links a user to a group (both by name).
|
||||||
|
func (d *DB) AddUserToGroup(username, groupName string) error {
|
||||||
|
u, err := d.GetUser(username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
g, err := d.GetGroup(groupName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = d.sql.Exec(`INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)`, u.ID, g.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveUserFromGroup unlinks a user from a group.
|
||||||
|
func (d *DB) RemoveUserFromGroup(username, groupName string) error {
|
||||||
|
u, err := d.GetUser(username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
g, err := d.GetGroup(groupName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = d.sql.Exec(`DELETE FROM user_groups WHERE user_id=? AND group_id=?`, u.ID, g.ID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserGroupNames returns the names of all groups a (local) user belongs to.
|
||||||
|
func (d *DB) GetUserGroupNames(username string) ([]string, error) {
|
||||||
|
rows, err := d.sql.Query(`
|
||||||
|
SELECT g.name FROM groups g
|
||||||
|
JOIN user_groups ug ON ug.group_id = g.id
|
||||||
|
JOIN users u ON u.id = ug.user_id
|
||||||
|
WHERE u.username = ?
|
||||||
|
ORDER BY g.name
|
||||||
|
`, username)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []string
|
||||||
|
for rows.Next() {
|
||||||
|
var n string
|
||||||
|
if err := rows.Scan(&n); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncUserGroups ensures the given group names exist and that the user is a
|
||||||
|
// member of exactly those groups that are also present in the DB. Used to keep
|
||||||
|
// a local mirror of an OIDC user's group membership for the admin UI.
|
||||||
|
func (d *DB) SyncUserGroups(username string, groupNames []string) error {
|
||||||
|
u, err := d.GetUser(username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx, err := d.sql.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err := tx.Exec(`DELETE FROM user_groups WHERE user_id=?`, u.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, name := range groupNames {
|
||||||
|
var gid int64
|
||||||
|
if err := tx.QueryRow(`SELECT id FROM groups WHERE name=?`, name).Scan(&gid); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(`INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)`, u.ID, gid); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Login gate ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// LoginAllowed reports whether a subject may sign in: the user must have
|
||||||
|
// allow_login set, or belong to at least one login-enabled group (by name).
|
||||||
|
// The built-in role groups always permit login.
|
||||||
|
func (d *DB) LoginAllowed(username string, groupNames []string) bool {
|
||||||
|
if u, err := d.GetUser(username); err == nil {
|
||||||
|
if u.Role == "admin" || u.AllowLogin {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range groupNames {
|
||||||
|
if name == GroupAdmin || name == GroupReader {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
var allow int
|
||||||
|
d.sql.QueryRow(`SELECT allow_login FROM groups WHERE name=?`, name).Scan(&allow)
|
||||||
|
if allow == 1 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── ACL ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
type ACLEntry struct {
|
type ACLEntry struct {
|
||||||
ID int64
|
ID int64
|
||||||
Path string
|
Path string
|
||||||
SubjectType string
|
SubjectType string
|
||||||
SubjectID int64
|
SubjectID int64
|
||||||
|
Effect string // "allow" | "deny"
|
||||||
CanSearch bool
|
CanSearch bool
|
||||||
CanView bool
|
CanView bool
|
||||||
CanRead bool
|
CanRead bool
|
||||||
@@ -228,12 +540,26 @@ type ACLEntry struct {
|
|||||||
CanMove bool
|
CanMove bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetACL inserts or replaces an ACL entry.
|
// Perms is the resolved effective permission set for a subject on a path.
|
||||||
|
type Perms struct {
|
||||||
|
Search bool
|
||||||
|
View bool
|
||||||
|
Read bool
|
||||||
|
Edit bool
|
||||||
|
Create bool
|
||||||
|
Delete bool
|
||||||
|
Move bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetACL inserts or replaces an ACL entry keyed on (path, subject, effect).
|
||||||
func (d *DB) SetACL(entry ACLEntry) error {
|
func (d *DB) SetACL(entry ACLEntry) error {
|
||||||
|
if entry.Effect != "deny" {
|
||||||
|
entry.Effect = "allow"
|
||||||
|
}
|
||||||
_, err := d.sql.Exec(`
|
_, err := d.sql.Exec(`
|
||||||
INSERT INTO acl (path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
|
INSERT INTO acl (path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(path, subject_type, subject_id) DO UPDATE SET
|
ON CONFLICT(path, subject_type, subject_id, effect) DO UPDATE SET
|
||||||
can_search = excluded.can_search,
|
can_search = excluded.can_search,
|
||||||
can_view = excluded.can_view,
|
can_view = excluded.can_view,
|
||||||
can_read = excluded.can_read,
|
can_read = excluded.can_read,
|
||||||
@@ -241,7 +567,7 @@ func (d *DB) SetACL(entry ACLEntry) error {
|
|||||||
can_create = excluded.can_create,
|
can_create = excluded.can_create,
|
||||||
can_delete = excluded.can_delete,
|
can_delete = excluded.can_delete,
|
||||||
can_move = excluded.can_move;
|
can_move = excluded.can_move;
|
||||||
`, entry.Path, entry.SubjectType, entry.SubjectID,
|
`, entry.Path, entry.SubjectType, entry.SubjectID, entry.Effect,
|
||||||
entry.CanSearch, entry.CanView, entry.CanRead, entry.CanEdit,
|
entry.CanSearch, entry.CanView, entry.CanRead, entry.CanEdit,
|
||||||
entry.CanCreate, entry.CanDelete, entry.CanMove)
|
entry.CanCreate, entry.CanDelete, entry.CanMove)
|
||||||
return err
|
return err
|
||||||
@@ -253,23 +579,13 @@ func (d *DB) RemoveACL(id int64) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetACLsForSubject retrieves all ACL entries for a specific subject (user or group).
|
func scanACLRows(rows *sql.Rows) ([]ACLEntry, error) {
|
||||||
func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry, error) {
|
|
||||||
rows, err := d.sql.Query(`
|
|
||||||
SELECT id, path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move
|
|
||||||
FROM acl WHERE subject_type = ? AND subject_id = ?
|
|
||||||
ORDER BY path
|
|
||||||
`, subjectType, subjectID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
var entries []ACLEntry
|
var entries []ACLEntry
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var e ACLEntry
|
var e ACLEntry
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID,
|
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID, &e.Effect,
|
||||||
&e.CanSearch, &e.CanView, &e.CanRead, &e.CanEdit,
|
&e.CanSearch, &e.CanView, &e.CanRead, &e.CanEdit,
|
||||||
&e.CanCreate, &e.CanDelete, &e.CanMove,
|
&e.CanCreate, &e.CanDelete, &e.CanMove,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
@@ -280,106 +596,125 @@ func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry,
|
|||||||
return entries, rows.Err()
|
return entries, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetACLsForPath retrieves all ACL definitions for a specific document or folder.
|
const aclCols = `id, path, subject_type, subject_id, effect, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move`
|
||||||
|
|
||||||
|
// GetACLsForSubject retrieves all ACL entries for a specific subject.
|
||||||
|
func (d *DB) GetACLsForSubject(subjectType string, subjectID int64) ([]ACLEntry, error) {
|
||||||
|
rows, err := d.sql.Query(
|
||||||
|
`SELECT `+aclCols+` FROM acl WHERE subject_type = ? AND subject_id = ? ORDER BY path, effect`,
|
||||||
|
subjectType, subjectID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return scanACLRows(rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetACLsForPath retrieves all ACL definitions for a specific path.
|
||||||
func (d *DB) GetACLsForPath(path string) ([]ACLEntry, error) {
|
func (d *DB) GetACLsForPath(path string) ([]ACLEntry, error) {
|
||||||
rows, err := d.sql.Query(`
|
rows, err := d.sql.Query(`SELECT `+aclCols+` FROM acl WHERE path = ?`, path)
|
||||||
SELECT id, path, subject_type, subject_id, can_search, can_view, can_read, can_edit, can_create, can_delete, can_move
|
|
||||||
FROM acl WHERE path = ?
|
|
||||||
`, path)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
return scanACLRows(rows)
|
||||||
|
|
||||||
var entries []ACLEntry
|
|
||||||
for rows.Next() {
|
|
||||||
var e ACLEntry
|
|
||||||
if err := rows.Scan(
|
|
||||||
&e.ID, &e.Path, &e.SubjectType, &e.SubjectID,
|
|
||||||
&e.CanSearch, &e.CanView, &e.CanRead, &e.CanEdit,
|
|
||||||
&e.CanCreate, &e.CanDelete, &e.CanMove,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
entries = append(entries, e)
|
|
||||||
}
|
|
||||||
return entries, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Group represents a group stored in SQLite.
|
// EffectiveAccess resolves the permissions a user has on a path by combining
|
||||||
type Group struct {
|
// every ACL entry that applies to the user directly or to any of the given
|
||||||
ID int64
|
// groups, across the path and all of its ancestor folders.
|
||||||
Name string
|
//
|
||||||
IsLDAP bool
|
// Resolution rule (as specified): default deny. An explicit allow grants a
|
||||||
}
|
// permission; an explicit deny anywhere in the applicable set always wins over
|
||||||
|
// an allow. So a permission is granted only if some entry allows it and no
|
||||||
|
// entry denies it.
|
||||||
|
func (d *DB) EffectiveAccess(username string, groupNames []string, path string) Perms {
|
||||||
|
ancestors := pathAncestors(path)
|
||||||
|
ancestorSet := make(map[string]bool, len(ancestors))
|
||||||
|
for _, p := range ancestors {
|
||||||
|
ancestorSet[p] = true
|
||||||
|
}
|
||||||
|
|
||||||
// ListGroups returns all groups ordered by name.
|
// Build the subject filter: this user + these groups.
|
||||||
func (d *DB) ListGroups() ([]*Group, error) {
|
var where []string
|
||||||
rows, err := d.sql.Query(`SELECT id, name, is_ldap FROM groups ORDER BY name`)
|
var args []interface{}
|
||||||
|
if uid, ok := d.userID(username); ok {
|
||||||
|
where = append(where, `(subject_type='user' AND subject_id=?)`)
|
||||||
|
args = append(args, uid)
|
||||||
|
}
|
||||||
|
if gids := d.groupIDs(groupNames); len(gids) > 0 {
|
||||||
|
ph := make([]string, len(gids))
|
||||||
|
for i, id := range gids {
|
||||||
|
ph[i] = "?"
|
||||||
|
args = append(args, id)
|
||||||
|
}
|
||||||
|
where = append(where, `(subject_type='group' AND subject_id IN (`+strings.Join(ph, ",")+`))`)
|
||||||
|
}
|
||||||
|
if len(where) == 0 {
|
||||||
|
return Perms{}
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := d.sql.Query(
|
||||||
|
`SELECT `+aclCols+` FROM acl WHERE `+strings.Join(where, " OR "), args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return Perms{}
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
entries, err := scanACLRows(rows)
|
||||||
var groups []*Group
|
if err != nil {
|
||||||
for rows.Next() {
|
return Perms{}
|
||||||
g := &Group{}
|
|
||||||
if err := rows.Scan(&g.ID, &g.Name, &g.IsLDAP); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
groups = append(groups, g)
|
|
||||||
|
var allow, deny Perms
|
||||||
|
for _, e := range entries {
|
||||||
|
if !ancestorSet[e.Path] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
target := &allow
|
||||||
|
if e.Effect == "deny" {
|
||||||
|
target = &deny
|
||||||
|
}
|
||||||
|
target.Search = target.Search || e.CanSearch
|
||||||
|
target.View = target.View || e.CanView
|
||||||
|
target.Read = target.Read || e.CanRead
|
||||||
|
target.Edit = target.Edit || e.CanEdit
|
||||||
|
target.Create = target.Create || e.CanCreate
|
||||||
|
target.Delete = target.Delete || e.CanDelete
|
||||||
|
target.Move = target.Move || e.CanMove
|
||||||
|
}
|
||||||
|
|
||||||
|
return Perms{
|
||||||
|
Search: allow.Search && !deny.Search,
|
||||||
|
View: allow.View && !deny.View,
|
||||||
|
Read: allow.Read && !deny.Read,
|
||||||
|
Edit: allow.Edit && !deny.Edit,
|
||||||
|
Create: allow.Create && !deny.Create,
|
||||||
|
Delete: allow.Delete && !deny.Delete,
|
||||||
|
Move: allow.Move && !deny.Move,
|
||||||
}
|
}
|
||||||
return groups, rows.Err()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnsureGuestUser creates the built-in guest account if it does not already exist.
|
func (d *DB) userID(username string) (int64, bool) {
|
||||||
func (d *DB) EnsureGuestUser() error {
|
var id int64
|
||||||
_, err := d.sql.Exec(`
|
err := d.sql.QueryRow(`SELECT id FROM users WHERE username=?`, username).Scan(&id)
|
||||||
INSERT INTO users (username, pass_hash, role) VALUES ('guest', '', 'guest')
|
if err != nil {
|
||||||
ON CONFLICT(username) DO NOTHING;
|
return 0, false
|
||||||
`)
|
}
|
||||||
return err
|
return id, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanUserReadPath returns true if the given username has can_read access on the
|
func (d *DB) groupIDs(names []string) []int64 {
|
||||||
// exact path or any of its ancestor folder paths.
|
var out []int64
|
||||||
func (d *DB) CanUserReadPath(username, path string) bool {
|
for _, n := range names {
|
||||||
// Build a list of candidate paths: the path itself and each parent segment.
|
var id int64
|
||||||
candidates := pathAncestors(path)
|
if err := d.sql.QueryRow(`SELECT id FROM groups WHERE name=?`, n).Scan(&id); err == nil {
|
||||||
for _, p := range candidates {
|
out = append(out, id)
|
||||||
var n int
|
|
||||||
d.sql.QueryRow(`
|
|
||||||
SELECT COUNT(*) FROM acl
|
|
||||||
JOIN users ON users.id = acl.subject_id AND acl.subject_type = 'user'
|
|
||||||
WHERE users.username = ? AND acl.path = ? AND acl.can_read = 1
|
|
||||||
`, username, p).Scan(&n)
|
|
||||||
if n > 0 {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return out
|
||||||
}
|
|
||||||
|
|
||||||
// CanUserViewPath returns true if the given username has can_view access on the
|
|
||||||
// exact path or any of its ancestor folder paths.
|
|
||||||
func (d *DB) CanUserViewPath(username, path string) bool {
|
|
||||||
candidates := pathAncestors(path)
|
|
||||||
for _, p := range candidates {
|
|
||||||
var n int
|
|
||||||
d.sql.QueryRow(`
|
|
||||||
SELECT COUNT(*) FROM acl
|
|
||||||
JOIN users ON users.id = acl.subject_id AND acl.subject_type = 'user'
|
|
||||||
WHERE users.username = ? AND acl.path = ? AND acl.can_view = 1
|
|
||||||
`, username, p).Scan(&n)
|
|
||||||
if n > 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// pathAncestors returns the path and all its parent segments.
|
// pathAncestors returns the path and all its parent segments.
|
||||||
// e.g. "a/b/c" → ["a/b/c", "a/b", "a"]
|
// e.g. "a/b/c" → ["a/b/c", "a/b", "a"]
|
||||||
func pathAncestors(path string) []string {
|
func pathAncestors(path string) []string {
|
||||||
|
path = strings.TrimSuffix(path, "/")
|
||||||
out := []string{path}
|
out := []string{path}
|
||||||
for {
|
for {
|
||||||
idx := strings.LastIndex(path, "/")
|
idx := strings.LastIndex(path, "/")
|
||||||
@@ -391,3 +726,10 @@ func pathAncestors(path string) []string {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func boolInt(b bool) int {
|
||||||
|
if b {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -49,6 +49,18 @@ type Query {
|
|||||||
|
|
||||||
# Returns the role of the currently authenticated user ("admin", "user", "guest").
|
# Returns the role of the currently authenticated user ("admin", "user", "guest").
|
||||||
currentUserRole: String!
|
currentUserRole: String!
|
||||||
|
|
||||||
|
# Sign-in methods the login page should offer (public, no auth required).
|
||||||
|
loginOptions: LoginOptions!
|
||||||
|
|
||||||
|
# All local/external users with role & login state (admin only).
|
||||||
|
users: [UserInfo!]!
|
||||||
|
|
||||||
|
# Current OpenID Connect (Authentik) configuration (admin only, no secret).
|
||||||
|
oidcConfig: OIDCConfigView!
|
||||||
|
|
||||||
|
# Names of the groups a user belongs to (admin only).
|
||||||
|
userGroups(username: String!): [String!]!
|
||||||
}
|
}
|
||||||
|
|
||||||
type Mutation {
|
type Mutation {
|
||||||
@@ -73,9 +85,25 @@ type Mutation {
|
|||||||
# Modify LDAP Configuration (admin only).
|
# Modify LDAP Configuration (admin only).
|
||||||
updateLdapConfig(input: LDAPInput): Boolean!
|
updateLdapConfig(input: LDAPInput): Boolean!
|
||||||
|
|
||||||
|
# Modify OpenID Connect (Authentik) configuration (admin only).
|
||||||
|
updateOidcConfig(input: OIDCInput!): Boolean!
|
||||||
|
|
||||||
# Sync users/groups from LDAP
|
# Sync users/groups from LDAP
|
||||||
importLdapSubject(type: String!, name: String!): Boolean!
|
importLdapSubject(type: String!, name: String!): Boolean!
|
||||||
|
|
||||||
|
# Group management (admin only).
|
||||||
|
createGroup(name: String!): Boolean!
|
||||||
|
deleteGroup(name: String!): Boolean!
|
||||||
|
addUserToGroup(username: String!, group: String!): Boolean!
|
||||||
|
removeUserFromGroup(username: String!, group: String!): Boolean!
|
||||||
|
|
||||||
|
# Who may sign in (admin only).
|
||||||
|
setUserLogin(username: String!, allow: Boolean!): Boolean!
|
||||||
|
setGroupLogin(name: String!, allow: Boolean!): Boolean!
|
||||||
|
|
||||||
|
# Change a user's application role: "admin" | "user" (admin only).
|
||||||
|
setUserRole(username: String!, role: String!): Boolean!
|
||||||
|
|
||||||
# ACL Mutations
|
# ACL Mutations
|
||||||
setAcl(input: ACLInput!): Boolean!
|
setAcl(input: ACLInput!): Boolean!
|
||||||
removeAcl(id: Int!): Boolean!
|
removeAcl(id: Int!): Boolean!
|
||||||
@@ -127,6 +155,7 @@ type ACLEntry {
|
|||||||
path: String!
|
path: String!
|
||||||
subjectType: String!
|
subjectType: String!
|
||||||
subjectId: Int!
|
subjectId: Int!
|
||||||
|
effect: String! # "allow" | "deny" — deny always wins over allow
|
||||||
canSearch: Boolean!
|
canSearch: Boolean!
|
||||||
canView: Boolean!
|
canView: Boolean!
|
||||||
canRead: Boolean!
|
canRead: Boolean!
|
||||||
@@ -136,6 +165,35 @@ type ACLEntry {
|
|||||||
canMove: Boolean!
|
canMove: Boolean!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LoginOptions {
|
||||||
|
localEnabled: Boolean!
|
||||||
|
oidcEnabled: Boolean!
|
||||||
|
oidcButtonLabel: String!
|
||||||
|
publicEnabled: Boolean!
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserInfo {
|
||||||
|
username: String!
|
||||||
|
role: String!
|
||||||
|
isLdap: Boolean!
|
||||||
|
allowLogin: Boolean!
|
||||||
|
createdAt: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
type OIDCConfigView {
|
||||||
|
enabled: Boolean!
|
||||||
|
ready: Boolean!
|
||||||
|
issuer: String!
|
||||||
|
clientId: String!
|
||||||
|
clientSecretSet: Boolean!
|
||||||
|
redirectUrl: String!
|
||||||
|
publicUrl: String!
|
||||||
|
groupsClaim: String!
|
||||||
|
usernameClaim: String!
|
||||||
|
adminGroup: String!
|
||||||
|
readerGroup: String!
|
||||||
|
}
|
||||||
|
|
||||||
type ServerDirectory {
|
type ServerDirectory {
|
||||||
name: String!
|
name: String!
|
||||||
path: String!
|
path: String!
|
||||||
@@ -201,6 +259,8 @@ type ACLSubject {
|
|||||||
id: Int!
|
id: Int!
|
||||||
name: String!
|
name: String!
|
||||||
isLdap: Boolean!
|
isLdap: Boolean!
|
||||||
|
role: String # only present for users
|
||||||
|
allowLogin: Boolean!
|
||||||
}
|
}
|
||||||
|
|
||||||
type ACLSubjects {
|
type ACLSubjects {
|
||||||
@@ -212,6 +272,7 @@ input ACLInput {
|
|||||||
path: String!
|
path: String!
|
||||||
subjectType: String!
|
subjectType: String!
|
||||||
subjectId: Int!
|
subjectId: Int!
|
||||||
|
effect: String # "allow" (default) | "deny"
|
||||||
canSearch: Boolean!
|
canSearch: Boolean!
|
||||||
canView: Boolean!
|
canView: Boolean!
|
||||||
canRead: Boolean!
|
canRead: Boolean!
|
||||||
@@ -221,6 +282,19 @@ input ACLInput {
|
|||||||
canMove: Boolean!
|
canMove: Boolean!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
input OIDCInput {
|
||||||
|
enabled: Boolean!
|
||||||
|
issuer: String!
|
||||||
|
clientId: String!
|
||||||
|
clientSecret: String # empty = keep existing
|
||||||
|
redirectUrl: String
|
||||||
|
publicUrl: String
|
||||||
|
groupsClaim: String
|
||||||
|
usernameClaim: String
|
||||||
|
adminGroup: String
|
||||||
|
readerGroup: String
|
||||||
|
}
|
||||||
|
|
||||||
input SaveDocumentInput {
|
input SaveDocumentInput {
|
||||||
slug: String!
|
slug: String!
|
||||||
content: String!
|
content: String!
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ package graph
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
@@ -30,10 +32,11 @@ type Server struct {
|
|||||||
database *db.DB
|
database *db.DB
|
||||||
authMgr *auth.Manager
|
authMgr *auth.Manager
|
||||||
gitRepo *git.Repo
|
gitRepo *git.Repo
|
||||||
|
oidc *auth.OIDCProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(cfg *config.Config, configPath string) http.Handler {
|
func NewServer(cfg *config.Config, configPath string) http.Handler {
|
||||||
s := &Server{cfg: cfg, configPath: configPath}
|
s := &Server{cfg: cfg, configPath: configPath, oidc: auth.NewOIDCProvider()}
|
||||||
|
|
||||||
if cfg != nil {
|
if cfg != nil {
|
||||||
s.initRuntime(cfg)
|
s.initRuntime(cfg)
|
||||||
@@ -44,6 +47,8 @@ func NewServer(cfg *config.Config, configPath string) http.Handler {
|
|||||||
mux.HandleFunc("/health", s.handleHealth)
|
mux.HandleFunc("/health", s.handleHealth)
|
||||||
mux.HandleFunc("/api/upload", s.handleUpload)
|
mux.HandleFunc("/api/upload", s.handleUpload)
|
||||||
mux.HandleFunc("/media/", s.handleMedia)
|
mux.HandleFunc("/media/", s.handleMedia)
|
||||||
|
mux.HandleFunc("/auth/oidc/login", s.handleOIDCLogin)
|
||||||
|
mux.HandleFunc("/auth/oidc/callback", s.handleOIDCCallback)
|
||||||
|
|
||||||
uiDir := os.Getenv("UI_DIR")
|
uiDir := os.Getenv("UI_DIR")
|
||||||
if uiDir == "" {
|
if uiDir == "" {
|
||||||
@@ -75,10 +80,13 @@ func (s *Server) initRuntime(cfg *config.Config) {
|
|||||||
log.Printf("[db] failed to open at %s: %v", cfg.DBPath, err)
|
log.Printf("[db] failed to open at %s: %v", cfg.DBPath, err)
|
||||||
} else {
|
} else {
|
||||||
d = database
|
d = database
|
||||||
// Ensure guest user exists (handles upgrades from older versions).
|
// Ensure guest user + built-in role groups exist (handles upgrades).
|
||||||
if err := d.EnsureGuestUser(); err != nil {
|
if err := d.EnsureGuestUser(); err != nil {
|
||||||
log.Printf("[db] warning: could not ensure guest user: %v", err)
|
log.Printf("[db] warning: could not ensure guest user: %v", err)
|
||||||
}
|
}
|
||||||
|
if err := d.EnsureBuiltinGroups(); err != nil {
|
||||||
|
log.Printf("[db] warning: could not ensure built-in groups: %v", err)
|
||||||
|
}
|
||||||
log.Printf("[db] opened at %s", cfg.DBPath)
|
log.Printf("[db] opened at %s", cfg.DBPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +106,31 @@ func (s *Server) initRuntime(cfg *config.Config) {
|
|||||||
s.database = d
|
s.database = d
|
||||||
s.authMgr = am
|
s.authMgr = am
|
||||||
s.gitRepo = gr
|
s.gitRepo = gr
|
||||||
|
if s.oidc == nil {
|
||||||
|
s.oidc = auth.NewOIDCProvider()
|
||||||
|
}
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
s.configureOIDC(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// configureOIDC (re)initialises the OIDC provider from config. Discovery
|
||||||
|
// requires reaching the IdP, so it runs in the background to avoid blocking
|
||||||
|
// startup if Authentik is momentarily unavailable.
|
||||||
|
func (s *Server) configureOIDC(cfg *config.Config) {
|
||||||
|
if cfg == nil || s.oidc == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oc := cfg.OIDC
|
||||||
|
redirect := cfg.ResolvedRedirectURL()
|
||||||
|
provider := s.oidc
|
||||||
|
go func() {
|
||||||
|
if err := provider.Configure(context.Background(), oc, redirect); err != nil {
|
||||||
|
log.Printf("[oidc] provider not ready: %v", err)
|
||||||
|
} else if oc.Enabled {
|
||||||
|
log.Printf("[oidc] provider configured (issuer=%s, redirect=%s)", oc.Issuer, redirect)
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── GraphQL handler ───────────────────────────────────────────────────────────
|
// ── GraphQL handler ───────────────────────────────────────────────────────────
|
||||||
@@ -157,6 +189,11 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, `{"data":{"systemStatus":"OK"}}`)
|
writeJSON(w, `{"data":{"systemStatus":"OK"}}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Public: what sign-in methods the login page should offer. Must be
|
||||||
|
// matched before the "login" case since it also contains that substring.
|
||||||
|
case strings.Contains(q, "loginOptions"):
|
||||||
|
s.handleLoginOptions(w)
|
||||||
|
|
||||||
case strings.Contains(q, "testLdapConnection"):
|
case strings.Contains(q, "testLdapConnection"):
|
||||||
s.handleTestLdapConnection(w, req)
|
s.handleTestLdapConnection(w, req)
|
||||||
|
|
||||||
@@ -188,6 +225,37 @@ func (s *Server) dispatchAuthenticated(
|
|||||||
q := req.Query
|
q := req.Query
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
|
// ── Admin: OIDC / groups / membership / login gate (matched first) ─────────
|
||||||
|
case strings.Contains(q, "updateOidcConfig"):
|
||||||
|
s.handleUpdateOidcConfig(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "oidcConfig"):
|
||||||
|
s.handleOidcConfig(w, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "createGroup"):
|
||||||
|
s.handleCreateGroup(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "deleteGroup"):
|
||||||
|
s.handleDeleteGroup(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "addUserToGroup"):
|
||||||
|
s.handleAddUserToGroup(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "removeUserFromGroup"):
|
||||||
|
s.handleRemoveUserFromGroup(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "setUserLogin"):
|
||||||
|
s.handleSetUserLogin(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "setGroupLogin"):
|
||||||
|
s.handleSetGroupLogin(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "setUserRole"):
|
||||||
|
s.handleSetUserRole(w, req, sess)
|
||||||
|
|
||||||
|
case strings.Contains(q, "userGroups"):
|
||||||
|
s.handleUserGroups(w, req, sess)
|
||||||
|
|
||||||
case strings.Contains(q, "saveDocument"):
|
case strings.Contains(q, "saveDocument"):
|
||||||
s.handleSaveDocument(w, req, sess)
|
s.handleSaveDocument(w, req, sess)
|
||||||
|
|
||||||
@@ -398,6 +466,38 @@ func (s *Server) sessionFromRequest(r *http.Request) *auth.Session {
|
|||||||
return sess
|
return sess
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// allPerms is the permission set granted to administrators (who bypass ACLs).
|
||||||
|
var allPerms = db.Perms{Search: true, View: true, Read: true, Edit: true, Create: true, Delete: true, Move: true}
|
||||||
|
|
||||||
|
// access resolves the effective permissions the session has on a path.
|
||||||
|
// Administrators always get the full set; everyone else (users, readers,
|
||||||
|
// guest/public) is resolved through the allow/deny ACL model, which defaults
|
||||||
|
// to deny. A nil session gets nothing.
|
||||||
|
func (s *Server) access(sess *auth.Session, path string) db.Perms {
|
||||||
|
if sess == nil {
|
||||||
|
return db.Perms{}
|
||||||
|
}
|
||||||
|
if sess.Role == "admin" {
|
||||||
|
return allPerms
|
||||||
|
}
|
||||||
|
s.mu.RLock()
|
||||||
|
database := s.database
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if database == nil {
|
||||||
|
return db.Perms{}
|
||||||
|
}
|
||||||
|
return database.EffectiveAccess(sess.Username, sess.Groups, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// parentDir returns the folder containing a slug, or "" at the root.
|
||||||
|
func parentDir(slug string) string {
|
||||||
|
slug = strings.Trim(slug, "/")
|
||||||
|
if idx := strings.LastIndex(slug, "/"); idx >= 0 {
|
||||||
|
return slug[:idx]
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// ── Document handlers ─────────────────────────────────────────────────────────
|
// ── Document handlers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *auth.Session, store *storage.Store) {
|
func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *auth.Session, store *storage.Store) {
|
||||||
@@ -423,16 +523,11 @@ func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *au
|
|||||||
|
|
||||||
log.Printf("[document] user %q is opening document %q", sess.Username, slug)
|
log.Printf("[document] user %q is opening document %q", sess.Username, slug)
|
||||||
|
|
||||||
// Guest users may only read documents they have been given access to.
|
// Everyone except admin is gated by the allow/deny ACL model.
|
||||||
s.mu.RLock()
|
if !s.access(sess, slug).Read {
|
||||||
database := s.database
|
|
||||||
s.mu.RUnlock()
|
|
||||||
if sess.Role == "guest" && database != nil {
|
|
||||||
if !database.CanUserReadPath(sess.Username, slug) && !database.CanUserViewPath(sess.Username, slug) {
|
|
||||||
writeGQLError(w, "UNAUTHORIZED")
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
content, err := store.Read(slug)
|
content, err := store.Read(slug)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -467,15 +562,12 @@ func (s *Server) handleDocuments(w http.ResponseWriter, req gqlRequest, sess *au
|
|||||||
|
|
||||||
log.Printf("[document] user %q listed documents (found %d documents)", sess.Username, len(slugs))
|
log.Printf("[document] user %q listed documents (found %d documents)", sess.Username, len(slugs))
|
||||||
|
|
||||||
s.mu.RLock()
|
|
||||||
database := s.database
|
|
||||||
s.mu.RUnlock()
|
|
||||||
|
|
||||||
docs := make([]map[string]string, 0, len(slugs))
|
docs := make([]map[string]string, 0, len(slugs))
|
||||||
for _, slug := range slugs {
|
for _, slug := range slugs {
|
||||||
// Guest users may only see documents they have explicit read or view access to.
|
// Non-admins only see documents they can view, read or search for.
|
||||||
if sess.Role == "guest" && database != nil {
|
if sess.Role != "admin" {
|
||||||
if !database.CanUserReadPath(sess.Username, slug) && !database.CanUserViewPath(sess.Username, slug) {
|
p := s.access(sess, slug)
|
||||||
|
if !(p.Read || p.View || p.Search) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -525,6 +617,13 @@ func (s *Server) handleSaveDocument(w http.ResponseWriter, req gqlRequest, sess
|
|||||||
commitMsg = "Update " + slug
|
commitMsg = "Update " + slug
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Saving requires edit (existing docs) or create (new docs) permission.
|
||||||
|
if p := s.access(sess, slug); !(p.Edit || p.Create) {
|
||||||
|
log.Printf("[acl] save denied for %q on %q", sess.Username, slug)
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
log.Printf("[document] user %q is attempting to save document %q (commit msg: %q)", sess.Username, slug, commitMsg)
|
log.Printf("[document] user %q is attempting to save document %q (commit msg: %q)", sess.Username, slug, commitMsg)
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
@@ -584,6 +683,11 @@ func (s *Server) handleDeleteDocument(w http.ResponseWriter, req gqlRequest, ses
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Delete {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -704,11 +808,13 @@ func (s *Server) handleUsers(w http.ResponseWriter, sess *auth.Session) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
list := make([]map[string]string, 0, len(users))
|
list := make([]map[string]interface{}, 0, len(users))
|
||||||
for _, u := range users {
|
for _, u := range users {
|
||||||
list = append(list, map[string]string{
|
list = append(list, map[string]interface{}{
|
||||||
"username": u.Username,
|
"username": u.Username,
|
||||||
"role": u.Role,
|
"role": u.Role,
|
||||||
|
"isLdap": u.IsLDAP,
|
||||||
|
"allowLogin": u.AllowLogin,
|
||||||
"createdAt": u.CreatedAt.Format(time.RFC3339),
|
"createdAt": u.CreatedAt.Format(time.RFC3339),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -748,6 +854,7 @@ func (s *Server) handleSubjectAcl(w http.ResponseWriter, req gqlRequest, sess *a
|
|||||||
"path": a.Path,
|
"path": a.Path,
|
||||||
"subjectType": a.SubjectType,
|
"subjectType": a.SubjectType,
|
||||||
"subjectId": a.SubjectID,
|
"subjectId": a.SubjectID,
|
||||||
|
"effect": a.Effect,
|
||||||
"canSearch": a.CanSearch,
|
"canSearch": a.CanSearch,
|
||||||
"canView": a.CanView,
|
"canView": a.CanView,
|
||||||
"canRead": a.CanRead,
|
"canRead": a.CanRead,
|
||||||
@@ -810,6 +917,8 @@ func (s *Server) handleAclSubjects(w http.ResponseWriter, sess *auth.Session) {
|
|||||||
"id": u.ID,
|
"id": u.ID,
|
||||||
"name": u.Username,
|
"name": u.Username,
|
||||||
"isLdap": u.IsLDAP,
|
"isLdap": u.IsLDAP,
|
||||||
|
"role": u.Role,
|
||||||
|
"allowLogin": u.AllowLogin,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
groupList := make([]map[string]interface{}, 0, len(groups))
|
groupList := make([]map[string]interface{}, 0, len(groups))
|
||||||
@@ -818,6 +927,7 @@ func (s *Server) handleAclSubjects(w http.ResponseWriter, sess *auth.Session) {
|
|||||||
"id": g.ID,
|
"id": g.ID,
|
||||||
"name": g.Name,
|
"name": g.Name,
|
||||||
"isLdap": g.IsLDAP,
|
"isLdap": g.IsLDAP,
|
||||||
|
"allowLogin": g.AllowLogin,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1238,6 +1348,10 @@ func (s *Server) handleSetup(w http.ResponseWriter, req gqlRequest) {
|
|||||||
if err := database.EnsureGuestUser(); err != nil {
|
if err := database.EnsureGuestUser(); err != nil {
|
||||||
log.Printf("[setup] warning: could not create guest user: %v", err)
|
log.Printf("[setup] warning: could not create guest user: %v", err)
|
||||||
}
|
}
|
||||||
|
// Ensure the Archivum-admin / Archivum-reader role groups exist.
|
||||||
|
if err := database.EnsureBuiltinGroups(); err != nil {
|
||||||
|
log.Printf("[setup] warning: could not create built-in groups: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
log.Printf("[setup] admin user %q created", adminUser)
|
log.Printf("[setup] admin user %q created", adminUser)
|
||||||
|
|
||||||
@@ -1269,8 +1383,13 @@ func (s *Server) handleSetup(w http.ResponseWriter, req gqlRequest) {
|
|||||||
s.database = database
|
s.database = database
|
||||||
s.authMgr = auth.NewManager(cfg)
|
s.authMgr = auth.NewManager(cfg)
|
||||||
s.gitRepo = repo
|
s.gitRepo = repo
|
||||||
|
if s.oidc == nil {
|
||||||
|
s.oidc = auth.NewOIDCProvider()
|
||||||
|
}
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
s.configureOIDC(cfg)
|
||||||
|
|
||||||
log.Printf("[setup] complete")
|
log.Printf("[setup] complete")
|
||||||
writeJSON(w, `{"data":{"setup":true}}`)
|
writeJSON(w, `{"data":{"setup":true}}`)
|
||||||
}
|
}
|
||||||
@@ -1501,7 +1620,7 @@ func (s *Server) handleImportLdapSubject(w http.ResponseWriter, req gqlRequest,
|
|||||||
|
|
||||||
var err error
|
var err error
|
||||||
if typ == "user" {
|
if typ == "user" {
|
||||||
err = database.CreateOrUpdateLDAPUser(name)
|
err = database.CreateOrUpdateExternalUser(name, "user", true)
|
||||||
} else if typ == "group" {
|
} else if typ == "group" {
|
||||||
err = database.CreateOrUpdateGroup(name, true)
|
err = database.CreateOrUpdateGroup(name, true)
|
||||||
} else {
|
} else {
|
||||||
@@ -1536,6 +1655,10 @@ func (s *Server) handleSetAcl(w http.ResponseWriter, req gqlRequest, sess *auth.
|
|||||||
var entry db.ACLEntry
|
var entry db.ACLEntry
|
||||||
entry.Path = strVal(input, "path")
|
entry.Path = strVal(input, "path")
|
||||||
entry.SubjectType = strVal(input, "subjectType")
|
entry.SubjectType = strVal(input, "subjectType")
|
||||||
|
entry.Effect = strVal(input, "effect")
|
||||||
|
if entry.Effect != "deny" {
|
||||||
|
entry.Effect = "allow"
|
||||||
|
}
|
||||||
if idF, ok := input["subjectId"].(float64); ok {
|
if idF, ok := input["subjectId"].(float64); ok {
|
||||||
entry.SubjectID = int64(idF)
|
entry.SubjectID = int64(idF)
|
||||||
} else {
|
} else {
|
||||||
@@ -1611,6 +1734,7 @@ func (s *Server) handleAcl(w http.ResponseWriter, req gqlRequest, sess *auth.Ses
|
|||||||
"path": a.Path,
|
"path": a.Path,
|
||||||
"subjectType": a.SubjectType,
|
"subjectType": a.SubjectType,
|
||||||
"subjectId": a.SubjectID,
|
"subjectId": a.SubjectID,
|
||||||
|
"effect": a.Effect,
|
||||||
"canSearch": a.CanSearch,
|
"canSearch": a.CanSearch,
|
||||||
"canView": a.CanView,
|
"canView": a.CanView,
|
||||||
"canRead": a.CanRead,
|
"canRead": a.CanRead,
|
||||||
@@ -1662,6 +1786,11 @@ func (s *Server) handleHistory(w http.ResponseWriter, req gqlRequest, sess *auth
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Read {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
repo := s.gitRepo
|
repo := s.gitRepo
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -1701,6 +1830,11 @@ func (s *Server) handleDiff(w http.ResponseWriter, req gqlRequest, sess *auth.Se
|
|||||||
fromHash, _ := req.Variables["fromHash"].(string)
|
fromHash, _ := req.Variables["fromHash"].(string)
|
||||||
toHash, _ := req.Variables["toHash"].(string)
|
toHash, _ := req.Variables["toHash"].(string)
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Read {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
repo := s.gitRepo
|
repo := s.gitRepo
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -1727,6 +1861,11 @@ func (s *Server) handleDocumentAtCommit(w http.ResponseWriter, req gqlRequest, s
|
|||||||
slug, _ := req.Variables["slug"].(string)
|
slug, _ := req.Variables["slug"].(string)
|
||||||
hash, _ := req.Variables["hash"].(string)
|
hash, _ := req.Variables["hash"].(string)
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Read {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
repo := s.gitRepo
|
repo := s.gitRepo
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -1757,6 +1896,11 @@ func (s *Server) handleCreateFolder(w http.ResponseWriter, req gqlRequest, sess
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if p := s.access(sess, path); !(p.Create || p.Edit) {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -1794,6 +1938,16 @@ func (s *Server) handleMoveDocument(w http.ResponseWriter, req gqlRequest, sess
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Moving requires move permission on the source and write on the destination.
|
||||||
|
if !s.access(sess, oldSlug).Move {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if dst := s.access(sess, newSlug); !(dst.Edit || dst.Create) {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
repo := s.gitRepo
|
repo := s.gitRepo
|
||||||
@@ -1864,6 +2018,11 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if p := s.access(sess, slug); !(p.Edit || p.Create) {
|
||||||
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
file, header, err := r.FormFile("image")
|
file, header, err := r.FormFile("image")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Missing image", http.StatusBadRequest)
|
http.Error(w, "Missing image", http.StatusBadRequest)
|
||||||
@@ -1922,7 +2081,6 @@ func (s *Server) handleFolders(w http.ResponseWriter, sess *auth.Session) {
|
|||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
database := s.database
|
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
|
|
||||||
if store == nil {
|
if store == nil {
|
||||||
@@ -1937,11 +2095,12 @@ func (s *Server) handleFolders(w http.ResponseWriter, sess *auth.Session) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guest users may only see folders they have been granted view access to.
|
// Non-admins only see folders they may view/read/search into.
|
||||||
if sess.Role == "guest" && database != nil {
|
if sess.Role != "admin" {
|
||||||
visible := folders[:0]
|
visible := folders[:0]
|
||||||
for _, f := range folders {
|
for _, f := range folders {
|
||||||
if database.CanUserViewPath(sess.Username, f) {
|
p := s.access(sess, f)
|
||||||
|
if p.View || p.Read || p.Search {
|
||||||
visible = append(visible, f)
|
visible = append(visible, f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1968,6 +2127,11 @@ func (s *Server) handleImages(w http.ResponseWriter, req gqlRequest, sess *auth.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Read {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -2000,6 +2164,11 @@ func (s *Server) handleDeleteImage(w http.ResponseWriter, req gqlRequest, sess *
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !s.access(sess, slug).Edit {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
store := s.store
|
store := s.store
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -2017,3 +2186,359 @@ func (s *Server) handleDeleteImage(w http.ResponseWriter, req gqlRequest, sess *
|
|||||||
log.Printf("[storage] deleted image %q from %q by %s", filename, slug, sess.Username)
|
log.Printf("[storage] deleted image %q from %q by %s", filename, slug, sess.Username)
|
||||||
writeJSON(w, `{"data":{"deleteImage":true}}`)
|
writeJSON(w, `{"data":{"deleteImage":true}}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── OIDC HTTP endpoints ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (s *Server) handleOIDCLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.mu.RLock()
|
||||||
|
provider := s.oidc
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if provider == nil || !provider.Enabled() {
|
||||||
|
http.Error(w, "OIDC sign-in is not configured", http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
authURL, err := provider.AuthURL()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Redirect(w, r, authURL, http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.mu.RLock()
|
||||||
|
provider := s.oidc
|
||||||
|
database := s.database
|
||||||
|
mgr := s.authMgr
|
||||||
|
s.mu.RUnlock()
|
||||||
|
|
||||||
|
if provider == nil || database == nil || mgr == nil {
|
||||||
|
s.redirectLoginError(w, r, "server not ready")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
q := r.URL.Query()
|
||||||
|
if e := q.Get("error"); e != "" {
|
||||||
|
desc := q.Get("error_description")
|
||||||
|
if desc == "" {
|
||||||
|
desc = e
|
||||||
|
}
|
||||||
|
s.redirectLoginError(w, r, desc)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
oidcUser, err := provider.Exchange(ctx, q.Get("state"), q.Get("code"))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[oidc] token exchange failed: %v", err)
|
||||||
|
s.redirectLoginError(w, r, "sign-in failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, role, err := mgr.LoginOIDC(database, oidcUser)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[oidc] login denied for %q: %v", oidcUser.Username, err)
|
||||||
|
s.redirectLoginError(w, r, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[oidc] login: %s (%s) groups=%v", oidcUser.Username, role, oidcUser.Groups)
|
||||||
|
|
||||||
|
// The SPA reads these from the URL fragment; the fragment is never sent to
|
||||||
|
// a server, so the token stays on the client (mirrors the localStorage model).
|
||||||
|
frag := fmt.Sprintf("#token=%s&username=%s&role=%s",
|
||||||
|
url.QueryEscape(token), url.QueryEscape(oidcUser.Username), url.QueryEscape(role))
|
||||||
|
http.Redirect(w, r, "/oidc/callback"+frag, http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) redirectLoginError(w http.ResponseWriter, r *http.Request, msg string) {
|
||||||
|
http.Redirect(w, r, "/oidc/callback#error="+url.QueryEscape(msg), http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Login options (public) ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (s *Server) handleLoginOptions(w http.ResponseWriter) {
|
||||||
|
s.mu.RLock()
|
||||||
|
provider := s.oidc
|
||||||
|
database := s.database
|
||||||
|
s.mu.RUnlock()
|
||||||
|
|
||||||
|
oidcEnabled := provider != nil && provider.Enabled()
|
||||||
|
label := "Sign in with Authentik"
|
||||||
|
|
||||||
|
publicEnabled := false
|
||||||
|
if database != nil {
|
||||||
|
if _, err := database.GetUser("guest"); err == nil {
|
||||||
|
publicEnabled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSONObj(w, map[string]interface{}{
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"loginOptions": map[string]interface{}{
|
||||||
|
"localEnabled": true,
|
||||||
|
"oidcEnabled": oidcEnabled,
|
||||||
|
"oidcButtonLabel": label,
|
||||||
|
"publicEnabled": publicEnabled,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Admin helpers ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// requireAdmin writes an UNAUTHORIZED error and returns false if the session
|
||||||
|
// is missing or not an administrator.
|
||||||
|
func (s *Server) requireAdmin(w http.ResponseWriter, sess *auth.Session) bool {
|
||||||
|
if sess == nil || sess.Role != "admin" {
|
||||||
|
writeGQLError(w, "UNAUTHORIZED")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) db() *db.DB {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
return s.database
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── OIDC config (admin) ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (s *Server) handleOidcConfig(w http.ResponseWriter, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.RLock()
|
||||||
|
cfg := s.cfg
|
||||||
|
provider := s.oidc
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if cfg == nil {
|
||||||
|
writeGQLError(w, "server not initialised")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oc := cfg.OIDC
|
||||||
|
oc.Normalize()
|
||||||
|
writeJSONObj(w, map[string]interface{}{
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"oidcConfig": map[string]interface{}{
|
||||||
|
"enabled": oc.Enabled,
|
||||||
|
"ready": provider != nil && provider.Enabled(),
|
||||||
|
"issuer": oc.Issuer,
|
||||||
|
"clientId": oc.ClientID,
|
||||||
|
"clientSecretSet": oc.ClientSecret != "",
|
||||||
|
"redirectUrl": cfg.ResolvedRedirectURL(),
|
||||||
|
"publicUrl": cfg.PublicURL,
|
||||||
|
"groupsClaim": oc.GroupsClaim,
|
||||||
|
"usernameClaim": oc.UsernameClaim,
|
||||||
|
"adminGroup": oc.AdminGroup,
|
||||||
|
"readerGroup": oc.ReaderGroup,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleUpdateOidcConfig(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
input, ok := req.Variables["input"].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
input, _ = req.Variables["i"].(map[string]interface{})
|
||||||
|
}
|
||||||
|
if input == nil {
|
||||||
|
writeGQLError(w, "missing input")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.RLock()
|
||||||
|
cfg := s.cfg
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if cfg == nil {
|
||||||
|
writeGQLError(w, "server not initialised")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
newCfg := *cfg
|
||||||
|
oc := config.OIDCConfig{
|
||||||
|
Enabled: boolVal(input, "enabled"),
|
||||||
|
Issuer: strings.TrimSpace(strVal(input, "issuer")),
|
||||||
|
ClientID: strings.TrimSpace(strVal(input, "clientId")),
|
||||||
|
ClientSecret: strVal(input, "clientSecret"),
|
||||||
|
RedirectURL: strings.TrimSpace(strVal(input, "redirectUrl")),
|
||||||
|
GroupsClaim: strVal(input, "groupsClaim"),
|
||||||
|
UsernameClaim: strVal(input, "usernameClaim"),
|
||||||
|
AdminGroup: strVal(input, "adminGroup"),
|
||||||
|
ReaderGroup: strVal(input, "readerGroup"),
|
||||||
|
}
|
||||||
|
// Empty client secret means "keep existing".
|
||||||
|
if oc.ClientSecret == "" {
|
||||||
|
oc.ClientSecret = cfg.OIDC.ClientSecret
|
||||||
|
}
|
||||||
|
oc.Normalize()
|
||||||
|
newCfg.OIDC = oc
|
||||||
|
if pu := strings.TrimSpace(strVal(input, "publicUrl")); pu != "" {
|
||||||
|
newCfg.PublicURL = pu
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := config.Save(s.configPath, &newCfg); err != nil {
|
||||||
|
writeGQLError(w, fmt.Sprintf("failed to save config: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cfg = &newCfg
|
||||||
|
mgr := s.authMgr
|
||||||
|
s.mu.Unlock()
|
||||||
|
if mgr != nil {
|
||||||
|
mgr.UpdateConfig(&newCfg)
|
||||||
|
}
|
||||||
|
s.configureOIDC(&newCfg)
|
||||||
|
|
||||||
|
log.Printf("[admin] OIDC config updated by %s (enabled=%v)", sess.Username, oc.Enabled)
|
||||||
|
writeJSON(w, `{"data":{"updateOidcConfig":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Group management (admin) ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (s *Server) handleCreateGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimSpace(strVal(req.Variables, "name"))
|
||||||
|
if name == "" {
|
||||||
|
writeGQLError(w, "group name is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.db().CreateOrUpdateGroup(name, false); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[admin] group created: %s by %s", name, sess.Username)
|
||||||
|
writeJSON(w, `{"data":{"createGroup":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleDeleteGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strVal(req.Variables, "name")
|
||||||
|
if name == db.GroupAdmin || name == db.GroupReader {
|
||||||
|
writeGQLError(w, "built-in role groups cannot be deleted")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.db().DeleteGroup(name); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[admin] group deleted: %s by %s", name, sess.Username)
|
||||||
|
writeJSON(w, `{"data":{"deleteGroup":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAddUserToGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strVal(req.Variables, "username")
|
||||||
|
group := strVal(req.Variables, "group")
|
||||||
|
if err := s.db().AddUserToGroup(username, group); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, `{"data":{"addUserToGroup":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleRemoveUserFromGroup(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strVal(req.Variables, "username")
|
||||||
|
group := strVal(req.Variables, "group")
|
||||||
|
if err := s.db().RemoveUserFromGroup(username, group); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, `{"data":{"removeUserFromGroup":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleUserGroups(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strVal(req.Variables, "username")
|
||||||
|
names, err := s.db().GetUserGroupNames(username)
|
||||||
|
if err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if names == nil {
|
||||||
|
names = []string{}
|
||||||
|
}
|
||||||
|
writeJSONObj(w, map[string]interface{}{
|
||||||
|
"data": map[string]interface{}{"userGroups": names},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSetUserLogin(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strVal(req.Variables, "username")
|
||||||
|
allow := boolVal(req.Variables, "allow")
|
||||||
|
if err := s.db().SetUserLogin(username, allow); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[admin] user %q login set to %v by %s", username, allow, sess.Username)
|
||||||
|
writeJSON(w, `{"data":{"setUserLogin":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSetGroupLogin(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strVal(req.Variables, "name")
|
||||||
|
allow := boolVal(req.Variables, "allow")
|
||||||
|
if err := s.db().SetGroupLogin(name, allow); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[admin] group %q login set to %v by %s", name, allow, sess.Username)
|
||||||
|
writeJSON(w, `{"data":{"setGroupLogin":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSetUserRole(w http.ResponseWriter, req gqlRequest, sess *auth.Session) {
|
||||||
|
if !s.requireAdmin(w, sess) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := strVal(req.Variables, "username")
|
||||||
|
role := strVal(req.Variables, "role")
|
||||||
|
if role != "admin" && role != "user" {
|
||||||
|
writeGQLError(w, "role must be 'admin' or 'user'")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if username == "guest" {
|
||||||
|
writeGQLError(w, "cannot change the public user's role")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if username == sess.Username && role != "admin" {
|
||||||
|
writeGQLError(w, "cannot remove your own admin role")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.db().SetUserRole(username, role); err != nil {
|
||||||
|
writeGQLError(w, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[admin] user %q role set to %s by %s", username, role, sess.Username)
|
||||||
|
writeJSON(w, `{"data":{"setUserRole":true}}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolVal(m map[string]interface{}, key string) bool {
|
||||||
|
if m == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b, _ := m[key].(bool)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ COPY frontend/ ./
|
|||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# ── Stage 2: Build backend ────────────────────────────────────────────────────
|
# ── Stage 2: Build backend ────────────────────────────────────────────────────
|
||||||
FROM golang:1.22-alpine AS backend-builder
|
# Go 1.25 required by the OIDC dependency chain (go-oidc/v3, go-jose/v4).
|
||||||
|
FROM golang:1.25-alpine AS backend-builder
|
||||||
|
|
||||||
WORKDIR /app/backend
|
WORKDIR /app/backend
|
||||||
# Copy go.mod first for layer caching. go.sum is written by go mod download
|
# Copy go.mod first for layer caching. go.sum is written by go mod download
|
||||||
|
|||||||
125
docs/AUTHENTIK_SETUP.md
Normal file
125
docs/AUTHENTIK_SETUP.md
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
# Authentik (OIDC) + RBAC setup för Archivum
|
||||||
|
|
||||||
|
Archivum autentiserar via **OIDC mot Authentik** (samma mönster som Gitea och
|
||||||
|
Gym-API i den här miljön). Authentik autentiserar i sin tur mot OpenLDAP, så det
|
||||||
|
är dina LDAP-användare som loggar in. Grupp-medlemskap kommer med i `groups`-claimet
|
||||||
|
och styr roll + åtkomst i Archivum.
|
||||||
|
|
||||||
|
Två saker måste finnas: **(1)** grupperna i katalogen och **(2)** en
|
||||||
|
OAuth2/OIDC-provider + application i Authentik. Steg nedan.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Skapa grupperna
|
||||||
|
|
||||||
|
Skapa två grupper (i Authentik → Directory → Groups, eller i LDAP under
|
||||||
|
`ou=groups,dc=brasse-pc,dc=eu` som `groupOfNames`):
|
||||||
|
|
||||||
|
| Grupp | Effekt i Archivum |
|
||||||
|
|-------|-------------------|
|
||||||
|
| `Archivum-admin` | Full admin — administrerar sidan, tilldelar åtkomst, kringgår ACL |
|
||||||
|
| `Archivum-reader` | Vanlig inloggad användare — ser bara det som ACL uttryckligen tillåter |
|
||||||
|
|
||||||
|
Lägg dig själv (`bb01`) i `Archivum-admin`. Namnen kan ändras i Archivums
|
||||||
|
admin-panel (fälten *Admin group* / *Reader group*) om du vill.
|
||||||
|
|
||||||
|
> Grupperna syns i Archivums admin-panel så fort en medlem loggat in en gång —
|
||||||
|
> `Archivum-admin`/`Archivum-reader` seedas dessutom automatiskt vid start.
|
||||||
|
|
||||||
|
## 2. Skapa en OAuth2/OIDC-provider i Authentik
|
||||||
|
|
||||||
|
Authentik → Applications → Providers → **Create → OAuth2/OpenID Provider**:
|
||||||
|
|
||||||
|
| Fält | Värde |
|
||||||
|
|------|-------|
|
||||||
|
| Name | `archivum` |
|
||||||
|
| Authorization flow | ditt vanliga `default-authorization-flow` (explicit/implicit consent) |
|
||||||
|
| Client type | **Confidential** |
|
||||||
|
| Client ID | *(kopiera — behövs i Archivum)* |
|
||||||
|
| Client Secret | *(kopiera — behövs i Archivum)* |
|
||||||
|
| Redirect URIs | `https://archivum.brasse-pc.eu/auth/oidc/callback` |
|
||||||
|
| Signing Key | din vanliga certifikatnyckel |
|
||||||
|
| Scopes | `openid`, `profile`, `email` **+ en groups-scope** (se nedan) |
|
||||||
|
|
||||||
|
### groups-scope (viktigt)
|
||||||
|
|
||||||
|
Archivum läser gruppnamn ur `groups`-claimet. Återanvänd samma
|
||||||
|
scope-mapping-mönster som Gitea/Jellyfin redan använder, eller skapa en enkel:
|
||||||
|
|
||||||
|
Authentik → Customization → Property Mappings → **Create → Scope Mapping**:
|
||||||
|
- Name: `archivum-groups`
|
||||||
|
- Scope name: `groups`
|
||||||
|
- Expression:
|
||||||
|
```python
|
||||||
|
return [group.name for group in user.ak_groups.all()]
|
||||||
|
```
|
||||||
|
|
||||||
|
Lägg till den scope-mappingen i providerns *Scopes*.
|
||||||
|
|
||||||
|
## 3. Skapa applikationen + binda åtkomst
|
||||||
|
|
||||||
|
Authentik → Applications → **Create**:
|
||||||
|
- Name: `Archivum`, Slug: `archivum`
|
||||||
|
- Provider: `archivum` (den du nyss skapade)
|
||||||
|
|
||||||
|
Issuer-URL blir då:
|
||||||
|
```
|
||||||
|
https://authentik.brasse-pc.eu/application/o/archivum/
|
||||||
|
```
|
||||||
|
|
||||||
|
Bind vilka som får nå appen (Application → Policy/Group/User Bindings) — t.ex.
|
||||||
|
bara `Archivum-admin` + `Archivum-reader`. Det är den *primära* grinden för vem
|
||||||
|
som kan logga in; Archivums egen login-lista är ett andra lager.
|
||||||
|
|
||||||
|
## 4. Konfigurera Archivum
|
||||||
|
|
||||||
|
Logga in som den lokala admin som skapades i setup-guiden → **Admin Settings →
|
||||||
|
Single Sign-On (Authentik / OIDC)**:
|
||||||
|
|
||||||
|
| Fält | Värde |
|
||||||
|
|------|-------|
|
||||||
|
| Enable | ✔ |
|
||||||
|
| Issuer URL | `https://authentik.brasse-pc.eu/application/o/archivum/` |
|
||||||
|
| Client ID | *(från steg 2)* |
|
||||||
|
| Client Secret | *(från steg 2)* |
|
||||||
|
| Public URL | `https://archivum.brasse-pc.eu` |
|
||||||
|
| Admin group | `Archivum-admin` |
|
||||||
|
| Reader group | `Archivum-reader` |
|
||||||
|
| Groups claim | `groups` |
|
||||||
|
| Username claim | `preferred_username` |
|
||||||
|
|
||||||
|
Spara. Statusen ska bli **"Provider connected ✓"** (Archivum gör OIDC-discovery
|
||||||
|
mot issuern). Login-sidan visar nu **"Sign in with Authentik"**.
|
||||||
|
|
||||||
|
> Redirect-URI:n som Archivum använder visas i panelen — den **måste** matcha
|
||||||
|
> exakt det du la in i Authentik-providern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Så fungerar rollen + åtkomsten
|
||||||
|
|
||||||
|
- Medlem i **Archivum-admin** → roll `admin` → ser/gör allt, administrerar sidan.
|
||||||
|
- Alla andra inloggade (t.ex. **Archivum-reader**) → styrs helt av
|
||||||
|
åtkomstreglerna (ACL) i admin-panelen. **Standard = deny.**
|
||||||
|
- **Publik användare** ("Continue as public user" på login-sidan) → anonym,
|
||||||
|
ser bara det admin uttryckligen delat.
|
||||||
|
|
||||||
|
### Åtkomstmodell (allow / deny)
|
||||||
|
|
||||||
|
I **Admin Settings → Access Control**: välj en användare eller grupp och lägg
|
||||||
|
regler per sökväg (dokument-slug eller mapp).
|
||||||
|
|
||||||
|
- **allow** ger en rättighet på en sökväg *och allt under den*.
|
||||||
|
- **deny** vinner alltid över allow (kombineras över användarens alla grupper
|
||||||
|
och överliggande mappar).
|
||||||
|
- Finns ingen regel alls → **deny** (default).
|
||||||
|
|
||||||
|
Exempel: ge `Archivum-reader` `allow` **read+view** på mappen `handbok`, men lägg
|
||||||
|
`deny` **read** på `handbok/hemligt` för samma grupp → de ser hela handboken utom
|
||||||
|
den hemliga delen.
|
||||||
|
|
||||||
|
## Reverse proxy (NPM)
|
||||||
|
|
||||||
|
Lägg upp `archivum.brasse-pc.eu` → Archivum-containern (port 4000) i NPM med
|
||||||
|
Let's Encrypt, precis som övriga tjänster. OIDC-redirecten kräver att appen nås
|
||||||
|
på den publika HTTPS-URL:en som är registrerad i Authentik.
|
||||||
@@ -12,6 +12,8 @@ const ready = ref(false)
|
|||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
theme.init()
|
theme.init()
|
||||||
|
// Consume an OIDC callback (?/oidc/callback#token=…) before deciding view.
|
||||||
|
app.handleOidcCallback()
|
||||||
await app.checkStatus()
|
await app.checkStatus()
|
||||||
ready.value = true
|
ready.value = true
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -240,14 +240,17 @@ class TipTapToAsciidoc {
|
|||||||
nodes.forEach((t) => {
|
nodes.forEach((t) => {
|
||||||
if (t.type === 'text') {
|
if (t.type === 'text') {
|
||||||
let text = t.text || ''
|
let text = t.text || ''
|
||||||
|
// Apply inline marks. Note: the previous implementation built the
|
||||||
|
// marked string but never appended it, then appended the *unmarked*
|
||||||
|
// text — silently dropping bold/italic/code/strike/link on save.
|
||||||
if (t.marks) {
|
if (t.marks) {
|
||||||
t.marks.forEach(mark => {
|
t.marks.forEach((mark) => {
|
||||||
switch (mark.type) {
|
switch (mark.type) {
|
||||||
case 'bold': text = `*${text}*`; break
|
case 'bold': text = `*${text}*`; break
|
||||||
case 'italic': text = `_${text}_`; break
|
case 'italic': text = `_${text}_`; break
|
||||||
case 'strike': text = `[line-through]#${text}#`; break
|
case 'strike': text = `[line-through]#${text}#`; break
|
||||||
case 'code': text = `\`${text}\``; break
|
case 'code': text = `\`${text}\``; break
|
||||||
case 'link':
|
case 'link': {
|
||||||
const url = mark.attrs?.href || ''
|
const url = mark.attrs?.href || ''
|
||||||
if (url.startsWith('http://') || url.startsWith('https://')) {
|
if (url.startsWith('http://') || url.startsWith('https://')) {
|
||||||
text = `${url}[${text}]`
|
text = `${url}[${text}]`
|
||||||
@@ -256,16 +259,13 @@ class TipTapToAsciidoc {
|
|||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
textOut += text
|
||||||
} else if (t.type === 'footnote') {
|
} else if (t.type === 'footnote') {
|
||||||
textOut += `footnote:[${t.attrs?.content || ''}]`
|
textOut += `footnote:[${t.attrs?.content || ''}]`
|
||||||
}
|
} else if (t.type === 'hardBreak') {
|
||||||
if (t.type === 'text') {
|
|
||||||
let text = t.text || ''
|
|
||||||
textOut += text
|
|
||||||
}
|
|
||||||
if (t.type === 'hardBreak') {
|
|
||||||
textOut += ' +\n'
|
textOut += ' +\n'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ export const router = createRouter({
|
|||||||
name: 'admin',
|
name: 'admin',
|
||||||
component: () => import('@/views/AdminView.vue'),
|
component: () => import('@/views/AdminView.vue'),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// OIDC redirect target. The token arrives in the URL fragment and is
|
||||||
|
// consumed by App.vue's onMounted before this renders; kept as an
|
||||||
|
// explicit route so the catch-all redirect does not swallow it.
|
||||||
|
path: '/oidc/callback',
|
||||||
|
name: 'oidc-callback',
|
||||||
|
component: HomeView,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/:pathMatch(.*)*',
|
path: '/:pathMatch(.*)*',
|
||||||
redirect: '/',
|
redirect: '/',
|
||||||
|
|||||||
@@ -8,6 +8,37 @@ export const useAppStore = defineStore('app', () => {
|
|||||||
const token = ref<string | null>(localStorage.getItem('token'))
|
const token = ref<string | null>(localStorage.getItem('token'))
|
||||||
const username = ref<string | null>(localStorage.getItem('username'))
|
const username = ref<string | null>(localStorage.getItem('username'))
|
||||||
const role = ref<string | null>(localStorage.getItem('role'))
|
const role = ref<string | null>(localStorage.getItem('role'))
|
||||||
|
// Surfaced on the login page (e.g. after a denied OIDC sign-in).
|
||||||
|
const loginError = ref('')
|
||||||
|
|
||||||
|
// Redirect the browser to the backend OIDC entry point. The backend bounces
|
||||||
|
// to Authentik and, on success, back to /oidc/callback with a token fragment.
|
||||||
|
function loginWithOidc() {
|
||||||
|
window.location.href = '/auth/oidc/login'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle the /oidc/callback route: read the token (or error) from the URL
|
||||||
|
// fragment, persist the session, and clean the address bar. Returns true if
|
||||||
|
// this was an OIDC callback navigation.
|
||||||
|
function handleOidcCallback(): boolean {
|
||||||
|
if (window.location.pathname !== '/oidc/callback') return false
|
||||||
|
const raw = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : ''
|
||||||
|
const params = new URLSearchParams(raw)
|
||||||
|
const tok = params.get('token')
|
||||||
|
const err = params.get('error')
|
||||||
|
if (tok) {
|
||||||
|
token.value = tok
|
||||||
|
username.value = params.get('username') || ''
|
||||||
|
role.value = params.get('role') || ''
|
||||||
|
localStorage.setItem('token', tok)
|
||||||
|
localStorage.setItem('username', username.value || '')
|
||||||
|
localStorage.setItem('role', role.value || '')
|
||||||
|
} else if (err) {
|
||||||
|
loginError.value = err
|
||||||
|
}
|
||||||
|
window.history.replaceState({}, '', '/')
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
async function checkStatus() {
|
async function checkStatus() {
|
||||||
try {
|
try {
|
||||||
@@ -95,6 +126,9 @@ export const useAppStore = defineStore('app', () => {
|
|||||||
localStorage.removeItem('role')
|
localStorage.removeItem('role')
|
||||||
}
|
}
|
||||||
|
|
||||||
return { requiresSetup, token, username, role, checkStatus, login, loginAsGuest, logout }
|
return {
|
||||||
|
requiresSetup, token, username, role, loginError,
|
||||||
|
checkStatus, login, loginAsGuest, loginWithOidc, handleOidcCallback, logout,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,31 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { useAppStore } from '@/stores/app'
|
import { useAppStore } from '@/stores/app'
|
||||||
|
import { gql } from '@/lib/gql'
|
||||||
|
|
||||||
const app = useAppStore()
|
const app = useAppStore()
|
||||||
const username = ref('')
|
const username = ref('')
|
||||||
const password = ref('')
|
const password = ref('')
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const error = ref('')
|
const error = ref(app.loginError || '')
|
||||||
|
|
||||||
|
const options = ref({
|
||||||
|
localEnabled: true,
|
||||||
|
oidcEnabled: false,
|
||||||
|
oidcButtonLabel: 'Sign in with Authentik',
|
||||||
|
publicEnabled: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const data = await gql<{ loginOptions: typeof options.value }>(
|
||||||
|
`{ loginOptions { localEnabled oidcEnabled oidcButtonLabel publicEnabled } }`,
|
||||||
|
)
|
||||||
|
options.value = data.loginOptions
|
||||||
|
} catch {
|
||||||
|
// fall back to defaults (local + public)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
error.value = ''
|
error.value = ''
|
||||||
@@ -20,17 +39,21 @@ async function submit() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function continueAsGuest() {
|
async function continueAsPublic() {
|
||||||
error.value = ''
|
error.value = ''
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
await app.loginAsGuest()
|
await app.loginAsGuest()
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
error.value = err instanceof Error ? err.message : 'Failed to sign in as guest'
|
error.value = err instanceof Error ? err.message : 'Failed to continue as public user'
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
loading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function signInWithOidc() {
|
||||||
|
app.loginWithOidc()
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -48,7 +71,31 @@ async function continueAsGuest() {
|
|||||||
|
|
||||||
<h2 class="text-center text-slate-500 dark:text-slate-400">Sign in to continue</h2>
|
<h2 class="text-center text-slate-500 dark:text-slate-400">Sign in to continue</h2>
|
||||||
|
|
||||||
<form @submit.prevent="submit" class="space-y-4">
|
<!-- OIDC / Authentik (primary when enabled) -->
|
||||||
|
<button
|
||||||
|
v-if="options.oidcEnabled"
|
||||||
|
type="button"
|
||||||
|
class="w-full flex justify-center items-center gap-2 py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-accent-600 hover:bg-accent-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-500 disabled:opacity-50"
|
||||||
|
:disabled="loading"
|
||||||
|
@click="signInWithOidc"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
|
||||||
|
</svg>
|
||||||
|
{{ options.oidcButtonLabel }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="options.oidcEnabled && options.localEnabled" class="relative">
|
||||||
|
<div class="absolute inset-0 flex items-center">
|
||||||
|
<div class="w-full border-t border-slate-200 dark:border-slate-700"></div>
|
||||||
|
</div>
|
||||||
|
<div class="relative flex justify-center text-xs uppercase">
|
||||||
|
<span class="bg-white dark:bg-slate-800 px-2 text-slate-400">or with a local account</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form v-if="options.localEnabled" @submit.prevent="submit" class="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-medium mb-1 text-slate-700 dark:text-slate-300">Username</label>
|
<label class="block text-sm font-medium mb-1 text-slate-700 dark:text-slate-300">Username</label>
|
||||||
<input
|
<input
|
||||||
@@ -71,10 +118,6 @@ async function continueAsGuest() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="error" class="text-sm text-red-600 bg-red-50 dark:bg-red-500/10 dark:text-red-400 p-3 rounded-lg border border-red-200 dark:border-red-500/20">
|
|
||||||
{{ error }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
class="w-full flex justify-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-accent-600 hover:bg-accent-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
class="w-full flex justify-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-accent-600 hover:bg-accent-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
@@ -88,7 +131,12 @@ async function continueAsGuest() {
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div class="relative">
|
<div v-if="error" class="text-sm text-red-600 bg-red-50 dark:bg-red-500/10 dark:text-red-400 p-3 rounded-lg border border-red-200 dark:border-red-500/20">
|
||||||
|
{{ error }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="options.publicEnabled">
|
||||||
|
<div class="relative mb-4">
|
||||||
<div class="absolute inset-0 flex items-center">
|
<div class="absolute inset-0 flex items-center">
|
||||||
<div class="w-full border-t border-slate-200 dark:border-slate-700"></div>
|
<div class="w-full border-t border-slate-200 dark:border-slate-700"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -101,10 +149,14 @@ async function continueAsGuest() {
|
|||||||
type="button"
|
type="button"
|
||||||
class="w-full flex justify-center py-2.5 px-4 border border-slate-300 dark:border-slate-600 rounded-lg shadow-sm text-sm font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-400 disabled:opacity-50 disabled:cursor-not-allowed"
|
class="w-full flex justify-center py-2.5 px-4 border border-slate-300 dark:border-slate-600 rounded-lg shadow-sm text-sm font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-400 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
:disabled="loading"
|
:disabled="loading"
|
||||||
@click="continueAsGuest"
|
@click="continueAsPublic"
|
||||||
>
|
>
|
||||||
Continue as Guest
|
Continue as public user
|
||||||
</button>
|
</button>
|
||||||
|
<p class="text-xs text-slate-400 text-center mt-2">
|
||||||
|
The public user only sees what an administrator has shared.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
Reference in New Issue
Block a user