Martin Dimitrov 76c048b5c9
All checks were successful
Build and push Doorman UI / API / docker (push) Successful in 1m22s
unlock by discord link option
2024-10-26 14:37:14 -07:00

92 lines
2.3 KiB
JavaScript

/**
* Try to unlock the door with auth mode
*/
exports.handler = async function(context, event, callback) {
const response = new Twilio.Response();
let door = event.door;
let pin = event.key;
if (!door || !pin) {
response.setStatusCode(400);
return callback(null, response);
}
const ddbPath = Runtime.getFunctions()['common/ddb'].path;
const ddb = require(ddbPath);
const client = ddb.createDDBClient(context);
const config = await client.send(ddb.getDoorConfigCommand(door));
if (!config.Item) {
response.setStatusCode(404);
return callback(null, response);
}
let correctPin = config.Item.pin.S;
let discordUsers = config.Item.discordUsers.SS;
let method;
if (correctPin === pin) {
method = "PIN";
}
if (discordUsers.includes(pin)) {
method = "DISCORD";
}
if (!method) {
response.setStatusCode(401);
return callback(null, response);
}
const fingerprint = {
method,
userAgent: event.request.headers['user-agent'],
ip: event.ip,
};
// 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);
};