feat: Add authentication configuration and validation

- Introduced new authentication settings in config.py including `auth_enabled`, `admin_username`, `admin_password`, and `session_secret`.
- Added validation for `session_secret` to ensure it meets security requirements when authentication is enabled.
- Updated main.py to conditionally mount static files and log warnings if the directory is not found.
- Removed unused email template files and added new authentication and notification setup documentation.
- Implemented authentication configuration validation in validators.py and updated settings display.
- Enhanced the user interface with a new login template and SVG assets for branding.
- Added comprehensive guides for setting up authentication and notifications in the documentation.
This commit is contained in:
Christian Krakau-Louis
2025-04-11 03:44:08 +02:00
parent 05ede35059
commit d79652b494
21 changed files with 785 additions and 181 deletions
+117 -10
View File
@@ -1,10 +1,13 @@
import os
import inspect
import hashlib
from functools import wraps
from authlib.integrations.starlette_client import OAuth
from fastapi import APIRouter, Request, status
from starlette.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
import pathlib
from app.config import settings
@@ -12,7 +15,15 @@ oauth = OAuth()
AUTH_ENABLED = settings.auth_enabled
if AUTH_ENABLED:
# Set up templates for authentication
templates_dir = pathlib.Path(__file__).parents[1] / "frontend" / "templates"
templates = Jinja2Templates(directory=str(templates_dir))
# Configure OAuth provider if credentials are provided
OAUTH_CONFIGURED = False
OAUTH_PROVIDER_NAME = "Single Sign-On"
if AUTH_ENABLED and settings.authentik_client_id and settings.authentik_client_secret:
oauth.register(
name="authentik",
client_id=settings.authentik_client_id,
@@ -20,6 +31,8 @@ if AUTH_ENABLED:
server_metadata_url=settings.authentik_config_url,
client_kwargs={"scope": "openid profile email"},
)
OAUTH_CONFIGURED = True
OAUTH_PROVIDER_NAME = settings.oauth_provider_name or "Authentik SSO"
router = APIRouter()
@@ -46,29 +59,123 @@ def require_login(func):
return wrapper
def get_gravatar_url(email):
"""Generate a Gravatar URL for the given email"""
email = email.lower().strip()
email_hash = hashlib.md5(email.encode('utf-8')).hexdigest()
return f"https://www.gravatar.com/avatar/{email_hash}?d=identicon"
if AUTH_ENABLED:
@router.get("/login")
async def login(request: Request):
redirect_uri = request.url_for("auth")
"""Show login page with appropriate authentication options"""
return templates.TemplateResponse(
"login.html",
{
"request": request,
"error": request.query_params.get("error"),
"message": request.query_params.get("message"),
"show_oauth": OAUTH_CONFIGURED,
"oauth_provider_name": OAUTH_PROVIDER_NAME,
"app_version": settings.version # Changed from app_version to version
}
)
@router.get("/oauth-login")
async def oauth_login(request: Request):
"""Handle OAuth login flow"""
if not OAUTH_CONFIGURED:
return RedirectResponse(
url="/login?error=OAuth+not+configured",
status_code=status.HTTP_302_FOUND
)
redirect_uri = request.url_for("oauth_callback")
return await oauth.authentik.authorize_redirect(request, redirect_uri)
@router.get("/auth")
@router.get("/oauth-callback")
async def oauth_callback(request: Request):
"""Handle OAuth callback from provider"""
try:
token = await oauth.authentik.authorize_access_token(request)
userinfo = token.get("userinfo")
if not userinfo:
return RedirectResponse(
url="/login?error=Failed+to+retrieve+user+information",
status_code=status.HTTP_302_FOUND
)
# Store user info in session
user_data = dict(userinfo)
# Add Gravatar picture if no picture is provided
if not user_data.get("picture") and user_data.get("email"):
user_data["picture"] = get_gravatar_url(user_data["email"])
request.session["user"] = user_data
# Log the successful authentication
print(f"User authenticated via OAuth: {user_data.get('email', 'No email')}")
# Redirect to original destination or default
redirect_url = request.session.pop("redirect_after_login", "/upload")
return RedirectResponse(url=redirect_url)
except Exception as e:
print(f"OAuth authentication error: {str(e)}")
return RedirectResponse(
url=f"/login?error=Authentication+failed:+{str(e)}",
status_code=status.HTTP_302_FOUND
)
@router.post("/auth")
async def auth(request: Request):
token = await oauth.authentik.authorize_access_token(request)
userinfo = token.get("userinfo")
request.session["user"] = dict(userinfo)
redirect_url = request.session.pop("redirect_after_login", "/upload")
return RedirectResponse(url=redirect_url)
"""Handle local username/password authentication"""
form_data = await request.form()
username = form_data.get("username")
password = form_data.get("password")
if (username == settings.admin_username and
password == settings.admin_password):
# Create user session
request.session["user"] = {
"id": "admin",
"name": "Administrator",
"email": f"{username}@local.docuelevate",
"preferred_username": username,
"picture": "/static/images/default-avatar.svg",
"is_admin": True
}
# Redirect to original destination or default
redirect_url = request.session.pop("redirect_after_login", "/upload")
return RedirectResponse(url=redirect_url, status_code=302)
else:
return RedirectResponse(
url="/login?error=Invalid+username+or+password",
status_code=302
)
@router.get("/logout")
async def logout(request: Request):
"""Handle user logout"""
request.session.pop("user", None)
return RedirectResponse(url="/")
return RedirectResponse(
url="/login?message=You+have+been+logged+out+successfully",
status_code=302
)
@router.get("/api/auth/whoami")
@require_login
async def whoami(request: Request):
"""API endpoint to get current user information"""
user = request.session.get("user")
return user or {"error": "Not authenticated"}
@router.get("/private")
@require_login
async def private_page(request: Request):
"""A protected endpoint that requires login."""
user = request.session.get("user") # e.g. {"email": "...", ...}
user = request.session.get("user")
return {"message": "This is a protected page.", "user": user}
+16 -1
View File
@@ -37,11 +37,17 @@ class Settings(BaseSettings):
gotenberg_url: str
external_hostname: str = "localhost" # Default to localhost
# Authentication settings
auth_enabled: bool = True # Default to enabled
admin_username: Optional[str] = None
admin_password: Optional[str] = None
session_secret: Optional[str] = None
# Authentik
authentik_client_id: Optional[str] = None
authentik_client_secret: Optional[str] = None
authentik_config_url: Optional[str] = None
auth_enabled: bool = True # Default to enabled
oauth_provider_name: Optional[str] = None # Name to display for the OAuth provider
# IMAP 1
imap1_host: Optional[str] = None
@@ -162,6 +168,15 @@ class Settings(BaseSettings):
return []
return v
@validator('session_secret')
def validate_session_secret(cls, v, values):
"""Validate that session_secret is set and has sufficient length when auth is enabled"""
if values.get('auth_enabled') and not v:
raise ValueError("SESSION_SECRET must be set when AUTH_ENABLED=True")
if values.get('auth_enabled') and v and len(v) < 32:
raise ValueError("SESSION_SECRET must be at least 32 characters long")
return v
# Get build date from environment or file
@property
def build_date(self) -> str:
+7 -3
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import os
import logging
import pathlib
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.staticfiles import StaticFiles
@@ -43,9 +44,12 @@ app.add_middleware(TrustedHostMiddleware, allowed_hosts=[
"127.0.0.1"
])
# Mount the static folder for CSS/JS:
frontend_static_dir = Path(__file__).parent.parent / "frontend" / "static"
app.mount("/static", StaticFiles(directory=frontend_static_dir), name="static")
# Mount the static files directory
static_dir = pathlib.Path(__file__).parents[1] / "frontend" / "static"
if os.path.exists(static_dir):
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
else:
print(f"WARNING: Static directory not found at {static_dir}. Static files will not be served.")
@app.on_event("startup")
def on_startup():
-2
View File
@@ -1,2 +0,0 @@
# This directory contains email templates
# The .gitkeep file ensures the directory is included in git
-161
View File
@@ -1,161 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document from DocuElevate</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.logo {
max-width: 200px;
margin-bottom: 15px;
}
.container {
background-color: #f9f9f9;
border-radius: 8px;
padding: 25px;
border: 1px solid #e0e0e0;
}
.footer {
margin-top: 30px;
font-size: 12px;
color: #666;
text-align: center;
border-top: 1px solid #eee;
padding-top: 20px;
}
.button {
display: inline-block;
background-color: #3182ce;
color: white !important;
padding: 10px 20px;
text-decoration: none;
border-radius: 4px;
margin-top: 15px;
text-align: center;
}
.message {
margin-bottom: 20px;
}
.attachment-info {
background-color: #ebf8ff;
border-left: 4px solid #3182ce;
padding: 10px 15px;
margin-bottom: 20px;
}
.metadata-section {
background-color: #f0fff4;
border-left: 4px solid #38a169;
padding: 10px 15px;
margin: 20px 0;
}
.metadata-title {
font-weight: bold;
margin-bottom: 10px;
color: #2f855a;
}
.metadata-table {
width: 100%;
border-collapse: collapse;
}
.metadata-table th, .metadata-table td {
text-align: left;
padding: 8px;
border-bottom: 1px solid #ddd;
}
.metadata-table th {
width: 40%;
color: #4a5568;
}
.metadata-value {
word-break: break-word;
}
.document-type {
display: inline-block;
background-color: #3182ce;
color: white;
padding: 4px 10px;
border-radius: 12px;
font-size: 0.85em;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="header">
{% if has_logo %}
<img src="cid:logo" alt="DocuElevate Logo" class="logo">
{% endif %}
<h1>Document Delivery</h1>
</div>
<div class="container">
<p class="message">
{% if custom_message %}
{{ custom_message }}
{% else %}
A document has been shared with you from DocuElevate.
{% endif %}
</p>
<div class="attachment-info">
<strong>Attached Document:</strong> {{ filename }}
</div>
{% if has_metadata %}
<div class="metadata-section">
<div class="metadata-title">Document Metadata</div>
{% if metadata.document_type %}
<span class="document-type">{{ metadata.document_type }}</span>
{% endif %}
<table class="metadata-table">
{% for key, value in metadata.items() %}
{% if key != "document_type" and value %}
<tr>
<th>{{ key | replace("_", " ") | title }}</th>
<td class="metadata-value">
{% if value is mapping %}
{% for subkey, subvalue in value.items() %}
<strong>{{ subkey | replace("_", " ") | title }}:</strong> {{ subvalue }}<br>
{% endfor %}
{% elif value is iterable and value is not string %}
{{ value | join(", ") }}
{% else %}
{{ value }}
{% endif %}
</td>
</tr>
{% endif %}
{% endfor %}
</table>
</div>
{% endif %}
<p>You can find the attached document in this email. Please let us know if you have any questions.</p>
{% if app_url %}
<p>
<a href="{{ app_url }}" class="button">Visit DocuElevate</a>
</p>
{% endif %}
</div>
<div class="footer">
<p>This is an automated message from DocuElevate Document Processing System.</p>
<p>© {{ now().year }} DocuElevate</p>
</div>
</body>
</html>
+2
View File
@@ -6,6 +6,7 @@ from app.utils.config_validator.validators import (
validate_email_config,
validate_storage_configs,
validate_notification_config,
validate_auth_config,
check_all_configs
)
from app.utils.config_validator.masking import mask_sensitive_value
@@ -19,6 +20,7 @@ __all__ = [
'validate_email_config',
'validate_storage_configs',
'validate_notification_config',
'validate_auth_config',
'mask_sensitive_value',
'get_provider_status',
'get_settings_for_display',
+23
View File
@@ -11,6 +11,29 @@ def get_provider_status():
"""
providers = {}
# Add Authentication configuration
auth_enabled = getattr(settings, 'auth_enabled', False)
using_oidc = bool(getattr(settings, 'authentik_client_id', None) and
getattr(settings, 'authentik_client_secret', None) and
getattr(settings, 'authentik_config_url', None))
auth_method = "OIDC" if using_oidc else "Basic Auth" if auth_enabled else "None"
providers["Authentication"] = {
"name": "Authentication",
"icon": "fa-solid fa-lock",
"configured": bool(auth_enabled and
(getattr(settings, 'admin_username', None) or
using_oidc)),
"enabled": auth_enabled,
"description": "Access control and user authentication",
"details": {
"method": auth_method,
"provider_name": getattr(settings, 'oauth_provider_name', 'Not set') if using_oidc else "N/A",
"session_security": "Configured" if getattr(settings, 'session_secret', None) else "Not configured"
}
}
# Add Notification configuration - Make sure this provider is near the top of the list
providers["Notifications"] = {
"name": "Notifications",
@@ -77,9 +77,13 @@ def get_settings_for_display(show_values=False):
],
"Authentication": [
"auth_enabled",
"session_secret",
"admin_username",
"admin_password",
"authentik_client_id",
"authentik_client_secret",
"authentik_config_url"
"authentik_config_url",
"oauth_provider_name"
],
"Email": [
"email_host",
+37
View File
@@ -33,6 +33,35 @@ def validate_email_config():
return issues
def validate_auth_config():
"""Validates authentication configuration settings"""
issues = []
# If auth is enabled, check for required settings
if getattr(settings, 'auth_enabled', False):
# Check for session secret
if not getattr(settings, 'session_secret', None):
issues.append("SESSION_SECRET is not configured but AUTH_ENABLED is True")
elif len(getattr(settings, 'session_secret', '')) < 32:
issues.append("SESSION_SECRET must be at least 32 characters long")
# Check if using simple authentication or OIDC
using_simple_auth = bool(getattr(settings, 'admin_username', None) and
getattr(settings, 'admin_password', None))
using_oidc = bool(getattr(settings, 'authentik_client_id', None) and
getattr(settings, 'authentik_client_secret', None) and
getattr(settings, 'authentik_config_url', None))
if not using_simple_auth and not using_oidc:
issues.append("Neither simple authentication nor OIDC are properly configured")
# If using OIDC, check for provider name
if using_oidc and not getattr(settings, 'oauth_provider_name', None):
issues.append("OAUTH_PROVIDER_NAME is not configured but OIDC is enabled")
return issues
def validate_storage_configs():
"""Validates configuration for all storage providers"""
issues = {}
@@ -176,6 +205,13 @@ def check_all_configs():
if hasattr(settings, 'debug') and settings.debug:
dump_all_settings()
# Check auth config
auth_issues = validate_auth_config()
if auth_issues:
logger.warning(f"Authentication configuration issues: {', '.join(auth_issues)}")
else:
logger.info("Authentication configuration OK")
# Check email config
email_issues = validate_email_config()
if email_issues:
@@ -200,6 +236,7 @@ def check_all_configs():
# Return all identified issues
return {
'auth': auth_issues,
'email': email_issues,
'storage': storage_issues,
'notification': notification_issues