45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
from rest_framework import serializers
|
|
from otpauth.models import OTPSeed
|
|
import pyotp
|
|
|
|
class OTPSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = OTPSeed
|
|
fields = ('name', 'realm')
|
|
|
|
token = serializers.CharField(max_length=128)
|
|
|
|
verifyname = serializers.CharField(max_length=128)
|
|
verifytoken = serializers.CharField(max_length=128)
|
|
verifyrealm = serializers.CharField(max_length=128)
|
|
|
|
|
|
class VerifySerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = OTPSeed
|
|
fields = ('name', 'realm')
|
|
|
|
token = serializers.CharField(max_length=128)
|
|
|
|
verifyname = serializers.CharField(max_length=128)
|
|
verifytoken = serializers.CharField(max_length=128)
|
|
verifyrealm = serializers.CharField(max_length=128)
|
|
|
|
def update(self, instance, validated_data):
|
|
token_in = validated_data.get('token')
|
|
name_in = validated_data.get('name')
|
|
realm_in = validated_data.get('realm')
|
|
|
|
try:
|
|
db_instance = otpauth.models.OTPSeed.objects.get(name=name_in, realm=realm_in)
|
|
except (OTPSeed.MultipleObjectsReturned, OTPSeed.DoesNotExist):
|
|
# FIXME: correct return?
|
|
return None
|
|
|
|
# Generate token and compare
|
|
totp = pyotp.TOTP(db_instance.seed)
|
|
|
|
if totp.verify(token_in, valid_window=3):
|
|
return "OK"
|
|
else:
|
|
return "FAIL"
|