|
| 1 | +import os |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +from datetime import datetime |
| 4 | +from typing import Annotated, Any |
| 5 | + |
| 6 | +import httpx |
| 7 | + |
| 8 | +from fastapi import FastAPI, HTTPException |
| 9 | +from fastapi_utilities import repeat_every |
| 10 | +from pydantic import AliasPath, BaseModel, Field |
| 11 | +from pydantic_settings import BaseSettings |
| 12 | + |
| 13 | + |
| 14 | +def transform_card_number_to_unique(card_number: str): |
| 15 | + """ |
| 16 | + For new, longer card ID format, we need to transform it to the old format |
| 17 | + New card ID is returned in the exact byte order that's on card, not reversed while shorter format was reversed |
| 18 | + to match the decimal representation printed on key fobs, so it can be just converted to hex and put in LDAP. |
| 19 | + """ |
| 20 | + if len(card_number) == 8: |
| 21 | + return card_number[4:6] + card_number[2:4] + card_number[0:2] |
| 22 | + else: |
| 23 | + return card_number |
| 24 | + |
| 25 | + |
| 26 | +def transform_card_number_to_mifare(card_number: str): |
| 27 | + """ |
| 28 | + For new, longer card ID format, we need to transform it to the old format |
| 29 | + New card ID is returned in the exact byte order that's on card, not reversed while shorter format was reversed |
| 30 | + to match the decimal representation printed on key fobs, so it can be just converted to hex and put in LDAP. |
| 31 | + """ |
| 32 | + if len(card_number) == 6: |
| 33 | + return card_number[4:6] + card_number[2:4] + card_number[0:2] + "00" |
| 34 | + else: |
| 35 | + return card_number |
| 36 | + |
| 37 | + |
| 38 | +class User(BaseModel): |
| 39 | + uid: Annotated[str, Field(validation_alias="username")] |
| 40 | + mifare_card_ids: Annotated[list[str], Field(validation_alias=AliasPath("attributes", "mifareCardId"))] = [] |
| 41 | + unique_card_ids: Annotated[list[str], Field(validation_alias=AliasPath("attributes", "uniquecardId"))] = [] |
| 42 | + membership_expiration: Annotated[int, Field(validation_alias=AliasPath("attributes", "membershipExpirationTimestamp"))] |
| 43 | + |
| 44 | + |
| 45 | +class Settings(BaseSettings): |
| 46 | + authentik_token: str = ... |
| 47 | + |
| 48 | + |
| 49 | +config = Settings() |
| 50 | + |
| 51 | + |
| 52 | +users: list[User] = [] |
| 53 | +users_by_card: dict[str, User] = {} |
| 54 | +users_last_success_run: datetime | None |
| 55 | +users_last_failed_run: datetime | None |
| 56 | +users_last_failed_reason: Any |
| 57 | + |
| 58 | + |
| 59 | +@asynccontextmanager |
| 60 | +async def lifespan(app: FastAPI): |
| 61 | + await fetch_users() |
| 62 | + yield |
| 63 | + |
| 64 | + |
| 65 | +app = FastAPI(lifespan=lifespan) |
| 66 | + |
| 67 | + |
| 68 | +def auth(): |
| 69 | + return |
| 70 | + |
| 71 | + |
| 72 | +async def fetch() -> list[User]: |
| 73 | + async with httpx.AsyncClient( |
| 74 | + headers={"Authorization": f"Bearer {config.authentik_token}"}, |
| 75 | + timeout=15.0, |
| 76 | + ) as client: |
| 77 | + response = await client.get("https://auth.apps.hskrk.pl/api/v3/core/users/?attributes={\"membershipExpirationTimestamp__gt\": 1734998400}&page_size=200") |
| 78 | + return [ |
| 79 | + User(**u) |
| 80 | + for u in response.json()['results'] |
| 81 | + ] |
| 82 | + |
| 83 | + |
| 84 | +@repeat_every(seconds=300) |
| 85 | +async def fetch_users(): |
| 86 | + global users |
| 87 | + global users_by_card |
| 88 | + users = await fetch() |
| 89 | + users_by_card = { |
| 90 | + **{ |
| 91 | + mifare.lower(): user |
| 92 | + for user in users for mifare in user.mifare_card_ids |
| 93 | + }, |
| 94 | + **{ |
| 95 | + transform_card_number_to_unique(mifare).lower(): user |
| 96 | + for user in users for mifare in user.mifare_card_ids |
| 97 | + }, |
| 98 | + **{ |
| 99 | + unique.lower(): user |
| 100 | + for user in users for unique in user.unique_card_ids |
| 101 | + }, |
| 102 | + **{ |
| 103 | + transform_card_number_to_mifare(unique).lower(): user |
| 104 | + for user in users for unique in user.unique_card_ids |
| 105 | + }, |
| 106 | + } |
| 107 | + |
| 108 | + |
| 109 | +@app.get("/users/-/stats") |
| 110 | +async def get_user_stats(): |
| 111 | + return { |
| 112 | + "users": { |
| 113 | + "count": len(users), |
| 114 | + }, |
| 115 | + "cards": { |
| 116 | + "count": len(users_by_card), |
| 117 | + }, |
| 118 | + } |
| 119 | + |
| 120 | + |
| 121 | +@app.get("/users/-/by-card/{card_id}") |
| 122 | +async def get_user_by_card(card_id: str): |
| 123 | + user = users_by_card.get(card_id.lower()) |
| 124 | + if user is None: |
| 125 | + raise HTTPException(status_code=404, detail="Item not found") |
| 126 | + return user |
0 commit comments