Skip to content

Instantly share code, notes, and snippets.

@pmburu
Forked from iMerica/urls.py
Last active August 27, 2020 10:25
Show Gist options
  • Save pmburu/eae610bd61abfae8e208efa2c2b53654 to your computer and use it in GitHub Desktop.
Save pmburu/eae610bd61abfae8e208efa2c2b53654 to your computer and use it in GitHub Desktop.
Email verification in Django Rest Framework, Django All-Auth, Django Rest-Auth. Suitable for Single Page Applications
urlpatterns = [
url(r'^auth/registration/confirm-email/(?P<key>[-:\w]+)/$', ConfirmEmailView.as_view(), name='account_confirm_email'),
]
from rest_framework.exceptions import NotFound
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from allauth.account.models import EmailConfirmation, EmailConfirmationHMAC
class ConfirmEmailView(APIView):
permission_classes = [AllowAny]
def get(self, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm(self.request)
# A React Router Route will handle the failure scenario
return HttpResponseRedirect('/register/success/')
def get_object(self, queryset=None):
key = self.kwargs['key']
email_confirmation = EmailConfirmationHMAC.from_key(key)
if not email_confirmation:
if queryset is None:
queryset = self.get_queryset()
try:
email_confirmation = queryset.get(key=key.lower())
except EmailConfirmation.DoesNotExist:
# A React Router Route will handle the failure scenario
return HttpResponseRedirect('/register/fail/')
return email_confirmation
def get_queryset(self):
qs = EmailConfirmation.objects.all_valid()
qs = qs.select_related("email_address__user")
return qs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment