### Install AuthTuna
Source: https://authtuna.shashstorm.in/getting-started
Use pip to install the AuthTuna package.
```bash
pip install authtuna
```
--------------------------------
### Create and Get or Create Permissions
Source: https://authtuna.shashstorm.in/managing-permissions
Use `create` to add a new permission, or `get_or_create` for idempotent operations to avoid duplicates. Ensure permissions have unique names and descriptive text.
```python
from authtuna.integrations import auth_service
permission_manager = auth_service.permissions
# Create a new permission
new_permission = await permission_manager.create(
name="posts:create",
description="Allows users to create new blog posts"
)
# Or use get_or_create for idempotent operations
permission, created = await permission_manager.get_or_create(
name="posts:publish",
defaults={"description": "Allows publishing posts to make them public"}
)
if created:
print("Permission was created")
else:
print("Permission already exists")
```
--------------------------------
### Get or Create Permission
Source: https://authtuna.shashstorm.in/managing-permissions
Safely retrieves a permission by name or creates it if it doesn't exist. Use the `defaults` argument to specify properties for new permissions.
```python
perm, created = await permission_manager.get_or_create(
"analytics:view",
defaults={"description": "View analytics dashboard"}
)
```
--------------------------------
### Get Permission by Name and Check Existence
Source: https://authtuna.shashstorm.in/managing-permissions
Retrieves a permission by its name and checks if it exists. Use this to fetch existing permissions before performing operations.
```python
permission = await permission_manager.get_by_name("posts:create")
if permission:
print(f"Found: {permission.name} - {permission.description}")
else:
print("Permission not found")
```
--------------------------------
### Get Current User Optional Dependency
Source: https://authtuna.shashstorm.in/integrations
Use `get_current_user_optional` for endpoints that can be accessed by both anonymous and authenticated users. It returns `None` for unauthenticated requests.
```python
@app.get('/home')
async def home(user = Depends(get_current_user_optional)):
if user:
return {"message": f"Welcome back {user.email}"}
return {"message": "Welcome, please sign in"}
```
--------------------------------
### Get Current User Dependency
Source: https://authtuna.shashstorm.in/integrations
Use `get_current_user` to retrieve the authenticated User instance. It supports COOKIE sessions and BEARER token authentication. Set `allow_public_key=True` to permit publishable API keys.
```python
# Cookie-backed session (requires session middleware)
@app.get('/dashboard')
async def dashboard(user = Depends(get_current_user)):
return {"welcome": f"Hello {user.email}"}
```
```python
# Allow publishable keys for a public endpoint (use carefully)
@app.get('/public-data')
async def public_data(user = Depends(lambda req: get_current_user(req, allow_public_key=True))):
return {"ok": True}
```
--------------------------------
### Get User IP Dependency
Source: https://authtuna.shashstorm.in/integrations
Use `get_user_ip` to obtain the resolved IP address of the client, typically populated by session middleware. Useful for logging or access control.
```python
@app.get('/whoami')
async def whoami(ip: str = Depends(get_user_ip)):
return {"ip": ip}
```
--------------------------------
### Perform privacy-aware user searches
Source: https://authtuna.shashstorm.in/managing-user
Use basic_search_users to return only non-sensitive user information. The API endpoint example demonstrates conditional access based on user roles.
```python
basic_results = await user_manager.basic_search_users(
identity="john",
skip=0,
limit=10
)
# Returns only: [{"user_id": "...", "username": "..."}]
# No email addresses or sensitive information
# Example API endpoint
@app.get("/api/users/search")
async def search_users(query: str, current_user=Depends(get_current_user)):
# Only admins can search with full details
if "admin" in [role.name for role in current_user.roles]:
return await user_manager.search_users(identity=query)
else:
return await user_manager.basic_search_users(identity=query)
```
--------------------------------
### Run Default Provisioning
Source: https://authtuna.shashstorm.in/defaults
Executes the default provisioning process to ensure roles and permissions exist in the database.
```python
from authtuna.core.defaults import provision_defaults
from authtuna.core.database import db_manager
# Run provisioning (typically done automatically on startup)
async with db_manager.get_db() as db:
await provision_defaults(db)
```
--------------------------------
### Set Up Frontend API Client with Credentials
Source: https://authtuna.shashstorm.in/rbac-example
Create a wrapper for frontend API calls that includes necessary headers and sets `credentials` to 'include' for session management. This ensures that cookies are sent with requests, maintaining user sessions.
```typescript
// advanced/todo_frontend/lib/api.ts
const API_BASE_URL = "http://localhost:5080";
async function apiFetch(endpoint: string, options: RequestInit = {}) {
const url = `${API_BASE_URL}${endpoint}`;
// ...
const config: RequestInit = {
...options,
headers: defaultHeaders,
credentials: "include", // <-- THIS IS THE KEY!
};
// ...
const response = await fetch(url, config);
// ...
}
export const api = {
get: (endpoint: string, options?: RequestInit) =>
apiFetch(endpoint, { ...options, method: "GET" }),
post: (endpoint: string, body: object, options?: RequestInit) =>
apiFetch(endpoint, { ...options, method: "POST", body: JSON.stringify(body) }),
// ...
};
```
--------------------------------
### Create Users with AuthTuna
Source: https://authtuna.shashstorm.in/managing-user
Demonstrates creating users with or without passwords, suitable for standard registration or OAuth flows.
```python
from authtuna.integrations import auth_service
user_manager = auth_service.users
# Create a user with password
new_user = await user_manager.create(
email="john.doe@example.com",
username="johndoe",
password="secure_password_123",
ip_address="192.168.1.100"
)
# Create a user without password (for OAuth/social login)
oauth_user = await user_manager.create(
email="jane.smith@example.com",
username="janesmith",
ip_address="192.168.1.100"
)
print(f"Created user: {new_user.id}")
```
--------------------------------
### Configure Environment Variables
Source: https://authtuna.shashstorm.in/getting-started
Define the API base URL and mandatory Fernet encryption keys in a .env file.
```text
# .env
API_BASE_URL=http://localhost:8000
# Mandatory encryption keys (generate with Fernet.generate_key().decode())
FERNET_KEYS='["YOUR_PRIMARY_KEY", "YOUR_SECONDARY_KEY"]'
```
--------------------------------
### Initialize Settings Manually
Source: https://authtuna.shashstorm.in/configuration-options
Provide all necessary settings manually to the `init_settings` function. This method disables the loading of environment variables, giving you complete control over the configuration.
```python
from authtuna import init_settings
# Manual settings (no env vars used)
init_settings({
"API_BASE_URL": "https://myapp.com",
"JWT_SECRET_KEY": "sekure-key",
"ENCRYPTION_PRIMARY_KEY": "encryption-key",
# ... all other required settings
})
```
--------------------------------
### Initialize AuthTuna in FastAPI
Source: https://authtuna.shashstorm.in/rbac-example
Use init_app to automatically register authentication routes and session middleware.
```python
# simple/main.py
# 2. Setup FastAPI and Jinja2
app = FastAPI(title="Simple Todo App")
templates = Jinja2Templates(directory="templates")
# 3. Initialize AuthTuna
# This is the magic. It adds all auth routes (/auth/login, /auth/signup)
# and the session middleware.
init_app(app)
```
--------------------------------
### Quick Import for FastAPI Integration
Source: https://authtuna.shashstorm.in/integrations
Import necessary components from authtuna.integrations.fastapi_integration for use with FastAPI.
```python
from fastapi import FastAPI, Depends, Request
from authtuna.integrations.fastapi_integration import (
get_current_user,
get_current_user_optional,
get_user_ip,
resolve_token_method,
PermissionChecker,
RoleChecker,
)
app = FastAPI()
```
--------------------------------
### Create Custom Roles
Source: https://authtuna.shashstorm.in/defaults
Instantiates a new role and associates it with existing permissions.
```python
# Create a custom role
analyst_role = Role(
name="DataAnalyst",
level=10,
description="Can access reports and analytics"
)
# Assign permissions
analyst_permissions = ["reports:view", "billing:manage"]
for perm_name in analyst_permissions:
permission = get_permission_by_name(perm_name)
analyst_role.permissions.append(permission)
```
--------------------------------
### Override AuthTuna Theme Programmatically
Source: https://authtuna.shashstorm.in/configuration-options
Create a custom theme object by copying the existing settings and applying modifications, then pass it to init_settings.
```python
from authtuna import Theme, init_settings, ThemeMode, settings
new_theme = settings.THEME.dark.model_copy(deep=True)
new_theme.background_start = "#143497"
new_theme.background_end = "#000000"
custom_theme = Theme(
mode="single", # only light mode vars but just set them to whatever you want they will be used in dark mode also.
light=new_theme,
)
# Override settings with custom theme
init_settings(THEME=custom_theme, dont_use_env=False))
# remember to keep THEME ALL CAPS otherwise youd be wondering why colorz not changin.
```
--------------------------------
### Configure CORS and Initialize AuthTuna
Source: https://authtuna.shashstorm.in/rbac-example
Add CORS middleware to allow frontend communication and initialize AuthTuna with the FastAPI application.
```python
# advanced/main.py
# 1. Add CORS Middleware
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"http://localhost(:[0-9]+)?",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 2. Initialize AuthTuna
init_app(app)
```
--------------------------------
### Render Todo List Template
Source: https://authtuna.shashstorm.in/rbac-example
Jinja2 template for displaying user-specific todos and AuthTuna navigation links.
```html
Your Todos
{% for todo in todos %}
-
{{ todo.content }}
Delete
{% else %}
- You have no todos yet!
{% endfor %}
```
--------------------------------
### Integrate AuthTuna with FastAPI
Source: https://authtuna.shashstorm.in/getting-started
Initialize AuthTuna in a FastAPI application and use dependency injection for user authentication.
```python
from fastapi import FastAPI, Depends
from fastapi.responses import RedirectResponse
from authtuna import init_app
from authtuna.integrations import get_current_user_optional
app = FastAPI(title="AuthTuna Demo API")
# This single function adds all middleware and routers
init_app(app)
@app.get("/", tags=["Root"])
async def root(user=Depends(get_current_user_optional)):
"""
Automatically redirects to login page if not authenticated,
else redirects to the dashboard.
"""
if user is None:
return RedirectResponse("/auth/login")
return RedirectResponse("/ui/dashboard")
```
--------------------------------
### Connect to MongoDB for SPA
Source: https://authtuna.shashstorm.in/rbac-example
Configure a separate MongoDB connection for application data in a decoupled architecture.
```python
# advanced/database.py
import os
import motor.motor_asyncio
import dotenv
dotenv.load_dotenv(os.getenv("ENV_FILE_PATH"))
# Create a client to connect to MongoDB
client = motor.motor_asyncio.AsyncIOMotorClient(os.getenv("MONGO_CONNECTION_STRING", "mongodb://localhost:27017"))
# ...
db = client[os.getenv("MONGO_DATABASE_NAME", "authtuna_todo_app")]
```
--------------------------------
### Handle Duplicate Permission Creation
Source: https://authtuna.shashstorm.in/managing-permissions
AuthTuna raises a `ValueError` if attempting to create a permission that already exists. Use `get_or_create` for safer, idempotent operations.
```python
# This will raise ValueError if permission already exists
try:
permission = await permission_manager.create("posts:create", "Create posts")
except ValueError as e:
print(f"Permission creation failed: {e}")
# Use get_or_create for safe operations
permission, created = await permission_manager.get_or_create("posts:create")
if not created:
print("Permission already exists - no action needed")
```
--------------------------------
### Override Settings Programmatically
Source: https://authtuna.shashstorm.in/configuration-options
Programmatically override specific settings by passing a dictionary to the `init_settings` function. This allows for dynamic configuration within your application code. Ensure `dont_use_env` is set to `False` if you still want to load environment variables.
```python
from authtuna import init_settings
# Override specific settings
init_settings({
"APP_NAME": "Mein Custom App",
"MFA_ENABLED": False,
"DATABASE_POOL_SIZE": 100
}, dont_use_env=False)
```
--------------------------------
### Implement Custom Login Page
Source: https://authtuna.shashstorm.in/rbac-example
Create a custom login form component using React that utilizes the `api` client to send user credentials to AuthTuna's login endpoint. Upon successful login, it redirects the user to the homepage.
```typescript
// advanced/todo_frontend/app/login/page.tsx
'use client';
// ... imports
import { api } from '@/lib/api';
export default function LoginPage() {
// ... state variables
const router = useRouter();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
// ...
try {
await api.post('/auth/login', {
username_or_email: username,
password: password,
});
router.push('/');
} catch (err: unknown) {
// ... error handling
}
};
// ... return JSX
}
```
--------------------------------
### Theme Configuration API
Source: https://authtuna.shashstorm.in/configuration-options
This section details how to configure the AuthTuna UI theme. The theme is controlled by a Pydantic model that defines various styling options for both light and dark modes. It is recommended to override the theme programmatically.
```APIDOC
## Theme Configuration
The theme setting is a complex Pydantic model that controls the visual appearance of the AuthTuna UI. It includes colors, fonts, spacing, and other styling options. Due to its complex structure, it's recommended to override the theme programmatically in your code rather than through environment variables to prevent configuration mistakes.
The default theme provides a clean, modern look that works well for most applications. You can customize it by creating a custom theme object and passing it to the settings.
### Code Example: Programmatic Theme Override
```python
from authtuna import Theme, init_settings, ThemeMode, settings
new_theme = settings.THEME.dark.model_copy(deep=True)
new_theme.background_start = "#143497"
new_theme.background_end = "#000000"
custom_theme = Theme(
mode="single", # only light mode vars but just set them to whatever you want they will be used in dark mode also.
light=new_theme,
)
# Override settings with custom theme
init_settings(THEME=custom_theme, dont_use_env=False))
# remember to keep THEME ALL CAPS otherwise youd be wondering why colorz not changin.
```
### Theme Properties
The theme is a structured Pydantic model (see `authtuna.core.config.Theme`) that defines the visual appearance for light and dark modes. Because it has many fields and nested values, we strongly recommend overriding it programmatically to avoid mistakes.
Below is a table describing every theme property, the default value for the **light** and**dark** modes, and what each property controls in the UI.
| Property | Light default | Dark default | What it controls |
|---|---|---|---|
| mode | "system" | "system" | Controls theme mode selection: "single", "multi", or "system" |
| background_start | "#F8FAFC" | "#0B0B0F" | Page background gradient start (behind content) |
| background_end | "#FFFFFF" | "#020817" | Page background gradient end |
| foreground | "#020817" | "#F8FAFC" | Primary text color |
| muted_foreground | "#64748B" | "#94A3B8" | Secondary / muted text color (helper text, captions) |
| card | "#FFFFFF" | "#777e9145" | Card / panel background color |
| card_foreground | "#020817" | "#F8FAFC" | Text color used on cards |
| popover | "#FFFFFF" | "#020817" | Popovers / modal backgrounds |
| popover_foreground | "#020817" | "#F8FAFC" | Text color inside popovers/modals |
| primary | "#6D28D9" | "#7C3AED" | Primary interactive color (buttons, links) |
| primary_foreground | "#F8FAFC" | "#F8FAFC" | Text color used on primary elements |
| secondary | "#F1F5F9" | "#6572887d" | Secondary interactive color / surfaces |
| secondary_foreground | "#0F172A" | "#F8FAFC" | Text color on secondary elements |
| muted | "#F1F5F9" | "#1E293B" | Muted surfaces / dividers |
| accent | "#F1F5F9" | "#93b2e6a8" | Accent overlays / highlights |
| destructive | "#EF4444" | "#7F1D1D" | Destructive actions (e.g., delete buttons) |
| destructive_foreground | "#F8FAFC" | "#F8FAFC" | Text color for destructive elements |
| border | "transparent" | "transparent" | Border color for elements |
| input | "#E2E8F0" | "#1E293B" | Input field borders |
| ring | "#94A3B8" | "#475569" | Focus rings for accessibility
```
--------------------------------
### Define Todo Model with AuthTuna
Source: https://authtuna.shashstorm.in/rbac-example
Inherit from AuthTuna's Base class to manage the table and establish a relationship with the User model.
```python
# simple/main.py
# 1. Define our custom Todo model
# We inherit from authtuna's 'Base' so it's managed by the same system
class Todo(Base):
__tablename__ = "todos"
id: Mapped[int] = Column(Integer, primary_key=True, index=True)
content: Mapped[str] = Column(String, index=True)
# This is the crucial link to the User model
user_id: Mapped[str] = Column(String(64), ForeignKey("users.id"))
# This relationship lets us access todo.user
user: Mapped["User"] = relationship("User")
```
--------------------------------
### Protect Routes and Scope Data
Source: https://authtuna.shashstorm.in/rbac-example
Use dependency injection to restrict access to user-specific data.
```python
# simple/main.py
@app.get("/todos")
async def get_todos(request: Request, user: User = Depends(get_current_user_optional)):
"""
Protected route. Only logged-in users can access this.
It fetches *only* the todos for the current user.
"""
if not user:
return RedirectResponse("/")
todos = []
async with db_manager.get_db() as db:
stmt = select(Todo).where(Todo.user_id == user.id)
result = await db.execute(stmt)
todos = result.scalars().all()
return templates.TemplateResponse("todos.html", {
"request": request,
"todos": todos,
"username": user.username
})
@app.post("/todos/add")
async def add_todo(content: str = Form(...), user: User = Depends(get_current_user)):
"""
Protected route to add a new todo.
"""
async with db_manager.get_db() as db:
new_todo = Todo(content=content, user_id=user.id)
db.add(new_todo)
await db.commit()
return RedirectResponse(url="/todos", status_code=303)
```
--------------------------------
### Generate Encryption Keys
Source: https://authtuna.shashstorm.in/getting-started
Use the cryptography library to generate valid Fernet keys for AuthTuna.
```python
from cryptography.fernet import Fernet
# Generate a key
key = Fernet.generate_key().decode()
print(key)
```
--------------------------------
### Create Hierarchical and Organizational Roles
Source: https://authtuna.shashstorm.in/creating-roles
Use `role_manager.create` to define new roles. Hierarchical roles have a level (1-100), while organizational roles have level 0 and are not part of the hierarchical system.
```python
from authtuna.integrations import auth_service
role_manager = auth_service.roles
# Create a hierarchical admin role
admin_role = await role_manager.create(
name="ContentModerator",
description="Can moderate user-generated content",
level=25
)
# Create an organizational role
team_lead_role = await role_manager.create(
name="TeamLead",
description="Leads a development team",
# Organizational roles have no level they do not use the hierarchical system.
# this is so that if you create a with level > 0 it will give permission to manage all these roles
# to to prevent this this uses grant system 2 see down for more details
)
```
--------------------------------
### Set Environment Variables in .env File
Source: https://authtuna.shashstorm.in/configuration-options
Use a .env file in your project root to configure application settings. This method is suitable for managing sensitive information and environment-specific configurations.
```dotenv
# .env
API_BASE_URL=https://yourapp.com
JWT_SECRET_KEY=dein-secure-jwt-secret
FERNET_KEYS=["der key"]
ENCRYPTION_PRIMARY_KEY=dein-encryption-key
MFA_ENABLED=True
DATABASE_POOL_SIZE=50
```
--------------------------------
### Add Custom Permissions
Source: https://authtuna.shashstorm.in/defaults
Defines and persists application-specific permissions to the database.
```python
# Add custom permissions
custom_permissions = {
"billing:manage": "Manage billing settings",
"reports:view": "Access analytics reports",
"api:webhooks": "Configure webhooks"
}
# Create them in your app startup
for name, desc in custom_permissions.items():
permission = Permission(name=name, description=desc)
db.add(permission)
```
--------------------------------
### Implement Organization-Scoped API Endpoint
Source: https://authtuna.shashstorm.in/rbac-example
Create a FastAPI endpoint to fetch todos based on the user's organization memberships, demonstrating multi-tenancy. This endpoint retrieves the current user, their associated organizations, and then queries MongoDB for todos belonging to those organizations.
```python
# advanced/main.py
@app.get("/api/todos", response_model=List[Todo])
async def get_all_todos_for_user(user: User = Depends(get_current_user)):
"""
Get all Todos for the current user.
This demonstrates the "advanced" logic:
1. Get the current user from AuthTuna.
2. Get all organizations this user belongs to from AuthTuna.
3. Get all Todos from MongoDB that belong to any of those organizations.
"""
# 1. Get orgs from authtuna's db
user_orgs = await auth_service.orgs.get_user_orgs(user.id)
org_ids = [org.id for org in user_orgs]
if not org_ids:
return []
# 2. Query MongoDB for todos in those orgs
todo_cursor = TodoCollection.find({"org_id": {"$in": org_ids}})
todos = await todo_cursor.to_list(100)
return todos
```
--------------------------------
### Query Role Information
Source: https://authtuna.shashstorm.in/creating-roles
Retrieves lists of roles, users associated with a role, or roles a specific user is authorized to assign.
```python
# Get all roles
all_roles = await role_manager.get_all_roles()
# Get users with a specific role
users_with_role = await role_manager.get_users_for_role(
role_name="Admin",
scope="global"
)
# Get roles a user can assign
assignable_roles = await role_manager.get_assignable_roles_for_user(
target_user_id="user_123",
assigning_user=current_user
)
```
--------------------------------
### Assign Roles to Users Globally and with Scopes
Source: https://authtuna.shashstorm.in/creating-roles
Use `role_manager.assign_to_user` to grant roles to users. Specify a `scope` to limit the role's applicability, such as 'global' for universal access or a specific string like 'team:frontend' for targeted access.
```python
# Assign ContentModerator role globally
await role_manager.assign_to_user(
user_id="user_123",
role_name="ContentModerator",
assigner_id=current_user.id,
scope="global" # Applies everywhere
)
# Assign TeamLead role with specific scope
await role_manager.assign_to_user(
user_id="user_456",
role_name="TeamLead",
assigner_id=current_user.id,
scope="team:frontend" # Only for frontend team
)
```
--------------------------------
### RoleChecker for Role-Based Access Control
Source: https://authtuna.shashstorm.in/integrations
Use `RoleChecker` as a dependency factory to enforce role requirements. It supports path parameter scoping and different modes (AND/OR) for multiple roles.
```python
# Require admin role
@app.post('/admin/only')
async def admin_endpoint(user = Depends(RoleChecker('admin'))):
return {"ok": True}
```
--------------------------------
### Reactivate User Accounts
Source: https://authtuna.shashstorm.in/managing-user
Restores access to a previously suspended user account.
```python
# Unsuspend a user account
reactivated_user = await user_manager.unsuspend_user(
user_id="user_123",
admin_id="admin_456",
reason="Appeal approved"
)
# User can log in again
# Account status is restored
# Reactivation is logged
```
--------------------------------
### Dependency: get_current_user_optional
Source: https://authtuna.shashstorm.in/integrations
Retrieves the authenticated user or returns None if unauthenticated.
```APIDOC
## get_current_user_optional(request)
### Description
Same behavior as get_current_user but returns None when the request is unauthenticated instead of raising an HTTP error.
```
--------------------------------
### Protect Client-Side Todo Page
Source: https://authtuna.shashstorm.in/rbac-example
This client-side component fetches todos and redirects to the login page if the user is unauthorized (status 401). Ensure your backend is running and accessible.
```typescript
'use client';
// ... imports
export default function Home() {
// ... state
const router = useRouter();
useEffect(() => {
const fetchTodos = async () => {
try {
const responseData = await api.get('/api/todos');
setTodos(responseData);
} catch (err: unknown) {
const error = err as { status?: number };
if (error.status === 401) {
router.push('/login');
} else {
setError('Failed to fetch todos. Is your backend running?');
}
} finally {
setLoading(false);
}
};
fetchTodos();
}, [router]);
// ... handlers for add/delete
// ... return JSX with link to http://localhost:5080/ui/organizations
}
```
--------------------------------
### Core Authentication API
Source: https://authtuna.shashstorm.in/batteries-included
Endpoints for managing user registration, login, password recovery, and session state.
```APIDOC
## POST /auth/signup
### Description
Registers a new user account.
### Method
POST
### Endpoint
/auth/signup
## POST /auth/login
### Description
Authenticates a user and returns a JWT token.
### Method
POST
### Endpoint
/auth/login
## POST/GET /auth/logout
### Description
Logs out the current user and invalidates the session.
### Method
POST/GET
### Endpoint
/auth/logout
## POST /auth/forgot-password
### Description
Initiates the password reset flow.
### Method
POST
### Endpoint
/auth/forgot-password
## POST /auth/reset-password
### Description
Completes the password reset process.
### Method
POST
### Endpoint
/auth/reset-password
## POST /auth/change-password
### Description
Updates the user's password.
### Method
POST
### Endpoint
/auth/change-password
## GET/POST /auth/user-info
### Description
Retrieves information about the authenticated user.
### Method
GET/POST
### Endpoint
/auth/user-info
## GET /auth/verify
### Description
Verifies a user's email address.
### Method
GET
### Endpoint
/auth/verify
```
--------------------------------
### PermissionChecker for Access Control
Source: https://authtuna.shashstorm.in/integrations
Use `PermissionChecker` as a dependency factory to enforce specific permissions. It supports path parameter scoping and different modes (AND/OR) for multiple permissions. For BEARER keys, it differentiates between master and scoped keys.
```python
# Require a specific permission scoped to path param project_id
@app.get('/projects/{project_id}')
async def read_project(project_id: str, user = Depends(PermissionChecker('projects.read', scope_from_path='project_id'))):
return {"project_id": project_id}
```
```python
# Require any of several permissions (OR mode)
@app.post('/projects/{project_id}/action')
async def project_action(project_id: str, user = Depends(PermissionChecker('projects.write', 'projects.admin', mode='OR', scope_from_path='project_id'))):
return {"ok": True}
```
--------------------------------
### Assign Permissions to Roles
Source: https://authtuna.shashstorm.in/creating-roles
Use `role_manager.add_permission_to_role` to grant specific permissions to a role. Ensure the `adder_id` is provided for audit trails. Permissions must exist before assignment.
```python
# Assign permissions to our ContentModerator role
await role_manager.add_permission_to_role(
role_name="ContentModerator",
permission_name="content:moderate",
adder_id=current_user.id # For audit trail
)
await role_manager.add_permission_to_role(
role_name="ContentModerator",
permission_name="users:ban",
adder_id=current_user.id
)
# Assign permissions to TeamLead role
await role_manager.add_permission_to_role(
role_name="TeamLead",
permission_name="team:manage_members",
adder_id=current_user.id
)
```
--------------------------------
### Retrieve User Information
Source: https://authtuna.shashstorm.in/managing-user
Methods for fetching user records by unique identifiers or listing users with pagination.
```python
# Get user by ID (with roles and permissions)
user = await user_manager.get_by_id("user_123", with_relations=True)
# Get user by email
user_by_email = await user_manager.get_by_email("john.doe@example.com")
# Get user by username
user_by_username = await user_manager.get_by_username("johndoe")
# List users with pagination
users = await user_manager.list(skip=0, limit=50)
# Check if user exists
if user:
print(f"Found user: {user.username} - {user.email}")
print(f"Roles: {[role.name for role in user.roles]}")
else:
print("User not found")
```
--------------------------------
### Dependency: PermissionChecker
Source: https://authtuna.shashstorm.in/integrations
Enforces permission checks for users and API keys.
```APIDOC
## PermissionChecker(*permissions, mode='AND', scope_prefix=None, scope_from_path=None, raise_error=True)
### Description
A dependency factory that enforces permission checks, supporting both COOKIE sessions and BEARER API keys.
### Parameters
- **permissions** (str...) - Required - Permission strings to check.
- **mode** (str) - Optional - 'AND' or 'OR' logic for multiple permissions.
- **scope_prefix** (str) - Optional - Prefix when deriving scope from path.
- **scope_from_path** (str) - Optional - Name of the path parameter to derive scope from.
- **raise_error** (bool) - Optional - If False, returns None on failure instead of raising.
```
--------------------------------
### View Permission Creation Audit Logs
Source: https://authtuna.shashstorm.in/managing-permissions
AuthTuna automatically logs permission creations, including who created it, when, and its details. Access these logs via the `db_manager` to review `PERMISSION_CREATED` events.
```python
# Permission creation automatically logs:
# - Who created the permission
# - When it was created
# - Permission name and description
# - Any errors or validation failures
# View audit logs
audit_logs = await db_manager.get_audit_logs(
action="PERMISSION_CREATED",
limit=50
)
```
--------------------------------
### Configure Admin to Moderator Assignment
Source: https://authtuna.shashstorm.in/creating-roles
Grants the Admin role the permission to assign the Moderator role.
```python
await role_manager.grant_relationship(
granter_role_name="Admin",
grantable_name="Moderator",
grantable_manager=role_manager,
relationship_attr="can_assign_roles"
)
```
--------------------------------
### Multi-Factor Authentication (MFA) API
Source: https://authtuna.shashstorm.in/batteries-included
Endpoints for managing TOTP-based MFA and account recovery.
```APIDOC
## POST /mfa/setup
### Description
Configures MFA for the authenticated user.
### Method
POST
### Endpoint
/mfa/setup
## POST /mfa/verify
### Description
Verifies an MFA code provided by the user.
### Method
POST
### Endpoint
/mfa/verify
## GET /mfa/qr-code
### Description
Retrieves the QR code for TOTP setup.
### Method
GET
### Endpoint
/mfa/qr-code
## POST /mfa/validate-login
### Description
Validates the MFA challenge during the login process.
### Method
POST
### Endpoint
/mfa/validate-login
## POST /mfa/disable
### Description
Disables MFA for the user account.
### Method
POST
### Endpoint
/mfa/disable
## GET /mfa/challenge
### Description
Retrieves the current MFA challenge.
### Method
GET
### Endpoint
/mfa/challenge
```
--------------------------------
### Implement OR-based Role Checking in FastAPI
Source: https://authtuna.shashstorm.in/integrations
Use the RoleChecker dependency to enforce that a user must have at least one of the specified roles to access the endpoint.
```python
@app.post('/manage/{org_id}')
async def manage(org_id: str, user = Depends(RoleChecker('manager', 'admin', mode='OR', scope_from_path='org_id'))):
return {"ok": True}
```
--------------------------------
### Dependency: RoleChecker
Source: https://authtuna.shashstorm.in/integrations
Enforces role-based access control.
```APIDOC
## RoleChecker(*roles, mode='AND', scope_prefix=None, scope_from_path=None, raise_error=True)
### Description
A dependency factory that enforces role requirements.
### Parameters
- **roles** (str...) - Required - Role names to require.
- **mode** (str) - Optional - 'AND' or 'OR' logic for multiple roles.
- **scope_prefix** (str) - Optional - Prefix when deriving scope from path.
- **scope_from_path** (str) - Optional - Name of the path parameter to derive scope from.
- **raise_error** (bool) - Optional - If False, returns None on failure instead of raising.
```
--------------------------------
### Assign Role to User
Source: https://authtuna.shashstorm.in/managing-permissions
Grants a role, and consequently its associated permissions, to a user. This is the standard method for user authorization.
```python
await role_manager.assign_to_user(
user_id="user_123",
role_name="ContentEditor",
assigner_id=admin_user.id
)
```
--------------------------------
### Search users with multiple filters
Source: https://authtuna.shashstorm.in/managing-user
Filters users by role, scope, and activity status.
```python
team_members = await user_manager.search_users(
role="Developer",
scope="team:frontend",
is_active=True
)
```
--------------------------------
### Passkey Authentication API
Source: https://authtuna.shashstorm.in/batteries-included
Endpoints for passwordless authentication using WebAuthn.
```APIDOC
## POST /passkey/register-options
### Description
Generates options for registering a new passkey.
### Method
POST
### Endpoint
/passkey/register-options
## POST /passkey/register
### Description
Registers a new passkey for the user.
### Method
POST
### Endpoint
/passkey/register
## POST /passkey/login-options
### Description
Generates options for passkey-based login.
### Method
POST
### Endpoint
/passkey/login-options
## POST /passkey/login
### Description
Performs passwordless login using a passkey.
### Method
POST
### Endpoint
/passkey/login
## GET /passkey/
### Description
Lists all passkeys associated with the user.
### Method
GET
### Endpoint
/passkey/
## DELETE /passkey/{credential_id_b64}
### Description
Deletes a specific passkey.
### Method
DELETE
### Endpoint
/passkey/{credential_id_b64}
### Parameters
#### Path Parameters
- **credential_id_b64** (string) - Required - The base64 encoded credential ID.
## POST /passkey/mfa-login
### Description
Uses a passkey as an MFA factor.
### Method
POST
### Endpoint
/passkey/mfa-login
```
--------------------------------
### User Profile Page
Source: https://authtuna.shashstorm.in/batteries-included
Retrieves the user profile page information.
```APIDOC
## GET /ui/profile
### Description
User profile page
### Method
GET
### Endpoint
/ui/profile
```
--------------------------------
### Dependency: get_current_user
Source: https://authtuna.shashstorm.in/integrations
Retrieves the authenticated User instance via cookie session or Bearer token.
```APIDOC
## get_current_user(request, allow_public_key=False)
### Description
Returns the authenticated User instance. Supports COOKIE (session middleware) and BEARER (Authorization: Bearer ) authentication.
### Parameters
#### Request Body
- **request** (Request) - Required - The FastAPI request object.
- **allow_public_key** (bool) - Optional - If True, publishable API keys are allowed; otherwise rejects with 403.
```
--------------------------------
### Manage User Passwords
Source: https://authtuna.shashstorm.in/managing-user
Updates user passwords, which are automatically hashed and trigger an audit trail.
```python
# Set a new password for a user
await user_manager.set_password(
user_id="user_123",
new_password="new_secure_password_456",
ip_address="192.168.1.100"
)
# Passwords are automatically hashed
# Previous passwords are invalidated
# Audit trail is created
```
--------------------------------
### Dependency: get_user_ip
Source: https://authtuna.shashstorm.in/integrations
Resolves the user's IP address from the session middleware.
```APIDOC
## get_user_ip(request)
### Description
Returns the resolved IP address populated by the session middleware, useful for logging or rate limiting.
```
--------------------------------
### User Dashboard
Source: https://authtuna.shashstorm.in/batteries-included
Retrieves the user dashboard information.
```APIDOC
## GET /ui/dashboard
### Description
User dashboard
### Method
GET
### Endpoint
/ui/dashboard
```
--------------------------------
### Resolve Token Method Utility
Source: https://authtuna.shashstorm.in/integrations
The `resolve_token_method` utility returns the inferred token method for a request (`'COOKIE'`, `'BEARER'`, or `None`). It can be used to conditionally handle different authentication types.
```python
def handler(request: Request):
method = resolve_token_method(request)
if method == 'COOKIE':
# UI session
pass
elif method == 'BEARER':
# API key
pass
else:
# unauthenticated
pass
```
--------------------------------
### Delete users with archiving
Source: https://authtuna.shashstorm.in/managing-user
Permanently removes user data while archiving essential information for compliance and audit trails.
```python
await user_manager.delete(
user_id="user_123",
ip_address="192.168.1.100"
)
# What happens:
# 1. User data is archived to DeletedUser table
# 2. User is removed from main User table
# 3. All associated data (sessions, role assignments) are cleaned up
# 4. Audit event is logged
# 5. Transaction is committed atomically
```
--------------------------------
### Add Permission to Role
Source: https://authtuna.shashstorm.in/managing-permissions
Assigns a permission to a specific role. Permissions should always be managed through roles, not directly assigned to users.
```python
await role_manager.add_permission_to_role(
role_name="ContentEditor",
permission_name="posts:create",
adder_id=current_user.id
)
```
--------------------------------
### Query audit logs
Source: https://authtuna.shashstorm.in/managing-user
Retrieves audit events filtered by user ID, IP address, or specific administrative actions.
```python
# Query audit events for a user
user_events = await db_manager.get_audit_logs(
user_id="user_123",
event_types=["USER_UPDATED", "USER_SUSPENDED"],
limit=50
)
# Query by IP address
ip_events = await db_manager.get_audit_logs(
ip_address="192.168.1.100",
since=datetime.now() - timedelta(days=7)
)
# Query by admin actions
admin_actions = await db_manager.get_audit_logs(
event_types=["USER_SUSPENDED", "USER_UNSUSPENDED", "USER_DELETED"],
limit=100
)
```
--------------------------------
### User Management & Admin API
Source: https://authtuna.shashstorm.in/batteries-included
Endpoints for administrative tasks, including user management, role-based access control (RBAC), and auditing.
```APIDOC
## GET /admin/users/search
### Description
Searches and filters users.
### Method
GET
### Endpoint
/admin/users/search
## GET /admin/users/{user_id}/details-data
### Description
Retrieves detailed information for a specific user.
### Method
GET
### Endpoint
/admin/users/{user_id}/details-data
## GET /admin/users/{user_id}/audit-log
### Description
Retrieves the audit log for a specific user.
### Method
GET
### Endpoint
/admin/users/{user_id}/audit-log
## POST /admin/users/{user_id}/suspend
### Description
Suspends a user account.
### Method
POST
### Endpoint
/admin/users/{user_id}/suspend
## POST /admin/users/{user_id}/unsuspend
### Description
Unsuspends a user account.
### Method
POST
### Endpoint
/admin/users/{user_id}/unsuspend
## GET /admin/roles
### Description
Lists all available roles.
### Method
GET
### Endpoint
/admin/roles
## POST /admin/roles
### Description
Creates a new role.
### Method
POST
### Endpoint
/admin/roles
## DELETE /admin/roles/{role_name}
### Description
Deletes a role.
### Method
DELETE
### Endpoint
/admin/roles/{role_name}
## POST /admin/roles/{role_name}/permissions
### Description
Adds a permission to a role.
### Method
POST
### Endpoint
/admin/roles/{role_name}/permissions
## POST /admin/users/roles/assign
### Description
Assigns a role to a user.
### Method
POST
### Endpoint
/admin/users/roles/assign
## POST /admin/users/roles/revoke
### Description
Revokes a role from a user.
### Method
POST
### Endpoint
/admin/users/roles/revoke
## POST /admin/permissions
### Description
Creates a new permission.
### Method
POST
### Endpoint
/admin/permissions
## GET /admin/roles/{role_name}/details-data
### Description
Retrieves details for a specific role.
### Method
GET
### Endpoint
/admin/roles/{role_name}/details-data
## GET /admin/assignable-roles
### Description
Retrieves a list of assignable roles.
### Method
GET
### Endpoint
/admin/assignable-roles
## GET /admin/users/{user_id}/assignable-roles
### Description
Retrieves assignable roles for a specific user.
### Method
GET
### Endpoint
/admin/users/{user_id}/assignable-roles
```
--------------------------------
### Social Authentication API
Source: https://authtuna.shashstorm.in/batteries-included
Endpoints for handling OAuth-based social logins.
```APIDOC
## GET /social/{provider_name}/login
### Description
Initiates the OAuth login flow for a specific provider.
### Method
GET
### Endpoint
/social/{provider_name}/login
### Parameters
#### Path Parameters
- **provider_name** (string) - Required - The name of the OAuth provider (e.g., google, github).
## GET /social/{provider_name}/callback
### Description
Handles the OAuth callback from the provider.
### Method
GET
### Endpoint
/social/{provider_name}/callback
### Parameters
#### Path Parameters
- **provider_name** (string) - Required - The name of the OAuth provider.
```
--------------------------------
### Assign Role via Permission Override
Source: https://authtuna.shashstorm.in/creating-roles
A user can be assigned a role if they possess a direct permission that overrides other checks, such as `roles:assign:Moderator`.
```python
# User has "roles:assign:Moderator" permission
await role_manager.assign_to_user(
user_id="target_user",
role_name="Moderator", # Allowed via permission
assigner_id=current_user.id
)
```
--------------------------------
### Utility: resolve_token_method
Source: https://authtuna.shashstorm.in/integrations
Infers the authentication method used for the request.
```APIDOC
## resolve_token_method(request)
### Description
Returns the token method inferred for the request: "COOKIE", "BEARER", or None.
```
--------------------------------
### Define Pydantic Models for MongoDB Data
Source: https://authtuna.shashstorm.in/rbac-example
Create Pydantic models for handling MongoDB data, ensuring proper serialization and type validation. The `Todo` model includes fields for content, user ID, and organization ID, with custom configuration for MongoDB object IDs.
```python
# advanced/main.py
class Todo(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
content: str
user_id: str # This ID comes from authtuna's User model
org_id: str # This ID comes from authtuna's Organization model
model_config = ConfigDict(
populate_by_name=True,
arbitrary_types_allowed=True,
json_encoders={ObjectId: str}
)
```
--------------------------------
### Add RBAC-Protected Admin Route
Source: https://authtuna.shashstorm.in/rbac-example
Secure an admin-only API endpoint using AuthTuna's `RoleChecker` to restrict access to specific roles, such as 'Admin', for sensitive operations like data cleanup.
```python
# advanced/main.py
@app.post("/api/admin/run-cleanup-step",
dependencies=[Depends(RoleChecker("Admin"))])
async def run_cleanup_step():
"""
This is the advanced user deletion task you requested.
It finds users in authtuna's 'DeletedUser' table with cleanup_counter=0,
deletes their data from our MongoDB, and increments the counter.
"""
users_processed = []
async with db_manager.get_db() as db:
# 1. Find users in authtuna's DB marked for deletion
stmt = select(DeletedUser).where(DeletedUser.cleanup_counter == 0)
# ... (implementation details)
for user in users_to_cleanup:
# 2. Delete their application data from MongoDB
delete_result = await TodoCollection.delete_many(
{"user_id": user.user_id}
)
# ... (update counter)
return { ... }
```
--------------------------------
### Search and Filter Users
Source: https://authtuna.shashstorm.in/managing-user
Performs advanced queries on the user database using identity, role, or scope filters.
```python
# Search by identity (email or username)
users = await user_manager.search_users(
identity="john", # Matches email or username containing "john"
skip=0,
limit=20
)
# Search by role
admin_users = await user_manager.search_users(
role="Admin",
is_active=True
)
# Search by scope
project_users = await user_manager.search_users(
scope="project:web-app"
)
```
--------------------------------
### Input Sanitization for Permission Names
Source: https://authtuna.shashstorm.in/managing-permissions
AuthTuna validates and sanitizes permission names to prevent injection attacks and ensure system stability by disallowing problematic special characters and enforcing length limits.
```python
# AuthTuna validates permission names:
# - No special characters that could cause issues
# - Reasonable length limits
```
--------------------------------
### Assign Role via Hierarchy
Source: https://authtuna.shashstorm.in/creating-roles
Assigns a role to a user based on the defined hierarchical level structure.
```python
await role_manager.assign_to_user(
user_id="target_user",
role_name="Moderator", # Allowed via hierarchy
assigner_id=admin_user.id
)
```
--------------------------------
### Suspend User Accounts
Source: https://authtuna.shashstorm.in/managing-user
Invalidates active sessions and prevents login for a specific user account.
```python
# Suspend a user account
suspended_user = await user_manager.suspend_user(
user_id="user_123",
admin_id="admin_456",
reason="Violation of terms of service"
)
# User cannot log in while suspended
# All active sessions are invalidated
# Reason is logged for audit purposes
```