Compare commits
9 Commits
88c1dd704f
...
feature/ss
| Author | SHA1 | Date | |
|---|---|---|---|
| 158af49727 | |||
| 4569fec82c | |||
|
b507f961cb
|
|||
|
41ec7bdc08
|
|||
|
da6a73e357
|
|||
|
4ad03403aa
|
|||
|
88ff6ddae5
|
|||
| 450ff488ea | |||
| 97ce26fb51 |
71
AGENTS.md
Normal file
71
AGENTS.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# AGENTS.md - labhelper
|
||||
|
||||
**Type**: Django 5.2 web app (lab inventory)
|
||||
**Python**: 3.13 | **DB**: SQLite (dev) | **Env**: `.venv/`
|
||||
|
||||
## Essential Commands
|
||||
|
||||
```bash
|
||||
# Activate venv first
|
||||
source .venv/bin/activate
|
||||
|
||||
# Dev server
|
||||
python manage.py runserver # localhost:8000
|
||||
python manage.py runserver 0.0.0.0:8000 # all interfaces
|
||||
|
||||
# Database
|
||||
python manage.py makemigrations boxes # after model changes
|
||||
python manage.py migrate
|
||||
python manage.py showmigrations
|
||||
|
||||
# Testing
|
||||
python manage.py test # all
|
||||
python manage.py test boxes # app only
|
||||
python manage.py test boxes.tests.BoxModelTests.test_method # specific
|
||||
|
||||
# Custom commands
|
||||
python manage.py create_default_users # admin/admin123, staff/staff123, viewer/viewer123
|
||||
python manage.py clean_orphaned_files --dry-run
|
||||
python manage.py clean_orphaned_images --dry-run
|
||||
python manage.py collectstatic # after CSS changes
|
||||
```
|
||||
|
||||
## Critical Rules
|
||||
|
||||
1. **NEVER commit/push without explicit permission** - wait for user to say "commit and push"
|
||||
2. Use `get_object_or_404()` not bare `.get()` for model lookups
|
||||
3. Run `makemigrations` then `migrate` after any model change
|
||||
4. Default users: `admin/admin123` (superuser), `staff/staff123`, `viewer/viewer123`
|
||||
|
||||
## Data Model
|
||||
|
||||
- **BoxType** → Box (1:N, PROTECT)
|
||||
- **Box** → Thing (1:N, PROTECT) — Box.pk is CharField(max=10)
|
||||
- **Facet** → Tag (1:N, CASCADE) — Facet.cardinality: single/multiple
|
||||
- **Thing** ↔ Tag (M2M)
|
||||
- **Thing** → ThingFile, ThingLink (1:N, CASCADE)
|
||||
|
||||
## Deployment (when instructed)
|
||||
|
||||
**Full deploy**: bump both versions in `argocd/deployment.yaml` (+0.001), then:
|
||||
```bash
|
||||
cp data/db.sqlite3 data-loader/preload.sqlite3
|
||||
```
|
||||
|
||||
**Partial deploy**: bump main container only, skip DB copy.
|
||||
|
||||
## Key Directories
|
||||
|
||||
- `boxes/` — main app (models, views, forms, templates)
|
||||
- `labhelper/` — project settings, base template
|
||||
- `argocd/` — Kubernetes manifests for production
|
||||
- `data-loader/` — init container with preloaded DB
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Template base: `labhelper/templates/base.html`
|
||||
- App templates: `boxes/templates/boxes/`
|
||||
- Box ID is CharField (e.g., "A1-001"), not auto-increment
|
||||
- Views use `conditional_login_required` - bypasses login for IPs in `ALLOWED_CIDR_NETS` env var
|
||||
- Markdown via `{{ text|render_markdown }}` (sanitized with bleach)
|
||||
- Third-party: django-mptt, sorl-thumbnail, bleach, markdown
|
||||
272
AGENTS.md.backup
Normal file
272
AGENTS.md.backup
Normal file
@@ -0,0 +1,272 @@
|
||||
# AGENTS.md - AI Coding Agent Guidelines
|
||||
|
||||
This document provides guidelines for AI coding agents working in the labhelper repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
- **Type**: Django web application
|
||||
- **Python**: 3.13.7
|
||||
- **Django**: 5.2.9
|
||||
- **Database**: SQLite (development)
|
||||
- **Virtual Environment**: `.venv/`
|
||||
|
||||
## Build/Run Commands
|
||||
|
||||
### Development Server
|
||||
|
||||
```bash
|
||||
python manage.py runserver # Start dev server on port 8000
|
||||
python manage.py runserver 0.0.0.0:8000 # Bind to all interfaces
|
||||
```
|
||||
|
||||
### Database Operations
|
||||
|
||||
```bash
|
||||
python manage.py makemigrations # Create migration files
|
||||
python manage.py makemigrations boxes # Create migrations for specific app
|
||||
python manage.py migrate # Apply all migrations
|
||||
python manage.py showmigrations # List migration status
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
python manage.py test
|
||||
|
||||
# Run tests for a specific app
|
||||
python manage.py test boxes
|
||||
|
||||
# Run a specific test class
|
||||
python manage.py test boxes.tests.TestClassName
|
||||
|
||||
# Run a single test method
|
||||
python manage.py test boxes.tests.TestClassName.test_method_name
|
||||
|
||||
# Run tests with verbosity
|
||||
python manage.py test -v 2
|
||||
|
||||
# Run tests with coverage
|
||||
coverage run manage.py test
|
||||
coverage report
|
||||
coverage html # Generate HTML report
|
||||
```
|
||||
|
||||
### Django Shell
|
||||
|
||||
```bash
|
||||
python manage.py shell # Interactive Django shell
|
||||
python manage.py createsuperuser # Create admin user
|
||||
python manage.py collectstatic # Collect static files
|
||||
```
|
||||
|
||||
### Production
|
||||
|
||||
```bash
|
||||
gunicorn labhelper.wsgi:application # Run with Gunicorn
|
||||
```
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
### Python Style
|
||||
|
||||
- Follow PEP 8 conventions
|
||||
- Use 4-space indentation (no tabs)
|
||||
- Maximum line length: 79 characters (PEP 8 standard)
|
||||
- Use single quotes for strings: `'string'`
|
||||
- Use double quotes for docstrings: `"""Docstring."""`
|
||||
|
||||
### Import Order
|
||||
|
||||
Organize imports in this order, with blank lines between groups:
|
||||
|
||||
```python
|
||||
# 1. Standard library imports
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 2. Django imports
|
||||
from django.db import models
|
||||
from django.contrib import admin
|
||||
from django.shortcuts import render, redirect
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
|
||||
# 3. Third-party imports
|
||||
import requests
|
||||
from markdown import markdown
|
||||
|
||||
# 4. Local application imports
|
||||
from .models import MyModel
|
||||
from .forms import MyForm
|
||||
```
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
| Type | Convention | Example |
|
||||
|------|------------|---------|
|
||||
| Modules | lowercase_with_underscores | `user_profile.py` |
|
||||
| Classes | PascalCase | `UserProfile` |
|
||||
| Functions | lowercase_with_underscores | `get_user_data()` |
|
||||
| Constants | UPPERCASE_WITH_UNDERSCORES | `MAX_CONNECTIONS` |
|
||||
| Variables | lowercase_with_underscores | `user_count` |
|
||||
| Django Models | PascalCase (singular) | `Box`, `UserProfile` |
|
||||
| Django Apps | lowercase (short) | `boxes`, `users` |
|
||||
|
||||
### Django-Specific Conventions
|
||||
|
||||
**Models:**
|
||||
```python
|
||||
from django.db import models
|
||||
|
||||
class Box(models.Model):
|
||||
"""A storage box in the lab."""
|
||||
|
||||
name = models.CharField(max_length=255)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name_plural = 'boxes'
|
||||
ordering = ['-created_at']
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
```
|
||||
|
||||
**Views:**
|
||||
```python
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.http import Http404
|
||||
|
||||
def box_detail(request, box_id):
|
||||
"""Display details for a specific box."""
|
||||
box = get_object_or_404(Box, pk=box_id)
|
||||
return render(request, 'boxes/detail.html', {'box': box})
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```python
|
||||
# Use specific exceptions
|
||||
try:
|
||||
result = some_operation()
|
||||
except SpecificError as exc:
|
||||
raise CustomError('Descriptive message') from exc
|
||||
|
||||
# Django: Use get_object_or_404 for model lookups
|
||||
box = get_object_or_404(Box, pk=box_id)
|
||||
|
||||
# Log errors appropriately
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.error('Error message: %s', error_detail)
|
||||
```
|
||||
|
||||
### Type Hints (Recommended)
|
||||
|
||||
```python
|
||||
from typing import Optional
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
|
||||
def get_box(request: HttpRequest, box_id: int) -> HttpResponse:
|
||||
"""Retrieve a box by ID."""
|
||||
...
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
labhelper/
|
||||
├── manage.py # Django CLI entry point
|
||||
├── requirements.txt # Python dependencies
|
||||
├── labhelper/ # Project configuration
|
||||
│ ├── settings.py # Django settings
|
||||
│ ├── urls.py # Root URL routing
|
||||
│ ├── wsgi.py # WSGI application
|
||||
│ └── asgi.py # ASGI application
|
||||
└── boxes/ # Django app
|
||||
├── admin.py # Admin configuration
|
||||
├── apps.py # App configuration
|
||||
├── models.py # Data models
|
||||
├── views.py # View functions
|
||||
├── tests.py # Test cases
|
||||
├── migrations/ # Database migrations
|
||||
└── templates/ # HTML templates
|
||||
```
|
||||
|
||||
## Available Django Extensions
|
||||
|
||||
The project includes these pre-installed packages:
|
||||
|
||||
- **django-mptt**: Tree structures (categories, hierarchies)
|
||||
- **django-mptt-admin**: Admin interface for MPTT models
|
||||
- **django-admin-sortable2**: Drag-and-drop ordering in admin
|
||||
- **django-nested-admin**: Nested inline forms in admin
|
||||
- **django-nested-inline**: Additional nested inline support
|
||||
- **django-revproxy**: Reverse proxy functionality
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
- Use `django.test.TestCase` for database tests
|
||||
- Use `django.test.SimpleTestCase` for tests without database
|
||||
- Name test files `test_*.py` or `*_tests.py`
|
||||
- Name test methods `test_*`
|
||||
- Use descriptive test method names
|
||||
|
||||
```python
|
||||
from django.test import TestCase
|
||||
from .models import Box
|
||||
|
||||
class BoxModelTests(TestCase):
|
||||
"""Tests for the Box model."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
self.box = Box.objects.create(name='Test Box')
|
||||
|
||||
def test_box_str_returns_name(self):
|
||||
"""Box __str__ should return the box name."""
|
||||
self.assertEqual(str(self.box), 'Test Box')
|
||||
```
|
||||
|
||||
## Files to Never Commit
|
||||
|
||||
Per `.gitignore`:
|
||||
- `__pycache__/`, `*.pyc` - Python bytecode
|
||||
- `.venv/` - Virtual environment
|
||||
- `.env` - Environment variables
|
||||
- `data/db.sqlite3` - Database file
|
||||
- `keys/` - Secret keys
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Always activate venv**: `source .venv/bin/activate`
|
||||
2. **Run migrations after model changes**: `makemigrations` then `migrate`
|
||||
3. **Add new apps to INSTALLED_APPS** in `settings.py`
|
||||
4. **Use get_object_or_404** instead of bare `.get()` calls
|
||||
5. **Never commit SECRET_KEY** - use environment variables in production
|
||||
|
||||
## Deployment Commands
|
||||
|
||||
### Prepare a Full Deployment
|
||||
|
||||
When instructed to "Prepare a full deployment", perform the following steps:
|
||||
|
||||
1. **Bump container versions**: In `argocd/deployment.yaml`, increment the version numbers by 0.001 for both containers:
|
||||
- `labhelper-data-loader` (initContainer)
|
||||
- `labhelper` (main container)
|
||||
|
||||
2. **Copy database**: Copy the current development database to the data-loader preload location:
|
||||
```bash
|
||||
cp data/db.sqlite3 data-loader/preload.sqlite3
|
||||
```
|
||||
|
||||
### Prepare a Partial Deployment
|
||||
|
||||
When instructed to "Prepare a partial deployment", perform the following step:
|
||||
|
||||
1. **Bump main container version only**: In `argocd/deployment.yaml`, increment the version number by 0.001 for the main container only:
|
||||
- `labhelper` (main container)
|
||||
|
||||
Do NOT bump the data-loader version or copy the database.
|
||||
@@ -46,6 +46,9 @@ RUN rm -rvf /app/Dockerfile* \
|
||||
/app/requirements.txt \
|
||||
/app/node_modules \
|
||||
/app/*.json \
|
||||
/app/AGENTS* \
|
||||
/app/*.md \
|
||||
/app/k8s-templates \
|
||||
/app/test_*.py && \
|
||||
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"]
|
||||
|
||||
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
|
||||
```
|
||||
@@ -6,7 +6,7 @@ metadata:
|
||||
data:
|
||||
DEBUG: "False"
|
||||
ALLOWED_HOSTS: "labhelper.adebaumann.com,*"
|
||||
ALLOWED_CIDR_NETS: "10.0.0.0/16"
|
||||
ALLOWED_CIDR_NETS: "10.0.0.0/16,192.168.0.0/16"
|
||||
LANGUAGE_CODE: "en-us"
|
||||
TIME_ZONE: "UTC"
|
||||
USE_I18N: "True"
|
||||
@@ -14,8 +14,11 @@ data:
|
||||
STATIC_URL: "/static/"
|
||||
MEDIA_URL: "/media/"
|
||||
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"
|
||||
LOGOUT_REDIRECT_URL: "login"
|
||||
LOGOUT_REDIRECT_URL: "/login/"
|
||||
OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL: "/login/"
|
||||
GUNICORN_OPTS: "--access-logfile -"
|
||||
IMAGE_TAG: "0.076"
|
||||
IMAGE_TAG: "0.083"
|
||||
|
||||
@@ -27,7 +27,7 @@ spec:
|
||||
mountPath: /data
|
||||
containers:
|
||||
- name: web
|
||||
image: git.baumann.gr/adebaumann/labhelper:0.076
|
||||
image: git.baumann.gr/adebaumann/labhelper:0.083
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 8000
|
||||
@@ -92,6 +92,21 @@ spec:
|
||||
configMapKeyRef:
|
||||
name: django-config
|
||||
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
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
@@ -102,6 +117,11 @@ spec:
|
||||
configMapKeyRef:
|
||||
name: django-config
|
||||
key: LOGOUT_REDIRECT_URL
|
||||
- name: OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: django-config
|
||||
key: OIDC_AUTHENTICATION_FAILURE_REDIRECT_URL
|
||||
- name: GUNICORN_OPTS
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
@@ -117,7 +137,7 @@ spec:
|
||||
mountPath: /app/data
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
path: /health/
|
||||
port: 8000
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
@@ -125,7 +145,7 @@ spec:
|
||||
failureThreshold: 6
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
path: /health/
|
||||
port: 8000
|
||||
initialDelaySeconds: 20
|
||||
periodSeconds: 20
|
||||
|
||||
@@ -5,13 +5,6 @@ metadata:
|
||||
namespace: labhelper
|
||||
annotations:
|
||||
argocd.argoproj.io/ignore-healthcheck: "true"
|
||||
gethomepage.dev/enabled: "true"
|
||||
gethomepage.dev/name: "Labhelper"
|
||||
gethomepage.dev/description: "Laboratory inventory system"
|
||||
gethomepage.dev/group: "Kubernetes"
|
||||
gethomepage.dev/icon: "shield.png"
|
||||
gethomepage.dev/href: "https://labhelper.adebaumann.com"
|
||||
gethomepage.dev/ping: "https://labhelper.adebaumann.com"
|
||||
spec:
|
||||
ingressClassName: traefik
|
||||
rules:
|
||||
|
||||
31
boxes/decorators.py
Normal file
31
boxes/decorators.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import functools
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
def conditional_login_required(view_func):
|
||||
"""Skip login_required if client IP is in ALLOWED_CIDR_NETS."""
|
||||
|
||||
@functools.wraps(view_func)
|
||||
def wrapper(request, *args, **kwargs):
|
||||
# Get client IP
|
||||
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
|
||||
if x_forwarded_for:
|
||||
ip = x_forwarded_for.split(",")[0].strip()
|
||||
else:
|
||||
ip = request.META.get("REMOTE_ADDR", "")
|
||||
|
||||
# Check if IP is in allowed networks
|
||||
from ipaddress import ip_address, ip_network
|
||||
|
||||
client_ip = ip_address(ip)
|
||||
for net in getattr(settings, "ALLOWED_CIDR_NETS", []):
|
||||
if client_ip in ip_network(net, strict=False):
|
||||
return view_func(request, *args, **kwargs)
|
||||
|
||||
# Fall back to login_required
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
return login_required(view_func)(request, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
@@ -284,6 +284,16 @@
|
||||
</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 %}
|
||||
|
||||
{% 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;">
|
||||
<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;">
|
||||
<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>
|
||||
</div>
|
||||
<i class="fas fa-expand lightbox-trigger" data-url="{{ file.file.url }}" style="color: #999; font-size: 14px; cursor: pointer;"></i>
|
||||
|
||||
398
boxes/views.py
398
boxes/views.py
@@ -1,7 +1,7 @@
|
||||
import bleach
|
||||
import markdown
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from boxes.decorators import conditional_login_required as login_required
|
||||
from django.db.models import Q, Prefetch
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
@@ -18,22 +18,27 @@ from .forms import (
|
||||
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):
|
||||
"""Convert Markdown to plain text and truncate."""
|
||||
if not text:
|
||||
return ''
|
||||
return ""
|
||||
html = markdown.markdown(text)
|
||||
plain_text = bleach.clean(html, tags=[], strip=True)
|
||||
plain_text = ' '.join(plain_text.split())
|
||||
plain_text = " ".join(plain_text.split())
|
||||
if len(plain_text) > max_length:
|
||||
return plain_text[:max_length].rsplit(' ', 1)[0] + '...'
|
||||
return plain_text[:max_length].rsplit(" ", 1)[0] + "..."
|
||||
return plain_text
|
||||
|
||||
|
||||
@login_required
|
||||
def index(request):
|
||||
"""Home page with search and tags."""
|
||||
facets = Facet.objects.all().prefetch_related('tags')
|
||||
facets = Facet.objects.all().prefetch_related("tags")
|
||||
|
||||
facet_tag_counts = {}
|
||||
for facet in facets:
|
||||
@@ -44,95 +49,107 @@ def index(request):
|
||||
facet_tag_counts[facet] = []
|
||||
facet_tag_counts[facet].append((tag, count))
|
||||
|
||||
return render(request, 'boxes/index.html', {
|
||||
'facets': facets,
|
||||
'facet_tag_counts': facet_tag_counts,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/index.html",
|
||||
{
|
||||
"facets": facets,
|
||||
"facet_tag_counts": facet_tag_counts,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def box_detail(request, box_id):
|
||||
"""Display contents of a box."""
|
||||
box = get_object_or_404(Box, pk=box_id)
|
||||
things = box.things.prefetch_related('tags').all()
|
||||
return render(request, 'boxes/box_detail.html', {
|
||||
'box': box,
|
||||
'things': things,
|
||||
})
|
||||
things = box.things.prefetch_related("tags").all()
|
||||
return render(
|
||||
request,
|
||||
"boxes/box_detail.html",
|
||||
{
|
||||
"box": box,
|
||||
"things": things,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def thing_detail(request, thing_id):
|
||||
"""Display details of a thing (read-only)."""
|
||||
thing = get_object_or_404(
|
||||
Thing.objects.select_related('box', 'box__box_type').prefetch_related('files', 'links', 'tags'),
|
||||
pk=thing_id
|
||||
Thing.objects.select_related("box", "box__box_type").prefetch_related(
|
||||
"files", "links", "tags"
|
||||
),
|
||||
pk=thing_id,
|
||||
)
|
||||
return render(request, 'boxes/thing_detail.html', {'thing': thing})
|
||||
return render(request, "boxes/thing_detail.html", {"thing": thing})
|
||||
|
||||
|
||||
@login_required
|
||||
def edit_thing(request, thing_id):
|
||||
"""Edit a thing's details."""
|
||||
thing = get_object_or_404(
|
||||
Thing.objects.select_related('box', 'box__box_type').prefetch_related('files', 'links', 'tags'),
|
||||
pk=thing_id
|
||||
Thing.objects.select_related("box", "box__box_type").prefetch_related(
|
||||
"files", "links", "tags"
|
||||
),
|
||||
pk=thing_id,
|
||||
)
|
||||
|
||||
boxes = Box.objects.select_related('box_type').all()
|
||||
facets = Facet.objects.all().prefetch_related('tags')
|
||||
boxes = Box.objects.select_related("box_type").all()
|
||||
facets = Facet.objects.all().prefetch_related("tags")
|
||||
picture_form = ThingPictureForm(instance=thing)
|
||||
file_form = ThingFileForm()
|
||||
link_form = ThingLinkForm()
|
||||
|
||||
if request.method == 'POST':
|
||||
action = request.POST.get('action')
|
||||
if request.method == "POST":
|
||||
action = request.POST.get("action")
|
||||
|
||||
if action == 'save_details':
|
||||
if action == "save_details":
|
||||
form = ThingForm(request.POST, request.FILES, instance=thing)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect('thing_detail', thing_id=thing.id)
|
||||
return redirect("thing_detail", thing_id=thing.id)
|
||||
|
||||
elif action == 'move':
|
||||
new_box_id = request.POST.get('new_box')
|
||||
elif action == "move":
|
||||
new_box_id = request.POST.get("new_box")
|
||||
if new_box_id:
|
||||
new_box = get_object_or_404(Box, pk=new_box_id)
|
||||
thing.box = new_box
|
||||
thing.save()
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'upload_picture':
|
||||
elif action == "upload_picture":
|
||||
picture_form = ThingPictureForm(request.POST, request.FILES, instance=thing)
|
||||
if picture_form.is_valid():
|
||||
picture_form.save()
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'delete_picture':
|
||||
elif action == "delete_picture":
|
||||
if thing.picture:
|
||||
thing.picture.delete()
|
||||
thing.picture = None
|
||||
thing.save()
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'add_file':
|
||||
elif action == "add_file":
|
||||
file_form = ThingFileForm(request.POST, request.FILES)
|
||||
if file_form.is_valid():
|
||||
thing_file = file_form.save(commit=False)
|
||||
thing_file.thing = thing
|
||||
thing_file.save()
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'add_link':
|
||||
elif action == "add_link":
|
||||
link_form = ThingLinkForm(request.POST)
|
||||
if link_form.is_valid():
|
||||
thing_link = link_form.save(commit=False)
|
||||
thing_link.thing = thing
|
||||
thing_link.save()
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'delete_file':
|
||||
file_id = request.POST.get('file_id')
|
||||
elif action == "delete_file":
|
||||
file_id = request.POST.get("file_id")
|
||||
if file_id:
|
||||
try:
|
||||
thing_file = ThingFile.objects.get(pk=file_id, thing=thing)
|
||||
@@ -140,20 +157,20 @@ def edit_thing(request, thing_id):
|
||||
thing_file.delete()
|
||||
except ThingFile.DoesNotExist:
|
||||
pass
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'delete_link':
|
||||
link_id = request.POST.get('link_id')
|
||||
elif action == "delete_link":
|
||||
link_id = request.POST.get("link_id")
|
||||
if link_id:
|
||||
try:
|
||||
thing_link = ThingLink.objects.get(pk=link_id, thing=thing)
|
||||
thing_link.delete()
|
||||
except ThingLink.DoesNotExist:
|
||||
pass
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'add_tag':
|
||||
tag_id = request.POST.get('tag_id')
|
||||
elif action == "add_tag":
|
||||
tag_id = request.POST.get("tag_id")
|
||||
if tag_id:
|
||||
try:
|
||||
tag = Tag.objects.get(pk=tag_id)
|
||||
@@ -164,102 +181,120 @@ def edit_thing(request, thing_id):
|
||||
thing.tags.add(tag)
|
||||
except Tag.DoesNotExist:
|
||||
pass
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
elif action == 'remove_tag':
|
||||
tag_id = request.POST.get('tag_id')
|
||||
elif action == "remove_tag":
|
||||
tag_id = request.POST.get("tag_id")
|
||||
if tag_id:
|
||||
try:
|
||||
tag = Tag.objects.get(pk=tag_id)
|
||||
thing.tags.remove(tag)
|
||||
except Tag.DoesNotExist:
|
||||
pass
|
||||
return redirect('edit_thing', thing_id=thing.id)
|
||||
return redirect("edit_thing", thing_id=thing.id)
|
||||
|
||||
thing_form = ThingForm(instance=thing)
|
||||
|
||||
return render(request, 'boxes/edit_thing.html', {
|
||||
'thing': thing,
|
||||
'boxes': boxes,
|
||||
'facets': facets,
|
||||
'picture_form': picture_form,
|
||||
'file_form': file_form,
|
||||
'link_form': link_form,
|
||||
'thing_form': thing_form,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/edit_thing.html",
|
||||
{
|
||||
"thing": thing,
|
||||
"boxes": boxes,
|
||||
"facets": facets,
|
||||
"picture_form": picture_form,
|
||||
"file_form": file_form,
|
||||
"link_form": link_form,
|
||||
"thing_form": thing_form,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def boxes_list(request):
|
||||
"""Boxes list page showing all boxes with contents."""
|
||||
boxes = Box.objects.select_related('box_type').prefetch_related('things').all()
|
||||
return render(request, 'boxes/boxes_list.html', {
|
||||
'boxes': boxes,
|
||||
})
|
||||
boxes = Box.objects.select_related("box_type").prefetch_related("things").all()
|
||||
return render(
|
||||
request,
|
||||
"boxes/boxes_list.html",
|
||||
{
|
||||
"boxes": boxes,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def search_api(request):
|
||||
"""AJAX endpoint for searching things."""
|
||||
query = request.GET.get('q', '').strip()
|
||||
query = request.GET.get("q", "").strip()
|
||||
if len(query) < 2:
|
||||
return JsonResponse({'results': []})
|
||||
return JsonResponse({"results": []})
|
||||
|
||||
# Check for "Facet:Word" format
|
||||
if ':' in query:
|
||||
parts = query.split(':',1)
|
||||
if ":" in query:
|
||||
parts = query.split(":", 1)
|
||||
facet_name = parts[0].strip()
|
||||
tag_name = parts[1].strip()
|
||||
|
||||
# Search for things with specific facet and tag
|
||||
things = Thing.objects.filter(
|
||||
Q(tags__facet__name__icontains=facet_name) &
|
||||
Q(tags__name__icontains=tag_name)
|
||||
).prefetch_related('files', 'links', 'tags').select_related('box').distinct()[:50]
|
||||
things = (
|
||||
Thing.objects.filter(
|
||||
Q(tags__facet__name__icontains=facet_name)
|
||||
& Q(tags__name__icontains=tag_name)
|
||||
)
|
||||
.prefetch_related("files", "links", "tags")
|
||||
.select_related("box")
|
||||
.distinct()[:50]
|
||||
)
|
||||
else:
|
||||
# Normal search
|
||||
things = Thing.objects.filter(
|
||||
Q(name__icontains=query) |
|
||||
Q(description__icontains=query) |
|
||||
Q(files__title__icontains=query) |
|
||||
Q(files__file__icontains=query) |
|
||||
Q(links__title__icontains=query) |
|
||||
Q(links__url__icontains=query) |
|
||||
Q(tags__name__icontains=query) |
|
||||
Q(tags__facet__name__icontains=query)
|
||||
).prefetch_related('files', 'links', 'tags').select_related('box').distinct()[:50]
|
||||
things = (
|
||||
Thing.objects.filter(
|
||||
Q(name__icontains=query)
|
||||
| Q(description__icontains=query)
|
||||
| Q(files__title__icontains=query)
|
||||
| Q(files__file__icontains=query)
|
||||
| Q(links__title__icontains=query)
|
||||
| Q(links__url__icontains=query)
|
||||
| Q(tags__name__icontains=query)
|
||||
| Q(tags__facet__name__icontains=query)
|
||||
)
|
||||
.prefetch_related("files", "links", "tags")
|
||||
.select_related("box")
|
||||
.distinct()[:50]
|
||||
)
|
||||
|
||||
results = [
|
||||
{
|
||||
'id': thing.id,
|
||||
'name': thing.name,
|
||||
'box': thing.box.id,
|
||||
'description': _strip_markdown(thing.description),
|
||||
'tags': [
|
||||
"id": thing.id,
|
||||
"name": thing.name,
|
||||
"box": thing.box.id,
|
||||
"description": _strip_markdown(thing.description),
|
||||
"tags": [
|
||||
{
|
||||
'name': tag.name,
|
||||
'color': tag.facet.color,
|
||||
"name": tag.name,
|
||||
"color": tag.facet.color,
|
||||
}
|
||||
for tag in thing.tags.all()
|
||||
],
|
||||
'files': [
|
||||
"files": [
|
||||
{
|
||||
'title': f.title,
|
||||
'filename': f.filename(),
|
||||
"title": f.title,
|
||||
"filename": f.filename(),
|
||||
}
|
||||
for f in thing.files.all()
|
||||
],
|
||||
'links': [
|
||||
"links": [
|
||||
{
|
||||
'title': l.title,
|
||||
'url': l.url,
|
||||
"title": l.title,
|
||||
"url": l.url,
|
||||
}
|
||||
for l in thing.links.all()
|
||||
],
|
||||
}
|
||||
for thing in things
|
||||
]
|
||||
return JsonResponse({'results': results})
|
||||
return JsonResponse({"results": results})
|
||||
|
||||
|
||||
@login_required
|
||||
@@ -269,8 +304,10 @@ def add_things(request, box_id):
|
||||
|
||||
success_message = None
|
||||
|
||||
if request.method == 'POST':
|
||||
formset = ThingFormSet(request.POST, request.FILES, queryset=Thing.objects.filter(box=box))
|
||||
if request.method == "POST":
|
||||
formset = ThingFormSet(
|
||||
request.POST, request.FILES, queryset=Thing.objects.filter(box=box)
|
||||
)
|
||||
|
||||
if formset.is_valid():
|
||||
things = formset.save(commit=False)
|
||||
@@ -281,152 +318,189 @@ def add_things(request, box_id):
|
||||
thing.save()
|
||||
created_count += 1
|
||||
if created_count > 0:
|
||||
success_message = f'Added {created_count} thing{"s" if created_count > 1 else ""} successfully.'
|
||||
success_message = f"Added {created_count} thing{'s' if created_count > 1 else ''} successfully."
|
||||
formset = ThingFormSet(queryset=Thing.objects.filter(box=box))
|
||||
else:
|
||||
formset = ThingFormSet(queryset=Thing.objects.filter(box=box))
|
||||
|
||||
return render(request, 'boxes/add_things.html', {
|
||||
'box': box,
|
||||
'formset': formset,
|
||||
'success_message': success_message,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/add_things.html",
|
||||
{
|
||||
"box": box,
|
||||
"formset": formset,
|
||||
"success_message": success_message,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def box_management(request):
|
||||
"""Main page for managing boxes and box types."""
|
||||
box_types = BoxType.objects.all().prefetch_related('boxes')
|
||||
boxes = Box.objects.select_related('box_type').all().prefetch_related('things')
|
||||
box_types = BoxType.objects.all().prefetch_related("boxes")
|
||||
boxes = Box.objects.select_related("box_type").all().prefetch_related("things")
|
||||
box_type_form = BoxTypeForm()
|
||||
box_form = BoxForm()
|
||||
|
||||
return render(request, 'boxes/box_management.html', {
|
||||
'box_types': box_types,
|
||||
'boxes': boxes,
|
||||
'box_type_form': box_type_form,
|
||||
'box_form': box_form,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/box_management.html",
|
||||
{
|
||||
"box_types": box_types,
|
||||
"boxes": boxes,
|
||||
"box_type_form": box_type_form,
|
||||
"box_form": box_form,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def add_box_type(request):
|
||||
"""Add a new box type."""
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
form = BoxTypeForm(request.POST)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
|
||||
|
||||
@login_required
|
||||
def edit_box_type(request, type_id):
|
||||
"""Edit an existing box type."""
|
||||
box_type = get_object_or_404(BoxType, pk=type_id)
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
form = BoxTypeForm(request.POST, instance=box_type)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_box_type(request, type_id):
|
||||
"""Delete a box type."""
|
||||
box_type = get_object_or_404(BoxType, pk=type_id)
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
if box_type.boxes.exists():
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
box_type.delete()
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
|
||||
|
||||
@login_required
|
||||
def add_box(request):
|
||||
"""Add a new box."""
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
form = BoxForm(request.POST)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
|
||||
|
||||
@login_required
|
||||
def edit_box(request, box_id):
|
||||
"""Edit an existing box."""
|
||||
box = get_object_or_404(Box, pk=box_id)
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
form = BoxForm(request.POST, instance=box)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_box(request, box_id):
|
||||
"""Delete a box."""
|
||||
box = get_object_or_404(Box, pk=box_id)
|
||||
if request.method == 'POST':
|
||||
if request.method == "POST":
|
||||
if box.things.exists():
|
||||
return redirect('box_management')
|
||||
return redirect("box_management")
|
||||
box.delete()
|
||||
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
|
||||
def resources_list(request):
|
||||
"""List all links and files from things that have them."""
|
||||
things_with_files = Thing.objects.filter(files__isnull=False).prefetch_related('files').distinct()
|
||||
things_with_links = Thing.objects.filter(links__isnull=False).prefetch_related('links').distinct()
|
||||
things_with_files = (
|
||||
Thing.objects.filter(files__isnull=False).prefetch_related("files").distinct()
|
||||
)
|
||||
things_with_links = (
|
||||
Thing.objects.filter(links__isnull=False).prefetch_related("links").distinct()
|
||||
)
|
||||
|
||||
all_things = (things_with_files | things_with_links).distinct().order_by('name')
|
||||
all_things = (things_with_files | things_with_links).distinct().order_by("name")
|
||||
|
||||
resources = []
|
||||
for thing in all_things.prefetch_related('files', 'links'):
|
||||
for thing in all_things.prefetch_related("files", "links"):
|
||||
for file in thing.files.all():
|
||||
resources.append({
|
||||
'type': 'file',
|
||||
'thing_name': thing.name,
|
||||
'thing_id': thing.id,
|
||||
'title': file.title,
|
||||
'url': file.file.url,
|
||||
})
|
||||
resources.append(
|
||||
{
|
||||
"type": "file",
|
||||
"thing_name": thing.name,
|
||||
"thing_id": thing.id,
|
||||
"title": file.title,
|
||||
"url": file.file.url,
|
||||
}
|
||||
)
|
||||
for link in thing.links.all():
|
||||
resources.append({
|
||||
'type': 'link',
|
||||
'thing_name': thing.name,
|
||||
'thing_id': thing.id,
|
||||
'title': link.title,
|
||||
'url': link.url,
|
||||
})
|
||||
resources.append(
|
||||
{
|
||||
"type": "link",
|
||||
"thing_name": thing.name,
|
||||
"thing_id": thing.id,
|
||||
"title": link.title,
|
||||
"url": link.url,
|
||||
}
|
||||
)
|
||||
|
||||
return render(request, 'boxes/resources_list.html', {
|
||||
'resources': resources,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/resources_list.html",
|
||||
{
|
||||
"resources": resources,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def fixme(request):
|
||||
"""Page to find and fix things missing tags for specific facets."""
|
||||
facets = Facet.objects.all().prefetch_related('tags')
|
||||
facets = Facet.objects.all().prefetch_related("tags")
|
||||
|
||||
selected_facet = None
|
||||
missing_things = []
|
||||
|
||||
if request.method == 'GET' and 'facet_id' in request.GET:
|
||||
if request.method == "GET" and "facet_id" in request.GET:
|
||||
try:
|
||||
selected_facet = Facet.objects.get(pk=request.GET['facet_id'])
|
||||
selected_facet = Facet.objects.get(pk=request.GET["facet_id"])
|
||||
# Find things that don't have any tag from this facet
|
||||
missing_things = Thing.objects.exclude(
|
||||
tags__facet=selected_facet
|
||||
).select_related('box', 'box__box_type').prefetch_related('tags')
|
||||
missing_things = (
|
||||
Thing.objects.exclude(tags__facet=selected_facet)
|
||||
.select_related("box", "box__box_type")
|
||||
.prefetch_related("tags")
|
||||
)
|
||||
except Facet.DoesNotExist:
|
||||
selected_facet = None
|
||||
|
||||
elif request.method == 'POST':
|
||||
facet_id = request.POST.get('facet_id')
|
||||
tag_ids = request.POST.getlist('tag_ids')
|
||||
thing_ids = request.POST.getlist('thing_ids')
|
||||
elif request.method == "POST":
|
||||
facet_id = request.POST.get("facet_id")
|
||||
tag_ids = request.POST.getlist("tag_ids")
|
||||
thing_ids = request.POST.getlist("thing_ids")
|
||||
|
||||
if facet_id and tag_ids and thing_ids:
|
||||
facet = get_object_or_404(Facet, pk=facet_id)
|
||||
@@ -442,10 +516,14 @@ def fixme(request):
|
||||
if tag.facet == facet:
|
||||
thing.tags.add(tag)
|
||||
|
||||
return redirect('fixme')
|
||||
return redirect("fixme")
|
||||
|
||||
return render(request, 'boxes/fixme.html', {
|
||||
'facets': facets,
|
||||
'selected_facet': selected_facet,
|
||||
'missing_things': missing_things,
|
||||
})
|
||||
return render(
|
||||
request,
|
||||
"boxes/fixme.html",
|
||||
{
|
||||
"facets": facets,
|
||||
"selected_facet": selected_facet,
|
||||
"missing_things": missing_things,
|
||||
},
|
||||
)
|
||||
|
||||
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...')
|
||||
|
||||
groups = {
|
||||
'Lab Administrators': 'Full access to all lab functions',
|
||||
'Lab Staff': 'Can view and search items, add things to boxes',
|
||||
'Lab Viewers': 'Read-only access to view and search',
|
||||
'LabHelper Administrators': 'Full access to all lab functions',
|
||||
'LabHelper Staff': 'Can view and search items, add things to boxes',
|
||||
'LabHelper Viewers': 'Read-only access to view and search',
|
||||
}
|
||||
|
||||
for group_name, description in groups.items():
|
||||
@@ -22,9 +22,9 @@ class Command(BaseCommand):
|
||||
self.stdout.write(f'Group already exists: {group_name}')
|
||||
|
||||
users = {
|
||||
'admin': ('Lab Administrators', True),
|
||||
'staff': ('Lab Staff', False),
|
||||
'viewer': ('Lab Viewers', False),
|
||||
'admin': ('LabHelper Administrators', True),
|
||||
'staff': ('LabHelper Staff', False),
|
||||
'viewer': ('LabHelper Viewers', False),
|
||||
}
|
||||
|
||||
for username, (group_name, is_superuser) in users.items():
|
||||
|
||||
@@ -21,69 +21,76 @@ BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'f0arjg8q3ut4iuqrguqfjaruf0eripIZZN3t1kymy8ugqnj$li2knhha0@gc5v8f3bge=$+gbybj2$jt28uqm')
|
||||
SECRET_KEY = os.environ.get(
|
||||
"DJANGO_SECRET_KEY",
|
||||
"f0arjg8q3ut4iuqrguqfjaruf0eripIZZN3t1kymy8ugqnj$li2knhha0@gc5v8f3bge=$+gbybj2$jt28uqm",
|
||||
)
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = os.environ.get('DEBUG', 'True').lower() == 'true'
|
||||
DEBUG = os.environ.get("DEBUG", "True").lower() == "true"
|
||||
|
||||
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '*').split(',')
|
||||
ALLOWED_CIDR_NETS = os.environ.get('ALLOWED_CIDR_NETS', '10.0.0.0/16').split(',')
|
||||
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split(",")
|
||||
ALLOWED_CIDR_NETS = os.environ.get(
|
||||
"ALLOWED_CIDR_NETS", "10.0.0.0/16,192.168.0.0/16"
|
||||
).split(",")
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'mptt',
|
||||
'django_mptt_admin',
|
||||
'sorl.thumbnail',
|
||||
'boxes',
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
"mozilla_django_oidc",
|
||||
"mptt",
|
||||
"django_mptt_admin",
|
||||
"sorl.thumbnail",
|
||||
"boxes",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'whitenoise.middleware.WhiteNoiseMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"mozilla_django_oidc.middleware.SessionRefresh",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'labhelper.urls'
|
||||
ROOT_URLCONF = "labhelper.urls"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [BASE_DIR / 'labhelper' / 'templates'],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
'labhelper.context_processors.image_tag',
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [BASE_DIR / "labhelper" / "templates"],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
"labhelper.context_processors.image_tag",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'labhelper.wsgi.application'
|
||||
WSGI_APPLICATION = "labhelper.wsgi.application"
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'data' / 'db.sqlite3',
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": BASE_DIR / "data" / "db.sqlite3",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,16 +100,16 @@ DATABASES = {
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
|
||||
},
|
||||
]
|
||||
|
||||
@@ -110,35 +117,90 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = os.environ.get('LANGUAGE_CODE', 'en-us')
|
||||
LANGUAGE_CODE = os.environ.get("LANGUAGE_CODE", "en-us")
|
||||
|
||||
TIME_ZONE = os.environ.get('TIME_ZONE', 'UTC')
|
||||
TIME_ZONE = os.environ.get("TIME_ZONE", "UTC")
|
||||
|
||||
USE_I18N = os.environ.get('USE_I18N', 'True').lower() == 'true'
|
||||
USE_I18N = os.environ.get("USE_I18N", "True").lower() == "true"
|
||||
|
||||
USE_TZ = os.environ.get('USE_TZ', 'True').lower() == 'true'
|
||||
USE_TZ = os.environ.get("USE_TZ", "True").lower() == "true"
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
||||
|
||||
STATIC_URL = os.environ.get('STATIC_URL', '/static/')
|
||||
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
||||
STATIC_URL = os.environ.get("STATIC_URL", "/static/")
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
|
||||
# WhiteNoise static file serving configuration
|
||||
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
||||
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
|
||||
|
||||
# Media files (user uploads)
|
||||
MEDIA_URL = os.environ.get('MEDIA_URL', '/media/')
|
||||
MEDIA_ROOT = BASE_DIR / 'data' / 'media'
|
||||
MEDIA_URL = os.environ.get("MEDIA_URL", "/media/")
|
||||
MEDIA_ROOT = BASE_DIR / "data" / "media"
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
||||
|
||||
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_REDIRECT_URL = os.environ.get('LOGIN_REDIRECT_URL', 'index')
|
||||
LOGOUT_REDIRECT_URL = os.environ.get('LOGOUT_REDIRECT_URL', 'login')
|
||||
LOGIN_URL = os.environ.get("LOGIN_URL", "oidc_authentication_init")
|
||||
LOGIN_REDIRECT_URL = os.environ.get("LOGIN_REDIRECT_URL", "index")
|
||||
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 and media files from the session-refresh middleware redirect
|
||||
import re
|
||||
|
||||
OIDC_EXEMPT_URLS = ["search_api", "health_check", re.compile(r"^/media/")]
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
<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="/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 %}
|
||||
</form>
|
||||
<a href="#" onclick="document.getElementById('logout-form').submit(); return false;">
|
||||
|
||||
@@ -9,70 +9,24 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="section" style="max-width: 500px; margin: 0 auto;">
|
||||
{% if form.errors %}
|
||||
<div class="alert alert-error">
|
||||
<i class="fas fa-exclamation-circle"></i> Your username and password didn't match. Please try again.
|
||||
<div class="section" style="max-width: 500px; margin: 0 auto; text-align: center;">
|
||||
{% if request.GET.next and user.is_authenticated %}
|
||||
<div class="alert alert-error" style="margin-bottom: 24px;">
|
||||
<i class="fas fa-info-circle"></i> Your account doesn't have access to this page.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% 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">
|
||||
{% elif request.GET.next %}
|
||||
<div class="alert alert-error" style="margin-bottom: 24px;">
|
||||
<i class="fas fa-info-circle"></i> Please login to see this page.
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="{% url 'login' %}" style="display: flex; flex-direction: column; gap: 20px;">
|
||||
{% csrf_token %}
|
||||
<p style="color: #555; margin-bottom: 28px;">
|
||||
Authentication is handled via Single Sign-On. Click below to continue to the login page.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<label for="{{ form.username.id_for_label }}" style="display: block; font-weight: 600; margin-bottom: 8px; color: #555;">
|
||||
<i class="fas fa-user"></i> Username
|
||||
</label>
|
||||
<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>
|
||||
<a href="{% url 'oidc_authentication_init' %}{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}"
|
||||
class="btn" style="justify-content: center; display: inline-flex;">
|
||||
<i class="fas fa-sign-in-alt"></i> Login with SSO
|
||||
</a>
|
||||
</div>
|
||||
{% 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.urls.static import static
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.urls import include, path
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from boxes.views import (
|
||||
add_box,
|
||||
@@ -29,10 +29,12 @@ from boxes.views import (
|
||||
boxes_list,
|
||||
delete_box,
|
||||
delete_box_type,
|
||||
delete_thing,
|
||||
edit_box,
|
||||
edit_box_type,
|
||||
edit_thing,
|
||||
fixme,
|
||||
health_check,
|
||||
index,
|
||||
resources_list,
|
||||
search_api,
|
||||
@@ -40,8 +42,9 @@ from boxes.views import (
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
|
||||
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
|
||||
path('oidc/', include('mozilla_django_oidc.urls')),
|
||||
path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
|
||||
path('health/', health_check, name='health_check'),
|
||||
path('', index, name='index'),
|
||||
path('box-management/', box_management, name='box_management'),
|
||||
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('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>/delete/', delete_thing, name='delete_thing'),
|
||||
path('box/<str:box_id>/add/', add_things, name='add_things'),
|
||||
path('boxes/', boxes_list, name='boxes_list'),
|
||||
path('inventory/', boxes_list, name='inventory'),
|
||||
|
||||
@@ -37,3 +37,4 @@ sorl-thumbnail==12.11.0
|
||||
bleach==6.1.0
|
||||
coverage==7.6.1
|
||||
whitenoise==6.8.2
|
||||
mozilla-django-oidc==4.0.1
|
||||
|
||||
Reference in New Issue
Block a user