jazzband / django-rest-knox

Authentication Module for django rest auth
MIT License
1.18k stars 213 forks source link

Subclass AuthToken and AuthTokenManger to give a token an extra property #196

Closed alrhalford closed 4 months ago

alrhalford commented 5 years ago

I have used django knox a few times in the past. This time, I need each token to have a human readable 'name'. I thought that the easiest way might be to subclass AuthToken and AuthTokenManager's create method, to add a name field to the model. I would then subclass the login view to use my new model field. Obviously, knox still has its migrations, so the knox_authtoken table will still be created, even if it remains empty. Does this sound like a reasonable approach, or do people who know the project better than I do see a major issue here?

akshaybabloo commented 4 years ago

The following works, I wouldn't recommend using it

class CustomAuthTokenManager(models.Manager):
    def create(self, user, name, expiry=knox_settings.TOKEN_TTL):
        token = crypto.create_token_string()
        salt = crypto.create_salt_string()
        digest = crypto.hash_token(token, salt)

        if expiry is not None:
            expiry = timezone.now() + expiry

        instance = super(CustomAuthTokenManager, self).create(
            token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH], digest=digest,
            salt=salt, user=user, expiry=expiry, name=name)
        return instance, token

class CustomAuthToken(AuthToken):
    objects = CustomAuthTokenManager()
    name = models.CharField(max_length=200, null=False, blank=False)

Should wait for #184

johnraz commented 4 months ago

Should be covered now.