-
Notifications
You must be signed in to change notification settings - Fork 3
/
lockandkey.js
284 lines (220 loc) · 7.79 KB
/
lockandkey.js
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
var express = require('express')
var adminexpress = require('express')
var sqlite3 = require('sqlite3').verbose();
var bcrypt = require('bcrypt-nodejs');
var validator = require('node-validator');
var fs = require('fs');
/* A note on security
*
* I find that no one remembers passwords, let alone infrequently used URLs. So, I haven't setup an admin login.
*
* To facilitate administration, I run two webservers
* One on an internal "admin only" port, presumably hidden behind a firewall
* The app one should be externally accessible
*
* This is probably the biggest security issue, and I'm aware of it. If you're reading this, and identify other issues, I'd like to know them.
*
* I chose bcrypt because faults are widely known in other algorithms, but given the other gaps in this application, this is likely
* the smallest concern.
*
* Because I haven't setup login names, it has to manually compute the supplied passphrase hash against hashes in the DB line by line.
* If you have more than a couple passphrases setup, this will take forever. Given enough, and client browsers will time out.
*
*
*/
//
//
//
var app = express()
var admin = adminexpress()
//apparently, POST needs this:
var bodyParser = require('body-parser')
//app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); // to support URL-encoded bodies
admin.use(bodyParser.urlencoded({ extended: true})); // to support URL-encoded bodies
//Config
var data = fs.readFileSync('./lockandkeyconfig.json'),Config;
try {
Config = JSON.parse(data);
}
catch (err) {
console.log('Error parsing config')
console.log(err);
}
//Start of Modem Stuff
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var PickUpAndDialNine = false;
//use this to store port of desired modem
var modemport;
var modem;
serialport.list(function (err, ports) {
ports.forEach(function(port) {
if (!(port.manufacturer==undefined)) {
if(port.manufacturer.search(Config.modemmanufacturerstring)>=0) {
modemport=port.comName;
console.log("Using modem on " + modemport);
}
}
});
if (modemport==undefined)
{
console.log("No modem found. Check that modem is connected and modemmanufacturerstring is set in lockandkeyconfig.json");
process.exit(1);
}
modem = new SerialPort(modemport, {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
function modemPickup(callback) {
modem.write("ATH1\r", function () {
});
}
//you would change this if your building took another number
function modemDial9(callback) {
modem.write("ATDT9\r", function () {
});
}
function modemHangup(callback) {
modem.write("ATH0\r", function () {
});
}
modem.on("open", function () {
console.log('open');
//Increase dialtone length
modem.write("ATS11=150\r", function(err, results) {
});
modem.on('data', function(data) {
console.log(data);
if ((data.substring(0,4) == "RING")&&(PickUpAndDialNine == true))
{
//Using delays worked better than reading an OK response from the modem and sending the next command
//You may have to play with timeout values
setTimeout(modemPickup, 200);
setTimeout(modemDial9, 2000);
setTimeout(modemHangup, 4000); }
if ((data.substring(0,4) == "RING")&&(PickUpAndDialNine == false))
{
console.log("Ring Detected, but don't pick up");
}
if (data.substring(0,2) == "OK")
{
console.log("Command Acknowledged");
}
else
{
console.log(data);
}
});
});
});
//End of Modem Stuff
var db = new sqlite3.Database('lockandkey.db');
var server = app.listen(Config.port, function () {
var host = server.address().address
var port = server.address().port
console.log('Lock and Key - Public Interface Listening At http://%s:%s', host, port)
})
var adminserver = admin.listen(Config.adminport, function () {
var host = adminserver.address().address
var port = adminserver.address().port
console.log('Lock and Key - Admin Interface Listening At http://%s:%s', host, port)
})
app.use('/', express.static(__dirname + '/public'));
admin.use('/', express.static(__dirname + '/admin'));
admin.get('/', function(req, res) {
res.sendFile('admin.html', { root: __dirname + '/admin'});
});
admin.get('/admin', function(req, res) {
res.sendFile('admin.html', { root: __dirname + '/admin'});
});
admin.get('/access', function(req, res) {
db.all("select * from access;", function(err, rows) {
res.send(JSON.stringify(rows));
});
});
admin.post('/addaccess', function (request, response){
console.log(request.body);
//this is where we can do the post
errmsg = "";
if (!validator.isIsoDate(request.body.startdate)) {errmsg=errmsg +"Bad start date. ";}
if (!validator.isIsoDate(request.body.stopdate)) {errmsg=errmsg +"Bad stop date. ";}
if (request.body.password.length<10) {errmsg=errmsg +"Password must be at least 10 characters. ";}
if (request.body.note.length<1) {errmsg=errmsg +"Please enter a note. ";}
if (errmsg.length>0) {
response.redirect('/admin?error='+encodeURIComponent(errmsg));
}
password = bcrypt.hashSync(request.body.password);
startdate = request.body.startdate;
stopdate = request.body.stopdate;
note = request.body.note;
if (typeof request.body.admin !== 'undefined') { admin = 'TRUE'; } else { admin = 'FALSE';}
try {
query = "insert into access (password, note, startdate, stopdate,admin) values ('"+password+"','"+note+"','"+startdate+"','"+stopdate+"','"+admin+"');";
console.log(query);
db.run(query);
response.redirect('/admin?success');
}
catch (exception) {
response.redirect('/admin?error');
}
});
admin.post('/delete', function (request, response){
//this is where we can do the post
errmsg = "";
if (!validator.isInteger(request.body.id)) {errmsg=errmsg +"Invalid record ";}
if (errmsg.length>0) {
response.redirect('/admin?recordbad='+encodeURIComponent(errmsg));
}
try {
query = "delete from access where id="+request.body.id+";";
console.log(query);
db.run(query);
response.redirect('/admin?recordgood');
}
catch (exception) {
response.redirect('/admin?recordbad');
}
});
//Run this periodically to see if we should re-lock the door (ie: set a flag to not answer and dial nine)
setInterval(function(){
db.serialize(function() {
console.log("Checking locks");
db.all("select * from lock where locked = 'TRUE' and current_timestamp > datetime(timestamp, '+"+Config.unlocktimeout+" Minute');", function(err, row) {
if(row.length > 0){
//turn off auto-answer
PickUpAndDialNine = false;
//clear lock
console.log("Clear Lock");
db.run("update lock set locked = 'FALSE' where id =1;");
}
});
});
}, 10*1000);
app.post('/authorize', function (request, response){
var match = false;
db.each("select password from access where startdate<=current_timestamp and date(stopdate, \'+1 day\')>=current_timestamp", function(err, row) {
if (match==false) {
console.log("web:"+request.body.pwd);
dbpassword = row.password;
console.log("db:"+dbpassword)
match = bcrypt.compareSync(request.body.pwd,row.password);
console.log("match:" + match );
if(match) {
console.log("Log in succesful, setting lock, turn on auto answer");
db.run("update lock set timestamp= current_timestamp, locked= 'TRUE' where id = 1;");
//Turn On Auto Answer
PickUpAndDialNine = true;
//response.sendFile('success.html', { root: __dirname + '/public'});
response.redirect('success.html?unlocktimeout='+Config.unlocktimeout);
}
}
},
//it took me forever to figure this one out
//this function runs after it pulls the last row
function(err, rows) {
if (match == false) {
response.redirect('/?error');
}}
);
});