Skip to content

Instantly share code, notes, and snippets.

@tmirza-dinCloud
Created June 13, 2020 20:36
Show Gist options
  • Save tmirza-dinCloud/11dc671327b50555c1fd5ca896dbd991 to your computer and use it in GitHub Desktop.
Save tmirza-dinCloud/11dc671327b50555c1fd5ca896dbd991 to your computer and use it in GitHub Desktop.
# Create your views here.
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework import status
from .serializers import UserSerializer
from rest_framework.response import Response
from django.contrib.auth import authenticate, login
import pyotp
class Register(APIView):
def post(self, request):
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
serialized.save()
uri = pyotp.totp.TOTP(serialized.data['mfa_hash']).provisioning_uri(serialized.data['email'],issuer_name="SecureApp")
qrcode_uri = "https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl={}".format(uri)
return Response({'message':'User Created Successfully',
'qrcode': qrcode_uri}, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
class Login(APIView):
def post(self, request):
data = request.data
email = data.get('email', None)
password = data.get('password', None)
otp = data.get('otp', None)
user = authenticate(username=email, password=password)
if user:
totp = pyotp.TOTP(user.mfa_hash)
print(totp.now())
if totp.verify(otp, valid):
return Response({'message':'User authenticated Successfully'}, status=status.HTTP_200_OK)
else:
return Response({'message':'Invalid OTP'}, status=HTTP_401_UNAUTHORIZED)
else:
return Response({'message':'Invalid email/password'}, status=status.HTTP_401_UNAUTHORIZED)
@alexpopa3
Copy link

hello! can you also upload the urls.py files(from the totp and demo)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment