Skip to content

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

Python

csrf issu

Murtaza Nasir5e0bed3bfcf7
diff --git a/app.py b/app.py
index 0524e50c..3cb8b370 100644
--- a/app.py
+++ b/app.py
@@ -880,7 +880,7 @@ def format_api_error_message(error_str):
# Check for token limit errors
if 'maximum context length' in error_lower and 'tokens' in error_lower:
- return "[Summary generation failed: The transcription is too long for AI processing. Try using a different LLM with a larger context size.]"
+ return "[Summary generation failed: The transcription is too long for AI processing. Request your admin to try using a different LLM with a larger context size, or set a limit for the transcript_length_limit in the system settings.]"
# Check for other common API errors
if 'rate limit' in error_lower:
@@ -2603,6 +2603,17 @@ def get_config():
app.logger.error(f"Error fetching configuration: {e}")
return jsonify({'error': str(e)}), 500
[email protected]('/api/csrf-token', methods=['GET'])
+def get_csrf_token():
+ """Get a fresh CSRF token for the frontend."""
+ try:
+ from flask_wtf.csrf import generate_csrf
+ token = generate_csrf()
+ return jsonify({'csrf_token': token})
+ except Exception as e:
+ app.logger.error(f"Error generating CSRF token: {e}")
+ return jsonify({'error': str(e)}), 500
+
# --- Flask Routes ---
@app.route('/')
@login_required
diff --git a/static/js/csrf-refresh.js b/static/js/csrf-refresh.js
new file mode 100644
index 00000000..ca1c121a
--- /dev/null
+++ b/static/js/csrf-refresh.js
@@ -0,0 +1,111 @@
+// CSRF Token Management with Auto-Refresh
+class CSRFManager {
+ constructor() {
+ this.token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ this.refreshPromise = null;
+ this.setupFetchInterceptor();
+ }
+
+ async refreshToken() {
+ // Prevent multiple simultaneous refresh requests
+ if (this.refreshPromise) {
+ return this.refreshPromise;
+ }
+
+ this.refreshPromise = this.performTokenRefresh();
+ try {
+ const newToken = await this.refreshPromise;
+ return newToken;
+ } finally {
+ this.refreshPromise = null;
+ }
+ }
+
+ async performTokenRefresh() {
+ try {
+ console.log('Refreshing CSRF token...');
+ const response = await fetch('/api/csrf-token', {
+ method: 'GET',
+ credentials: 'same-origin'
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to refresh CSRF token: ${response.status}`);
+ }
+
+ const data = await response.json();
+ if (data.csrf_token) {
+ this.token = data.csrf_token;
+ // Update the meta tag for any other code that might read it
+ const metaTag = document.querySelector('meta[name="csrf-token"]');
+ if (metaTag) {
+ metaTag.setAttribute('content', this.token);
+ }
+ console.log('CSRF token refreshed successfully');
+ return this.token;
+ } else {
+ throw new Error('No CSRF token in response');
+ }
+ } catch (error) {
+ console.error('Failed to refresh CSRF token:', error);
+ throw error;
+ }
+ }
+
+ setupFetchInterceptor() {
+ const originalFetch = window.fetch;
+
+ window.fetch = async (url, options = {}) => {
+ // Add CSRF token to headers
+ const newOptions = { ...options };
+ newOptions.headers = {
+ 'X-CSRFToken': this.token,
+ ...newOptions.headers
+ };
+
+ // Make the request
+ let response = await originalFetch(url, newOptions);
+
+ // Check if the request failed due to CSRF token expiration
+ if (response.status === 400) {
+ try {
+ const errorData = await response.clone().json();
+ const errorMessage = errorData.error || '';
+
+ // Check if it's a CSRF token error
+ if (errorMessage.toLowerCase().includes('csrf') ||
+ errorMessage.toLowerCase().includes('token')) {
+
+ console.log('CSRF token expired, attempting refresh and retry...');
+
+ // Refresh the token
+ await this.refreshToken();
+
+ // Retry the original request with the new token
+ newOptions.headers['X-CSRFToken'] = this.token;
+ response = await originalFetch(url, newOptions);
+
+ if (response.ok) {
+ console.log('Request succeeded after CSRF token refresh');
+ }
+ }
+ } catch (parseError) {
+ // If we can't parse the error response, just return the original response
+ console.warn('Could not parse error response for CSRF check:', parseError);
+ }
+ }
+
+ return response;
+ };
+ }
+
+ // Method to manually get current token
+ getToken() {
+ return this.token;
+ }
+}
+
+// Initialize CSRF manager when DOM is loaded
+document.addEventListener('DOMContentLoaded', () => {
+ window.csrfManager = new CSRFManager();
+});
diff --git a/templates/index.html b/templates/index.html
index ff58a100..efb1d2ca 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -1854,6 +1854,9 @@
</div>
</div>
+ <!-- CSRF Token Management -->
+ <script src="{{ url_for('static', filename='js/csrf-refresh.js') }}"></script>
+
<!-- Vue.js Application Script -->
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
</body>