import hashlib import hmac import random import string from datetime import datetime, timedelta from django.db import models 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 + 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)) def everUsed(self): return self.last_used > datetime.fromtimestamp(0) 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)]) @property def keyId(self): return self.id @property def displayValue(self): return "{}${}".format(self.keyId, self.key) def __str__(self): return self.displayValue def isCorrect(self, timestamp, inpMac, data): claimedDate = datetime.fromtimestamp(timestamp) if datetime.now() - timedelta(minutes=5) > claimedDate: return False 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")) return hmac.compare_digest(mac.hexdigest(), inpMac)