From 372ae10f133a6f5a8c9dcf27cb218a8e3f264e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Madis=20M=C3=A4gi?= Date: Thu, 10 Aug 2023 22:12:14 +0300 Subject: [PATCH] Add swipe endpoint from presence proxy --- inventory-app/doorboy.py | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/inventory-app/doorboy.py b/inventory-app/doorboy.py index 534161f..9e82401 100644 --- a/inventory-app/doorboy.py +++ b/inventory-app/doorboy.py @@ -199,3 +199,71 @@ def view_doorboy_token_events(token_id): token = db.inventory.find_one({"_id": ObjectId(token_id)}) latest_events = db.eventlog.find({"component": "doorboy", "event":"card-swiped", "token.uid": token.get("token").get("uid")}).sort([("timestamp", -1)]) return render_template("doorboy.html", **locals()) + +class FormSwipe(FlaskForm): + class Meta: + csrf = False + uid = StringField('uid', validators=[]) + uid_hash = StringField('uid', validators=[]) + door = StringField('door', validators=[DataRequired()]) + success = BooleanField('success', validators=[]) + timestamp = DateTimeField('timestamp') + +@page_doorboy.route("/m/doorboy/swipe", methods=["POST"]) +def view_swipe(): + form = FormSwipe(request.form) + now = datetime.utcnow() + if form.validate_on_submit(): + # Make sure token exists + db.inventory.update_one({ + "type": "token", + "component": "doorboy", + "token.uid_hash": form.uid_hash.data + }, { + "$set": { + "last_seen": form.timestamp.data or now, + }, + "$setOnInsert": { + "component": "doorboy", + "type": "token", + "first_seen": now, + "inventory": { + "claimable": True, + } + } + }, upsert=True) + + # Fetch token to read owner + token = db.inventory.find_one({ + "type": "token", + "component": "doorboy", + "token.uid_hash": form.uid_hash.data + }) + + event_swipe = { + "component": "doorboy", + "timestamp": form.timestamp.data, + "door": form.door.data, + "event": "card-swiped", + "success": form.success.data, + "token": { + "uid_hash": form.uid_hash.data + }, + "inventory": {} + } + + if token.get("inventory", {}).get("owner", {}).get("username", None): + event_swipe["inventory"]["owner_id"] = token["inventory"]["owner"]["username"] + + db.eventlog.insert_one(event_swipe) + + status = "Permitted" if form.success.data else "Denied" + username = token.get("inventory", {}).get("owner", {}).get("username", None) + if username and username in users_lookup: + subject = users_lookup[username].display_name or username + else: + subject = "Unknown" + msg = "%s %s door access for %s identified by keycard/keyfob" % (status, form.door.data, subject) + spam(msg) + return "ok" + raise ValueError()