2017-09-24 00:42:36 +02:00
|
|
|
import hashlib
|
2024-10-23 11:06:57 +02:00
|
|
|
import hmac
|
2017-09-24 18:20:10 +02:00
|
|
|
import random
|
|
|
|
import string
|
2024-10-23 11:06:57 +02:00
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
|
|
from django.db import models
|
2017-09-24 00:42:36 +02:00
|
|
|
|
2017-10-16 17:23:56 +02:00
|
|
|
|
2017-09-24 00:42:36 +02:00
|
|
|
class ApiKey(models.Model):
|
2024-10-23 11:06:57 +02:00
|
|
|
"""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 + data, sha256)`
|
|
|
|
where `data` is the normalized (`json.dumps(json.loads(...))`) value of
|
|
|
|
the data part of the request.
|
|
|
|
"""
|
|
|
|
|
|
|
|
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))
|
2017-09-24 00:42:36 +02:00
|
|
|
|
|
|
|
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
|
2024-10-23 11:06:57 +02:00
|
|
|
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
|
|
|
|
|
2024-10-23 11:06:57 +02:00
|
|
|
mac = hmac.new(
|
|
|
|
self.key.encode("utf-8"),
|
|
|
|
msg=str(int(claimedDate.timestamp())).encode("utf-8"),
|
|
|
|
digestmod=hashlib.sha256,
|
|
|
|
)
|
|
|
|
mac.update(data.encode("utf-8"))
|
2017-09-24 00:42:36 +02:00
|
|
|
|
|
|
|
return hmac.compare_digest(mac.hexdigest(), inpMac)
|