[Feature] Create API Key Authenticaton for v1 API (#327)

Add API key authentication to v1 API
Also includes:
- management command to create keys for users
- Improvements to API tests

Minor:
- more robust way to start docker dev container.

Reviewed-on: enviPath/enviPy#327
Co-authored-by: Tobias O <tobias.olenyi@envipath.com>
Co-committed-by: Tobias O <tobias.olenyi@envipath.com>
This commit is contained in:
2026-02-11 02:29:54 +13:00
committed by jebus
parent c0cfdb9255
commit 5789f20e7f
15 changed files with 282 additions and 165 deletions

View File

@ -170,17 +170,18 @@ class APIToken(TimeStampedModel):
return token, raw_key
@classmethod
def authenticate(cls, raw_key: str) -> Optional[User]:
def authenticate(cls, token: str, *, hashed: bool = False) -> Optional[User]:
"""
Authenticate a user using an API token.
Args:
raw_key: Raw token key
token: Raw token key or SHA-256 hash (when hashed=True)
hashed: Whether the token is already hashed
Returns:
User if token is valid, None otherwise
"""
hashed_key = hashlib.sha256(raw_key.encode()).hexdigest()
hashed_key = token if hashed else hashlib.sha256(token.encode()).hexdigest()
try:
token = cls.objects.select_related("user").get(hashed_key=hashed_key)