Skip to main content

Complete authentication system for FastHTML applications with beautiful UI, role-based access control, and session management

Project description

FastHTML-Auth

Complete authentication system for FastHTML applications with built-in admin interface

Drop-in authentication with beautiful UI, role-based access control, and a powerful admin dashboard for user management. No configuration required โ€“ just install and go!

pip install fasthtml-auth

PyPI version Python 3.8+


โญ Key Features

  • ๐Ÿ” Complete Authentication - Login, logout, registration with secure bcrypt hashing
  • ๐Ÿ‘‘ Built-in Admin Interface - Full user management dashboard
  • ๐ŸŒ Google OAuth - Allow users to sign in with their Google account
  • ๐ŸŽจ Beautiful UI - Responsive MonsterUI components, zero custom CSS needed
  • ๐Ÿ›ก๏ธ Role-Based Access - User, Manager, Admin roles with decorators
  • ๐Ÿ“ฑ Mobile Ready - Works perfectly on all devices
  • โšก Zero Config - Works out of the box, customize as needed

๐Ÿš€ Quick Start

Basic Authentication

from fasthtml.common import *
from monsterui.all import *
from fasthtml_auth import AuthManager

# Initialize auth system
auth = AuthManager(db_path="data/app.db")
db = auth.initialize()
beforeware = auth.create_beforeware()

# Create app
app = FastHTML(before=beforeware, hdrs=Theme.blue.headers())
auth.register_routes(app)

@app.route("/")
def dashboard(req):
    user = req.scope['user']  # Automatically available
    return H1(f"Welcome, {user.username}!")

@app.route("/admin")
@auth.require_admin()
def admin_only(req):
    return H1("Admin Area")

serve()

That's it! Your app now has:

  • Login/logout at /auth/login and /auth/logout
  • User registration at /auth/register
  • Profile management at /auth/profile
  • Role-based access control
  • Default admin account: admin / admin123

๐Ÿ‘‘ Built-in Admin Interface

Enable powerful user management with one parameter:

# Add this one parameter to get a complete admin dashboard
auth.register_routes(app, include_admin=True)

Instantly adds:

Feature Route Description
๐Ÿ“Š Admin Dashboard /auth/admin User statistics and quick actions
๐Ÿ‘ฅ User Management /auth/admin/users List, search, filter all users
โž• Create Users /auth/admin/users/create Add users with role assignment
โœ๏ธ Edit Users /auth/admin/users/edit?id={id} Modify details, roles, status
๐Ÿ—‘๏ธ Delete Users /auth/admin/users/delete?id={id} Remove users (with protection)

Admin Interface Features

  • ๐Ÿ” Search & Filter - Find users by username, email, role, or status
  • ๐Ÿ“„ Pagination - Handle thousands of users efficiently
  • ๐Ÿ›ก๏ธ Safety Features - Prevent self-deletion and last admin removal
  • ๐Ÿ“Š Statistics Dashboard - User counts by role and status
  • ๐ŸŽจ Beautiful UI - Consistent MonsterUI design throughout

๐Ÿ“– Real-World Example

See FastHTML-Auth in action with a complete todo application:

๐Ÿ“ FastHTML Todo App

This real-world example shows:

  • User authentication and registration
  • Role-based task management
  • Admin interface for user management
  • Database integration patterns
  • Production deployment setup

โš™๏ธ Configuration

config = {
    'allow_registration': True,              # Enable user registration
    'public_paths': ['/about', '/api'],      # Routes that skip authentication  
    'login_path': '/auth/login',             # Custom login URL
    'oauth_redirect_url': 'https://yourdomain.com/auth/google/callback',  # Google OAuth callback URL
}

auth = AuthManager(db_path="data/app.db", config=config)

๐ŸŒ Google OAuth

FastHTML-Auth supports Google OAuth as an alternative login method. When enabled, a "Sign in with Google" button appears automatically on the login form.

Setup

  1. Create OAuth credentials in Google Cloud Console:

    • Go to APIs & Services โ†’ Credentials โ†’ Create Credentials โ†’ OAuth 2.0 Client ID
    • Add your callback URL as an authorised redirect URI: https://yourdomain.com/auth/google/callback
  2. Add credentials to your .env file:

GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
OAUTH_REDIRECT_URL=https://yourdomain.com/auth/google/callback
  1. Call setup_oauth() before register_routes():
auth = AuthManager(db_path="data/app.db", config={
    ...
    'oauth_redirect_url': os.getenv('OAUTH_REDIRECT_URL')
})
db = auth.initialize()
auth.setup_oauth()                  # Load credentials and enable OAuth
beforeware = auth.create_beforeware()
app = FastHTML(before=beforeware, ...)
auth.register_routes(app)

OAuth users are stored in the same users table with auth_provider='google' and no password. They are automatically created on first login with basic user role.


๐Ÿ” Role-Based Access Control

Built-in Roles

  • user - Basic authenticated access
  • manager - Manager privileges + user access
  • admin - Full system access + admin interface

Route Protection

# Require specific roles
@app.route("/manager-area")
@auth.require_role('manager', 'admin')
def manager_view(req):
    return H1("Manager+ Only")

# Admin only (shortcut)
@app.route("/admin")
@auth.require_admin()
def admin_panel(req):
    return H1("Admin Only")

# Check roles in templates
@app.route("/dashboard")
def dashboard(req):
    user = req.scope['user']
    
    admin_link = A("Admin Panel", href="/auth/admin") if user.role == 'admin' else None
    return Div(admin_link)

