working add and remove dns via config

This commit is contained in:
Karl 2025-07-19 11:05:09 +01:00
parent 5106686a12
commit 785fdb6dbb
2 changed files with 64 additions and 16 deletions

52
app.py
View File

@ -107,7 +107,7 @@ def index() -> Union[Response, str]:
@app.route('/vapid-public-key', methods=['GET']) @app.route('/vapid-public-key', methods=['GET'])
def proxy_vapid_public_key(): def proxy_vapid_public_key():
"""Proxies the request for the VAPID public key to the backend.""" """Proxies the request for the VAPID public key to the backend."""
backend_url = f"{app.config['BASE_URL']}/vapid-public-key" backend_url = f"{app.config['BACKEND_URL']}/vapid-public-key"
try: try:
response = requests.get(backend_url) response = requests.get(backend_url)
return Response(response.content, status=response.status_code, mimetype=response.headers['Content-Type']) return Response(response.content, status=response.status_code, mimetype=response.headers['Content-Type'])
@ -120,7 +120,7 @@ def proxy_save_subscription():
if not session.get("logged_in"): if not session.get("logged_in"):
return jsonify({'error': 'Unauthorized'}), 401 return jsonify({'error': 'Unauthorized'}), 401
backend_url = f"{app.config['BASE_URL']}/save-subscription" backend_url = f"{app.config['BACKEND_URL']}/save-subscription"
credentials = base64.b64decode(session["auth_credentials"]).decode() credentials = base64.b64decode(session["auth_credentials"]).decode()
username, password = credentials.split(":", 1) username, password = credentials.split(":", 1)
@ -140,7 +140,7 @@ def send_test_notification():
if not session.get("logged_in"): if not session.get("logged_in"):
return jsonify({'error': 'Unauthorized'}), 401 return jsonify({'error': 'Unauthorized'}), 401
backend_url = f"{app.config['BASE_URL']}/send-test-notification" backend_url = f"{app.config['BACKEND_URL']}/send-test-notification"
credentials = base64.b64decode(session["auth_credentials"]).decode() credentials = base64.b64decode(session["auth_credentials"]).decode()
username, password = credentials.split(":", 1) username, password = credentials.split(":", 1)
@ -159,7 +159,7 @@ def send_test_notification():
def home() -> str: def home() -> str:
"""Renders the home page with account statistics.""" """Renders the home page with account statistics."""
if session.get("logged_in"): if session.get("logged_in"):
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
all_accounts = get_user_accounts(base_url, session["auth_credentials"]) all_accounts = get_user_accounts(base_url, session["auth_credentials"])
return render_template( return render_template(
"home.html", "home.html",
@ -177,7 +177,7 @@ def login() -> Union[Response, str]:
password = request.form["password"] password = request.form["password"]
credentials = f"{username}:{password}" credentials = f"{username}:{password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode() encoded_credentials = base64.b64encode(credentials.encode()).decode()
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
login_url = f"{base_url}/Login" login_url = f"{base_url}/Login"
try: try:
@ -205,7 +205,7 @@ def urls() -> Union[Response, str]:
"""Renders the URLs page.""" """Renders the URLs page."""
if not session.get("logged_in"): if not session.get("logged_in"):
return redirect(url_for("home")) return redirect(url_for("home"))
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
return render_template( return render_template(
"urls.html", urls=get_urls(base_url, session["auth_credentials"]) "urls.html", urls=get_urls(base_url, session["auth_credentials"])
) )
@ -216,7 +216,7 @@ def user_accounts() -> Union[Response, str]:
"""Renders the user accounts page.""" """Renders the user accounts page."""
if not session.get("logged_in"): if not session.get("logged_in"):
return redirect(url_for("home")) return redirect(url_for("home"))
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
user_accounts_data = get_user_accounts(base_url, session["auth_credentials"]) user_accounts_data = get_user_accounts(base_url, session["auth_credentials"])
return render_template( return render_template(
"user_accounts.html", "user_accounts.html",
@ -238,7 +238,7 @@ def add_account() -> Union[Response, str]:
"""Handles adding a new user account.""" """Handles adding a new user account."""
if not session.get("logged_in"): if not session.get("logged_in"):
return redirect(url_for("index", next=request.url)) return redirect(url_for("index", next=request.url))
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
shared_text = request.args.get('shared_text') shared_text = request.args.get('shared_text')
if request.method == "POST": if request.method == "POST":
@ -262,7 +262,7 @@ def delete_account() -> Response:
"""Handles deleting a user account.""" """Handles deleting a user account."""
stream = request.form.get("stream") stream = request.form.get("stream")
username = request.form.get("username") username = request.form.get("username")
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
delete_user_account(base_url, session["auth_credentials"], stream, username) delete_user_account(base_url, session["auth_credentials"], stream, username)
cache.delete_memoized(user_accounts, key_prefix=make_cache_key) cache.delete_memoized(user_accounts, key_prefix=make_cache_key)
return redirect(url_for("user_accounts")) return redirect(url_for("user_accounts"))
@ -270,7 +270,7 @@ def delete_account() -> Response:
@app.route("/validateAccount", methods=["POST"]) @app.route("/validateAccount", methods=["POST"])
def validate_account() -> Tuple[Response, int]: def validate_account() -> Tuple[Response, int]:
"""Forwards account validation requests to the backend.""" """Forwards account validation requests to the backend."""
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
validate_url = f"{base_url}/validateAccount" validate_url = f"{base_url}/validateAccount"
credentials = base64.b64decode(session["auth_credentials"]).decode() credentials = base64.b64decode(session["auth_credentials"]).decode()
username, password = credentials.split(":", 1) username, password = credentials.split(":", 1)
@ -294,7 +294,7 @@ def stream_names() -> Union[Response, str]:
"""Fetches and returns stream names as JSON.""" """Fetches and returns stream names as JSON."""
if not session.get("logged_in"): if not session.get("logged_in"):
return redirect(url_for("home")) return redirect(url_for("home"))
base_url = app.config["BASE_URL"] base_url = app.config["BACKEND_URL"]
return jsonify(get_stream_names(base_url, session["auth_credentials"])) return jsonify(get_stream_names(base_url, session["auth_credentials"]))
@ -323,7 +323,7 @@ def check_expiring_accounts():
if not session.get("config_logged_in"): if not session.get("config_logged_in"):
return jsonify({'error': 'Unauthorized'}), 401 return jsonify({'error': 'Unauthorized'}), 401
backend_url = f"{app.config['BASE_URL']}/check-expiry" backend_url = f"{app.config['BACKEND_URL']}/check-expiry"
try: try:
response = requests.post(backend_url) response = requests.post(backend_url)
return Response(response.content, status=response.status_code, mimetype=response.headers['Content-Type']) return Response(response.content, status=response.status_code, mimetype=response.headers['Content-Type'])
@ -331,6 +331,34 @@ def check_expiring_accounts():
return jsonify({"error": str(e)}), 502 return jsonify({"error": str(e)}), 502
@app.route('/dns', methods=['GET', 'POST', 'DELETE'])
def proxy_dns():
"""Proxies DNS management requests to the backend."""
if not session.get("config_logged_in"):
return jsonify({'error': 'Unauthorized'}), 401
backend_url = f"{app.config['BACKEND_URL']}/dns"
credentials = base64.b64decode(session["auth_credentials"]).decode()
username, password = credentials.split(":", 1)
auth = requests.auth.HTTPBasicAuth(username, password)
try:
if request.method == 'GET':
response = requests.get(backend_url, auth=auth)
elif request.method == 'POST':
response = requests.post(backend_url, auth=auth, json=request.get_json())
if response.ok:
cache.clear()
elif request.method == 'DELETE':
response = requests.delete(backend_url, auth=auth, json=request.get_json())
if response.ok:
cache.clear()
return Response(response.content, status=response.status_code, mimetype=response.headers['Content-Type'])
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 502
if __name__ == "__main__": if __name__ == "__main__":
app.run( app.run(
debug=app.config["DEBUG"], debug=app.config["DEBUG"],

View File

@ -46,10 +46,21 @@
const dnsEntryInput = document.getElementById('dns-entry-input'); const dnsEntryInput = document.getElementById('dns-entry-input');
function fetchDnsList() { function fetchDnsList() {
fetch("{{ config.BASE_URL }}/dns") fetch("{{ url_for('proxy_dns') }}")
.then(response => response.json()) .then(response => {
if (!response.ok) {
// Log the error response text for debugging
response.text().then(text => console.error('Error response from proxy:', text));
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => { .then(data => {
dnsListTableBody.innerHTML = ''; dnsListTableBody.innerHTML = '';
if (!Array.isArray(data)) {
console.error("Received data is not an array:", data);
throw new Error("Invalid data format received from server.");
}
if (data.length === 0) { if (data.length === 0) {
const row = dnsListTableBody.insertRow(); const row = dnsListTableBody.insertRow();
const cell = row.insertCell(); const cell = row.insertCell();
@ -69,13 +80,22 @@
actionCell.appendChild(removeBtn); actionCell.appendChild(removeBtn);
}); });
} }
})
.catch(e => {
console.error('Error during fetchDnsList:', e);
dnsListTableBody.innerHTML = '';
const row = dnsListTableBody.insertRow();
const cell = row.insertCell();
cell.colSpan = 2;
cell.textContent = 'Error loading DNS entries. See browser console for details.';
cell.classList.add('text-center', 'text-danger');
}); });
} }
function addDnsEntry() { function addDnsEntry() {
const dnsEntry = dnsEntryInput.value.trim(); const dnsEntry = dnsEntryInput.value.trim();
if (dnsEntry) { if (dnsEntry) {
fetch("{{ config.BASE_URL }}/dns", { fetch("{{ url_for('proxy_dns') }}", {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@ -89,7 +109,7 @@
} }
function removeDnsEntry(dnsEntry) { function removeDnsEntry(dnsEntry) {
fetch("{{ config.BASE_URL }}/dns", { fetch("{{ url_for('proxy_dns') }}", {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'