susioma/smsauth/views.py

56 lines
1.7 KiB
Python
Raw 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
for t in Token.objects.filter(token=str(token).zfill(6)): # pylint: disable=E1101
t.used = True
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", None))
telegram = getValue("smsauth.buyer.telegram", None)
elif recipient == SELLER:
phone = getValue("smsauth.seller.phone", getValue("buyer.recipient", None))
telegram = getValue("smsauth.seller.telegram", None)
else:
raise ValueError("Invalid value for recipient: %s" % str(recipient))
if phone:
sendSMS(text, phone)
if telegram:
sendTelegram(text, telegram)