Skip to content

Commit 57bbb81

Browse files
Update settings.py
1 parent f9e0f82 commit 57bbb81

File tree

1 file changed

+69
-66
lines changed

1 file changed

+69
-66
lines changed

app/settings.py

Lines changed: 69 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for
1+
from flask import Blueprint, render_template, request, jsonify
22
from flask_login import login_required, current_user
33
from app.models import db
44
from app.directadmin_api import DirectAdminAPI
55
import traceback
6-
import json
76

87
settings_bp = Blueprint('settings', __name__, url_prefix='/settings')
98

@@ -12,9 +11,11 @@
1211
def index():
1312
return render_template('settings.html')
1413

14+
# SEPARATE routes for GET and POST
1515
@settings_bp.route('/api/da-config', methods=['GET'])
1616
@login_required
1717
def get_da_config():
18+
"""GET endpoint to retrieve current config"""
1819
try:
1920
return jsonify({
2021
'da_server': current_user.da_server or '',
@@ -23,113 +24,115 @@ def get_da_config():
2324
'has_password': bool(current_user.da_password_encrypted)
2425
})
2526
except Exception as e:
26-
print(f"Error getting DA config: {e}")
27+
print(f"Error in GET da-config: {e}")
2728
return jsonify({'error': str(e)}), 500
2829

2930
@settings_bp.route('/api/da-config', methods=['POST'])
3031
@login_required
3132
def update_da_config():
32-
"""Save DirectAdmin settings"""
33-
print(f"\n=== SAVE ENDPOINT CALLED ===")
34-
print(f"Request method: {request.method}")
35-
print(f"Content-Type: {request.content_type}")
36-
print(f"Request headers: {dict(request.headers)}")
37-
38-
# Check if request has JSON content type
39-
if not request.content_type or 'application/json' not in request.content_type:
40-
print(f"ERROR: Wrong content type: {request.content_type}")
41-
return jsonify({
42-
'error': 'Content-Type must be application/json',
43-
'received_content_type': request.content_type
44-
}), 400
33+
"""POST endpoint to update config"""
34+
print(f"POST to da-config from user: {current_user.username}")
4535

4636
try:
47-
# Try to get JSON data
48-
try:
49-
data = request.get_json(force=True) # Force parsing even if content-type is wrong
50-
if not data:
51-
print("ERROR: No JSON data in request body")
52-
return jsonify({'error': 'No JSON data provided'}), 400
53-
except Exception as json_error:
54-
print(f"ERROR: Failed to parse JSON: {json_error}")
55-
print(f"Request data: {request.data}")
56-
return jsonify({
57-
'error': 'Invalid JSON in request body',
58-
'details': str(json_error)
59-
}), 400
37+
# Get JSON data
38+
data = request.get_json()
39+
if not data:
40+
return jsonify({'error': 'No data provided'}), 400
6041

6142
print(f"Received data: {data}")
62-
print(f"Current user: {current_user.username}")
6343

6444
# Validate required fields
6545
required_fields = ['da_server', 'da_username', 'da_domain']
66-
missing_fields = []
67-
68-
for field in required_fields:
69-
if not data.get(field, '').strip():
70-
missing_fields.append(field)
46+
missing_fields = [field for field in required_fields if not data.get(field, '').strip()]
7147

7248
if missing_fields:
73-
print(f"Missing fields: {missing_fields}")
7449
return jsonify({
7550
'error': f'Missing required fields: {", ".join(missing_fields)}',
7651
'missing_fields': missing_fields
7752
}), 400
7853

7954
# Ensure user has encryption key
8055
if not current_user.encryption_key:
81-
print("Generating encryption key")
8256
current_user.generate_encryption_key()
8357

8458
# Clean and save the server URL
8559
server_url = data['da_server'].strip()
8660
if not server_url.startswith(('http://', 'https://')):
8761
server_url = 'https://' + server_url
8862

89-
# Update DirectAdmin settings
63+
# Update settings
9064
current_user.da_server = server_url.rstrip('/')
9165
current_user.da_username = data['da_username'].strip()
9266
current_user.da_domain = data['da_domain'].strip()
9367

94-
# Only update password if provided
68+
# Update password if provided
9569
if data.get('da_password'):
96-
print("Updating DA password")
9770
current_user.set_da_password(data['da_password'])
9871
elif not current_user.da_password_encrypted:
99-
# No existing password and none provided
10072
return jsonify({
10173
'error': 'Password is required for initial setup',
10274
'missing_fields': ['da_password']
10375
}), 400
10476

105-
# Save to database
106-
try:
107-
db.session.commit()
108-
print("✓ Settings saved successfully")
109-
110-
return jsonify({
111-
'success': True,
112-
'message': 'Settings saved successfully!',
113-
'saved_data': {
114-
'da_server': current_user.da_server,
115-
'da_username': current_user.da_username,
116-
'da_domain': current_user.da_domain
117-
}
118-
})
77+
# Commit to database
78+
db.session.commit()
11979

120-
except Exception as db_error:
121-
print(f"Database error: {db_error}")
122-
db.session.rollback()
123-
return jsonify({
124-
'error': 'Database error while saving',
125-
'details': str(db_error)
126-
}), 500
80+
return jsonify({
81+
'success': True,
82+
'message': 'Settings saved successfully!'
83+
})
12784

12885
except Exception as e:
129-
print(f"ERROR in update_da_config: {str(e)}")
86+
print(f"Error in POST da-config: {str(e)}")
13087
print(traceback.format_exc())
13188
db.session.rollback()
89+
return jsonify({'error': str(e)}), 500
90+
91+
# Keep test-connection separate
92+
@settings_bp.route('/api/test-connection', methods=['POST'])
93+
@login_required
94+
def test_connection():
95+
"""Test DirectAdmin connection"""
96+
try:
97+
data = request.get_json()
98+
99+
# Use provided or saved credentials
100+
server = data.get('da_server') or current_user.da_server
101+
username = data.get('da_username') or current_user.da_username
102+
password = data.get('da_password') or current_user.get_da_password()
103+
104+
if not all([server, username, password]):
105+
return jsonify({'error': 'Missing credentials'}), 400
106+
107+
# Ensure proper URL format
108+
if not server.startswith(('http://', 'https://')):
109+
server = 'https://' + server
110+
111+
# Test connection
112+
api = DirectAdminAPI(server, username, password)
113+
success, message = api.test_connection()
114+
132115
return jsonify({
133-
'error': f'Failed to save settings: {str(e)}',
134-
'exception_type': type(e).__name__
135-
}), 500
116+
'success': success,
117+
'message': message
118+
})
119+
120+
except Exception as e:
121+
print(f"Test connection error: {str(e)}")
122+
return jsonify({'error': str(e), 'success': False}), 200
123+
124+
# Debug route to check available routes
125+
@settings_bp.route('/api/debug-routes', methods=['GET'])
126+
@login_required
127+
def debug_routes():
128+
"""Show all registered routes for debugging"""
129+
from flask import current_app
130+
routes = []
131+
for rule in current_app.url_map.iter_rules():
132+
if '/settings/' in rule.rule:
133+
routes.append({
134+
'endpoint': rule.endpoint,
135+
'methods': list(rule.methods),
136+
'path': rule.rule
137+
})
138+
return jsonify(routes)

0 commit comments

Comments
 (0)