1

I am trying to implement a Django backend for a mobile app where users authenticate through their mobile numbers only. When the user tries to login, the backend will send him an OTP so that he can login. For this use case, I think I don't need a password field. However, I think I need a password for superusers. I am thinking of a solution but I don't know whether it is a suitable solution.

models.py:

class UserManager(BaseUserManager):
    def create_user(self, email, phone_number, password=None):
        user = self.model(email=email, phone_number=phone_number)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, phone_number, password=None):
        user = self.create_user(email, phone_number, password)
        user.is_staff = True
        user.save()
        return user


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(blank=False, null=False, unique=True)
    phone_number = PhoneNumberField(blank=False, null=False, unique=True)
    is_staff = models.BooleanField(default=False, blank=False, null=False)

    objects = UserManager()
    USERNAME_FIELD = 'phone_number'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.phone_number

Will the code above do the job?

Ambitions
  • 2,369
  • 3
  • 13
  • 24
  • 1
    https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend – iklinac Mar 16 '20 at 11:11
  • @iklinac I will write my own authentication backend if it is necessary. May you please tell me what's wrong with my solution so that I can learn from my mistakes? – Ambitions Mar 16 '20 at 11:24
  • The code you provided didn't say anything. It's just a custom User model and UserManager. – Andrey Nelubin Mar 16 '20 at 12:32
  • @AndreyNelubin I am sorry if I was not clear. Does the code provided do the job? Will I be able to login at admin panel with my superuser username and password while being able to login to my API without a password? – Ambitions Mar 16 '20 at 12:46
  • 1
    @Ambitions yes the code can do this. – Andrey Nelubin Mar 16 '20 at 13:23

0 Answers0