Home > Net >  assigning role for different users in Django Rest Framework
assigning role for different users in Django Rest Framework

Time:09-17

I have used AbstractUser defined in Django for user model and have a UserProfile model which is one to one relation with the User. Now I have to implement a role-based authorization for the CRM project that I am writing.

What will be the best approach to assign a role? Should I use add fields inside the user model or inside the UserProfile model? Or I should use the already defined superuser,is_staff or active status inside User model.

My models:

class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
    def create_user(self,first_name,last_name,email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError("The email must be set")
        first_name = first_name.capitalize()
        last_name = last_name.capitalize()
        email = self.normalize_email(email)

        user = self.model(
            first_name=first_name, last_name=last_name, email=email, **extra_fields
        )
        #user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self.db)
        return user

    def create_superuser(self, first_name,last_name,email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', 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(first_name,last_name,email, password, **extra_fields)


class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email


ROLE = (('admin','ADMIN'),('manager','MANAGER'),('staff','STAFF'))

class UserProfile(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,related_name='profile')  # Delete profile when user is deleted
    image = models.ImageField(default='default.jpg',blank=True,null=True)
    address = models.CharField(max_length=150,blank=True)
    mobile = models.CharField(max_length=15,blank=True)
    job_position = models.CharField(max_length=25, blank=True)
    role = models.CharField(max_length=15,choices=ROLE,default='staff')

    def __str__(self):
        return f'{self.user.username} Profile'  # show how we want it to be displayed

For now, I have added the roles inside the profile model. But what I think is, if I am dealing with user inside every api, the field role should be defined inside the User model as it makes it easier.

CodePudding user response:

You should define fields in User model that are used in Authentication or Authorization and other mandatory information about user.

And define extra information about user in Profile model such as profile picture, social media, etc.

Therefore you are right, store user roles in User model.

PS: [How to extend Django user model]

  • Related