-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
221 lines (203 loc) · 6.6 KB
/
server.js
File metadata and controls
221 lines (203 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import express from "express";
import mqtt from "mqtt";
import { MongoClient, ObjectId } from "mongodb";
import bodyParser from "body-parser";
import morgan from "morgan";
import { doorHeartbeats } from "./state.js";
import { syncUsers } from "./sync.js";
import auth from "./auth.js";
import { hybridAuth } from "./middleware/hybridAuth.js";
import { checkAccess } from "./access.js";
// API routes
import memberProjects from "./routes/memberProjects.js";
import doors from "./routes/doors.js";
import keys from "./routes/keys.js";
import users from "./routes/users.js";
import mobile from "./routes/mobile.js";
//fetch user from the https endpoint
async function fetchUser(endpoint, token, memberProjectsId) {
const url = new URL(`${endpoint}/projects/by-key/${memberProjectsId}`);
const res = await fetch(url, {
headers: { Authorization: token },
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return res.json();
}
// Apparently, automatic reconnection is the default!
const mongoClient = new MongoClient(process.env.GK_MONGO_SERVER, {
maxPoolSize: 0,
minPoolSize: 0,
});
const connectionPromise = mongoClient.connect();
connectionPromise.then(async () => {
console.log("DB Connection opened!");
const db = mongoClient.db("gatekeeper");
await Promise.all([
db.collection("users").createIndex("id", {unique: true}),
db.collection("keys").createIndex("doorsId", {unique: true}),
db.collection("keys").createIndex("drinkId", {unique: true}),
db.collection("keys").createIndex("memberProjectsId", {unique: true}),
]);
async function scheduledTasks() {
console.log("Scheduled task time!");
await syncUsers(db);
console.log("Tasks completed. Running again in 5 minutes!");
// 5 minutes
setTimeout(scheduledTasks, 1000 * 60 * 5);
}
if (process.env.NODE_ENV == "development") {
scheduledTasks();
} else {
const backoff = Math.floor(Math.random() * 1000 * 60 * 60);
console.log(
`Production. Running our work tasks in ${backoff / 1000 / 60} minutes`
);
setTimeout(scheduledTasks, backoff);
}
console.log("Opening MQTT @", process.env.GK_MQTT_SERVER);
const client = mqtt.connect(process.env.GK_MQTT_SERVER, {
username: process.env.GK_MQTT_USERNAME,
password: process.env.GK_MQTT_PASSWORD,
reconnectPeriod: 1000,
rejectUnauthorized: false,
});
client.on("error", (err) => {
console.log("MQTT errored!", err);
});
client.on("offline", () => {
console.log("Client went offline?");
});
const app = express();
app.listen(process.env.GK_HTTP_PORT || 3000, '0.0.0.0');
app.use(
morgan(":method :url :status :res[content-length] - :response-time ms")
);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") return res.sendStatus(204);
next();
});
app.use(bodyParser.json());
app.use((req, res, next) => {
req.ctx = {
db,
mqtt: client,
};
next();
});
app.use(
"/projects",
auth("projects"),
(req, res, next) => {
req.associationType = "memberProjectsId";
next();
},
memberProjects
);
// Make life easier for drink admins for now...
app.use(
"/drink",
auth("drink"),
(req, res, next) => {
req.associationType = "drinkId";
next();
},
memberProjects
);
app.use("/doors", hybridAuth("admin"), doors);
app.use("/admin/keys", auth("admin"), keys);
app.use("/admin/users", auth("admin"), users);
app.use("/mobile", mobile);
client.on("connect", async () => {
console.log("Connected to MQTT broker!");
const doors = await db.collection("doors").find({}, {projection: {_id: 1}});
for await (const door of doors) {
console.log("Subscribing to door", door._id);
const prefix = `gk/${door._id}/`;
// client.subscribe(prefix + "fetch_user");
client.subscribe(prefix + "access_requested");
client.subscribe(prefix + "heartbeat");
}
});
client.on("message", async (topic, message) => {
console.log("Got a message from server", topic, message);
let payload;
try {
payload = JSON.parse(message.toString("utf8"));
} catch (err) {
console.error("Got an invalid packet!", topic, message.toString("utf8"));
return;
}
console.log(topic, payload);
if (topic.endsWith("/access_requested")) {
const doorId = topic.slice(3, -17);
const key = await db.collection("keys").findOne({
doorsId: {$eq: payload.association},
enabled: {$eq: true},
});
// Doesn't exist??
if (!key) return;
// Fetch user info from HTTP endpoint
const endpoint = process.env.GK_HTTP_ENDPOINT;
const token = process.env.GK_SERVER_TOKEN;
const [userData, doorDoc, granted] = await Promise.all([
endpoint && token
? fetchUser(endpoint, token, key.memberProjectsId).catch((err) => {
console.error("User fetch failed:", err.message);
return {};
})
: Promise.resolve({}),
db.collection("doors").findOne({
$or: [
{ _id: doorId },
...(ObjectId.isValid(doorId)
? [{ _id: new ObjectId(doorId) }]
: []),
],
}),
checkAccess(db, key.userId, doorId),
]);
const user = userData?.user || {};
const username = user.uid || null;
const name = user.cn || null;
// Resolve door name
const doorName = doorDoc?.name || null;
//timestamps (DUHHH?)
const timestamp = new Date().toLocaleString("en-US", {
timeZone: "America/New_York",
});
// Structured log
console.log({
timestamp,
door: doorId,
doorName,
username,
name,
doorsId: payload.association,
keyId: key._id,
granted: !!granted,
});
if (granted) {
console.log(
`[${timestamp}] ${name} (${username}) is unlocking ${doorName || doorId}`
);
client.publish(`gk/${doorId}/unlock`);
} else {
console.log(
`[${timestamp}] Attempted unlock of ${doorName || doorId} by ${name} (${username})! Not allowed...`
);
}
} else if (topic.endsWith("/heartbeat")) {
const doorId = topic.slice(3, -10);
doorHeartbeats.set(doorId, Date.now());
console.log(`ACKing a heartbeat from ${doorId}!`);
}
});
});
connectionPromise.catch((err) => {
console.error("Failed connecting to mongo", err);
});