From 0bac206bdd04fbb143b466d8583bd34c23782926 Mon Sep 17 00:00:00 2001 From: Martin Dimitrov Date: Tue, 24 Sep 2024 19:31:48 -0700 Subject: [PATCH] toggle on auth api also take timeout from query params --- .../serverless/functions/api/door/auth.js | 50 ++++++++++++++----- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/packages/serverless/functions/api/door/auth.js b/packages/serverless/functions/api/door/auth.js index dc235a3..58e1f65 100644 --- a/packages/serverless/functions/api/door/auth.js +++ b/packages/serverless/functions/api/door/auth.js @@ -35,21 +35,45 @@ exports.handler = async function(context, event, callback) { method: "PIN", userAgent: event.request.headers['user-agent'], }; - const timeout = config.Item.timeout.N; - await client.send(ddb.setLockStatusCommand(door, timeout, fingerprint)) - .then(async (item) => { - response - .setStatusCode(200) - .appendHeader('Content-Type', 'application/json') - .setBody({ msg: `Opened the door "${door}" for ${timeout}s` }); - }).catch((e) => { - console.log(e); - response - .setStatusCode(500) - .appendHeader('Content-Type', 'application/json') - .setBody({ err: e }); + // take timeout from the query string + const timeout = event.timeout ? parseInt(event.timeout) : config.Item.timeout.N; + + // check lock status if locked, then unlock. If unlocked then lock + await client.send(ddb.getLockStatusCommand(door)) + .then(async (lock) => { + const isOpen = ddb.isLockOpen(lock); + + if (isOpen) { + const fingerprint = JSON.parse(lock.Item.fingerprint.S); + + response + .setStatusCode(200) + .appendHeader('Content-Type', 'application/json') + .setBody({ + status: "CLOSED", + fingerprint, + }); + + await client.send(ddb.clearLockStatusCommand(lock)); + return; + } + + await client.send(ddb.setLockStatusCommand(door, timeout, fingerprint)) + .then(async (item) => { + response + .setStatusCode(200) + .appendHeader('Content-Type', 'application/json') + .setBody({ msg: `Opened the door "${door}" for ${timeout}s` }); + }).catch((e) => { + console.log(e); + response + .setStatusCode(500) + .appendHeader('Content-Type', 'application/json') + .setBody({ err: e }); + }); }); + await client.destroy(); return callback(null, response); };