#!/usr/bin/env python3 from datetime import date, datetime from sanic import Sanic from sanic.response import text, json from sanic_prometheus import monitor from dateutil.parser import parse import httpx from motor.motor_asyncio import AsyncIOMotorClient from pymongo.errors import PyMongoError import os from .slack import add_slack_routes app = Sanic(__name__) add_slack_routes(app) monitor(app).expose_endpoint() DOORBOY_SECRET_FLOOR = os.environ["DOORBOY_SECRET_FLOOR"] # API key for godoor controllers authenticating for k-space:floor DOORBOY_SECRET_WORKSHOP = os.environ["DOORBOY_SECRET_WORKSHOP"] # API key for godoor controllers authenticating for k-space:workshop FLOOR_ACCESS_GROUP = os.environ["FLOOR_ACCESS_GROUP"] WORKSHOP_ACCESS_GROUP = os.environ["WORKSHOP_ACCESS_GROUP"] MONGO_URI = os.environ["MONGO_URI"] INVENTORY_API_KEY = os.environ["INVENTORY_API_KEY"] # asshole forwards to inventory-app, instead of using mongo directly CARD_URI = os.environ["CARD_URI"] assert len(DOORBOY_SECRET_FLOOR) >= 10 assert len(DOORBOY_SECRET_WORKSHOP) >= 10 @app.listener("before_server_start") async def setup_db(app, loop): # TODO: find cleaner way to do this, for more see # https://github.com/sanic-org/sanic/issues/919 app.ctx.db = AsyncIOMotorClient(MONGO_URI).get_default_database() @app.route("/allowed") async def view_doorboy_uids(request): key = request.headers.get("KEY") if not key or key not in [DOORBOY_SECRET_FLOOR, DOORBOY_SECRET_WORKSHOP]: return text("how about no") groups = [] if key == DOORBOY_SECRET_FLOOR: groups.append(FLOOR_ACCESS_GROUP) if key == DOORBOY_SECRET_WORKSHOP: groups.append(WORKSHOP_ACCESS_GROUP) if not groups: return "fail", 500 async with httpx.AsyncClient() as client: r = await client.post(CARD_URI, json={ "groups": groups }, headers={ "Content-Type": "application/json", "Authorization": f"Basic {INVENTORY_API_KEY}" }) j = r.json() allowed_uids = [] for obj in j: allowed_uids.append({ "token": obj["token"] }) return json({"allowed_uids": allowed_uids}) def datetime_to_json_formatting(o): if isinstance(o, (date, datetime)): return o.isoformat() # Only identified and successful events. **Endpoint not in use.** @app.route("/logs") async def view_open_door_events(request): return text("not an admin"), 403 results = await app.ctx.db.eventlog.find({ "component": "doorboy", "type": "open-door", "approved": True, "$or": [ { "type": "open-door" }, { "event": "card-swiped" }, ], "door": { "$exists": True }, "timestamp": { "$exists": True } }).sort("timestamp", -1).to_list(length=None) transformed = [] for r in results: if r.get("type") == "open-door" and r.get("approved") and r.get("method"): transformed.append({ "method": r.get("method"), "door": r["door"], "timestamp": r.get("timestamp"), "member": r.get("member"), }) if r.get("event") == "card-swiped" and r.get("success"): transformed.append({ "method": "card-swiped", "door": r["door"], "timestamp": r.get("timestamp"), "member": r.get("inventory", {}).get("owner") }) return json(transformed, default=datetime_to_json_formatting) @app.route("/longpoll", stream=True) async def view_longpoll(request): key = request.headers.get("KEY") if not key or key not in [DOORBOY_SECRET_FLOOR, DOORBOY_SECRET_WORKSHOP]: return text("Invalid token") # authenticate response = await request.respond(content_type="text/event-stream") await response.send("data: response-generator-started\n\n") pipeline = [ { "$match": { "operationType": "insert", } } ] try: async with app.ctx.db.eventlog.watch(pipeline) as stream: await response.send("data: watch-stream-opened\n\n") async for event in stream: ev = event["fullDocument"] if ev["approved"] != "true": continue if ev["type"] == "token": continue response.send("data: %s\n\n" % ev["door"]) except PyMongoError as e: print(e) await response.send("data: response-generator-ended\n\n") return # Called by the door to log a card swipe. Does not decide whether the door should be opened. @app.post("/swipe") async def swipe(request): # authenticate key = request.headers.get("KEY") if not key or key not in [DOORBOY_SECRET_FLOOR, DOORBOY_SECRET_WORKSHOP]: return text("Invalid token", status=401) # authorize data = request.json doors = set() if key == DOORBOY_SECRET_FLOOR: doors.update(["backdoor", "frontdoor", "grounddoor"]) if key == DOORBOY_SECRET_WORKSHOP: doors.add("workshopdoor") if data.get("door") not in doors: print("Door", repr(data.get("door")), "not in", doors) return text("Not allowed", 403) timestamp = parse(data["timestamp"]) if data.get("timestamp") else datetime.now(datetime.timezone.utc) # Update token, create if unknown app.ctx.db.inventory.update_one({ "component": "doorboy", "type": "token", "token.uid_hash": data["uid_hash"] }, { "$set": { "last_seen": timestamp }, "$setOnInsert": { "first_seen": timestamp, "inventory": { "claimable": True, } } }, upsert=True) token = app.ctx.db.inventory.find_one({ "component": "doorboy", "type": "token", "token.uid_hash": data["uid_hash"] }) event_swipe = { "component": "doorboy", "method": "token", "timestamp": timestamp, "door": data["door"], "event": "card-swiped", "approved": data["approved"], "uid_hash": data["uid_hash"], "user": { "id": token.get("inventory", {}).get("owner", {}).get("username", ""), "name": token.get("inventory", {}).get("owner", {}).get("display_name", "Unclaimed Token") } } app.ctx.db.eventlog.insert_one(event_swipe) return text("ok") if __name__ == "__main__": app.run(debug=False, host="0.0.0.0", port=5000, single_process=True, access_log=True)