๐Ÿ“Š User Object

In protected routes, access user data via req.scope['user']:

user.id             # Unique user ID  
user.username       # Username
user.email          # Email address
user.role           # 'user', 'manager', or 'admin'
user.active         # Boolean - account status
user.created_at     # Account creation timestamp
user.last_login     # Last login timestamp
user.auth_provider  # 'local' for password login, 'google' for OAuth

๐ŸŽจ Styling & Themes

FastHTML-Auth uses MonsterUI for beautiful, responsive components:

# Choose your theme
app = FastHTML(
    before=beforeware,
    hdrs=Theme.blue.headers()    # or red, green, slate, etc.
)

All forms include professional styling, validation, error handling, and mobile optimization.

๐Ÿ› ๏ธ API Reference

AuthManager

auth = AuthManager(db_path="data/app.db", config={})
auth.initialize()                                    # Set up database
auth.setup_oauth()                                   # Enable Google OAuth (optional)
auth.register_routes(app, include_admin=True)        # Add all routes
auth.create_beforeware()                             # Create middleware

@auth.require_admin()                                # Admin-only decorator
@auth.require_role('manager', 'admin')               # Role-based decorator

Available Routes

Authentication Routes:

  • GET/POST /auth/login - User login
  • GET /auth/logout - Logout and redirect
  • GET/POST /auth/register - User registration
  • GET/POST /auth/profile - Profile management

Admin Routes (when include_admin=True):

  • GET /auth/admin - Admin dashboard
  • GET /auth/admin/users - User management
  • GET/POST /auth/admin/users/create - Create user
  • GET/POST /auth/admin/users/edit?id={id} - Edit user
  • GET/POST /auth/admin/users/delete?id={id} - Delete user

OAuth Routes (when setup_oauth() is called):

  • GET /auth/google/login - Redirect to Google sign-in
  • GET /auth/google/callback - Handle Google OAuth callback

๐Ÿ“ Examples

For complete examples, see the /examples directory:

๐Ÿ”’ Security Features

  • Bcrypt password hashing - Industry standard security
  • Google OAuth - Secure third-party authentication via Google
  • Session management - Secure session handling with FastHTML
  • Remember me functionality - Optional persistent sessions
  • Role-based protection - Automatic route access control
  • Admin safety - Prevent self-deletion and last admin removal
  • Input validation - Server-side validation for all forms

๐Ÿ“ฆ Installation & Dependencies

pip install fasthtml-auth

Dependencies:

  • python-fasthtml>=0.12.0 - Web framework
  • monsterui>=1.0.20 - UI components
  • fastlite>=0.2.0 - Database ORM
  • bcrypt>=4.0.0 - Password hashing
  • python-dotenv>=1.0.0 - Environment variable management (required for OAuth)

๐Ÿค Contributing

We welcome contributions! Areas for contribution:

  • Password reset functionality
  • Two-factor authentication
  • Additional OAuth providers (GitHub, Microsoft, etc.)
  • Email verification
  • Bulk user operations
  • Custom user fields

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ“ Changelog

v0.3.0 (Current Release)

  • โœ… Google OAuth integration
  • โœ… auth_provider field to distinguish login method
  • โœ… OAuth routes automatically added to public paths
  • โœ… Login form automatically shows Google button when OAuth is enabled

v0.2.0

  • โœ… Built-in admin interface for user management
  • โœ… User CRUD operations with beautiful UI
  • โœ… Dashboard with user statistics
  • โœ… Search, filter, and pagination
  • โœ… Safety features for admin operations

v0.1.2

  • โœ… "Remember me" functionality
  • โœ… Terms acceptance validation
  • โœ… Improved form styling

v0.1.0

  • โœ… Initial release with core authentication
  • โœ… Role-based access control
  • โœ… MonsterUI integration

FastHTML-Auth - Authentication made simple for FastHTML applications.

For questions and support: GitHub Issues

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fasthtml_auth-0.3.0.tar.gz (32.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fasthtml_auth-0.3.0-py3-none-any.whl (27.2 kB view details)

Uploaded Python 3

File details

Details for the file fasthtml_auth-0.3.0.tar.gz.

File metadata

  • Download URL: fasthtml_auth-0.3.0.tar.gz
  • Upload date:
  • Size: 32.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for fasthtml_auth-0.3.0.tar.gz
Algorithm Hash digest
SHA256 fd5824451b132c6119c61ff3e8545822b262f1225028edae8c877158089a4d86
MD5 89f4ceef3ece14556bc7f69fd710931c
BLAKE2b-256 2ec151ff0871282d7def4cb601e3e0344027203cf177a8bec9b8b2f02cef635e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fasthtml_auth-0.3.0.tar.gz:

Publisher: publish.yml on fromLittleAcorns/fasthtml_toolbox

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fasthtml_auth-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: fasthtml_auth-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 27.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for fasthtml_auth-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f27c8d1f630c635cdca9f90522d92c8ee48779be231b9b41a867246c5a0fe51b
MD5 480c9b1d4b2f31c9da2c4fd3123bcd05
BLAKE2b-256 4e5c25b9a49e30fe726bbcab2f9073516fb586de06acbcecf2326925adba5067

See more details on using hashes here.

Provenance

The following attestation bundles were made for fasthtml_auth-0.3.0-py3-none-any.whl:

Publisher: publish.yml on fromLittleAcorns/fasthtml_toolbox

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page