Reputation: 834
I'm trying to create an api with token authentiaction. My problem is that I don't want tokens to be associated with user accounts but rather an account model.
For example:
class Account(models.Model):
slug = models.SlugField()
name = models.CharField(max_length=255)
website = models.URLField(blank=True, default='')
members = models.ManyToManyField(User, through='AccountMember')
class AccountMember(models.Model):
ADMIN = 1
MANAGER = 2
MEMBER = 3
ROLES = (
(ADMIN, 'administrator'),
(MANAGER, 'manager'),
(MEMBER, 'member'),
)
user = models.ForeignKey(User)
account = models.ForeignKey(Account)
role = models.PositiveSmallIntegerField(choices=ROLES)
date_joined = models.DateField(auto_now_add=True)
class Token(models.Model):
"""
The default authorization token model.
"""
key = models.CharField(max_length=40, primary_key=True)
account = models.ForeignKey(Account, related_name='auth_tokens')
only_allowed_ips = models.BooleanField(default=False)
ip_list = models.TextField(default='', blank=True)
created = models.DateTimeField(auto_now_add=True)
As you can see, there are multiple users associated with an account so assigning the token to them would be useless.
I also want to be able to add multiple tokens to an account.
Does anyone know the best way I could add authentication/permissions to a system like this?
Upvotes: 7
Views: 788
Reputation: 1372
I just faced the problem myself. What I decided to do is too duplicate django rest framework's authtoken module in my application and to apply my own modifications.
You can copy the folder from DRF's repository in your own application's folder. Be sure to change related fields in your settings.py, application/authtoken/admin.py and of course in your application/authtoken/models.py
Upvotes: 1
Reputation: 3806
You must replicate the following classes:
django.contrib.auth.backends.ModelBackend: to check for auth and permissions django.contrib.auth.middleware.AuthenticationMiddleware: to set your Account linked with the request
probably you must create another django.contrib.auth.models.Permission to store your Account related permissions
Upvotes: 1