1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2024-12-27 16:45:22 +00:00
webvirtcloud/accounts/utils.py

62 lines
1.7 KiB
Python
Raw Normal View History

2020-10-14 08:37:46 +00:00
import base64
import binascii
import struct
2020-10-19 08:26:08 +00:00
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
2020-10-08 11:57:51 +00:00
from django_otp import devices_for_user
from django_otp.plugins.otp_totp.models import TOTPDevice
def get_user_totp_device(user):
devices = devices_for_user(user)
for device in devices:
if isinstance(device, TOTPDevice):
return device
2020-10-14 08:37:46 +00:00
2020-10-19 08:26:08 +00:00
device = user.totpdevice_set.create()
return device
2020-10-14 08:37:46 +00:00
def validate_ssh_key(key):
array = key.encode().split()
# Each rsa-ssh key has 3 different strings in it, first one being
# typeofkey second one being keystring third one being username .
if len(array) != 3:
return False
typeofkey = array[0]
string = array[1]
2022-08-24 12:15:27 +00:00
2020-10-14 08:37:46 +00:00
# must have only valid rsa-ssh key characters ie binascii characters
try:
data = base64.decodebytes(string)
2020-10-14 08:37:46 +00:00
except binascii.Error:
return False
# unpack the contents of data, from data[:4] , property of ssh key .
try:
str_len = struct.unpack(">I", data[:4])[0]
2020-10-14 08:37:46 +00:00
except struct.error:
return False
# data[4:str_len] must have string which matches with the typeofkey, another ssh key property.
2022-08-24 12:15:27 +00:00
if data[4 : 4 + str_len] != typeofkey:
2020-10-14 08:37:46 +00:00
return False
2022-08-24 12:15:27 +00:00
return True
2020-10-19 08:26:08 +00:00
def send_email_with_otp(user, device):
send_mail(
_("OTP QR Code"),
_("Please view HTML version of this message."),
2020-10-19 08:26:08 +00:00
None,
[user.email],
html_message=render_to_string(
"accounts/email/otp.html",
2020-10-19 08:26:08 +00:00
{
"totp_url": device.config_url,
"user": user,
2020-10-19 08:26:08 +00:00
},
),
fail_silently=False,
)