44 lines
1.7 KiB
Python
44 lines
1.7 KiB
Python
|
import cherrypy
|
||
|
from services.wireguard_service import read_config, write_config, create_backup, reload_wireguard_service
|
||
|
from auth.token_auth import validate_token
|
||
|
from utils.crypto_utils import encrypt_data
|
||
|
|
||
|
class WireGuardController:
|
||
|
@cherrypy.expose
|
||
|
@cherrypy.tools.json_in()
|
||
|
@cherrypy.tools.json_out()
|
||
|
def index(self):
|
||
|
if cherrypy.request.method != "POST":
|
||
|
raise cherrypy.HTTPError(405, "Method Not Allowed. Use POST.")
|
||
|
|
||
|
auth_header = cherrypy.request.headers.get('Authorization')
|
||
|
encrypted_data = cherrypy.request.body.read()
|
||
|
|
||
|
try:
|
||
|
# Decrypt the request and get the symmetric key
|
||
|
decrypted_data, symmetric_key = validate_token(auth_header, encrypted_data)
|
||
|
action = decrypted_data.get('action')
|
||
|
|
||
|
response_data = {}
|
||
|
|
||
|
# Handle different actions (as an example, adding a peer)
|
||
|
if action == 'add_peer':
|
||
|
create_backup()
|
||
|
new_peer = decrypted_data.get('peer')
|
||
|
config = read_config("/etc/wireguard/wg0.conf")
|
||
|
config += "\n\n" + peer_to_string(new_peer)
|
||
|
write_config("/etc/wireguard/wg0.conf", config)
|
||
|
reload_wireguard_service("/etc/wireguard/wg0.conf")
|
||
|
response_data = {"message": "Peer added successfully"}
|
||
|
else:
|
||
|
response_data = {"error": "Invalid action"}
|
||
|
|
||
|
# Encrypt the response data before sending
|
||
|
encrypted_response = encrypt_data(response_data, symmetric_key)
|
||
|
return {"data": encrypted_response}
|
||
|
|
||
|
except Exception as e:
|
||
|
cherrypy.log(f"Error processing request: {str(e)}")
|
||
|
return {"error": "Invalid request"}, 400
|
||
|
|