forked from uncloud/uncloud
70 lines
1.8 KiB
Python
Executable file
70 lines
1.8 KiB
Python
Executable file
import binascii
|
|
import requests
|
|
|
|
from decouple import config
|
|
from pyotp import TOTP
|
|
from config import VM_POOL
|
|
|
|
|
|
def check_otp(name, realm, token):
|
|
try:
|
|
data = {
|
|
"auth_name": config("AUTH_NAME", ""),
|
|
"auth_token": TOTP(config("AUTH_SEED", "")).now(),
|
|
"auth_realm": config("AUTH_REALM", ""),
|
|
"name": name,
|
|
"realm": realm,
|
|
"token": token,
|
|
}
|
|
except binascii.Error:
|
|
return 400
|
|
|
|
response = requests.get(
|
|
"{OTP_SERVER}{OTP_VERIFY_ENDPOINT}".format(
|
|
OTP_SERVER=config("OTP_SERVER", ""),
|
|
OTP_VERIFY_ENDPOINT=config("OTP_VERIFY_ENDPOINT", "verify"),
|
|
),
|
|
json=data,
|
|
)
|
|
return response.status_code
|
|
|
|
|
|
def resolve_vm_name(name, owner):
|
|
"""Return UUID of Virtual Machine of name == name and owner == owner
|
|
|
|
Input: name of vm, owner of vm.
|
|
Output: uuid of vm if found otherwise None
|
|
"""
|
|
result = next(
|
|
filter(
|
|
lambda vm: vm.value["owner"] == owner and vm.value["name"] == name,
|
|
VM_POOL.vms,
|
|
),
|
|
None,
|
|
)
|
|
if result:
|
|
return result.key.split("/")[-1]
|
|
|
|
return None
|
|
|
|
import random
|
|
|
|
def random_bytes(num=6):
|
|
return [random.randrange(256) for _ in range(num)]
|
|
|
|
def generate_mac(uaa=False, multicast=False, oui=None, separator=':', byte_fmt='%02x'):
|
|
mac = random_bytes()
|
|
if oui:
|
|
if type(oui) == str:
|
|
oui = [int(chunk) for chunk in oui.split(separator)]
|
|
mac = oui + random_bytes(num=6-len(oui))
|
|
else:
|
|
if multicast:
|
|
mac[0] |= 1 # set bit 0
|
|
else:
|
|
mac[0] &= ~1 # clear bit 0
|
|
if uaa:
|
|
mac[0] &= ~(1 << 1) # clear bit 1
|
|
else:
|
|
mac[0] |= 1 << 1 # set bit 1
|
|
return separator.join(byte_fmt % b for b in mac)
|