Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Separate token creation logic from the create method #250

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 34 additions & 12 deletions knox/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,52 @@

class AuthTokenManager(models.Manager):
def create(self, user, expiry=knox_settings.TOKEN_TTL):
crypto_obj = self.generate_token()
token = crypto_obj.get("token")
digest = crypto_obj.get("digest")
expiry = crypto_obj.get("expiry")
instance = super(AuthTokenManager, self).create(
token_key=token[: CONSTANTS.TOKEN_KEY_LENGTH],
digest=digest,
user=user,
expiry=expiry,
)
return instance, token

def generate_token(self):
"""
Returns a dict with token, digest and expiry datetime

Example:
{
"token": <token string>,
"expiry": <digest hash>,
"expiry": <expiry datetime>,
}
"""
token = crypto.create_token_string()
digest = crypto.hash_token(token)

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

instance = super(AuthTokenManager, self).create(
token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH], digest=digest,
user=user, expiry=expiry)
return instance, token
return {"token": token, "digest": digest, "expiry": expiry}


class AuthToken(models.Model):

objects = AuthTokenManager()

digest = models.CharField(
max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True)
token_key = models.CharField(
max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True)
user = models.ForeignKey(User, null=False, blank=False,
related_name='auth_token_set', on_delete=models.CASCADE)
digest = models.CharField(max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True)
token_key = models.CharField(max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True)
user = models.ForeignKey(
User,
null=False,
blank=False,
related_name="auth_token_set",
on_delete=models.CASCADE,
)
created = models.DateTimeField(auto_now_add=True)
expiry = models.DateTimeField(null=True, blank=True)

def __str__(self):
return '%s : %s' % (self.digest, self.user)
return "%s : %s" % (self.digest, self.user)