How to create a App Specific User roles and access in Django?

379 Views Asked by At

I want to create a user management system in Django where I will have multiple apps and for a single user, I want to assign different roles for the various apps as in the image below. Expert advice would be appreciated. The Image shows the different roles assigned to a user for different apps

1

There are 1 best solutions below

0
Arvind Kumar On

Let's start with the user model as you want to use the custom user model. I would recommend that you inherit your user model with AbstractUser from django.contrib.auth.models.

class User(AbstractUser):
    username = models.CharField(db_index=True, unique=True, max_length=255)
    email = models.CharField(max_length=50, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    # your custom fields here 

    objects = UserManager()

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

Add this User Model to your settings file

AUTH_USER_MODEL = 'app_name.User'

After that, I would recommend to create a class CustomLogin and inherit it form ModelBackend from django.contrib.auth.backends.

If you want to use a custom scheme for login other than standard username/password, Override the authenticate function, otherwise leave it.

For permissions and roles part, I would recommend that you override the two function _get_user_permissions and _get_group_permissions. write your custom logic to provide permissions assigned a particular user and groups. you can use your roles as groups here and write custom logic.

Here is the documentation if you want to read further on this - Authentication Backend in Django