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
โญ 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/loginand/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:
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 local user registration form
'oauth_create_users': True, # Allow OAuth to auto-create new accounts (set False for admin-only signups)
'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
-
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
-
Add credentials to your
.envfile:
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
OAUTH_REDIRECT_URL=https://yourdomain.com/auth/google/callback
- Call
setup_oauth()beforeregister_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 (default behaviour).
Admin-controlled OAuth access
If you want to restrict who can log in via OAuth (e.g. no open self-registration), set oauth_create_users to False:
config = {
'allow_registration': False, # Disable local signup form
'oauth_create_users': False, # Disable OAuth auto account creation
...
}
With this setup, an admin pre-creates user accounts via the admin interface. Users whose email matches a pre-existing account can sign in with either their local password or Google OAuth โ their role and password are never modified by an OAuth login.
๐ Role-Based Access Control
Built-in Roles
user- Basic authenticated accessmanager- Manager privileges + user accessadmin- 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 loginGET /auth/logout- Logout and redirectGET/POST /auth/register- User registrationGET/POST /auth/profile- Profile management
Admin Routes (when include_admin=True):
GET /auth/admin- Admin dashboardGET /auth/admin/users- User managementGET/POST /auth/admin/users/create- Create userGET/POST /auth/admin/users/edit?id={id}- Edit userGET/POST /auth/admin/users/delete?id={id}- Delete user
OAuth Routes (when setup_oauth() is called):
GET /auth/google/login- Redirect to Google sign-inGET /auth/google/callback- Handle Google OAuth callback
๐ Examples
For complete examples, see the /examples directory:
basic_app.py- Simple authentication setupexample_with_admin.py- Full admin interface demo- FastHTML Todo App - Real-world application
๐ 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 frameworkmonsterui>=1.0.20- UI componentsfastlite>=0.2.0- Database ORMbcrypt>=4.0.0- Password hashingpython-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.3 (Current release)
- โ
New
oauth_create_usersconfig flag to restrict OAuth logins to pre-registered accounts - โ Users can now log in via local password or Google OAuth interchangeably โ roles and passwords unaffected by OAuth login
- โ Clear error message shown when an unrecognised email attempts OAuth login
v0.3.2
- โ Bug fix adding a config variable to AuthManager class
- โ Updated github actions versions
v0.3.0
- โ Google OAuth integration
- โ
auth_providerfield 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fasthtml_auth-0.3.3.tar.gz.
File metadata
- Download URL: fasthtml_auth-0.3.3.tar.gz
- Upload date:
- Size: 33.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eb33921bfc2c2c385f349e409e964c40f03f13f80878ea63aeb5e53e86acdb69
|
|
| MD5 |
428f809d45930a99afc6d2d0556cc493
|
|
| BLAKE2b-256 |
4a5b584f38f5c69c21fb82d8573d23e6b81a54af2511ff0bf0cbb92e7a0ddd34
|
Provenance
The following attestation bundles were made for fasthtml_auth-0.3.3.tar.gz:
Publisher:
publish.yml on fromLittleAcorns/fasthtml_toolbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fasthtml_auth-0.3.3.tar.gz -
Subject digest:
eb33921bfc2c2c385f349e409e964c40f03f13f80878ea63aeb5e53e86acdb69 - Sigstore transparency entry: 1239254577
- Sigstore integration time:
-
Permalink:
fromLittleAcorns/fasthtml_toolbox@3f50a462afa2fde3a9e16504ca7cb0bd73b8cf12 -
Branch / Tag:
refs/tags/v0.3.3 - Owner: https://github.com/fromLittleAcorns
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@3f50a462afa2fde3a9e16504ca7cb0bd73b8cf12 -
Trigger Event:
release
-
Statement type:
File details
Details for the file fasthtml_auth-0.3.3-py3-none-any.whl.
File metadata
- Download URL: fasthtml_auth-0.3.3-py3-none-any.whl
- Upload date:
- Size: 27.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a5a7c9acb296f5bd03a2aa9ffd41ea9b24776cc29276b83ba8a4ec1f732e201f
|
|
| MD5 |
dd082233899455915032b1dc213b1850
|
|
| BLAKE2b-256 |
901598607d8387ddad2376a229a3894b8f03b7568a9927b41906aa599eb5791a
|
Provenance
The following attestation bundles were made for fasthtml_auth-0.3.3-py3-none-any.whl:
Publisher:
publish.yml on fromLittleAcorns/fasthtml_toolbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fasthtml_auth-0.3.3-py3-none-any.whl -
Subject digest:
a5a7c9acb296f5bd03a2aa9ffd41ea9b24776cc29276b83ba8a4ec1f732e201f - Sigstore transparency entry: 1239254579
- Sigstore integration time:
-
Permalink:
fromLittleAcorns/fasthtml_toolbox@3f50a462afa2fde3a9e16504ca7cb0bd73b8cf12 -
Branch / Tag:
refs/tags/v0.3.3 - Owner: https://github.com/fromLittleAcorns
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@3f50a462afa2fde3a9e16504ca7cb0bd73b8cf12 -
Trigger Event:
release
-
Statement type: