Home > database >  Multiple user access to one primary account Django auth
Multiple user access to one primary account Django auth

Time:04-05

I have already configured custom User authentication for my project, however, I would appreciate some advice on how to implement the following:

Overview of requirements:

My project requires that a customer be able to setup an account to use our online services.

That same customer (as administrator of the account) would then be able to add sub-users to that account and also be able to configure permissions for each of those sub-users with respect to that account.

My question:

I am not sure how to begin to implement this and I would appreciate some practical guidance on where start.

Update:

It seems to me that there will be 2 auth systems - one for the users and the other for the account, but how can I restrict a specific group of users to a single account? Additionally, I will need to designate one user (or maybe more than one) as the account administrator(s) and the other users as something less.

CodePudding user response:

I would keep this setup simple and would follow the following steps:

  1. Extend user model to handle "subaccounts" (belongs_to)
  2. Add permission to the user with properties (you could create roles)
  3. When linking an object (e.g. Blog article) always link it to the main user and when retrieving objects filter for the main user. (user.get_main_user())

This way you do not need two authentication backends and can manage all your permissions and everything within the user model.

To create a subaccount simply create a new account instance and link it via belongs_to to the main account.

class MyUserModel:
    # ....
    # If you want role based access
    role = models.ChoiceField(....)
    belongs_to = models.ForeignKeyField("self", null=True, default=None)

    def get_main_user(self):
        if self.is_main_user:
            return self
        return self.belongs_to

    @property
    def is_main_user(self):
        return self.belongs_to is None

    @property
    def can_do_something(self):
        return True  # Do some checks here if the current is allowed to do something
  • Related