Home > Software engineering >  username and email interchanged for social user
username and email interchanged for social user

Time:10-26

I am using google oauth2 for social authentication, I get the user's username and email and save it on my models, but the username and email fields are being swapped. What is causing such a problem?

models.py

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=255, db_index=True)
    email = models.EmailField(max_length=255, unique=True, db_index=True)
    is_verified = models.BooleanField(default=False)
    # is_authenticated = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    auth_provider  = models.CharField(max_length=225, blank=False, null=False, default=AUTH_PROVIDERS.get('email'))

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()

    def __str__(self):
        return self.email

    def tokens(self):
        refresh = RefreshToken.for_user(self)
        return {
            'refresh': str(refresh),
            'access': str(refresh.access_token)
        }

register.py

def register_social_user(provider, user_id, email, name):
    filtered_user_by_email = User.objects.filter(email=email)

    if filtered_user_by_email.exists():
        
        if provider == filtered_user_by_email[0].auth_provider:

            registered_user = authenticate(
                email=email, password=os.environ.get('SOCIAL_SECRET'))

            return {
                'username': registered_user.username,
                'email': registered_user.email,
                'tokens': registered_user.tokens()}

        else:
            raise AuthenticationFailed(
                detail='Please continue your login using '   filtered_user_by_email[0].auth_provider)

    else:
        user = {
            'username': generate_username(name), 'email': email,
            'password': os.environ.get('SOCIAL_SECRET')}
        user = User.objects.create_user(**user)
        user.is_verified = True
        user.auth_provider = provider
        user.save()
        print('user',user)

        new_user = authenticate(
            email=email, password=os.environ.get('SOCIAL_SECRET'))
        print ('new:',new_user)
        return {
            'id':user.id,
            'email': user.email,
            'username': user.username,
            'tokens': user.tokens()
        }

Here is the link to the full code: https://github.com/abinashkarki/rest_framework_authentication

CodePudding user response:

I run the createsuperuser command and I saw that it saves the email value into the username field and vice versa. I found the problem in your custom UserManager, you've written the order of username and email fields wrong inside the UserManager.create_user method:

def create_user(self, username, email, password=None, **extra_fields):
    return self._create_user(email, username, password, **extra_fields)

def create_superuser(self, username, email, password=None, **extra_fields):
    user = self.create_user(username, email, password)
    user.is_superuser = True
    user.is_staff = True
    user.has_delete_permission = True
    user.save()
    return user

What you should do is basically fix the create_user method like this:

def create_user(self, username, email, password=None, **extra_fields):
    return self._create_user(username, email, password, **extra_fields)

It should work now

  • Related