TISbackup/libtisbackup/auth/base.py
k3nny f12d89f3da feat(auth): add pluggable authentication system for Flask routes
Implement comprehensive authentication system with support for
Basic Auth, Flask-Login, and OAuth2 providers.

Features:
- Pluggable architecture via factory pattern
- Multiple authentication providers:
  * None: No authentication (development/testing)
  * Basic Auth: HTTP Basic with bcrypt support
  * Flask-Login: Session-based with multiple users
  * OAuth2: Google, GitHub, GitLab, and generic providers
- Decorator-based route protection (@auth.require_auth)
- User authorization by domain or email (OAuth)
- bcrypt password hashing support
- Comprehensive documentation and examples

Components:
- libtisbackup/auth/__init__.py: Factory function and exports
- libtisbackup/auth/base.py: Base provider interface
- libtisbackup/auth/basic_auth.py: HTTP Basic Auth implementation
- libtisbackup/auth/flask_login_auth.py: Flask-Login implementation
- libtisbackup/auth/oauth_auth.py: OAuth2 implementation
- libtisbackup/auth/example_integration.py: Integration examples
- libtisbackup/auth/README.md: API reference and examples

Documentation:
- AUTHENTICATION.md: Complete authentication guide
  * Setup instructions for each provider
  * Configuration examples
  * Security best practices
  * Troubleshooting guide
  * Migration guide
- samples/auth-config-examples.ini: Configuration templates

Dependencies:
- Add optional dependencies in pyproject.toml:
  * auth-basic: bcrypt>=4.0.0
  * auth-login: flask-login>=0.6.0, bcrypt>=4.0.0
  * auth-oauth: authlib>=1.3.0, requests>=2.32.0
  * auth-all: All auth providers

Installation:
```bash
# Install specific provider
uv sync --extra auth-basic

# Install all providers
uv sync --extra auth-all
```

Usage:
```python
from libtisbackup.auth import get_auth_provider

# Initialize
auth = get_auth_provider("basic", {
    "username": "admin",
    "password": "$2b$12$...",
    "use_bcrypt": True
})
auth.init_app(app)

# Protect routes
@app.route("/")
@auth.require_auth
def index():
    user = auth.get_current_user()
    return f"Hello {user['username']}"
```

Security features:
- bcrypt password hashing (work factor 12)
- OAuth domain/user restrictions
- Session-based authentication
- Clear separation of concerns
- Environment variable support for secrets

OAuth providers supported:
- Google (OpenID Connect)
- GitHub
- GitLab
- Generic OAuth2 provider

Breaking change: None - new feature, backward compatible
Users can continue without authentication (type=none)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-05 02:02:46 +02:00

75 lines
1.7 KiB
Python

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Base authentication provider interface
"""
from abc import ABC, abstractmethod
from functools import wraps
class AuthProvider(ABC):
"""Base class for authentication providers."""
def __init__(self, config):
"""Initialize the auth provider.
Args:
config: Dict with provider-specific configuration
"""
self.config = config
def init_app(self, app):
"""Initialize the provider with Flask app.
Args:
app: Flask application instance
"""
pass
def require_auth(self, f):
"""Decorator to require authentication for a route.
Args:
f: Flask route function
Returns:
Decorated function
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not self.is_authenticated():
return self.handle_unauthorized()
return f(*args, **kwargs)
return decorated_function
def is_authenticated(self):
"""Check if current request is authenticated.
Returns:
bool: True if authenticated, False otherwise
"""
# Default: no authentication required
return True
def handle_unauthorized(self):
"""Handle unauthorized access.
Returns:
Flask response for unauthorized access
"""
from flask import jsonify
return jsonify({"error": "Unauthorized"}), 401
def get_current_user(self):
"""Get current authenticated user.
Returns:
User object or dict, or None if not authenticated
"""
return None
def logout(self):
"""Logout current user."""
pass