Compare commits
8 Commits
master
...
feature/ss
| Author | SHA1 | Date | |
|---|---|---|---|
| 4569fec82c | |||
|
b507f961cb
|
|||
|
41ec7bdc08
|
|||
|
da6a73e357
|
|||
|
4ad03403aa
|
|||
|
88ff6ddae5
|
|||
| 450ff488ea | |||
| 97ce26fb51 |
@@ -46,6 +46,9 @@ RUN rm -rvf /app/Dockerfile* \
|
|||||||
/app/requirements.txt \
|
/app/requirements.txt \
|
||||||
/app/node_modules \
|
/app/node_modules \
|
||||||
/app/*.json \
|
/app/*.json \
|
||||||
|
/app/AGENTS* \
|
||||||
|
/app/*.md \
|
||||||
|
/app/k8s-templates \
|
||||||
/app/test_*.py && \
|
/app/test_*.py && \
|
||||||
python3 /app/manage.py collectstatic --noinput
|
python3 /app/manage.py collectstatic --noinput
|
||||||
CMD ["sh", "-c", "python manage.py thumbnail clear && gunicorn --bind 0.0.0.0:8000 --workers 3 $GUNICORN_OPTS labhelper.wsgi:application"]
|
CMD ["sh", "-c", "python manage.py thumbnail clear && gunicorn --bind 0.0.0.0:8000 --workers 3 $GUNICORN_OPTS labhelper.wsgi:application"]
|
||||||
|
|||||||
207
Keycloak-installation.md
Normal file
207
Keycloak-installation.md
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
# Keycloak SSO Integration
|
||||||
|
|
||||||
|
This document describes how Keycloak SSO was integrated into labhelper, replacing the built-in Django username/password authentication.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Authentication is handled via OpenID Connect (OIDC) using the `mozilla-django-oidc` library. When a user visits any protected page, they are redirected to Keycloak to authenticate. On return, Keycloak group memberships are synced to Django groups, controlling what the user can do in the app.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Keycloak Setup
|
||||||
|
|
||||||
|
### 1. Create a client
|
||||||
|
|
||||||
|
In the Keycloak admin console, go to **Clients → Create client**.
|
||||||
|
|
||||||
|
| Field | Value | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| Client type | OpenID Connect | The protocol mozilla-django-oidc speaks |
|
||||||
|
| Client ID | `labhelper` | Must match `OIDC_RP_CLIENT_ID` in the app |
|
||||||
|
| Client authentication | On (confidential) | Server-side apps use a client secret; this is more secure than a public client |
|
||||||
|
| Authentication flow | Standard flow only | labhelper uses the standard authorisation code flow |
|
||||||
|
|
||||||
|
After saving, go to the **Credentials** tab and copy the **Client secret** — this is `OIDC_RP_CLIENT_SECRET`.
|
||||||
|
|
||||||
|
### 2. Set the redirect URI
|
||||||
|
|
||||||
|
In the client **Settings** tab:
|
||||||
|
|
||||||
|
| Field | Value | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| Valid redirect URIs | `https://your-app/oidc/callback/` | Keycloak will only redirect back to whitelisted URIs after authentication. The trailing slash is required — without it Keycloak rejects the request. For local dev also add `http://127.0.0.1:8000/oidc/callback/` |
|
||||||
|
|
||||||
|
### 3. Set the PKCE code challenge method
|
||||||
|
|
||||||
|
In the client **Advanced** tab, find **"Proof Key for Code Exchange Code Challenge Method"** and set it to **S256**.
|
||||||
|
|
||||||
|
Why: Keycloak 26 configures new clients with PKCE enforced. `mozilla-django-oidc` sends `S256` as the challenge method (the more secure option). If Keycloak is set to `plain`, the two sides don't agree and authentication fails with `code challenge method is not matching the configured one`.
|
||||||
|
|
||||||
|
### 4. Add a Groups mapper
|
||||||
|
|
||||||
|
This makes Keycloak include the user's group memberships in the token so the app can sync them to Django groups.
|
||||||
|
|
||||||
|
Go to **Clients → labhelper → Client scopes** tab → click the dedicated scope (named `labhelper-dedicated`) → **Add mapper → By configuration → Group Membership**.
|
||||||
|
|
||||||
|
| Field | Value | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| Name | `groups` | Label for this mapper |
|
||||||
|
| Token Claim Name | `groups` | The claim name the app reads from the token |
|
||||||
|
| Full group path | Off | Sends `LabHelper Administrators` instead of `/LabHelper Administrators`. The app strips leading slashes anyway, but this is cleaner |
|
||||||
|
| Add to ID token | On | |
|
||||||
|
| Add to access token | On | |
|
||||||
|
| Add to userinfo | On | The app fetches userinfo after the token exchange |
|
||||||
|
|
||||||
|
### 5. Create groups
|
||||||
|
|
||||||
|
Go to **Groups** (left sidebar) and create these three groups with exactly these names — they map to the existing Django groups:
|
||||||
|
|
||||||
|
- `LabHelper Administrators` — gets `is_staff=True` in Django (admin access)
|
||||||
|
- `LabHelper Staff`
|
||||||
|
- `LabHelper Viewers`
|
||||||
|
|
||||||
|
### 6. Ensure users have an email address
|
||||||
|
|
||||||
|
`mozilla-django-oidc` requires the `email` claim to be present in the token. Every Keycloak user who will log into labhelper must have:
|
||||||
|
|
||||||
|
- An **Email** address set (Users → select user → Details tab)
|
||||||
|
- **Email verified** ticked
|
||||||
|
|
||||||
|
Without an email, authentication fails silently with `Claims verification failed` in the Django logs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## App Configuration
|
||||||
|
|
||||||
|
The app is configured entirely via environment variables.
|
||||||
|
|
||||||
|
### Required variables
|
||||||
|
|
||||||
|
```bash
|
||||||
|
OIDC_OP_BASE_URL=https://keycloak.example.com/realms/your-realm
|
||||||
|
OIDC_RP_CLIENT_ID=labhelper
|
||||||
|
OIDC_RP_CLIENT_SECRET=<client-secret-from-keycloak-credentials-tab>
|
||||||
|
```
|
||||||
|
|
||||||
|
`OIDC_OP_BASE_URL` is the realm URL. All OIDC endpoints (authorisation, token, userinfo, JWKS, logout) are derived from it automatically in `settings.py`.
|
||||||
|
|
||||||
|
### Other relevant variables
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ALLOWED_HOSTS=your-app-hostname
|
||||||
|
CSRF_TRUSTED_ORIGINS=https://your-app
|
||||||
|
```
|
||||||
|
|
||||||
|
`CSRF_TRUSTED_ORIGINS` must include the app's origin. The OIDC callback goes through Django's CSRF middleware, and requests from untrusted origins are rejected.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How the App Side Works
|
||||||
|
|
||||||
|
### Library
|
||||||
|
|
||||||
|
`mozilla-django-oidc` handles the full OIDC flow: redirecting to Keycloak, validating the returned token (RS256 signature verified against Keycloak's JWKS endpoint), exchanging the authorisation code, and fetching userinfo.
|
||||||
|
|
||||||
|
### Key settings
|
||||||
|
|
||||||
|
| Setting | Value | Why |
|
||||||
|
|---|---|---|
|
||||||
|
| `OIDC_RP_SIGN_ALGO` | `RS256` | Keycloak signs tokens with RS256 by default |
|
||||||
|
| `OIDC_RP_SCOPES` | `openid email profile` | `profile` is needed to get `preferred_username`, `given_name`, `family_name` from Keycloak |
|
||||||
|
| `OIDC_USE_PKCE` | `True` | Required because Keycloak enforces PKCE on this client |
|
||||||
|
| `OIDC_STORE_ID_TOKEN` | `True` | The ID token is stored in the session and passed as `id_token_hint` when logging out, so Keycloak also ends its own session |
|
||||||
|
| `OIDC_EXEMPT_URLS` | `['search_api']` | The search endpoint is called via AJAX. The `SessionRefresh` middleware would return a redirect instead of JSON for unauthenticated AJAX calls, breaking the UI |
|
||||||
|
| `LOGIN_URL` | `oidc_authentication_init` | When `@login_required` intercepts an unauthenticated request, it redirects directly to the OIDC flow rather than a local login form |
|
||||||
|
|
||||||
|
### Authentication backend (`labhelper/auth_backend.py`)
|
||||||
|
|
||||||
|
Overrides `OIDCAuthenticationBackend` to:
|
||||||
|
|
||||||
|
- Use `preferred_username` from Keycloak as the Django username
|
||||||
|
- Set `first_name` and `last_name` from `given_name` / `family_name` claims
|
||||||
|
- Sync group memberships on every login — if a user is added to or removed from a Keycloak group, it takes effect at their next login
|
||||||
|
- Set `is_staff=True` for members of `LabHelper Administrators` (grants Django admin access)
|
||||||
|
|
||||||
|
`django.contrib.auth.backends.ModelBackend` is kept as a fallback so the Django admin login form still works with a local username/password (useful for emergency superuser access without Keycloak).
|
||||||
|
|
||||||
|
### Session refresh middleware
|
||||||
|
|
||||||
|
`mozilla_django_oidc.middleware.SessionRefresh` is added after `AuthenticationMiddleware`. It periodically checks whether the user's OIDC session is still valid and forces re-authentication if the token has expired, rather than keeping a stale Django session alive indefinitely.
|
||||||
|
|
||||||
|
### URLs
|
||||||
|
|
||||||
|
All OIDC routes are mounted under `/oidc/`:
|
||||||
|
|
||||||
|
| URL | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `/oidc/authenticate/` | Initiates the OIDC flow, redirects to Keycloak |
|
||||||
|
| `/oidc/callback/` | Keycloak redirects here after authentication |
|
||||||
|
| `/oidc/logout/` | Logs out of Django and ends the Keycloak session |
|
||||||
|
|
||||||
|
`/login/` is kept as a static landing page with a "Login with SSO" button, used when users navigate to it manually or are redirected there after logout.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Auth Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
User visits protected page
|
||||||
|
↓
|
||||||
|
@login_required → redirect to /oidc/authenticate/?next=/original/url/
|
||||||
|
↓
|
||||||
|
Redirect to Keycloak (with code_challenge for PKCE)
|
||||||
|
↓
|
||||||
|
User authenticates in Keycloak
|
||||||
|
↓
|
||||||
|
Keycloak redirects to /oidc/callback/?code=...
|
||||||
|
↓
|
||||||
|
App exchanges code for tokens, verifies RS256 signature
|
||||||
|
↓
|
||||||
|
App fetches userinfo, syncs groups and attributes
|
||||||
|
↓
|
||||||
|
User redirected to original URL
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Error | Cause | Fix |
|
||||||
|
|---|---|---|
|
||||||
|
| `Invalid parameter: redirect_uri` | Redirect URI not in Keycloak whitelist, or trailing slash missing | Add exact URI including trailing slash to Keycloak client Valid Redirect URIs |
|
||||||
|
| `Missing parameter: code_challenge_method` | Keycloak requires PKCE but app wasn't sending it | Set `OIDC_USE_PKCE = True` in settings |
|
||||||
|
| `code challenge method is not matching the configured one` | Keycloak client set to `plain`, app sends `S256` | Set PKCE method to `S256` in Keycloak client Advanced settings |
|
||||||
|
| `Claims verification failed` | User has no email set in Keycloak | Set email address and tick Email Verified on the Keycloak user |
|
||||||
|
| `NoReverseMatch` for `OIDC_EXEMPT_URLS` | Regex pattern used instead of URL name | Use the Django URL name (`'search_api'`), not a regex |
|
||||||
|
| Login loops without showing Keycloak | Existing Keycloak session auto-authenticates | Expected behaviour — Keycloak reuses its session. Log out of Keycloak admin console to test a clean login |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Kubernetes Deployment
|
||||||
|
|
||||||
|
Split the configuration across a ConfigMap and a Secret. The client secret must not go in a ConfigMap as the contents are visible in plain text to anyone with cluster access.
|
||||||
|
|
||||||
|
**ConfigMap**
|
||||||
|
```yaml
|
||||||
|
data:
|
||||||
|
OIDC_OP_BASE_URL: https://keycloak.example.com/realms/your-realm
|
||||||
|
OIDC_RP_CLIENT_ID: labhelper
|
||||||
|
CSRF_TRUSTED_ORIGINS: https://labhelper.adebaumann.com
|
||||||
|
ALLOWED_HOSTS: labhelper.adebaumann.com
|
||||||
|
```
|
||||||
|
|
||||||
|
**Secret**
|
||||||
|
```yaml
|
||||||
|
stringData:
|
||||||
|
OIDC_RP_CLIENT_SECRET: <client-secret-from-keycloak-credentials-tab>
|
||||||
|
DJANGO_SECRET_KEY: <random-secret-key>
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference both in the deployment:
|
||||||
|
```yaml
|
||||||
|
envFrom:
|
||||||
|
- configMapRef:
|
||||||
|
name: labhelper-config
|
||||||
|
- secretRef:
|
||||||
|
name: labhelper-secret
|
||||||
|
```
|
||||||
@@ -14,8 +14,11 @@ data:
|
|||||||
STATIC_URL: "/static/"
|
STATIC_URL: "/static/"
|
||||||
MEDIA_URL: "/media/"
|
MEDIA_URL: "/media/"
|
||||||
CSRF_TRUSTED_ORIGINS: "https://labhelper.adebaumann.com"
|
CSRF_TRUSTED_ORIGINS: "https://labhelper.adebaumann.com"
|
||||||
LOGIN_URL: "login"
|
LOGIN_URL: "oidc_authentication_init"
|
||||||
|
OIDC_OP_BASE_URL: "https://sso.baumann.gr/realms/homelab"
|
||||||
|
OIDC_RP_CLIENT_ID: "labhelper"
|
||||||
LOGIN_REDIRECT_URL: "index"
|
LOGIN_REDIRECT_URL: "index"
|
||||||
LOGOUT_REDIRECT_URL: "login"
|
LOGOUT_REDIRECT_URL: "/login/"
|
||||||
|
OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL: "/login/"
|
||||||
GUNICORN_OPTS: "--access-logfile -"
|
GUNICORN_OPTS: "--access-logfile -"
|
||||||
IMAGE_TAG: "0.076"
|
IMAGE_TAG: "0.079"
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ spec:
|
|||||||
mountPath: /data
|
mountPath: /data
|
||||||
containers:
|
containers:
|
||||||
- name: web
|
- name: web
|
||||||
image: git.baumann.gr/adebaumann/labhelper:0.076
|
image: git.baumann.gr/adebaumann/labhelper:0.082
|
||||||
imagePullPolicy: Always
|
imagePullPolicy: Always
|
||||||
ports:
|
ports:
|
||||||
- containerPort: 8000
|
- containerPort: 8000
|
||||||
@@ -92,6 +92,21 @@ spec:
|
|||||||
configMapKeyRef:
|
configMapKeyRef:
|
||||||
name: django-config
|
name: django-config
|
||||||
key: LOGIN_URL
|
key: LOGIN_URL
|
||||||
|
- name: OIDC_OP_BASE_URL
|
||||||
|
valueFrom:
|
||||||
|
configMapKeyRef:
|
||||||
|
name: django-config
|
||||||
|
key: OIDC_OP_BASE_URL
|
||||||
|
- name: OIDC_RP_CLIENT_ID
|
||||||
|
valueFrom:
|
||||||
|
configMapKeyRef:
|
||||||
|
name: django-config
|
||||||
|
key: OIDC_RP_CLIENT_ID
|
||||||
|
- name: OIDC_RP_CLIENT_SECRET
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: django-secret
|
||||||
|
key: oidc-client-secret
|
||||||
- name: LOGIN_REDIRECT_URL
|
- name: LOGIN_REDIRECT_URL
|
||||||
valueFrom:
|
valueFrom:
|
||||||
configMapKeyRef:
|
configMapKeyRef:
|
||||||
@@ -102,6 +117,11 @@ spec:
|
|||||||
configMapKeyRef:
|
configMapKeyRef:
|
||||||
name: django-config
|
name: django-config
|
||||||
key: LOGOUT_REDIRECT_URL
|
key: LOGOUT_REDIRECT_URL
|
||||||
|
- name: OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL
|
||||||
|
valueFrom:
|
||||||
|
configMapKeyRef:
|
||||||
|
name: django-config
|
||||||
|
key: OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL
|
||||||
- name: GUNICORN_OPTS
|
- name: GUNICORN_OPTS
|
||||||
valueFrom:
|
valueFrom:
|
||||||
configMapKeyRef:
|
configMapKeyRef:
|
||||||
@@ -117,7 +137,7 @@ spec:
|
|||||||
mountPath: /app/data
|
mountPath: /app/data
|
||||||
readinessProbe:
|
readinessProbe:
|
||||||
httpGet:
|
httpGet:
|
||||||
path: /
|
path: /health/
|
||||||
port: 8000
|
port: 8000
|
||||||
initialDelaySeconds: 5
|
initialDelaySeconds: 5
|
||||||
periodSeconds: 10
|
periodSeconds: 10
|
||||||
@@ -125,7 +145,7 @@ spec:
|
|||||||
failureThreshold: 6
|
failureThreshold: 6
|
||||||
livenessProbe:
|
livenessProbe:
|
||||||
httpGet:
|
httpGet:
|
||||||
path: /
|
path: /health/
|
||||||
port: 8000
|
port: 8000
|
||||||
initialDelaySeconds: 20
|
initialDelaySeconds: 20
|
||||||
periodSeconds: 20
|
periodSeconds: 20
|
||||||
|
|||||||
@@ -284,6 +284,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<form method="post" action="{% url 'delete_thing' thing.id %}"
|
||||||
|
onsubmit="return confirm('Are you sure you want to delete {{ thing.name }}? This cannot be undone.');">
|
||||||
|
{% csrf_token %}
|
||||||
|
<button type="submit" class="btn btn-danger">
|
||||||
|
<i class="fas fa-trash"></i> Delete Thing
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_css %}
|
{% block extra_css %}
|
||||||
|
|||||||
@@ -98,7 +98,7 @@
|
|||||||
<div style="display: flex; align-items: center; gap: 10px; padding: 12px 15px; background: #f8f9fa; border-radius: 8px; border:1px solid #e9ecef;">
|
<div style="display: flex; align-items: center; gap: 10px; padding: 12px 15px; background: #f8f9fa; border-radius: 8px; border:1px solid #e9ecef;">
|
||||||
<img class="lightbox-trigger" data-url="{{ file.file.url }}" src="{{ thumb.url }}" alt="{{ file.title }}" style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
|
<img class="lightbox-trigger" data-url="{{ file.file.url }}" src="{{ thumb.url }}" alt="{{ file.title }}" style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
|
||||||
<div style="flex-grow: 1;">
|
<div style="flex-grow: 1;">
|
||||||
<a href="{{ file.file.url }}" target="_blank" style="color: #667eea; text-decoration: none; font-weight: 500; font-size: 15px;">{{ file.title }}</a>
|
<a href="#" class="lightbox-trigger" data-url="{{ file.file.url }}" style="color: #667eea; text-decoration: none; font-weight: 500; font-size: 15px;">{{ file.title }}</a>
|
||||||
<span style="color: #999; font-size: 12px;">({{ file.filename }})</span>
|
<span style="color: #999; font-size: 12px;">({{ file.filename }})</span>
|
||||||
</div>
|
</div>
|
||||||
<i class="fas fa-expand lightbox-trigger" data-url="{{ file.file.url }}" style="color: #999; font-size: 14px; cursor: pointer;"></i>
|
<i class="fas fa-expand lightbox-trigger" data-url="{{ file.file.url }}" style="color: #999; font-size: 14px; cursor: pointer;"></i>
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ from .forms import (
|
|||||||
from .models import Box, BoxType, Facet, Tag, Thing, ThingFile, ThingLink
|
from .models import Box, BoxType, Facet, Tag, Thing, ThingFile, ThingLink
|
||||||
|
|
||||||
|
|
||||||
|
def health_check(request):
|
||||||
|
"""Health check endpoint for Kubernetes liveness/readiness probes."""
|
||||||
|
return HttpResponse('OK', status=200)
|
||||||
|
|
||||||
|
|
||||||
def _strip_markdown(text, max_length=100):
|
def _strip_markdown(text, max_length=100):
|
||||||
"""Convert Markdown to plain text and truncate."""
|
"""Convert Markdown to plain text and truncate."""
|
||||||
if not text:
|
if not text:
|
||||||
@@ -373,6 +378,21 @@ def delete_box(request, box_id):
|
|||||||
return redirect('box_management')
|
return redirect('box_management')
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
def delete_thing(request, thing_id):
|
||||||
|
"""Delete a thing and its associated files."""
|
||||||
|
thing = get_object_or_404(Thing, pk=thing_id)
|
||||||
|
if request.method == 'POST':
|
||||||
|
box_id = thing.box.id
|
||||||
|
if thing.picture:
|
||||||
|
thing.picture.delete(save=False)
|
||||||
|
for thing_file in thing.files.all():
|
||||||
|
thing_file.file.delete(save=False)
|
||||||
|
thing.delete()
|
||||||
|
return redirect('box_detail', box_id=box_id)
|
||||||
|
return redirect('edit_thing', thing_id=thing_id)
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
@login_required
|
||||||
def resources_list(request):
|
def resources_list(request):
|
||||||
"""List all links and files from things that have them."""
|
"""List all links and files from things that have them."""
|
||||||
|
|||||||
54
labhelper/auth_backend.py
Normal file
54
labhelper/auth_backend.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
|
||||||
|
from django.contrib.auth.models import Group
|
||||||
|
|
||||||
|
# Keycloak group name → Django group name mapping.
|
||||||
|
# Keycloak may send group paths with a leading slash (e.g. "/LabHelper Administrators");
|
||||||
|
# these are stripped before comparison.
|
||||||
|
KEYCLOAK_GROUP_MAP = {
|
||||||
|
'LabHelper Administrators': 'LabHelper Administrators',
|
||||||
|
'LabHelper Staff': 'LabHelper Staff',
|
||||||
|
'LabHelper Viewers': 'LabHelper Viewers',
|
||||||
|
}
|
||||||
|
|
||||||
|
# Members of these groups receive is_staff=True (Django admin access)
|
||||||
|
STAFF_GROUPS = {'LabHelper Administrators'}
|
||||||
|
|
||||||
|
|
||||||
|
class KeycloakOIDCBackend(OIDCAuthenticationBackend):
|
||||||
|
"""OIDC backend that maps Keycloak groups to Django groups on every login."""
|
||||||
|
|
||||||
|
def get_username(self, claims):
|
||||||
|
return claims.get('preferred_username') or super().get_username(claims)
|
||||||
|
|
||||||
|
def create_user(self, claims):
|
||||||
|
user = super().create_user(claims)
|
||||||
|
self._sync_from_claims(user, claims)
|
||||||
|
return user
|
||||||
|
|
||||||
|
def update_user(self, user, claims):
|
||||||
|
user = super().update_user(user, claims)
|
||||||
|
self._sync_from_claims(user, claims)
|
||||||
|
return user
|
||||||
|
|
||||||
|
def _sync_from_claims(self, user, claims):
|
||||||
|
"""Sync user attributes and group memberships from Keycloak token claims."""
|
||||||
|
user.first_name = claims.get('given_name', user.first_name)
|
||||||
|
user.last_name = claims.get('family_name', user.last_name)
|
||||||
|
|
||||||
|
# Keycloak sends group paths like "/LabHelper Administrators"; normalise them.
|
||||||
|
raw_groups = claims.get('groups', [])
|
||||||
|
keycloak_groups = {g.lstrip('/') for g in raw_groups}
|
||||||
|
|
||||||
|
user.is_staff = bool(keycloak_groups & STAFF_GROUPS)
|
||||||
|
user.save()
|
||||||
|
|
||||||
|
# Add/remove the user from each managed Django group to match Keycloak.
|
||||||
|
for kc_group, django_group_name in KEYCLOAK_GROUP_MAP.items():
|
||||||
|
try:
|
||||||
|
group = Group.objects.get(name=django_group_name)
|
||||||
|
except Group.DoesNotExist:
|
||||||
|
continue
|
||||||
|
if kc_group in keycloak_groups:
|
||||||
|
user.groups.add(group)
|
||||||
|
else:
|
||||||
|
user.groups.remove(group)
|
||||||
@@ -9,9 +9,9 @@ class Command(BaseCommand):
|
|||||||
self.stdout.write('Creating default users and groups...')
|
self.stdout.write('Creating default users and groups...')
|
||||||
|
|
||||||
groups = {
|
groups = {
|
||||||
'Lab Administrators': 'Full access to all lab functions',
|
'LabHelper Administrators': 'Full access to all lab functions',
|
||||||
'Lab Staff': 'Can view and search items, add things to boxes',
|
'LabHelper Staff': 'Can view and search items, add things to boxes',
|
||||||
'Lab Viewers': 'Read-only access to view and search',
|
'LabHelper Viewers': 'Read-only access to view and search',
|
||||||
}
|
}
|
||||||
|
|
||||||
for group_name, description in groups.items():
|
for group_name, description in groups.items():
|
||||||
@@ -22,9 +22,9 @@ class Command(BaseCommand):
|
|||||||
self.stdout.write(f'Group already exists: {group_name}')
|
self.stdout.write(f'Group already exists: {group_name}')
|
||||||
|
|
||||||
users = {
|
users = {
|
||||||
'admin': ('Lab Administrators', True),
|
'admin': ('LabHelper Administrators', True),
|
||||||
'staff': ('Lab Staff', False),
|
'staff': ('LabHelper Staff', False),
|
||||||
'viewer': ('Lab Viewers', False),
|
'viewer': ('LabHelper Viewers', False),
|
||||||
}
|
}
|
||||||
|
|
||||||
for username, (group_name, is_superuser) in users.items():
|
for username, (group_name, is_superuser) in users.items():
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ INSTALLED_APPS = [
|
|||||||
'django.contrib.sessions',
|
'django.contrib.sessions',
|
||||||
'django.contrib.messages',
|
'django.contrib.messages',
|
||||||
'django.contrib.staticfiles',
|
'django.contrib.staticfiles',
|
||||||
|
'mozilla_django_oidc',
|
||||||
'mptt',
|
'mptt',
|
||||||
'django_mptt_admin',
|
'django_mptt_admin',
|
||||||
'sorl.thumbnail',
|
'sorl.thumbnail',
|
||||||
@@ -52,6 +53,7 @@ MIDDLEWARE = [
|
|||||||
'django.middleware.common.CommonMiddleware',
|
'django.middleware.common.CommonMiddleware',
|
||||||
'django.middleware.csrf.CsrfViewMiddleware',
|
'django.middleware.csrf.CsrfViewMiddleware',
|
||||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||||
|
'mozilla_django_oidc.middleware.SessionRefresh',
|
||||||
'django.contrib.messages.middleware.MessageMiddleware',
|
'django.contrib.messages.middleware.MessageMiddleware',
|
||||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||||
]
|
]
|
||||||
@@ -137,8 +139,47 @@ MEDIA_ROOT = BASE_DIR / 'data' / 'media'
|
|||||||
|
|
||||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||||
|
|
||||||
CSRF_TRUSTED_ORIGINS=os.environ.get('CSRF_TRUSTED_ORIGINS', 'https://labhelper.adebaumann.com').split(',')
|
CSRF_TRUSTED_ORIGINS=os.environ.get('CSRF_TRUSTED_ORIGINS', 'https://labhelper.adebaumann.com,http://127.0.0.1:8000').split(',')
|
||||||
|
|
||||||
LOGIN_URL = os.environ.get('LOGIN_URL', 'login')
|
LOGIN_URL = os.environ.get('LOGIN_URL', 'oidc_authentication_init')
|
||||||
LOGIN_REDIRECT_URL = os.environ.get('LOGIN_REDIRECT_URL', 'index')
|
LOGIN_REDIRECT_URL = os.environ.get('LOGIN_REDIRECT_URL', 'index')
|
||||||
LOGOUT_REDIRECT_URL = os.environ.get('LOGOUT_REDIRECT_URL', 'login')
|
LOGOUT_REDIRECT_URL = os.environ.get('LOGOUT_REDIRECT_URL', 'login')
|
||||||
|
|
||||||
|
AUTHENTICATION_BACKENDS = [
|
||||||
|
'labhelper.auth_backend.KeycloakOIDCBackend',
|
||||||
|
# ModelBackend kept as fallback for Django admin emergency access
|
||||||
|
'django.contrib.auth.backends.ModelBackend',
|
||||||
|
]
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Keycloak / OIDC configuration
|
||||||
|
#
|
||||||
|
# Set OIDC_OP_BASE_URL to your realm URL, e.g.:
|
||||||
|
# https://keycloak.example.com/realms/myrealm
|
||||||
|
#
|
||||||
|
# All individual endpoints are derived from OIDC_OP_BASE_URL automatically.
|
||||||
|
# You can override any individual endpoint with its own env var.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
_oidc_base = os.environ.get('OIDC_OP_BASE_URL', '').rstrip('/')
|
||||||
|
_oidc_connect = f'{_oidc_base}/protocol/openid-connect' if _oidc_base else ''
|
||||||
|
|
||||||
|
OIDC_RP_CLIENT_ID = os.environ.get('OIDC_RP_CLIENT_ID', '')
|
||||||
|
OIDC_RP_CLIENT_SECRET = os.environ.get('OIDC_RP_CLIENT_SECRET', '')
|
||||||
|
OIDC_RP_SIGN_ALGO = 'RS256'
|
||||||
|
OIDC_RP_SCOPES = 'openid email profile'
|
||||||
|
OIDC_USE_PKCE = True
|
||||||
|
|
||||||
|
OIDC_OP_AUTHORIZATION_ENDPOINT = os.environ.get('OIDC_OP_AUTHORIZATION_ENDPOINT', f'{_oidc_connect}/auth')
|
||||||
|
OIDC_OP_TOKEN_ENDPOINT = os.environ.get('OIDC_OP_TOKEN_ENDPOINT', f'{_oidc_connect}/token')
|
||||||
|
OIDC_OP_USER_ENDPOINT = os.environ.get('OIDC_OP_USER_ENDPOINT', f'{_oidc_connect}/userinfo')
|
||||||
|
OIDC_OP_JWKS_ENDPOINT = os.environ.get('OIDC_OP_JWKS_ENDPOINT', f'{_oidc_connect}/certs')
|
||||||
|
OIDC_OP_LOGOUT_ENDPOINT = os.environ.get('OIDC_OP_LOGOUT_ENDPOINT', f'{_oidc_connect}/logout')
|
||||||
|
|
||||||
|
# Store the ID token in the session so Keycloak logout can use id_token_hint
|
||||||
|
OIDC_STORE_ID_TOKEN = True
|
||||||
|
|
||||||
|
# Redirect to the static login page on auth failure instead of looping back into OIDC
|
||||||
|
OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL = os.environ.get('OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL', '/login/')
|
||||||
|
|
||||||
|
# Exempt AJAX endpoints from the session-refresh middleware redirect
|
||||||
|
OIDC_EXEMPT_URLS = ['search_api']
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
<a href="/resources/"><i class="fas fa-folder-open"></i> Resources</a>
|
<a href="/resources/"><i class="fas fa-folder-open"></i> Resources</a>
|
||||||
<a href="/fixme/"><i class="fas fa-exclamation-triangle"></i> Fixme</a>
|
<a href="/fixme/"><i class="fas fa-exclamation-triangle"></i> Fixme</a>
|
||||||
<a href="/admin/"><i class="fas fa-cog"></i> Admin</a>
|
<a href="/admin/"><i class="fas fa-cog"></i> Admin</a>
|
||||||
<form method="post" action="{% url 'logout' %}" id="logout-form">
|
<form method="post" action="{% url 'oidc_logout' %}" id="logout-form">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
</form>
|
</form>
|
||||||
<a href="#" onclick="document.getElementById('logout-form').submit(); return false;">
|
<a href="#" onclick="document.getElementById('logout-form').submit(); return false;">
|
||||||
|
|||||||
@@ -9,70 +9,24 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="section" style="max-width: 500px; margin: 0 auto;">
|
<div class="section" style="max-width: 500px; margin: 0 auto; text-align: center;">
|
||||||
{% if form.errors %}
|
{% if request.GET.next and user.is_authenticated %}
|
||||||
<div class="alert alert-error">
|
<div class="alert alert-error" style="margin-bottom: 24px;">
|
||||||
<i class="fas fa-exclamation-circle"></i> Your username and password didn't match. Please try again.
|
<i class="fas fa-info-circle"></i> Your account doesn't have access to this page.
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% elif request.GET.next %}
|
||||||
|
<div class="alert alert-error" style="margin-bottom: 24px;">
|
||||||
{% if next %}
|
|
||||||
{% if user.is_authenticated %}
|
|
||||||
<div class="alert alert-error">
|
|
||||||
<i class="fas fa-info-circle"></i> Your account doesn't have access to this page. To proceed,
|
|
||||||
please login with an account that has access.
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<div class="alert alert-error">
|
|
||||||
<i class="fas fa-info-circle"></i> Please login to see this page.
|
<i class="fas fa-info-circle"></i> Please login to see this page.
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<form method="post" action="{% url 'login' %}" style="display: flex; flex-direction: column; gap: 20px;">
|
<p style="color: #555; margin-bottom: 28px;">
|
||||||
{% csrf_token %}
|
Authentication is handled via Single Sign-On. Click below to continue to the login page.
|
||||||
|
</p>
|
||||||
|
|
||||||
<div>
|
<a href="{% url 'oidc_authentication_init' %}{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}"
|
||||||
<label for="{{ form.username.id_for_label }}" style="display: block; font-weight: 600; margin-bottom: 8px; color: #555;">
|
class="btn" style="justify-content: center; display: inline-flex;">
|
||||||
<i class="fas fa-user"></i> Username
|
<i class="fas fa-sign-in-alt"></i> Login with SSO
|
||||||
</label>
|
</a>
|
||||||
<input type="{{ form.username.field.widget.input_type }}"
|
|
||||||
name="{{ form.username.name }}"
|
|
||||||
id="{{ form.username.id_for_label }}"
|
|
||||||
{% if form.username.value %}value="{{ form.username.value }}"{% endif %}
|
|
||||||
required
|
|
||||||
autofocus
|
|
||||||
style="width: 100%; padding: 12px 16px; border: 2px solid #e0e0e0; border-radius: 10px; font-size: 15px; transition: all 0.3s;">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label for="{{ form.password.id_for_label }}" style="display: block; font-weight: 600; margin-bottom: 8px; color: #555;">
|
|
||||||
<i class="fas fa-lock"></i> Password
|
|
||||||
</label>
|
|
||||||
<input type="password"
|
|
||||||
name="{{ form.password.name }}"
|
|
||||||
id="{{ form.password.id_for_label }}"
|
|
||||||
required
|
|
||||||
style="width: 100%; padding: 12px 16px; border: 2px solid #e0e0e0; border-radius: 10px; font-size: 15px; transition: all 0.3s;">
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<input type="hidden" name="next" value="{{ next }}">
|
|
||||||
|
|
||||||
<button type="submit" class="btn" style="justify-content: center; margin-top: 10px;">
|
|
||||||
<i class="fas fa-sign-in-alt"></i> Login
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_js %}
|
|
||||||
<script>
|
|
||||||
$('input[type="text"], input[type="password"]').on('focus', function() {
|
|
||||||
$(this).css('border-color', '#667eea');
|
|
||||||
$(this).css('box-shadow', '0 0 0 3px rgba(102, 126, 234, 0.1)');
|
|
||||||
}).on('blur', function() {
|
|
||||||
$(this).css('border-color', '#e0e0e0');
|
|
||||||
$(this).css('box-shadow', 'none');
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ Including another URLconf
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.conf.urls.static import static
|
from django.conf.urls.static import static
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.urls import path
|
from django.urls import include, path
|
||||||
from django.contrib.auth import views as auth_views
|
from django.views.generic import TemplateView
|
||||||
|
|
||||||
from boxes.views import (
|
from boxes.views import (
|
||||||
add_box,
|
add_box,
|
||||||
@@ -29,10 +29,12 @@ from boxes.views import (
|
|||||||
boxes_list,
|
boxes_list,
|
||||||
delete_box,
|
delete_box,
|
||||||
delete_box_type,
|
delete_box_type,
|
||||||
|
delete_thing,
|
||||||
edit_box,
|
edit_box,
|
||||||
edit_box_type,
|
edit_box_type,
|
||||||
edit_thing,
|
edit_thing,
|
||||||
fixme,
|
fixme,
|
||||||
|
health_check,
|
||||||
index,
|
index,
|
||||||
resources_list,
|
resources_list,
|
||||||
search_api,
|
search_api,
|
||||||
@@ -40,8 +42,9 @@ from boxes.views import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
|
path('oidc/', include('mozilla_django_oidc.urls')),
|
||||||
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
|
path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
|
||||||
|
path('health/', health_check, name='health_check'),
|
||||||
path('', index, name='index'),
|
path('', index, name='index'),
|
||||||
path('box-management/', box_management, name='box_management'),
|
path('box-management/', box_management, name='box_management'),
|
||||||
path('box-type/add/', add_box_type, name='add_box_type'),
|
path('box-type/add/', add_box_type, name='add_box_type'),
|
||||||
@@ -53,6 +56,7 @@ urlpatterns = [
|
|||||||
path('box/<str:box_id>/', box_detail, name='box_detail'),
|
path('box/<str:box_id>/', box_detail, name='box_detail'),
|
||||||
path('thing/<int:thing_id>/', thing_detail, name='thing_detail'),
|
path('thing/<int:thing_id>/', thing_detail, name='thing_detail'),
|
||||||
path('thing/<int:thing_id>/edit/', edit_thing, name='edit_thing'),
|
path('thing/<int:thing_id>/edit/', edit_thing, name='edit_thing'),
|
||||||
|
path('thing/<int:thing_id>/delete/', delete_thing, name='delete_thing'),
|
||||||
path('box/<str:box_id>/add/', add_things, name='add_things'),
|
path('box/<str:box_id>/add/', add_things, name='add_things'),
|
||||||
path('boxes/', boxes_list, name='boxes_list'),
|
path('boxes/', boxes_list, name='boxes_list'),
|
||||||
path('inventory/', boxes_list, name='inventory'),
|
path('inventory/', boxes_list, name='inventory'),
|
||||||
|
|||||||
@@ -37,3 +37,4 @@ sorl-thumbnail==12.11.0
|
|||||||
bleach==6.1.0
|
bleach==6.1.0
|
||||||
coverage==7.6.1
|
coverage==7.6.1
|
||||||
whitenoise==6.8.2
|
whitenoise==6.8.2
|
||||||
|
mozilla-django-oidc==4.0.1
|
||||||
|
|||||||
Reference in New Issue
Block a user