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-23 21:40:45 +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
|
|
|
|
a timestamp `ts`, the key id `kid` and hmac = `HMAC(key, ts, sha256)`.
|
|
|
|
'''
|
|
|
|
keyId = models.IntegerField("API key id",
|
|
|
|
primary_key=True)
|
|
|
|
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)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "{}${}".format(self.keyId, self.key)
|
|
|
|
|
|
|
|
def isCorrect(self, timestamp, inpMac):
|
|
|
|
claimedDate = datetime.fromtimestamp(timestamp)
|
|
|
|
if datetime.now() - timedelta(minutes=5) > claimedDate:
|
|
|
|
return False
|
|
|
|
|
|
|
|
mac = hmac.new(self.key,
|
|
|
|
msg=int(claimedDate.timestamp()),
|
|
|
|
digestmod=hashlib.sha256)
|
|
|
|
|
|
|
|
return hmac.compare_digest(mac.hexdigest(), inpMac)
|