susioma/smsauth/views.py

57 lines
1.7 KiB
Python

from django.shortcuts import render
from django.utils import timezone
from datetime import timedelta
from smsauth.models import Token
from dbsettings.views import getValue
from kumisms import KumiSMS
import telegram
import random
BUYER = 0
SELLER = 1
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), used=False): # pylint: disable=E1101
t.used = True
t.save()
if timezone.now() - timedelta(seconds=300) < t.sent:
retval = True
return retval
def requestToken():
token = generateToken()
storeToken(token)
sendMessage("Bitte verwende diesen Code, um deine Anfrage zu bestätigen: %s" % token, BUYER)
def sendSMS(text, number):
gateway = KumiSMS(getValue("smsauth.kumisms.key"))
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)
elif recipient == SELLER:
phone = getValue("smsauth.seller.phone", getValue("buyer.recipient", False))
telegram = getValue("smsauth.seller.telegram", False)
else:
raise ValueError("Invalid value for recipient: %s" % str(recipient))
if phone:
sendSMS(text, phone)
if telegram:
sendTelegram(text, telegram)