diff --git a/api_v2/tests.py b/api_v2/tests.py index 03f0071..1c1fff0 100644 --- a/api_v2/tests.py +++ b/api_v2/tests.py @@ -5,7 +5,9 @@ from django.test import TestCase from api_v2.models import ApiKey from dns.models import DNSSettings, StaticHost - +from vpn_invite.models import InviteSettings, PeerInvite +from wireguard.models import Peer, WireGuardInstance +from wireguard_tools.models import EmailSettings class ApiV2ManageDnsRecordTests(TestCase): def setUp(self): @@ -117,3 +119,180 @@ class ApiV2ManageDnsRecordTests(TestCase): self.assertEqual(response.status_code, 200) self.assertFalse(StaticHost.objects.filter(hostname="del.example.com").exists()) mock_export.assert_not_called() + +class ApiV2PeerInviteTests(TestCase): + def setUp(self): + self.api_key = ApiKey.objects.create(name="invite-test-key", enabled=True) + self.wireguard_instance = WireGuardInstance.objects.create( + instance_id=0, + name="wg0", + address="10.0.0.1", + netmask=24, + listen_port=51820, + public_key="public_key", + private_key="private_key" + ) + self.api_key.allowed_instances.add(self.wireguard_instance) + + self.peer = Peer.objects.create( + wireguard_instance=self.wireguard_instance, + name="Test Peer", + public_key="peer_public_key", + private_key="peer_private_key" + ) + + # Create invite settings + InviteSettings.objects.create( + name='default_settings', + invite_url='https://vpn.example.com/invite/', + invite_expiration=30, + required_user_level=50, + invite_email_enabled=True + ) + + # Create email settings + EmailSettings.objects.create( + name='email_settings', + enabled=True, + smtp_host='smtp.example.com', + smtp_port=587, + smtp_username='user', + smtp_password='password', + smtp_from_address='vpn@example.com', + smtp_encryption='tls' + ) + + self.url = "/api/v2/peer_invite/" + + def test_create_invite_without_email(self): + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0", + "peer_uuid": str(self.peer.uuid) + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["status"], "success") + self.assertEqual(body["message"], "Invitation created successfully.") + self.assertIn("invite_data", body) + self.assertIn("url", body["invite_data"]) + self.assertIn("password", body["invite_data"]) + self.assertIn("expiration", body["invite_data"]) + + # Verify invite was created + self.assertTrue(PeerInvite.objects.filter(peer=self.peer).exists()) + + def test_create_invite_with_invalid_peer_uuid(self): + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0", + "peer_uuid": "00000000-0000-0000-0000-000000000000" + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 404) + body = response.json() + self.assertEqual(body["status"], "error") + self.assertEqual(body["error_message"], "Peer not found.") + + def test_create_invite_without_peer_uuid(self): + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0" + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 400) + body = response.json() + self.assertEqual(body["status"], "error") + self.assertEqual(body["error_message"], "peer_uuid is required.") + + def test_create_invite_with_invalid_instance(self): + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg999", + "peer_uuid": str(self.peer.uuid) + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 400) + body = response.json() + self.assertEqual(body["status"], "error") + self.assertEqual(body["error_message"], "Invalid or missing WireGuard instance.") + + @patch("wgwadmlibrary.tools.send_email") + def test_create_invite_with_email(self, mock_send_email): + mock_send_email.return_value = ('success', 'Email sent successfully.') + + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0", + "peer_uuid": str(self.peer.uuid), + "email": "user@example.com" + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["status"], "success") + self.assertEqual(body["message"], "Invitation created and email sent successfully.") + self.assertIn("invite_data", body) + + # Verify email was sent + mock_send_email.assert_called_once() + + @patch("wgwadmlibrary.tools.send_email") + def test_create_invite_with_email_failure(self, mock_send_email): + mock_send_email.return_value = ('error', 'SMTP server not available') + + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0", + "peer_uuid": str(self.peer.uuid), + "email": "user@example.com" + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 400) + body = response.json() + self.assertEqual(body["status"], "error") + self.assertIn("email failed", body["error_message"]) + self.assertIn("invite_data", body) + + def test_create_invite_without_invite_settings(self): + InviteSettings.objects.all().delete() + + response = self.client.post( + self.url, + data=json.dumps({ + "instance": "wg0", + "peer_uuid": str(self.peer.uuid) + }), + content_type="application/json", + HTTP_TOKEN=str(self.api_key.token), + ) + + self.assertEqual(response.status_code, 400) + body = response.json() + self.assertEqual(body["status"], "error") + self.assertEqual(body["error_message"], "VPN Invite not configured.") diff --git a/api_v2/urls_api.py b/api_v2/urls_api.py index 6c8ed5a..ebeb2d3 100644 --- a/api_v2/urls_api.py +++ b/api_v2/urls_api.py @@ -4,6 +4,7 @@ from .views_api import ( api_v2_manage_dns_record, api_v2_manage_peer, api_v2_peer_detail, + api_v2_peer_invite, api_v2_peer_list, api_v2_wireguard_status, ) @@ -13,5 +14,6 @@ urlpatterns = [ path('manage_dns_record/', api_v2_manage_dns_record, name='api_v2_manage_dns_record'), path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'), path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'), + path('peer_invite/', api_v2_peer_invite, name='api_v2_peer_invite'), path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'), ] diff --git a/api_v2/views_api.py b/api_v2/views_api.py index 521375b..3025505 100644 --- a/api_v2/views_api.py +++ b/api_v2/views_api.py @@ -6,6 +6,7 @@ from typing import List, Optional, Tuple from django.db import transaction from django.http import JsonResponse +from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from api.views import func_get_wireguard_status @@ -16,6 +17,9 @@ from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance from wireguard_peer.functions import func_create_new_peer from wireguard_tools.functions import func_reload_wireguard_interface from wireguard_tools.views import export_wireguard_configuration +from vpn_invite.models import InviteSettings, PeerInvite +from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email, user_has_access_to_peer + from .models import ApiKey @@ -848,3 +852,117 @@ def api_v2_wireguard_status(request): data = func_get_wireguard_status() return JsonResponse(data) + +@csrf_exempt +@api_doc( + summary="Create and send VPN peer invitations", + auth="Header token: ", + methods=["POST"], + params=[ + {"name": "instance", "in": "json", "type": "string", "required": True, "example": "wg0", + "description": "Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."}, + {"name": "peer_uuid", "in": "json", "type": "string", "required": True, + "description": "Peer UUID to create invitation for."}, + {"name": "email", "in": "json", "type": "string", "required": False, + "description": "Email address to send the invitation to. If provided, the invitation will be sent automatically."}, + ], + returns=[ + {"status": 200, "body": {"status": "success", "message": "Invitation created successfully.", "invite_data": {"url": "...", "password": "...", "expiration": "...", "email_subject": "...", "email_body": "...", "whatsapp_body": "...", "text_body": "...", "uuid": "..."}}}, + {"status": 400, "body": {"status": "error", "error_message": "Invalid payload: ..."}}, + {"status": 403, "body": {"status": "error", "error_message": "Invalid API key or permission denied."}}, + {"status": 404, "body": {"status": "error", "error_message": "Peer not found."}}, + ], + examples={ + "create_invite": { + "method": "POST", + "json": { + "instance": "wg0", + "peer_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + } + }, + "create_and_send_invite": { + "method": "POST", + "json": { + "instance": "wg0", + "peer_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", + "email": "user@example.com" + } + } + } +) +def api_v2_peer_invite(request): + if request.method != "POST": + return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405) + + try: + payload = json.loads(request.body.decode("utf-8")) if request.body else {} + except Exception: + return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400) + + # Validate API key + api_key, api_error = validate_api_key(request) + if not api_key: + return JsonResponse({"status": "error", "error_message": api_error}, status=403) + + # Get and validate instance + try: + wireguard_instance = WireGuardInstance.objects.get(instance_id=int(payload.get("instance", "").replace("wg", ""))) + except Exception: + wireguard_instance = None + + if not wireguard_instance: + return JsonResponse({"status": "error", "error_message": "Invalid or missing WireGuard instance."}, status=400) + + # Validate API key has access to this instance + if api_key.allowed_instances.exists(): + if not api_key.allowed_instances.filter(uuid=wireguard_instance.uuid).exists(): + return JsonResponse({"status": "error", "error_message": "This API key is not allowed to access the requested instance."}, status=403) + + # Get peer + peer_uuid = payload.get("peer_uuid") + if not peer_uuid: + return JsonResponse({"status": "error", "error_message": "peer_uuid is required."}, status=400) + + peer = Peer.objects.filter(uuid=peer_uuid, wireguard_instance=wireguard_instance).first() + if not peer: + return JsonResponse({"status": "error", "error_message": "Peer not found."}, status=404) + + # Check if API key has access to this peer - API keys have access to all peers in allowed instances + + # Clean up expired invites + PeerInvite.objects.filter(invite_expiration__lt=timezone.now()).delete() + + # Get invite settings + invite_settings = InviteSettings.objects.filter(name='default_settings').first() + if not invite_settings: + return JsonResponse({"status": "error", "error_message": "VPN Invite not configured."}, status=400) + + # Check user level - API keys are considered as admin level (50) + if invite_settings.required_user_level > 50: + return JsonResponse({"status": "error", "error_message": "Permission denied."}, status=403) + + # Get or create peer invite + peer_invite = PeerInvite.objects.filter(peer=peer).first() + if not peer_invite: + peer_invite = create_peer_invite(peer, invite_settings) + + # Prepare response data + data = { + 'status': 'success', + 'message': 'Invitation created successfully.', + 'invite_data': get_peer_invite_data(peer_invite, invite_settings) + } + + # Send email if requested + email = payload.get("email") + if email: + status, message = send_email(email, data['invite_data']['email_subject'], data['invite_data']['email_body']) + if status != 'success': + return JsonResponse({ + "status": "error", + "error_message": f"Invitation created but email failed: {message}", + "invite_data": data['invite_data'] + }, status=400) + data['message'] = 'Invitation created and email sent successfully.' + + return JsonResponse(data, status=200) diff --git a/wgwadmlibrary/tools.py b/wgwadmlibrary/tools.py index e2aed1b..abea108 100644 --- a/wgwadmlibrary/tools.py +++ b/wgwadmlibrary/tools.py @@ -148,7 +148,7 @@ def replace_message_variables(message: str, peer_invite: PeerInvite, invite_sett def get_peer_invite_data(peer_invite: PeerInvite, invite_settings: InviteSettings): data = { # The & at the end is to prevent the token from being concatenated with any other template text. - 'url': f'{invite_settings.invite_url}?token{peer_invite.uuid}&', + 'url': f'{invite_settings.invite_url}?token={peer_invite.uuid}&', 'password': peer_invite.invite_password, 'expiration': peer_invite.invite_expiration.isoformat(), 'email_subject': replace_message_variables(invite_settings.invite_email_subject, peer_invite, invite_settings),