0
votes

I am using django 2.1 and python 3.6....I want to authenticate users using custom authentication and return token along with email and id after validating user.

settinge.py

AUTHENTICATION_BACKENDS = (
    "users.views.authentication_backend.UserAuthenticationBackend",
)

views.py

class UserAuthenticationBackend(object):

    def authenticate(self, request, email=None, password=None):

        validate_email(email)
        valid_email = True
        kwargs = {'email': email}

        try:
            user = get_user_model().objects.get(**kwargs)

        except get_user_model().DoesNotExist:
            raise exceptions.AuthenticationFailed('User does not exist.')

        if valid_email and user.check_password(password) and user.is_valid is True:

            return user

        elif valid_email and user.check_password(password) and user.is_valid is False:
            raise exceptions.AuthenticationFailed('Sorry your account is suspended temporarily,'
               )

        else:
            raise exceptions.AuthenticationFailed('Sorry, your email and password does not match.')

I want to return response as follow:

{'token':"", 'user': {'id': 1, 'email': '[email protected]', 'is_active': True}}

Thanks in advance...

1
Authentication class is not for returning responses - JPG

1 Answers

0
votes

You can use Token Authentication or even JSON Web Tokens(JWT) These can help you get a token as a response TokenAuthentication, JSONWebToken

These can be helpful for your requirement,If you need any other additional help please do mention it!!!