susioma/smsauth/views.py

58 lines
1.7 KiB
Python
Raw Permalink Normal View History

2019-10-27 15:20:28 +00:00
from django.shortcuts import render
from django.utils import timezone
from datetime import timedelta
from smsauth.models import Token
from dbsettings.views import getValue
2020-10-24 14:50:04 +00:00
from kumisms import KumiSMS
2021-02-06 11:42:45 +00:00
import telegram
2019-10-27 15:20:28 +00:00
import random
2021-02-06 11:42:45 +00:00
BUYER = 0
SELLER = 1
2019-10-27 15:20:28 +00:00
def generateToken():
return str(random.SystemRandom().choice(range(999999))).zfill(6)
def storeToken(token):
return Token.objects.create(token=token) # pylint: disable=E1101
def useToken(token):
retval = False
2021-05-24 12:39:43 +00:00
for t in Token.objects.filter(token=str(token).zfill(6), used=False): # pylint: disable=E1101
2019-10-27 15:20:28 +00:00
t.used = True
2021-05-24 12:39:43 +00:00
t.save()
2019-10-27 15:20:28 +00:00
if timezone.now() - timedelta(seconds=300) < t.sent:
retval = True
return retval
def requestToken():
token = generateToken()
storeToken(token)
2021-02-06 11:42:45 +00:00
sendMessage("Bitte verwende diesen Code, um deine Anfrage zu bestätigen: %s" % token, BUYER)
2019-10-27 15:20:28 +00:00
2021-02-06 11:42:45 +00:00
def sendSMS(text, number):
2020-10-24 14:50:04 +00:00
gateway = KumiSMS(getValue("smsauth.kumisms.key"))
2021-02-06 11:42:45 +00:00
return gateway.send(number, text)
def sendTelegram(text, recipient):
bot = telegram.Bot(getValue("smsauth.telegram.token"))
return bot.send_message(recipient, text)
def sendMessage(text, recipient):
if recipient == BUYER:
phone = getValue("smsauth.buyer.phone", getValue("smsauth.recipient", False))
telegram = getValue("smsauth.buyer.telegram", False)
2021-02-06 11:42:45 +00:00
elif recipient == SELLER:
phone = getValue("smsauth.seller.phone", getValue("buyer.recipient", False))
telegram = getValue("smsauth.seller.telegram", False)
2021-02-06 11:42:45 +00:00
else:
raise ValueError("Invalid value for recipient: %s" % str(recipient))
if phone:
sendSMS(text, phone)
if telegram:
2021-05-24 12:39:43 +00:00
sendTelegram(text, telegram)