Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

v0.6.3: Add API token authentication for programmatic access

Murtaza Nasir904a77cf5a58
diff --git a/README.md b/README.md
index d3573ca2..e5ba5007 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
<a href="https://www.gnu.org/licenses/agpl-3.0"><img alt="AGPL v3" src="https://img.shields.io/badge/License-AGPL_v3-blue.svg"></a>
<a href="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml"><img alt="Docker Build" src="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml/badge.svg"></a>
<a href="https://hub.docker.com/r/learnedmachine/speakr"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/learnedmachine/speakr"></a>
- <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.6.2-brightgreen.svg"></a>
+ <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.6.3-brightgreen.svg"></a>
</p>
<p align="center">
@@ -145,17 +145,24 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:
- [Troubleshooting](https://murtaza-nasir.github.io/speakr/troubleshooting) - Common issues and solutions
- [FAQ](https://murtaza-nasir.github.io/speakr/faq) - Frequently asked questions
-## Latest Release (v0.6.2)
+## Latest Release (v0.6.3)
-**Maintenance Release** - UX Polish & Bug Fixes
+**New Feature** - API Token Authentication
-- **Standardized Modal UX** - All 20+ modals now close on backdrop click with consistent X button placement
-- **Markdown Support** - Recording disclaimer now supports full markdown formatting
-- **Crash Recovery** - Fixed IndexedDB errors and blank screen issues after browser crashes
-- **Processing Queue Fix** - Deleted recordings properly removed from queue (no more ghost entries)
-- **Performance** - Reduced recording chunk interval to 5 seconds for 80% less overhead
+- **API Tokens** - Create personal access tokens for programmatic API access (automation tools, scripts, n8n/Zapier)
+- **Multiple Auth Methods** - Bearer token, X-API-Token header, API-Token header, or query parameter
+- **Token Management** - Create, revoke, and track token usage from Account Settings
+- **Flexible Expiration** - Set custom expiration periods or create non-expiring tokens
+- **Secure Storage** - Tokens are hashed (SHA-256) and never stored in plaintext
-Fully backward compatible with v0.6.0. No configuration changes required.
+Fully backward compatible with v0.6.x. No configuration changes required.
+
+### Previous Release (v0.6.2)
+
+- Standardized modal UX with backdrop click and consistent X button placement
+- Recording disclaimer markdown support
+- IndexedDB crash recovery fixes
+- Processing queue cleanup on delete
### Previous Release (v0.5.10)
diff --git a/VERSION b/VERSION
index 45964c66..e4c57af0 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-v0.6.2
+v0.6.3
diff --git a/docs/features.md b/docs/features.md
index 87f3e177..baee3c21 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -124,6 +124,27 @@ Export recordings in multiple formats for different purposes. Generate Word docu
Track all your shared recordings from a central dashboard. See what's been shared, when, and with what permissions. Modify share settings without generating new links, or instantly revoke access when shares are no longer appropriate. View shared recordings alongside your own content with clear visual indicators showing ownership and group affiliation.
+## API Access
+
+### Personal Access Tokens
+
+Speakr provides [API token authentication](user-guide/api-tokens.md) for programmatic access to your recordings. Create personal access tokens from your Account Settings to authenticate automation tools, scripts, and custom integrations without sharing your password.
+
+Tokens work with multiple authentication methods - the standard Authorization Bearer header, custom X-API-Token or API-Token headers, or query parameters for simple integrations. Each token is tied to your user account and provides the same access as logging in through the web interface.
+
+### Integration Support
+
+Build powerful workflows with popular automation platforms:
+
+- **n8n / Zapier / Make** - Trigger transcriptions, retrieve recordings, and integrate Speakr into your automation workflows
+- **Custom scripts** - Access your recordings programmatically with Python, JavaScript, or any language that supports HTTP
+- **CI/CD pipelines** - Automate audio processing as part of development workflows
+- **Mobile apps** - Build custom interfaces that connect to your Speakr instance
+
+### Token Security
+
+All tokens are hashed using SHA-256 before storage - the plaintext token is shown only once at creation. Set custom expiration periods for temporary integrations, or create non-expiring tokens for permanent workflows. Revoke tokens instantly from the Account Settings if compromised.
+
## Advanced Capabilities
### Audio Chunking
diff --git a/docs/index.md b/docs/index.md
index f8fc2a93..e2529a6c 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -6,16 +6,16 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,
<img src="assets/images/screenshots/Main view.png" alt="Main Interface" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
</div>
-!!! info "Latest Release: v0.6.2 - UX Polish & Bug Fixes"
- **Maintenance Release** - Improved user experience and stability
+!!! info "Latest Release: v0.6.3 - API Token Authentication"
+ **New Feature** - Programmatic API access for automation tools
- - **Standardized Modal UX** - All 20+ modals now close on backdrop click with consistent X button
- - **Markdown Support** - Recording disclaimer now supports full markdown formatting
- - **Crash Recovery** - Fixed IndexedDB errors and blank screen issues after browser crashes
- - **Processing Queue Fix** - Deleted recordings properly removed from queue
- - **Performance** - Reduced recording chunk interval to 5 seconds for 80% less overhead
+ - **API Tokens** - Create personal access tokens for programmatic API access (n8n, Zapier, scripts)
+ - **Multiple Auth Methods** - Bearer token, X-API-Token header, API-Token header, or query parameter
+ - **Token Management** - Create, revoke, and track token usage from Account Settings
+ - **Flexible Expiration** - Set custom expiration periods or create non-expiring tokens
+ - **Secure Storage** - Tokens are hashed (SHA-256) and never stored in plaintext
- ✅ Fully backward compatible with v0.6.0. No configuration changes required. [View full release notes](https://github.com/murtaza-nasir/speakr/releases/tag/v0.6.2)
+ ✅ Fully backward compatible with v0.6.x. No configuration changes required. [View full release notes](https://github.com/murtaza-nasir/speakr/releases/tag/v0.6.3)
## Quick Navigation
@@ -120,6 +120,15 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,
<li><a href="user-guide/sharing">Secure sharing</a></li>
</ul>
</div>
+
+ <div class="feature-card">
+ <h4>🔑 API Access</h4>
+ <ul>
+ <li><a href="user-guide/api-tokens">Personal access tokens</a></li>
+ <li>Automation tool integration</li>
+ <li>Secure token management</li>
+ </ul>
+ </div>
</div>
## Interactive Audio Synchronization
@@ -138,17 +147,22 @@ Learn more about [audio synchronization features](user-guide/transcripts.md#audi
## Latest Updates
-!!! info "Version 0.6.2 - UX Polish & Bug Fixes"
- **Maintenance Release** - Improved user experience and stability
+!!! info "Version 0.6.3 - API Token Authentication"
+ **New Feature** - Programmatic API access for automation tools
+
+ - **API Tokens** - Create personal access tokens for programmatic API access
+ - **Multiple Auth Methods** - Bearer token, X-API-Token header, API-Token header, or query parameter
+ - **Token Management** - Create, revoke, and track token usage from Account Settings
+ - **Flexible Expiration** - Set custom expiration periods or create non-expiring tokens
+ - **Secure Storage** - Tokens are hashed (SHA-256) and never stored in plaintext
- - **Standardized Modal UX** - All 20+ modals close on backdrop click with consistent X button placement
- - **Markdown Support** - Recording disclaimer supports full markdown formatting (headings, lists, links, code blocks)
- - **Crash Recovery Fixed** - Resolved IndexedDB errors and blank screen issues after browser/tab crashes
- - **Processing Queue Fix** - Deleted recordings properly removed from queue (no more ghost entries)
- - **Recording Performance** - Reduced chunk interval to 5 seconds for 80% less IndexedDB overhead
- - **Console Cleanup** - Removed repetitive logging during recording sessions
+ ✅ Fully backward compatible with v0.6.x. No configuration changes required.
- ✅ Fully backward compatible with v0.6.0. No configuration changes required.
+!!! success "Version 0.6.2 - UX Polish & Bug Fixes"
+ - Standardized modal UX with backdrop click and consistent X button placement
+ - Recording disclaimer markdown support
+ - IndexedDB crash recovery fixes
+ - Processing queue cleanup on delete
!!! success "Version 0.6.1 - Offline Ready"
- **HuggingFace Model Caching** - Embedding model persists across container restarts
diff --git a/docs/user-guide/api-tokens.md b/docs/user-guide/api-tokens.md
new file mode 100644
index 00000000..1f8ac1ca
--- /dev/null
+++ b/docs/user-guide/api-tokens.md
@@ -0,0 +1,214 @@
+# API Tokens
+
+API tokens enable programmatic access to your Speakr instance, allowing you to integrate with automation tools like n8n, Zapier, Make, or custom scripts. Each token is tied to your user account and provides the same access as logging in through the web interface.
+
+## Overview
+
+API tokens are personal access tokens that authenticate API requests on your behalf. They're perfect for:
+
+- **Automation workflows** - Trigger transcriptions from n8n, Zapier, or Make
+- **Custom scripts** - Build integrations with your existing tools
+- **CI/CD pipelines** - Automate audio processing in development workflows
+- **Mobile apps** - Access your recordings from custom applications
+
+!!! warning "Security Notice"
+ Treat API tokens like passwords. They provide full access to your account. Never share tokens publicly, commit them to version control, or expose them in client-side code.
+
+## Creating a Token
+
+1. Navigate to **Account Settings** → **API Tokens** tab
+2. Click **Create Token**
+3. Enter a descriptive name (e.g., "n8n automation", "CLI access")
+4. Choose an expiration period:
+ - **No expiration** - Token remains valid until manually revoked
+ - **30 days**, **90 days**, **1 year** - Token automatically expires
+5. Click **Create**
+
+!!! important "Save Your Token"
+ The token value is only shown once after creation. Copy it immediately and store it securely. If you lose it, you'll need to create a new token.
+
+## Using Your Token
+
+Speakr accepts tokens through multiple methods, giving you flexibility based on your integration needs.
+
+### Authorization Header (Recommended)
+
+The most secure and standard method:
+
+```bash
+curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
+ https://your-speakr-instance.com/api/recordings
+```
+
+### X-API-Token Header
+
+Alternative header format:
+
+```bash
+curl -H "X-API-Token: YOUR_TOKEN_HERE" \
+ https://your-speakr-instance.com/api/recordings
+```
+
+### API-Token Header
+
+Another alternative:
+
+```bash
+curl -H "API-Token: YOUR_TOKEN_HERE" \
+ https://your-speakr-instance.com/api/recordings
+```
+
+### Query Parameter
+
+For simple integrations (less secure - token visible in logs):
+
+```bash
+curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"
+```
+
+## Available API Endpoints
+
+Once authenticated, you can access the same data available through the web interface:
+
+| Endpoint | Method | Description |
+|----------|--------|-------------|
+| `/api/recordings` | GET | List your recordings with pagination |
+| `/api/recordings/<id>` | GET | Get a specific recording's details |
+| `/api/recordings/<id>/transcript` | GET | Get the transcript text |
+| `/api/recordings/<id>/summary` | GET | Get the AI-generated summary |
+| `/api/tags` | GET | List your tags |
+
+### Example: List Recordings
+
+```bash
+curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
+ "https://your-speakr-instance.com/api/recordings?page=1&per_page=25"
+```
+
+Response:
+```json
+{
+ "pagination": {
+ "page": 1,
+ "per_page": 25,
+ "total": 42,
+ "total_pages": 2,
+ "has_next": true,
+ "has_prev": false
+ },
+ "recordings": [
+ {
+ "id": 123,
+ "title": "Team Meeting Notes",
+ "status": "COMPLETED",
+ "created_at": "Nov 27, 2025, 2:30:00 PM",
+ "tags": [...]
+ }
+ ]
+}
+```
+
+## Managing Tokens
+
+### Viewing Active Tokens
+
+The API Tokens tab shows all your active tokens with:
+
+- **Name** - The descriptive name you assigned
+- **Status** - Active, expired, or revoked
+- **Created date** - When the token was created
+- **Last used** - When the token was last used for authentication
+- **Expiration** - When the token will expire (if set)
+
+### Revoking Tokens
+
+Click the trash icon next to any token to revoke it immediately. Revoked tokens:
+
+- Stop working instantly
+- Cannot be restored
+- Should be replaced with a new token if needed
+
+!!! tip "Best Practice"
+ Revoke tokens you no longer need. If you suspect a token has been compromised, revoke it immediately and create a new one.
+
+## Security Best Practices
+
+### Do's
+
+- ✅ Use descriptive names to track token purposes
+- ✅ Set expiration dates for temporary integrations
+- ✅ Revoke unused tokens promptly
+- ✅ Store tokens in secure credential managers
+- ✅ Use environment variables in scripts
+
+### Don'ts
+
+- ❌ Share tokens with others (create separate tokens per user)
+- ❌ Commit tokens to version control
+- ❌ Include tokens in client-side JavaScript
+- ❌ Use the same token for multiple purposes
+- ❌ Log full token values in application logs
+
+## Integration Examples
+
+### n8n Workflow
+
+In n8n, use the HTTP Request node with:
+
+- **Authentication**: Header Auth
+- **Name**: `Authorization`
+- **Value**: `Bearer YOUR_TOKEN_HERE`
+
+### Python Script
+
+```python
+import requests
+
+TOKEN = "YOUR_TOKEN_HERE"
+BASE_URL = "https://your-speakr-instance.com"
+
+headers = {"Authorization": f"Bearer {TOKEN}"}
+
+# List recordings
+response = requests.get(f"{BASE_URL}/api/recordings", headers=headers)
+recordings = response.json()["recordings"]
+
+for recording in recordings:
+ print(f"{recording['id']}: {recording['title']}")
+```
+
+### Shell Script
+
+```bash
+#!/bin/bash
+TOKEN="YOUR_TOKEN_HERE"
+BASE_URL="https://your-speakr-instance.com"
+
+# Get all recordings
+curl -s -H "Authorization: Bearer $TOKEN" \
+ "$BASE_URL/api/recordings" | jq '.recordings[].title'
+```
+
+## Troubleshooting
+
+### Token Not Working
+
+1. **Check token value** - Ensure you copied the complete token without extra spaces
+2. **Verify header format** - The Bearer prefix requires a space: `Bearer TOKEN`
+3. **Check expiration** - Expired tokens silently fail authentication
+4. **Verify endpoint** - Ensure you're using the correct URL
+
+### 401 Unauthorized
+
+- Token may be expired or revoked
+- Check the token is being sent correctly
+- Verify the endpoint requires authentication
+
+### 403 Forbidden
+
+- Token is valid but you don't have permission for that resource
+- Check if the recording belongs to your account
+
+---
+
+Next: Return to [Account Settings](settings.md) →
diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md
index f776528c..654335da 100644
--- a/docs/user-guide/index.md
+++ b/docs/user-guide/index.md
@@ -59,6 +59,13 @@ Welcome to the Speakr User Guide! This documentation will help you master every
<p>Configure preferences, manage speakers, create tags, and customize AI prompts.</p>
<a href="settings" class="card-link">Customize →</a>
</div>
+
+ <div class="guide-card">
+ <div class="card-icon">🔑</div>
+ <h3>API Tokens</h3>
+ <p>Create personal access tokens for automation tools, scripts, and programmatic API access.</p>
+ <a href="api-tokens" class="card-link">API Access →</a>
+ </div>
</div>
## Pro Tips for Success
diff --git a/docs/user-guide/settings.md b/docs/user-guide/settings.md
index 373768a3..784fa0b8 100644
--- a/docs/user-guide/settings.md
+++ b/docs/user-guide/settings.md
@@ -167,6 +167,56 @@ The ASR defaults feature is particularly valuable for consistent meeting types.
Edit and delete buttons on each card provide full control. Edit to refine prompts based on results, adjust colors for better organization, or update ASR defaults as meeting patterns change. Delete removes tags no longer needed, though this doesn't affect recordings already tagged - they retain their labels for historical accuracy.
+## API Tokens Tab
+
+The API Tokens tab enables programmatic access to your Speakr instance through personal access tokens. These tokens allow automation tools, scripts, and custom integrations to authenticate as your user account.
+
+### Creating Tokens
+
+Click the **Create Token** button to generate a new token. You'll provide a descriptive name (like "n8n automation" or "CLI scripts") and optionally set an expiration period. The token value is shown only once after creation - copy it immediately and store it securely.
+
+!!! warning "Token Security"
+ Treat API tokens like passwords. They provide full access to your account. Never share tokens publicly, commit them to version control, or expose them in client-side code.
+
+### Token Display
+
+Active tokens appear as compact cards showing:
+
+- **Name** - The descriptive name you assigned
+- **Status badge** - Active (green), expired (yellow), or revoked (red)
+- **Created date** - When the token was created
+- **Last used** - When the token last authenticated a request
+- **Expiration** - When the token expires, or "No expiration" for permanent tokens
+
+### Using Tokens
+
+Tokens can authenticate API requests through multiple methods:
+
+```bash
+# Authorization header (recommended)
+curl -H "Authorization: Bearer YOUR_TOKEN" https://speakr.example.com/api/recordings
+
+# X-API-Token header
+curl -H "X-API-Token: YOUR_TOKEN" https://speakr.example.com/api/recordings
+
+# Query parameter (less secure)
+curl "https://speakr.example.com/api/recordings?token=YOUR_TOKEN"
+```
+
+### Revoking Tokens
+
+Click the trash icon on any token card to revoke it immediately. Revoked tokens stop working instantly and cannot be restored. Create a new token if you need continued access.
+
+### Best Practices
+
+- Use descriptive names to track each token's purpose
+- Set expiration dates for temporary integrations
+- Revoke tokens you no longer need
+- Create separate tokens for different integrations
+- Never share tokens between users - each person should create their own
+
+For detailed API documentation and integration examples, see the [API Tokens Guide](api-tokens.md).
+
## About Tab
![About](../assets/images/screenshots/settings about page.png)
diff --git a/src/api/tokens.py b/src/api/tokens.py
new file mode 100644
index 00000000..1c19339b
--- /dev/null
+++ b/src/api/tokens.py
@@ -0,0 +1,187 @@
+"""
+API Token management routes.
+
+This blueprint handles creating, listing, and revoking API tokens
+for user authentication.
+"""
+
+import secrets
+from datetime import datetime, timedelta
+from flask import Blueprint, request, jsonify
+from flask_login import login_required, current_user
+
+from src.database import db
+from src.models import APIToken
+from src.utils.token_auth import hash_token
+
+# Create blueprint
+tokens_bp = Blueprint('tokens', __name__, url_prefix='/api/tokens')
+
+# Extensions (injected after app initialization)
+bcrypt = None
+csrf = None
+limiter = None
+
+
+def init_tokens_helpers(_bcrypt, _csrf, _limiter):
+ """Initialize extensions after app creation."""
+ global bcrypt, csrf, limiter
+ bcrypt = _bcrypt
+ csrf = _csrf
+ limiter = _limiter
+
+
+def rate_limit(limit_string):
+ """Decorator that applies rate limiting if limiter is available."""
+ def decorator(f):
+ from functools import wraps
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ return f(*args, **kwargs)
+ wrapper._rate_limit = limit_string
+ return wrapper
+ return decorator
+
+
+def generate_token():
+ """
+ Generate a secure random API token.
+
+ Returns:
+ str: A cryptographically secure random token
+ """
+ return secrets.token_urlsafe(32)
+
+
+@tokens_bp.route('', methods=['GET'])
+@login_required
+def list_tokens():
+ """
+ List all API tokens for the current user.
+
+ Returns:
+ JSON: List of token objects (without the actual token values)
+ """
+ tokens = APIToken.query.filter_by(user_id=current_user.id).all()
+ return jsonify({
+ 'tokens': [token.to_dict() for token in tokens]
+ })
+
+
+@tokens_bp.route('', methods=['POST'])
+@login_required
+@rate_limit("10 per hour")
+def create_token():
+ """
+ Create a new API token for the current user.
+
+ Request JSON:
+ name (str, optional): A friendly name for the token
+ expires_in_days (int, optional): Number of days until expiration (0 = no expiration)
+
+ Returns:
+ JSON: The new token object including the plaintext token (shown only once)
+ """
+ data = request.get_json()
+
+ # Validate input
+ name = data.get('name', 'Unnamed Token')
+ expires_in_days = data.get('expires_in_days', 0)
+
+ # Validate expiration
+ if not isinstance(expires_in_days, int) or expires_in_days < 0:
+ return jsonify({'error': 'expires_in_days must be a non-negative integer'}), 400
+
+ # Generate the token
+ plaintext_token = generate_token()
+ token_hash = hash_token(plaintext_token)
+
+ # Calculate expiration date
+ expires_at = None
+ if expires_in_days > 0:
+ expires_at = datetime.utcnow() + timedelta(days=expires_in_days)
+
+ # Create the token record
+ api_token = APIToken(
+ user_id=current_user.id,
+ token_hash=token_hash,
+ name=name,
+ expires_at=expires_at
+ )
+
+ db.session.add(api_token)
+ db.session.commit()
+
+ # Return the token data INCLUDING the plaintext token
+ # This is the only time the plaintext token will be shown
+ response = api_token.to_dict()
+ response['token'] = plaintext_token
+
+ return jsonify(response), 201
+
+
+@tokens_bp.route('/<int:token_id>', methods=['DELETE'])
+@login_required
+@rate_limit("20 per hour")
+def revoke_token(token_id):
+ """
+ Revoke (delete) an API token.
+
+ Args:
+ token_id (int): The ID of the token to revoke
+
+ Returns:
+ JSON: Success message
+ """
+ # Find the token
+ api_token = APIToken.query.filter_by(
+ id=token_id,
+ user_id=current_user.id
+ ).first()
+
+ if not api_token:
+ return jsonify({'error': 'Token not found'}), 404
+
+ # Delete the token
+ db.session.delete(api_token)
+ db.session.commit()
+
+ return jsonify({'message': 'Token revoked successfully'}), 200
+
+
+@tokens_bp.route('/<int:token_id>', methods=['PATCH'])
+@login_required
+@rate_limit("20 per hour")
+def update_token(token_id):
+ """
+ Update an API token's metadata (name only).
+
+ Args:
+ token_id (int): The ID of the token to update
+
+ Request JSON:
+ name (str): The new name for the token
+
+ Returns:
+ JSON: Updated token object
+ """
+ # Find the token
+ api_token = APIToken.query.filter_by(
+ id=token_id,
+ user_id=current_user.id
+ ).first()
+
+ if not api_token:
+ return jsonify({'error': 'Token not found'}), 404
+
+ # Update the name
+ data = request.get_json()
+ new_name = data.get('name')
+
+ if not new_name:
+ return jsonify({'error': 'name is required'}), 400
+
+ api_token.name = new_name
+ db.session.commit()
+
+ return jsonify(api_token.to_dict()), 200
diff --git a/src/app.py b/src/app.py
index 7f25e21f..2052c84e 100644
--- a/src/app.py
+++ b/src/app.py
@@ -438,6 +438,28 @@ def exempt_status_endpoints():
csrf = CSRFProtect(app)
+
+# Exempt token-authenticated requests from CSRF protection
+def csrf_exempt_for_api_tokens():
+ """
+ Exempt API token-authenticated requests from CSRF validation.
+
+ This allows automation tools (n8n, Zapier, curl, etc.) to make
+ authenticated requests without needing CSRF tokens.
+ """
+ from src.utils.token_auth import is_token_authenticated
+
+ # If request has a valid token, skip CSRF check
+ if is_token_authenticated():
+ # Mark this view as CSRF exempt
+ if hasattr(request, 'endpoint') and request.endpoint:
+ view_func = app.view_functions.get(request.endpoint)
+ if view_func:
+ csrf.exempt(view_func)
+
+
# Add context processor to make 'now' available to all templates
@app.context_processor
def inject_now():
@@ -497,9 +519,23 @@ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
def load_user(user_id):
return db.session.get(User, int(user_id))
+
+@login_manager.request_loader
+def load_user_from_request(request):
+ """
+ Load user from API token in the request.
+
+ This enables token-based authentication for API access
+ (e.g., from curl, n8n, Zapier, etc.).
+ """
+ from src.utils.token_auth import load_user_from_token
+ return load_user_from_token()
+
+
# --- Embedding and Chunking Utilities ---
from src.api.auth import auth_bp, init_auth_extensions
+from src.api.tokens import tokens_bp, init_tokens_helpers
from src.api.shares import shares_bp, init_shares_helpers
from src.api.recordings import recordings_bp, init_recordings_helpers
from src.api.tags import tags_bp, init_tags_helpers
@@ -523,6 +559,7 @@ client, chunking_service, version = initialize_config(app)
# Initialize blueprint helpers (inject extensions and utility functions)
init_auth_extensions(bcrypt, csrf, limiter)
+init_tokens_helpers(bcrypt, csrf, limiter)
init_shares_helpers(has_recording_access)
init_recordings_helpers(has_recording_access=has_recording_access, get_user_recording_status=get_user_recording_status, set_user_recording_status=set_user_recording_status, enrich_recording_dict_with_user_status=enrich_recording_dict_with_user_status, bcrypt=bcrypt, csrf=csrf, limiter=limiter, chunking_service=chunking_service)
init_tags_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
@@ -536,6 +573,7 @@ init_system_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, cs
# Register blueprints
app.register_blueprint(auth_bp)
+app.register_blueprint(tokens_bp)
app.register_blueprint(shares_bp)
app.register_blueprint(recordings_bp)
app.register_blueprint(tags_bp)
diff --git a/src/models/__init__.py b/src/models/__init__.py
index e7cbe38a..7312d268 100644
--- a/src/models/__init__.py
+++ b/src/models/__init__.py
@@ -15,6 +15,7 @@ from src.database import db
# Import all models
from .user import User, Speaker
+from .api_token import APIToken
from .speaker_snippet import SpeakerSnippet
from .recording import Recording, TranscriptChunk
from .sharing import Share, InternalShare, SharedRecordingState
@@ -34,6 +35,7 @@ __all__ = [
# User models
'User',
'Speaker',
+ 'APIToken',
'SpeakerSnippet',
# Recording models
'Recording',
diff --git a/src/models/api_token.py b/src/models/api_token.py
new file mode 100644
index 00000000..37a6a047
--- /dev/null
+++ b/src/models/api_token.py
@@ -0,0 +1,51 @@
+"""
+API Token database model.
+
+This module defines the APIToken model for managing user API tokens
+that allow authentication via Bearer tokens for automation tools.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class APIToken(db.Model):
+ """API Token model for token-based authentication."""
+
+ __tablename__ = 'api_token'
+
+ id = db.Column(db.Integer, primary_key=True)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ token_hash = db.Column(db.String(64), unique=True, nullable=False, index=True)
+ name = db.Column(db.String(100), nullable=True) # User-friendly label (e.g., "n8n", "CLI")
+ created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
+ last_used_at = db.Column(db.DateTime, nullable=True)
+ expires_at = db.Column(db.DateTime, nullable=True)
+ revoked = db.Column(db.Boolean, default=False, nullable=False, index=True)
+
+ # Relationship to User
+ user = db.relationship('User', backref=db.backref('api_tokens', lazy=True, cascade='all, delete-orphan'))
+
+ def __repr__(self):
+ return f"APIToken(name='{self.name}', user_id={self.user_id}, revoked={self.revoked})"
+
+ def to_dict(self):
+ """Convert token to dictionary for API responses."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,
+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,
+ 'revoked': self.revoked
+ }
+
+ def is_expired(self):
+ """Check if token has expired."""
+ if not self.expires_at:
+ return False
+ return self.expires_at < datetime.utcnow()
+
+ def is_valid(self):
+ """Check if token is valid (not revoked and not expired)."""
+ return not self.revoked and not self.is_expired()
diff --git a/src/utils/__init__.py b/src/utils/__init__.py
index b4cf829c..69e2cf32 100644
--- a/src/utils/__init__.py
+++ b/src/utils/__init__.py
@@ -34,6 +34,13 @@ from .database import (
migrate_column_type
)
+from .token_auth import (
+ extract_token_from_request,
+ hash_token,
+ load_user_from_token,
+ is_token_authenticated
+)
+
__all__ = [
# JSON parsing
'auto_close_json',
@@ -51,4 +58,9 @@ __all__ = [
# Database
'add_column_if_not_exists',
'migrate_column_type',
+ # Token authentication
+ 'extract_token_from_request',
+ 'hash_token',
+ 'load_user_from_token',
+ 'is_token_authenticated',
]
diff --git a/src/utils/token_auth.py b/src/utils/token_auth.py
new file mode 100644
index 00000000..9fd0086f
--- /dev/null
+++ b/src/utils/token_auth.py
@@ -0,0 +1,108 @@
+"""
+Token authentication utilities.
+
+This module provides token-based authentication for API access,
+allowing users to authenticate with Bearer tokens instead of session cookies.
+"""
+
+import hashlib
+from datetime import datetime
+from flask import request
+from src.models import APIToken, User
+
+
+def extract_token_from_request():
+ """
+ Extract API token from various possible locations in the request.
+
+ Checks in order:
+ 1. Authorization header with Bearer scheme
+ 2. X-API-Token header
+ 3. API-Token header
+ 4. 'token' query parameter
+
+ Returns:
+ str: The extracted token, or None if not found
+ """
+ # Check Authorization header (Bearer token)
+ auth_header = request.headers.get('Authorization', '')
+ if auth_header.startswith('Bearer '):
+ return auth_header[7:] # Remove 'Bearer ' prefix
+
+ # Check X-API-Token header
+ token = request.headers.get('X-API-Token')
+ if token:
+ return token
+
+ # Check API-Token header
+ token = request.headers.get('API-Token')
+ if token:
+ return token
+
+ # Check query parameter
+ token = request.args.get('token')
+ if token:
+ return token
+
+ return None
+
+
+def hash_token(token):
+ """
+ Hash a token using SHA-256.
+
+ Args:
+ token (str): The plaintext token to hash
+
+ Returns:
+ str: The hexadecimal hash of the token
+ """
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+def load_user_from_token():
+ """
+ Load a user from an API token in the request.
+
+ This function is used by Flask-Login's request_loader to authenticate
+ users via API tokens instead of sessions.
+
+ Returns:
+ User: The authenticated user, or None if authentication fails
+ """
+ # Extract token from request
+ token = extract_token_from_request()
+ if not token:
+ return None
+
+ # Hash the token to look up in database
+ token_hash = hash_token(token)
+
+ # Find the token in the database
+ api_token = APIToken.query.filter_by(token_hash=token_hash).first()
+
+ # Validate token
+ if not api_token:
+ return None
+
+ if not api_token.is_valid():
+ return None
+
+ # Update last used timestamp
+ api_token.last_used_at = datetime.utcnow()
+ from src.database import db
+ db.session.commit()
+
+ # Return the associated user
+ return api_token.user
+
+
+def is_token_authenticated():
+ """
+ Check if the current request is authenticated via API token.
+
+ Returns:
+ bool: True if a valid token was provided, False otherwise
+ """
+ token = extract_token_from_request()
+ return token is not None
diff --git a/static/js/modules/composables/index.js b/static/js/modules/composables/index.js
index 5c0d970d..d5411a24 100644
--- a/static/js/modules/composables/index.js
+++ b/static/js/modules/composables/index.js
@@ -13,6 +13,7 @@
* - modals: Modal dialog management
* - chat: AI chat functionality
* - pwa: PWA features (install prompt, notifications, badging, media session)
+ * - tokens: API token management
*/
export { useRecordings } from './recordings.js';
@@ -26,3 +27,4 @@ export { useTranscription } from './transcription.js';
export { useSpeakers } from './speakers.js';
export { useChat } from './chat.js';
export { usePWA } from './pwa.js';
+export { useTokens } from './tokens.js';
diff --git a/static/js/modules/composables/tokens.js b/static/js/modules/composables/tokens.js
new file mode 100644
index 00000000..c1d4323c
--- /dev/null
+++ b/static/js/modules/composables/tokens.js
@@ -0,0 +1,286 @@
+/**
+ * API Tokens Management Composable
+ * Handles API token operations for user authentication
+ */
+
+const { ref, computed } = Vue;
+
+export function useTokens({ showToast, setGlobalError }) {
+ // State
+ const tokens = ref([]);
+ const isLoadingTokens = ref(false);
+ const showCreateTokenModal = ref(false);
+ const showTokenSecretModal = ref(false);
+ const newTokenSecret = ref('');
+ const newTokenData = ref(null);
+ const tokenForm = ref({
+ name: '',
+ expires_in_days: 0 // 0 = no expiration
+ });
+
+ // Computed
+ const hasTokens = computed(() => tokens.value.length > 0);
+
+ const activeTokens = computed(() => {
+ return tokens.value.filter(token => !token.revoked && !isTokenExpired(token));
+ });
+
+ const expiredOrRevokedTokens = computed(() => {
+ return tokens.value.filter(token => token.revoked || isTokenExpired(token));
+ });
+
+ // Helper methods
+ const isTokenExpired = (token) => {
+ if (!token.expires_at) return false;
+ const expiryDate = new Date(token.expires_at);
+ return expiryDate < new Date();
+ };
+
+ const formatTokenDate = (dateString) => {
+ if (!dateString) return 'Never';
+ const date = new Date(dateString);
+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
+ };
+
+ const getTokenStatus = (token) => {
+ if (token.revoked) return 'revoked';
+ if (isTokenExpired(token)) return 'expired';
+ return 'active';
+ };
+
+ const getTokenStatusClass = (token) => {
+ const status = getTokenStatus(token);
+ const baseClasses = 'px-2 py-1 text-xs font-semibold rounded';
+
+ switch (status) {
+ case 'active':
+ return `${baseClasses} bg-green-100 text-green-800`;
+ case 'expired':
+ return `${baseClasses} bg-yellow-100 text-yellow-800`;
+ case 'revoked':
+ return `${baseClasses} bg-red-100 text-red-800`;
+ default:
+ return `${baseClasses} bg-gray-100 text-gray-800`;
+ }
+ };
+
+ // API methods
+ const loadTokens = async () => {
+ isLoadingTokens.value = true;
+ try {
+ const response = await fetch('/api/tokens', {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to load tokens');
+ }
+
+ const data = await response.json();
+ tokens.value = data.tokens || [];
+ } catch (error) {
+ console.error('Error loading tokens:', error);
+ setGlobalError('Failed to load API tokens: ' + error.message);
+ } finally {
+ isLoadingTokens.value = false;
+ }
+ };
+
+ const createToken = async () => {
+ if (!tokenForm.value.name || tokenForm.value.name.trim() === '') {
+ showToast('Please enter a token name', 'error');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const response = await fetch('/api/tokens', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ name: tokenForm.value.name,
+ expires_in_days: parseInt(tokenForm.value.expires_in_days) || 0
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to create token');
+ }
+
+ const data = await response.json();
+
+ // Store the plaintext token to show to user (only shown once)
+ newTokenSecret.value = data.token;
+ newTokenData.value = {
+ id: data.id,
+ name: data.name,
+ created_at: data.created_at,
+ expires_at: data.expires_at
+ };
+
+ // Add to tokens list (without the plaintext token)
+ tokens.value.unshift({
+ id: data.id,
+ name: data.name,
+ created_at: data.created_at,
+ last_used_at: data.last_used_at,
+ expires_at: data.expires_at,
+ revoked: data.revoked
+ });
+
+ // Reset form
+ tokenForm.value = {
+ name: '',
+ expires_in_days: 0
+ };
+
+ // Close create modal and show secret modal
+ showCreateTokenModal.value = false;
+ showTokenSecretModal.value = true;
+
+ showToast('API token created successfully', 'success');
+ } catch (error) {
+ console.error('Error creating token:', error);
+ showToast('Failed to create token: ' + error.message, 'error');
+ }
+ };
+
+ const revokeToken = async (tokenId, tokenName) => {
+ if (!confirm(`Are you sure you want to revoke the token "${tokenName}"? This action cannot be undone and any applications using this token will lose access.`)) {
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const response = await fetch(`/api/tokens/${tokenId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to revoke token');
+ }
+
+ // Remove from local list
+ tokens.value = tokens.value.filter(t => t.id !== tokenId);
+
+ showToast('Token revoked successfully', 'success');
+ } catch (error) {
+ console.error('Error revoking token:', error);
+ showToast('Failed to revoke token: ' + error.message, 'error');
+ }
+ };
+
+ const updateTokenName = async (tokenId, newName) => {
+ if (!newName || newName.trim() === '') {
+ showToast('Token name cannot be empty', 'error');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const response = await fetch(`/api/tokens/${tokenId}`, {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ name: newName })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to update token');
+ }
+
+ const data = await response.json();
+
+ // Update local token
+ const token = tokens.value.find(t => t.id === tokenId);
+ if (token) {
+ token.name = data.name;
+ }
+
+ showToast('Token name updated', 'success');
+ } catch (error) {
+ console.error('Error updating token:', error);
+ showToast('Failed to update token: ' + error.message, 'error');
+ }
+ };
+
+ const copyTokenToClipboard = async (token) => {
+ try {
+ await navigator.clipboard.writeText(token);
+ showToast('Token copied to clipboard', 'success');
+ } catch (error) {
+ console.error('Error copying token:', error);
+ showToast('Failed to copy token to clipboard', 'error');
+ }
+ };
+
+ const openCreateTokenModal = () => {
+ tokenForm.value = {
+ name: '',
+ expires_in_days: 0
+ };
+ showCreateTokenModal.value = true;
+ };
+
+ const closeCreateTokenModal = () => {
+ showCreateTokenModal.value = false;
+ tokenForm.value = {
+ name: '',
+ expires_in_days: 0
+ };
+ };
+
+ const closeTokenSecretModal = () => {
+ showTokenSecretModal.value = false;
+ newTokenSecret.value = '';
+ newTokenData.value = null;
+ };
+
+ return {
+ // State
+ tokens,
+ isLoadingTokens,
+ showCreateTokenModal,
+ showTokenSecretModal,
+ newTokenSecret,
+ newTokenData,
+ tokenForm,
+
+ // Computed
+ hasTokens,
+ activeTokens,
+ expiredOrRevokedTokens,
+
+ // Methods
+ isTokenExpired,
+ formatTokenDate,
+ getTokenStatus,
+ getTokenStatusClass,
+ loadTokens,
+ createToken,
+ revokeToken,
+ updateTokenName,
+ copyTokenToClipboard,
+ openCreateTokenModal,
+ closeCreateTokenModal,
+ closeTokenSecretModal
+ };
+}
diff --git a/static/locales/en.json b/static/locales/en.json
index daab6e94..4baa60d6 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -89,6 +89,7 @@
},
"accountTabs": {
"about": "About",
+ "apiTokens": "API Tokens",
"customPrompts": "Custom Prompts",
"promptOptions": "Prompt Options",
"sharedTranscripts": "Shared Transcripts",
@@ -96,6 +97,22 @@
"tagManagement": "Tag Management",
"transcriptTemplates": "Transcript Templates"
},
+ "apiTokens": {
+ "activeTokens": "Active Tokens",
+ "created": "Created",
+ "createFirstToken": "Create your first API token to enable programmatic access",
+ "createToken": "Create Token",
+ "description": "Create and manage API tokens for programmatic access to your account",
+ "expires": "Expires",
+ "lastUsed": "Last used",
+ "neverUsed": "Never used",
+ "noExpiration": "No expiration",
+ "noTokens": "No API Tokens",
+ "securityNotice": "Security Notice",
+ "securityWarning": "Treat API tokens like passwords. They provide full access to your account. Never share tokens in publicly accessible areas such as GitHub, client-side code, or logs",
+ "title": "API Tokens",
+ "usageExamples": "Usage Examples"
+ },
"eventExtraction": {
"title": "Event Extraction",
"enableLabel": "Enable automatic event extraction from transcripts",
diff --git a/templates/account.html b/templates/account.html
index 3d0a5584..455eefb7 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -460,6 +460,9 @@
<a href="#" id="tab-templates" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-file-alt mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.transcriptTemplates">Templates</span>
</a>
+ <a href="#" id="tab-tokens" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
+ <i class="fas fa-key mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.apiTokens">API Tokens</span>
+ </a>
<a href="#" id="tab-about" class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)] rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-info-circle mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span data-i18n="accountTabs.about">About</span>
</a>
@@ -929,6 +932,101 @@
</div>
</div>
+ <!-- API Tokens Tab Content -->
+ <div id="content-tokens" class="hidden tab-content pt-6">
+ <div class="space-y-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)]">
+ <i class="fas fa-key mr-2 text-[var(--text-accent)]"></i>
+ <span data-i18n="apiTokens.title">API Tokens</span>
+ </h2>
+ <p class="mt-2 text-sm text-[var(--text-muted)]" data-i18n="apiTokens.description">
+ Create and manage API tokens for programmatic access to your account.
+ </p>
+ </div>
+ <button id="createTokenBtn" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-plus mr-2"></i>
+ <span data-i18n="apiTokens.createToken">Create Token</span>
+ </button>
+ </div>
+
+ <!-- Security Notice -->
+ <div class="bg-amber-50 border border-amber-200 rounded-lg p-4">
+ <div class="flex">
+ <div class="flex-shrink-0">
+ <i class="fas fa-exclamation-triangle text-amber-400"></i>
+ </div>
+ <div class="ml-3">
+ <h3 class="text-sm font-medium text-amber-800" data-i18n="apiTokens.securityNotice">Security Notice</h3>
+ <div class="mt-2 text-sm text-amber-700">
+ <p data-i18n="apiTokens.securityWarning">
+ Treat API tokens like passwords. They provide full access to your account. Never share tokens in publicly accessible areas such as GitHub, client-side code, or logs.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Loading State -->
+ <div id="tokensLoading" class="text-center py-12">
+ <i class="fas fa-spinner fa-spin text-4xl text-[var(--text-muted)] mb-4"></i>
+ <p class="text-[var(--text-muted)]">Loading tokens...</p>
+ </div>
+
+ <!-- Token List Container -->
+ <div id="tokensContainer" class="hidden">
+ <!-- Active Tokens Section -->
+ <div id="activeTokensSection" class="hidden">
+ <h3 class="text-sm font-medium text-[var(--text-muted)] mb-3">
+ <span data-i18n="apiTokens.activeTokens">Active Tokens</span>
+ <span id="activeTokensCount" class="ml-1 text-xs"></span>
+ </h3>
+ <div id="activeTokensList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
+ <!-- Populated dynamically -->
+ </div>
+ </div>
+
+ <!-- No Tokens Message -->
+ <div id="noTokensMessage" class="hidden text-center py-12 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg">
+ <i class="fas fa-key text-4xl text-[var(--text-muted)] mb-4"></i>
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2" data-i18n="apiTokens.noTokens">No API Tokens</h3>
+ <p class="text-sm text-[var(--text-muted)] mb-4" data-i18n="apiTokens.createFirstToken">Create your first API token to enable programmatic access.</p>
+ <button id="createTokenBtnEmpty" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] transition-colors">
+ <i class="fas fa-plus mr-2"></i>
+ <span data-i18n="apiTokens.createToken">Create Token</span>
+ </button>
+ </div>
+
+ <!-- Usage Examples -->
+ <div class="mt-8">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-3">
+ <i class="fas fa-book mr-2"></i>
+ <span data-i18n="apiTokens.usageExamples">Usage Examples</span>
+ </h3>
+ <div class="bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg p-4 space-y-4">
+ <div>
+ <h4 class="text-sm font-semibold text-[var(--text-primary)] mb-2">Using with curl:</h4>
+ <pre class="bg-[var(--bg-tertiary)] p-3 rounded text-xs overflow-x-auto"><code>curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
+ https://your-speakr-instance.com/api/recordings</code></pre>
+ </div>
+ <div>
+ <h4 class="text-sm font-semibold text-[var(--text-primary)] mb-2">Alternative header formats:</h4>
+ <pre class="bg-[var(--bg-tertiary)] p-3 rounded text-xs overflow-x-auto"><code># X-API-Token header
+curl -H "X-API-Token: YOUR_TOKEN_HERE" ...
+
+# API-Token header
+curl -H "API-Token: YOUR_TOKEN_HERE" ...
+
+# Query parameter
+curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</code></pre>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<div id="content-about" class="hidden tab-content pt-6">
<div class="space-y-8">
<!-- Header Section -->
@@ -1606,7 +1704,7 @@
<div class="grid grid-cols-2 gap-3">
<div>
<label for="tagMinSpeakers" class="block text-sm font-medium text-[var(--text-muted)] mb-1" data-i18n="editTagModal.minSpeakers">Min Speakers</label>
- <input type="number" id="tagMinSpeakers" name="default_min_speakers" min="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ <input type="number" id="tagMinSpeakers" name="default_min_speakers" min="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
</div>
<div>
@@ -1628,6 +1726,98 @@
</div>
</div>
+ <!-- Create API Token Modal -->
+ <div id="createTokenModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">
+ <i class="fas fa-key mr-2 text-[var(--text-accent)]"></i>Create API Token
+ </h3>
+ <button id="closeCreateTokenModal" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none">&times;</button>
+ </div>
+
+ <form id="createTokenForm" class="space-y-4">
+ <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
+
+ <div>
+ <label for="tokenNameInput" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Token Name *</label>
+ <input type="text" id="tokenNameInput" name="name" required maxlength="100" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., n8n automation, CLI access">
+ <p class="text-xs text-[var(--text-light)] mt-1">A descriptive name to help you identify this token</p>
+ </div>
+
+ <div>
+ <label for="tokenExpirationSelect" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Expiration</label>
+ <select id="tokenExpirationSelect" name="expires_in_days" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="0">Never expires</option>
+ <option value="7">7 days</option>
+ <option value="30">30 days</option>
+ <option value="90">90 days</option>
+ <option value="365">1 year</option>
+ </select>
+ <p class="text-xs text-[var(--text-light)] mt-1">When this token should expire</p>
+ </div>
+
+ <div class="bg-amber-50 border border-amber-200 rounded-lg p-3">
+ <div class="flex">
+ <i class="fas fa-info-circle text-amber-500 mr-2 mt-0.5"></i>
+ <p class="text-xs text-amber-700">
+ The token will only be shown once after creation. Make sure to copy and save it securely.
+ </p>
+ </div>
+ </div>
+
+ <div class="flex justify-end space-x-3 pt-2">
+ <button type="button" id="cancelCreateTokenBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">Cancel</button>
+ <button type="submit" id="submitCreateTokenBtn" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ <i class="fas fa-plus mr-2"></i>Create Token
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ <!-- Token Secret Modal (shown after creation) -->
+ <div id="tokenSecretModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">
+ <i class="fas fa-check-circle mr-2 text-green-500"></i>Token Created!
+ </h3>
+ </div>
+
+ <div class="space-y-4">
+ <div class="bg-red-50 border border-red-200 rounded-lg p-3">
+ <div class="flex">
+ <i class="fas fa-exclamation-triangle text-red-500 mr-2 mt-0.5"></i>
+ <p class="text-xs text-red-700">
+ <strong>Important!</strong> This is the only time you'll see this token. Copy it now and store it securely.
+ </p>
+ </div>
+ </div>
+
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Your API Token</label>
+ <div class="relative">
+ <input type="text" id="newTokenValue" readonly class="w-full px-3 py-2 pr-12 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] text-[var(--text-primary)] font-mono text-sm">
+ <button type="button" id="copyTokenBtn" class="absolute right-2 top-1/2 transform -translate-y-1/2 px-3 py-1.5 hover:bg-[var(--bg-tertiary)] rounded-md transition-all duration-200 flex items-center gap-1.5 border border-transparent hover:border-[var(--border-secondary)]" title="Copy to clipboard">
+ <i id="copyTokenIcon" class="fas fa-copy text-[var(--text-muted)]"></i>
+ <span id="copyTokenText" class="text-xs text-[var(--text-muted)] hidden">Copied!</span>
+ </button>
+ </div>
+ </div>
+
+ <div id="newTokenInfo" class="space-y-2 text-sm">
+ <!-- Populated dynamically -->
+ </div>
+
+ <div class="flex justify-end pt-2">
+ <button type="button" id="closeTokenSecretModal" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
+ <i class="fas fa-check mr-2"></i>I've Saved My Token
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
<script>
document.addEventListener('DOMContentLoaded', async function() {
@@ -1841,6 +2031,7 @@
const tabShares = document.getElementById('tab-shares');
const tabTags = document.getElementById('tab-tags');
const tabTemplates = document.getElementById('tab-templates');
+ const tabTokens = document.getElementById('tab-tokens');
const tabAbout = document.getElementById('tab-about');
const contentAccount = document.getElementById('content-account');
const contentPrompts = document.getElementById('content-prompts');
@@ -1848,6 +2039,7 @@
const contentSpeakers = document.getElementById('content-speakers');
const contentTags = document.getElementById('content-tags');
const contentTemplates = document.getElementById('content-templates');
+ const contentTokens = document.getElementById('content-tokens');
const contentAbout = document.getElementById('content-about');
const sharesContainer = document.getElementById('shares-container');
@@ -1862,6 +2054,7 @@
{ tab: tabSpeakers, content: contentSpeakers, name: 'speakers' },
{ tab: tabTags, content: contentTags, name: 'tags' },
{ tab: tabTemplates, content: contentTemplates, name: 'templates' },
+ { tab: tabTokens, content: contentTokens, name: 'tokens' },
{ tab: tabAbout, content: contentAbout, name: 'about' }
];
@@ -1889,6 +2082,8 @@
loadTags();
} else if (targetName === 'templates') {
loadTemplates();
+ } else if (targetName === 'tokens') {
+ loadTokensTab();
} else if (targetName === 'about') {
loadSystemInfo();
}
@@ -1918,6 +2113,10 @@
switchToTab('templates');
}
+ function showTokensTab() {
+ switchToTab('tokens');
+ }
+
function showAboutTab() {
switchToTab('about');
}
@@ -1952,6 +2151,11 @@
showTemplatesTab();
});
+ tabTokens.addEventListener('click', (e) => {
+ e.preventDefault();
+ showTokensTab();
+ });
+
tabAbout.addEventListener('click', (e) => {
e.preventDefault();
showAboutTab();
@@ -3942,6 +4146,339 @@
}
});
+ // API Tokens Management Functions
+ let tokensData = [];
+ let tokensTabLoaded = false;
+
+ async function loadTokensTab() {
+ if (tokensTabLoaded) return;
+
+ const tokensLoading = document.getElementById('tokensLoading');
+ const tokensContainer = document.getElementById('tokensContainer');
+
+ try {
+ tokensLoading.classList.remove('hidden');
+ tokensContainer.classList.add('hidden');
+
+ const response = await fetch('/api/tokens');
+ if (!response.ok) {
+ throw new Error('Failed to load tokens');
+ }
+
+ const data = await response.json();
+ tokensData = data.tokens || [];
+
+ renderTokensList();
+ tokensTabLoaded = true;
+
+ tokensLoading.classList.add('hidden');
+ tokensContainer.classList.remove('hidden');
+ } catch (error) {
+ console.error('Error loading tokens:', error);
+ tokensLoading.innerHTML = `
+ <div class="text-center py-12">
+ <i class="fas fa-exclamation-triangle text-4xl text-red-500 mb-4"></i>
+ <p class="text-red-600">Failed to load tokens: ${error.message}</p>
+ </div>
+ `;
+ }
+ }
+
+ function renderTokensList() {
+ const activeTokensSection = document.getElementById('activeTokensSection');
+ const activeTokensList = document.getElementById('activeTokensList');
+ const activeTokensCount = document.getElementById('activeTokensCount');
+ const noTokensMessage = document.getElementById('noTokensMessage');
+
+ // Filter active tokens
+ const activeTokens = tokensData.filter(token => !token.revoked && !isTokenExpired(token));
+
+ if (activeTokens.length > 0) {
+ activeTokensSection.classList.remove('hidden');
+ noTokensMessage.classList.add('hidden');
+ activeTokensCount.textContent = `(${activeTokens.length})`;
+
+ activeTokensList.innerHTML = activeTokens.map(token => {
+ const statusClass = getTokenStatusClass(token);
+ const status = getTokenStatus(token);
+ const createdDate = new Date(token.created_at).toLocaleDateString();
+ const lastUsed = token.last_used_at ? new Date(token.last_used_at).toLocaleDateString() : null;
+
+ return `
+ <div class="bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] hover:border-[var(--border-accent)] transition-colors duration-200">
+ <div class="p-3">
+ <!-- Header with name, status badge, and delete button -->
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center gap-2 flex-1 min-w-0">
+ <i class="fas fa-key text-[var(--text-accent)] text-sm flex-shrink-0"></i>
+ <h4 class="font-medium text-sm text-[var(--text-primary)] truncate">${escapeHtml(token.name)}</h4>
+ </div>
+ <div class="flex items-center gap-1 flex-shrink-0">
+ <span class="${statusClass} capitalize">${status}</span>
+ <button onclick="revokeToken(${token.id}, '${escapeHtml(token.name).replace(/'/g, "\\'")}' )"
+ class="p-1 text-[var(--text-danger)] hover:bg-[var(--bg-danger-light)] rounded transition-colors"
+ title="Revoke token">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Compact stats grid -->
+ <div class="grid grid-cols-2 gap-1 text-[10px] text-[var(--text-muted)]">
+ <div class="flex items-center gap-1">
+ <i class="fas fa-calendar-plus opacity-60"></i>
+ <span>${createdDate}</span>
+ </div>
+ <div class="flex items-center gap-1">
+ <i class="fas fa-clock opacity-60"></i>
+ <span>${lastUsed || 'Never used'}</span>
+ </div>
+ </div>
+
+ <!-- Expiration badge -->
+ <div class="mt-2">
+ ${token.expires_at ? `
+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-800">
+ <i class="fas fa-hourglass-half"></i>
+ Expires ${new Date(token.expires_at).toLocaleDateString()}
+ </span>
+ ` : `
+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-gray-100 text-gray-600">
+ <i class="fas fa-infinity"></i>
+ No expiration
+ </span>
+ `}
+ </div>
+ </div>
+ </div>
+ `;
+ }).join('');
+ } else {
+ activeTokensSection.classList.add('hidden');
+ noTokensMessage.classList.remove('hidden');
+ }
+ }
+
+ function isTokenExpired(token) {
+ if (!token.expires_at) return false;
+ const expiryDate = new Date(token.expires_at);
+ return expiryDate < new Date();
+ }
+
+ function formatTokenDate(dateString) {
+ if (!dateString) return 'Never';
+ const date = new Date(dateString);
+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
+ }
+
+ function getTokenStatus(token) {
+ if (token.revoked) return 'revoked';
+ if (isTokenExpired(token)) return 'expired';
+ return 'active';
+ }
+
+ function getTokenStatusClass(token) {
+ const status = getTokenStatus(token);
+ const baseClasses = 'px-2 py-1 text-xs font-semibold rounded';
+
+ switch (status) {
+ case 'active':
+ return `${baseClasses} bg-green-100 text-green-800`;
+ case 'expired':
+ return `${baseClasses} bg-yellow-100 text-yellow-800`;
+ case 'revoked':
+ return `${baseClasses} bg-red-100 text-red-800`;
+ default:
+ return `${baseClasses} bg-gray-100 text-gray-800`;
+ }
+ }
+
+ // Token modal elements - same pattern as tag modal
+ const createTokenModal = document.getElementById('createTokenModal');
+ const tokenSecretModal = document.getElementById('tokenSecretModal');
+ const createTokenForm = document.getElementById('createTokenForm');
+ const createTokenBtn = document.getElementById('createTokenBtn');
+ const createTokenBtnEmpty = document.getElementById('createTokenBtnEmpty');
+
+ // Close create token modal
+ function closeCreateTokenModal() {
+ createTokenModal.classList.add('hidden');
+ createTokenForm.reset();
+ }
+
+ // Close token secret modal
+ function closeTokenSecretModal() {
+ tokenSecretModal.classList.add('hidden');
+ }
+
+ // Open create token modal
+ function openCreateTokenModal() {
+ createTokenForm.reset();
+ createTokenModal.classList.remove('hidden');
+ }
+
+ // Show token secret modal
+ function showTokenSecretModal(tokenValue, tokenName, expiresAt) {
+ document.getElementById('newTokenValue').value = tokenValue;
+ document.getElementById('newTokenInfo').innerHTML = `
+ <div class="flex justify-between">
+ <span class="text-[var(--text-muted)]">Name:</span>
+ <span class="text-[var(--text-primary)] font-medium">${escapeHtml(tokenName)}</span>
+ </div>
+ <div class="flex justify-between">
+ <span class="text-[var(--text-muted)]">Expires:</span>
+ <span class="text-[var(--text-primary)]">${expiresAt ? formatTokenDate(expiresAt) : 'Never'}</span>
+ </div>
+ `;
+ tokenSecretModal.classList.remove('hidden');
+ }
+
+ // Create token button click handlers
+ if (createTokenBtn) {
+ createTokenBtn.addEventListener('click', openCreateTokenModal);
+ }
+ if (createTokenBtnEmpty) {
+ createTokenBtnEmpty.addEventListener('click', openCreateTokenModal);
+ }
+
+ // Close modal handlers
+ document.getElementById('closeCreateTokenModal')?.addEventListener('click', closeCreateTokenModal);
+ document.getElementById('cancelCreateTokenBtn')?.addEventListener('click', closeCreateTokenModal);
+ document.getElementById('closeTokenSecretModal')?.addEventListener('click', closeTokenSecretModal);
+
+ // Close modals when clicking outside (on the backdrop)
+ createTokenModal?.addEventListener('click', (event) => {
+ if (event.target === createTokenModal) {
+ closeCreateTokenModal();
+ }
+ });
+ tokenSecretModal?.addEventListener('click', (event) => {
+ if (event.target === tokenSecretModal) {
+ closeTokenSecretModal();
+ }
+ });
+
+ // Copy token button
+ document.getElementById('copyTokenBtn')?.addEventListener('click', async () => {
+ const tokenValue = document.getElementById('newTokenValue').value;
+ const copyBtn = document.getElementById('copyTokenBtn');
+ const copyIcon = document.getElementById('copyTokenIcon');
+ const copyText = document.getElementById('copyTokenText');
+
+ try {
+ await navigator.clipboard.writeText(tokenValue);
+
+ // Visual feedback - change to success state
+ copyIcon.classList.remove('fa-copy', 'text-[var(--text-muted)]');
+ copyIcon.classList.add('fa-check', 'text-green-500');
+ copyText.classList.remove('hidden', 'text-[var(--text-muted)]');
+ copyText.classList.add('text-green-500');
+ copyBtn.classList.add('bg-green-50', 'border-green-200');
+
+ // Reset after 2 seconds
+ setTimeout(() => {
+ copyIcon.classList.remove('fa-check', 'text-green-500');
+ copyIcon.classList.add('fa-copy', 'text-[var(--text-muted)]');
+ copyText.classList.add('hidden', 'text-[var(--text-muted)]');
+ copyText.classList.remove('text-green-500');
+ copyBtn.classList.remove('bg-green-50', 'border-green-200');
+ }, 2000);
+
+ showToast('Token copied to clipboard', 'success');
+ } catch (error) {
+ console.error('Error copying token:', error);
+ showToast('Failed to copy token to clipboard', 'error');
+ }
+ });
+
+ // Form submission handler
+ createTokenForm?.addEventListener('submit', async (e) => {
+ e.preventDefault();
+
+ const tokenName = document.getElementById('tokenNameInput').value.trim();
+ const expiresInDays = parseInt(document.getElementById('tokenExpirationSelect').value);
+
+ if (!tokenName) {
+ showToast('Please enter a token name', 'error');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch('/api/tokens', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ name: tokenName,
+ expires_in_days: expiresInDays
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to create token');
+ }
+
+ const data = await response.json();
+
+ // Add to local list
+ tokensData.unshift({
+ id: data.id,
+ name: data.name,
+ created_at: data.created_at,
+ last_used_at: data.last_used_at,
+ expires_at: data.expires_at,
+ revoked: data.revoked
+ });
+
+ renderTokensList();
+
+ // Close create modal and show secret modal
+ closeCreateTokenModal();
+ showTokenSecretModal(data.token, data.name, data.expires_at);
+
+ showToast('API token created successfully', 'success');
+ } catch (error) {
+ console.error('Error creating token:', error);
+ showToast('Failed to create token: ' + error.message, 'error');
+ }
+ });
+
+ // Make revokeToken globally accessible for inline onclick handlers
+ window.revokeToken = async function(tokenId, tokenName) {
+ if (!confirm(`Are you sure you want to revoke the token "${tokenName}"? This action cannot be undone and any applications using this token will lose access.`)) {
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/tokens/${tokenId}`, {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to revoke token');
+ }
+
+ // Remove from local list
+ tokensData = tokensData.filter(t => t.id !== tokenId);
+ renderTokensList();
+
+ showToast('Token revoked successfully', 'success');
+ } catch (error) {
+ console.error('Error revoking token:', error);
+ showToast('Failed to revoke token: ' + error.message, 'error');
+ }
+ };
+
// Template Management Functions
let templates = [];
let currentTemplate = null;
@@ -4197,5 +4734,6 @@
}
});
</script>
+
</body>
</html>