user match query does not exist

user match query does not exist


0

I have been tasked to create separate user model for third_party users who are to access our endpoint so i created separate user named ApiCliet and inherited the Abstract user model of Django
i also created a custom authentication for that user model only and then crated two mutation to create an api client and also generate and access_toekn for the existing user how ever i get user matching query does not exist which is baffling after debugging i get the username is correct and the password is correct below is my code .

Model

class ApiClientManager(BaseUserManager):
    def create_user(self, username, email=None, password=None, **extra_fields):
        if not username:
            raise ValueError("The Username field must be set")
        
        email = self.normalize_email(email) if email else None
        user = ApiClient(username=username, email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(username, email, password, **extra_fields)

class ApiClient(AbstractBaseUser, PermissionsMixin):
    id = models.AutoField(db_column="Api_client_ID", primary_key=True)
    uuid = models.CharField(db_column="Api_clientUUID", max_length=36, default=uuid.uuid4, unique=True)
    username = models.CharField(db_column="Api_client_username", max_length=100, unique=True, default='test_username')
    email = models.EmailField(db_column="Api_client_email", blank=True, null=True)
    access_token = models.CharField(db_column="Api_client_access_token", max_length=100, blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name='api_clients'  # Add this line
    )

    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name='api_clients'  # Add this line
    )

    objects = ApiClientManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.username

    

    class Meta:
        managed = True
        db_table = "Api_Client"

** Custom authentication **

from django.contrib.auth.backends import ModelBackend
from .models import ApiClient


class ApiClientAuthenticationBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        print("Authentication backend triggered") 
        try:
            user = ApiClient.objects.get(username=username)
            print(f"Found user: {user}")
            if user.check_password(password):
                  print("Password is correct")
                  return user
        except ApiClient.DoesNotExist:
            print("User not found")
            return None

            

    def get_user(self, user_id):
        api_client = ApiClient
        try:
            return api_client.objects.get(pk=user_id)
        except api_client.DoesNotExist:
            return None

** Mutation **

class CreateApiClient(graphene.Mutation):
    class Arguments:
        input_data = ApiClientInpuType(required=True)

    Api_Client = graphene.Field(ApiClientType)

    @classmethod
    def mutate(cls, root, info, input_data=None):
        try:
            # Create an ApiClient instance
            api_client = ApiClient(username=input_data['username'], email=input_data['email'])
            api_client.set_password(input_data['password'])
            api_client.save()
            return CreateApiClient(Api_Client=api_client)
        except Exception as e:
            return cls(Api_Client= f" fail to crate {e} ")  # Return a CreateApiClient object with ApiClient=None and appropriate error messages


  

class ApiClientLogin(graphene.Mutation):
    class Arguments:
        username = graphene.String(required=True)
        password = graphene.String(required=True)

    token = graphene.String()

    @classmethod
    def mutate(cls, root, info, username, password):
        try:
            request = info.context
            print(request)
            backend = ApiClientAuthenticationBackend()
            user = backend.authenticate(request, username=username, password=password)

            if user and isinstance(user, ApiClient):
                token = get_token(user)  # Use graphene_jwt's function to generate a token
                return ApiClientLogin(token=token)
            else:
                raise Exception('Invalid credentials')
        except Exception as e:
            raise Exception(f"Failed to generate token: {str(e)}")

Note the CreateApiClient class is working is the second mutation that i say have errors on it says faild to generate access token user matching query does not exist

I am expting to return an access token after authenticating the user but it dosent this the errro again

errro

{
  "errors": [
    {
      "message": "Failed to generate token: User matching query does not exist.",
      "locations": [

Share
Improve this question

New contributor

lone survivar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


Load 5 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *