2020-12-13 10:38:41 +00:00
|
|
|
from django.db import transaction
|
2020-12-13 12:28:43 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
from .models import *
|
2020-12-13 12:28:43 +00:00
|
|
|
from .selectors import *
|
2020-12-13 17:34:43 +00:00
|
|
|
from .tasks import *
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-28 22:35:34 +00:00
|
|
|
|
2020-12-13 10:38:41 +00:00
|
|
|
@transaction.atomic
|
2020-12-13 16:59:35 +00:00
|
|
|
def create_wireguard_vpn(owner, public_key, network_mask):
|
2020-12-28 22:35:34 +00:00
|
|
|
# Check if the user has a membership.
|
|
|
|
#------------------------------------
|
|
|
|
# If yes, user is eligible for API access and 2 VPNs
|
|
|
|
# If user already has 2 VPNs, we deduct from the credit
|
|
|
|
# If deduction is higher than the allowed credit, we fail
|
|
|
|
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-28 22:35:34 +00:00
|
|
|
#
|
|
|
|
# Check if the user has suitable balance
|
|
|
|
# Create order
|
|
|
|
#
|
|
|
|
return create_wireguard_vpn_tech(owner, public_key, network_mask)
|
|
|
|
|
|
|
|
@transaction.atomic
|
|
|
|
def create_wireguard_vpn_tech(owner, public_key, network_mask):
|
2020-12-13 16:59:35 +00:00
|
|
|
pool = get_suitable_pools(network_mask)[0]
|
|
|
|
count = pool.wireguardvpn_set.count()
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
# Try re-using previously used networks first
|
2020-12-13 16:59:35 +00:00
|
|
|
try:
|
|
|
|
free_lease = WireGuardVPNFreeLeases.objects.get(vpnpool=pool)
|
|
|
|
|
|
|
|
vpn = WireGuardVPN.objects.create(owner=owner,
|
|
|
|
vpnpool=pool,
|
|
|
|
pool_index=free_lease.pool_index,
|
|
|
|
wireguard_public_key=public_key)
|
|
|
|
|
|
|
|
free_lease.delete()
|
|
|
|
|
|
|
|
except WireGuardVPNFreeLeases.DoesNotExist:
|
2020-12-13 17:34:43 +00:00
|
|
|
# First object
|
|
|
|
if count == 0:
|
|
|
|
vpn = WireGuardVPN.objects.create(owner=owner,
|
|
|
|
vpnpool=pool,
|
|
|
|
pool_index=0,
|
|
|
|
wireguard_public_key=public_key)
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
else: # Select last network and try +1 it
|
|
|
|
last_net = WireGuardVPN.objects.filter(vpnpool=pool).order_by('pool_index').last()
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
next_index = last_net.pool_index + 1
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
if next_index <= pool.max_pool_index:
|
|
|
|
vpn = WireGuardVPN.objects.create(owner=owner,
|
|
|
|
vpnpool=pool,
|
|
|
|
pool_index=next_index,
|
|
|
|
wireguard_public_key=public_key)
|
2020-12-13 10:38:41 +00:00
|
|
|
|
|
|
|
|
2020-12-26 13:42:53 +00:00
|
|
|
config = pool.wireguard_config
|
|
|
|
server = pool.vpn_server_hostname
|
|
|
|
wg_name = pool.wg_name
|
|
|
|
|
|
|
|
configure_wireguard_server_on_host.apply_async((wg_name, config),
|
|
|
|
queue=server)
|
2020-12-13 10:38:41 +00:00
|
|
|
|
2020-12-13 17:34:43 +00:00
|
|
|
return vpn
|