Search code examples
javascriptdjangodjango-rest-frameworkdjoser

Check if Djoser user exists by email


I am currently working developing a login screen where I am using djoser for authentication.

I already use the /users/ and /token/login/ endpoints to create and log in users respectively in the frontend (JS fetch) and I know that /users/ will return an error message if the user already exists (which I'm displaying with react-hook-form).

My question is: is there a way of verifying if the user already exists with their email only (without trying to create an account and working it out from the error message)


Solution

  • From what I've found, Djoser doesn't provide a way to check if the email exists, so I wrote an APIView

    class CheckEmail(APIView):
        permission_classes = [IsAuthenticatedOrReadOnly]
        def get(self, request, format=None):
            email = request.GET.get('email')
            user = UserAccount.objects.filter(email=email)
            if user:
                return Response('Email exists')
            else:
                return Response('Welcome aboard!')
    

    and used a get request with Yup and Formik:

    const LoginSchema = Yup.object().shape({
    checkEmail: Yup.boolean().default(true),
    email: Yup.string()
      .email("Please enter valid email")
      .required("Email is required")
      .when("checkEmail", {
        is: true,
        then: Yup.string()
          .test({
            message: () => "Email already exists",
            test: async(email) => {
              if(email) {
                try {
                  let response = await axios.get(`http://localhost:8000/accounts/users/check_email/?email=${email}`);
                  if (response.data === 'Welcome aboard!') {
                    return true;
                  } else {
                    return false;
                  }
                } catch (error) {
                  //console.log(error);
                }
              }
            }
          })
      }),   
    

    Hope that helps