www-bocal/api/models.py

61 lines
2 KiB
Python
Raw Normal View History

2017-09-23 21:40:45 +02:00
from django.db import models
2017-09-24 00:42:36 +02:00
from datetime import datetime, timedelta
import hmac
import hashlib
2017-09-24 18:20:10 +02:00
import random
import string
2017-09-24 00:42:36 +02:00
2017-09-24 00:42:36 +02:00
class ApiKey(models.Model):
''' An API key, to login using the API
An API key consists in a somewhat long chunk of ascii text, *not*
containing any dollar ($) sign. It is saved on the client's machine as
a string "keyId$key".
An API token (to authentify a request) is a triplet (ts, kid, hmac) of
2017-09-24 18:20:10 +02:00
a timestamp `ts`, the key id `kid` and
hmac = `HMAC(key, ts + data, sha256)`
where `data` is the normalized (`json.dumps(json.loads(...))`) value of
the data part of the request.
2017-09-24 00:42:36 +02:00
'''
key = models.CharField("API key",
max_length=128)
name = models.CharField("Key name",
max_length=256,
help_text="Where is this key used from?")
last_used = models.DateTimeField("Last used",
default=datetime.fromtimestamp(0))
def everUsed(self):
return self.last_used > datetime.fromtimestamp(0)
2017-09-24 18:20:10 +02:00
def initialFill(self):
if not self.key:
KEY_SIZE = 64
KEY_CHARS = string.ascii_letters + string.digits
self.key = ''.join(
[random.choice(KEY_CHARS) for _ in range(KEY_SIZE)])
2017-09-24 18:20:10 +02:00
@property
def keyId(self):
return self.id
@property
def displayValue(self):
2017-09-24 00:42:36 +02:00
return "{}${}".format(self.keyId, self.key)
2017-09-24 18:20:10 +02:00
def __str__(self):
return self.displayValue
def isCorrect(self, timestamp, inpMac, data):
2017-09-24 00:42:36 +02:00
claimedDate = datetime.fromtimestamp(timestamp)
if datetime.now() - timedelta(minutes=5) > claimedDate:
return False
2017-09-24 18:20:10 +02:00
mac = hmac.new(self.key.encode('utf-8'),
msg=str(int(claimedDate.timestamp())).encode('utf-8'),
2017-09-24 00:42:36 +02:00
digestmod=hashlib.sha256)
2017-09-24 18:20:10 +02:00
mac.update(data.encode('utf-8'))
2017-09-24 00:42:36 +02:00
return hmac.compare_digest(mac.hexdigest(), inpMac)