Search code examples
pythondjangodjango-rest-frameworkdjango-allauth

django jwt generate token if email confirmed


I have a situation guys, I'm using these packages in django for rest-api and authentication:

  • django-rest-framework (REST API provider)
  • django-allauth (User authentication)
  • django-rest-framework-jwt (Support JSON-Web-Token)

In django-allauth, I made mandatory to confirm email after sign-up (ACCOUNT_EMAIL_VERIFICATION = 'mandatory'), login with session authentication is fine and follow this option, but jwt generates token and ignore this option.

How can I handle this?


Solution

  • Finally I found the answer.

    We need to override ObtainJSONWebToken class:

    def post(self, request):
         serializer = self.get_serializer(data=request.DATA)
    
         if serializer.is_valid():
             user = serializer.object.get('user') or request.user
             # check if settings swith is on / then check validity
             if settings.ACCOUNT_EMAIL_VERIFICATION == settings.ACCOUNT_EMAIL_VERIFICATION_MANDATORY:
                 email_address = user.emailaddress_set.get(email=user.email)
                 if not email_address.verified:
                      return Response(status=403, data='E-mail is not verified.')
    
             token = serializer.object.get('token')
             response_data = jwt_response_payload_handler(token, user, request)
    
             return Response(response_data)
    
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    

    Note: Remember, check email validity with setting switch ACCOUNT_EMAIL_VERIFICATION, because we need to keep this dynamic.