-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
476 lines (451 loc) · 15 KB
/
api.py
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
from flask import Blueprint, request, make_response, jsonify
from db import get_db
import time
import string, random
from argon2 import PasswordHasher
import argon2
import requests, json
api = Blueprint('api', __name__)
def checkAccess(cookieOrKey):
db = get_db()
cur = db.cursor()
cur.execute('SELECT userID FROM APIKeys WHERE apiKey=?', (cookieOrKey,))
row = cur.fetchone()
if row == None:
#It might be a cookie not an apiKey
cur.execute('SELECT userID, cookieExpiry FROM Users WHERE userCookie=?', (cookieOrKey,))
cookieRow = cur.fetchone()
if cookieRow == None:
#No auth
return -1, 'invalidCookieOrKey'
else:
#It's a valid cookie
#Check expiry
if cookieRow[1] >= int(time.time()):
#Valid cookie
return cookieRow[0], 'validCookie'
else:
#Expired cookie
return -1, 'expiredCookie'
else:
#Valid apiKey
return row[0], 'validApi'
@api.route('/')
def apiMain():
print(get_db())
return 'Web docs soon, read code or md file for now.'
@api.route('/create/user', methods=["POST"])
def createUser():
data = request.json
username = data['username']
password = data['password']
#Initialise password hasher
password_hasher = PasswordHasher()
#Hash the password and get a string of hash.
password_hash = password_hasher.hash(password)
#Get database connection
db = get_db()
cur = db.cursor()
#Check if the username is taken
cur.execute('SELECT * FROM Users WHERE userName=?', (username,))
out = {}
rows = cur.fetchall()
if len(rows) != 0:
out['status'] = 'fail'
out['reason'] = 'Username already taken'
return jsonify(out)
else:
#Store username and password hash in database
cur.execute('INSERT INTO Users(userName, userPassword) VALUES (?, ?)', (username, password_hash))
db.commit()
userId = cur.lastrowid
#Return userID and userName in response
out['status'] = 'success'
out['userId'] = userId
out['userName'] = username
return jsonify(out)
@api.route('/delete/user', methods=["DELETE"])
def deleteUser():
#data = request.json
#username = data['username']
username = request.args.get('username')
userCookie = request.cookies.get('userCookie')
#Check if cookie matches stored cookie
db = get_db()
cur = db.cursor()
cur.execute('SELECT userCookie, cookieExpiry FROM Users WHERE userName=?', (username,))
row = cur.fetchone()
out = {}
try:
if row[0] == userCookie:
#Checks if used cookie is expired or not
if row[1] >= int(time.time()):
cur.execute('DELETE FROM Users WHERE userName=?', (username,))
db.commit()
out['status'] = 'success'
else:
out['status'] = 'fail'
out['reason'] = 'Expired Cookie'
else:
out['status'] = 'fail'
out['reason'] = 'Invalid Cookie'
return jsonify(out)
except Exception as e:
print(e)
out['status'] = 'fail'
out['reason'] = 'Unknown Error'
return jsonify(out)
@api.route('/user/login', methods=["POST"])
def userLogin():
data = request.json
username = data['username']
password = data['password']
password_hasher = PasswordHasher()
#Check if password matches
db = get_db()
cur = db.cursor()
cur.execute('SELECT userPassword FROM Users WHERE userName=?', (username,))
row = cur.fetchone()
out = {}
if row == None:
out['status'] = 'fail'
out['reason'] = 'Username or Password Wrong'
return jsonify(out), 403
try:
password_hasher.verify(row[0], password)
#Password Matches!
cookie = ''
for i in range(0,128):
cookie += random.choice(random.choice([string.ascii_letters, string.ascii_lowercase, string.digits]))
out['status'] = 'success'
out['cookie'] = cookie
reply = make_response(jsonify(out))
reply.set_cookie('userCookie', cookie, max_age=60*60*24)
cur.execute('UPDATE Users SET userCookie=?, cookieExpiry=? WHERE userName=?', (cookie, int(time.time())+60*60*24, username,))
db.commit()
return reply, 200
except argon2.exceptions.VerifyMismatchError:
out['status'] = 'fail'
out['reason'] = 'Username or Password Wrong'
return jsonify(out), 403
@api.route('/create/key', methods=["POST"])
def createApiKey():
userCookie = request.cookies.get('userCookie')
db = get_db()
cur = db.cursor()
cur.execute('SELECT userID, cookieExpiry FROM Users WHERE userCookie=?', (userCookie,))
row = cur.fetchone()
out = {}
if row == None:
out['status'] = 'fail'
out['reason'] = 'Invalid Cookie or Username'
return jsonify(out)
else:
#Check if the cookie is still valid
if row[1] >= int(time.time()):
#Cookie is still valid!
#Create the api key
newKey = ""
for i in range(0,16):
newKey += random.choice(random.choice([string.ascii_letters, string.ascii_lowercase, string.digits]))
cur.execute('INSERT INTO APIKeys(apiKey, userID) VALUES (?, ?)', (newKey, row[0]))
db.commit()
out['status'] = 'success'
out['key'] = newKey
else:
out['status'] = 'fail'
out['reason'] = 'Expired Cookie'
return jsonify(out)
@api.route('/delete/key', methods=["DELETE"])
def deleteApiKey():
#data = request.json
#apiKey = data['apiKey']
apiKey = request.args.get('key')
userCookie = request.cookies.get('userCookie')
db = get_db()
cur = db.cursor()
cur.execute('SELECT userID, cookieExpiry FROM Users WHERE userCookie=?', (userCookie,))
row = cur.fetchone()
out = {}
if row == None:
out['status'] = 'fail'
out['reason'] = 'Invalid Cookie or Username'
return jsonify(out)
else:
#Check if the cookie is still valid
if row[1] >= int(time.time()):
#Cookie is still valid!
#Delete the api key
cur.execute('DELETE FROM APIKeys WHERE apiKey=?', (apiKey,))
db.commit()
out['status'] = 'success'
else:
out['status'] = 'fail'
out['reason'] = 'Expired Cookie'
return jsonify(out)
@api.route('/create/sensor', methods=["POST"])
def createSensor():
data = request.json
sensorName = data['name']
sensorLat = data['sensorLat']
sensorLon = data['sensorLon']
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
db = get_db()
cur = db.cursor()
out = {}
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out), 403
cur.execute('INSERT INTO Sensors(sensorName, sensorLat, sensorLon, userID) VALUES (?, ?, ?, ?)', (sensorName, sensorLat, sensorLon, userID,))
db.commit()
out['status'] = 'success'
return jsonify(out)
@api.route('/delete/sensor', methods=["DELETE"])
def deleteSensor():
#data = request.json
#sensorName = data['name']
sensorName = request.args.get('name')
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
db = get_db()
cur = db.cursor()
#cur.execute('SELECT userID FROM APIKeys WHERE apiKey=?', (apiKey,))
#row = cur.fetchone()
out = {}
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out), 403
cur.execute('DELETE FROM Sensors WHERE sensorName=? AND userID=?', (sensorName, userID,))
db.commit()
out['status'] = 'success'
return jsonify(out)
@api.route('/info/sensor', methods=["GET"])
def getSensorInfo():
sensorName = request.args.get('sensorName')
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
db = get_db()
cur = db.cursor()
out = {}
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out)
cur.execute('SELECT * FROM Sensors WHERE sensorName=? AND userID=?', (sensorName, userID,))
row = cur.fetchone()
if row == None:
out['status'] = 'fail'
out['reason'] = 'Sensor Does Not Exist'
return jsonify(out)
out['status'] = 'success'
out['sensorID'] = row[0]
out['sensorName'] = row[1]
out['sensorLat'] = row[2]
out['sensorLon'] = row[3]
return jsonify(out)
@api.route('/info/sensors', methods=["GET"])
def listSensors():
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
db = get_db()
cur = db.cursor()
out = {}
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out)
cur.execute('SELECT sensorID,sensorName FROM Sensors WHERE userID=?', (userID,))
rows = cur.fetchall()
out['sensorIDs'] = []
out['sensorNames'] = []
for row in rows:
out['sensorIDs'].append(row[0])
out['sensorNames'].append(row[1])
out['status'] = 'success'
return jsonify(out)
@api.route('/info/keys', methods=["GET"])
def getKeys():
out = {}
#Auth
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out), 403
#DB
db = get_db()
cur = db.cursor()
#Get keys
cur.execute('SELECT apiKey FROM APIKeys WHERE userID=?', (userID,))
rows = cur.fetchall()
out['apiKeys'] = []
for row in rows:
out['apiKeys'].append(row[0])
out['status'] = 'success'
return jsonify(out)
@api.route('/data/sensor', methods=["GET", "POST"])
def dataInput():
out = {}
if request.method == "POST":
#Auth
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out), 403
#Incoming data, add to database
data = request.json
sensorID = data['sensorID']
temperature = data['temperature']
humidity = data['humidity']
#DB
db = get_db()
cur = db.cursor()
#Is sensor owned by authenticated user
cur.execute('SELECT userID FROM Sensors WHERE sensorID=?', (sensorID,))
row = cur.fetchone()
if row[0] != userID:
#Not the right user
out['status'] = 'fail'
out['reason'] = 'Incorrect Authentication'
return jsonify(out), 403
#Insert to database.
cur.execute('INSERT INTO SensorData(sensorID, time, temperature, humidity) VALUES (?, ?, ?, ?)', (sensorID, int(time.time()), temperature, humidity))
db.commit()
out['status'] = 'success'
return jsonify(out)
elif request.method == "GET":
#Auth
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
amnt = request.args.get('amount')
if amnt == None:
amnt = 5
if apiKey != None:
userID, valid = checkAccess(apiKey)
else:
#Get cookie
userCookie = request.cookies.get('userCookie')
userID, valid = checkAccess(userCookie)
if valid == 'validCookie' or valid == 'validApi':
#Keep going
pass
else:
out['status'] = 'fail'
out['reason'] = valid
return jsonify(out), 403
#DB
db = get_db()
cur = db.cursor()
#Is sensor owned by authenticated user
sensorID = request.args.get('sensorID')
cur.execute('SELECT userID FROM Sensors WHERE sensorID=?', (sensorID,))
row = cur.fetchone()
if row[0] != userID:
#Not the right user
out['status'] = 'fail'
out['reason'] = 'Incorrect Authentication'
return jsonify(out), 403
#Get sensor details
sensorDetails = cur.execute('SELECT * FROM Sensors WHERE sensorID = ?', (sensorID,))
sensorDetails = cur.fetchone()
#Retrieve last 5 data points from database, make it into a json structure and hand it back.
rows = cur.execute('SELECT * FROM SensorData WHERE sensorID = ? ORDER BY time DESC LIMIT ?', (sensorID,amnt,)).fetchall()
out['sensorID'] = sensorID
out['sensorLat'] = sensorDetails[2]
out['sensorLon'] = sensorDetails[3]
out['sensorName'] = sensorDetails[1]
out['data'] = []
for row in reversed(rows):
this = {}
this['time'] = row[2]
this['temperature'] = row[3]
this['humidity'] = row[4]
out['data'].append(this)
return jsonify(out)
@api.route('/data/ttnsensor', methods=["POST"])
def ttnInput():
datain = request.json
try:
apiKey = request.headers['apiKey']
except KeyError:
apiKey = None
data = {
'sensorID': datain['payload_fields']['sensorID'],
'humidity': datain['payload_fields']['humidity'],
'temperature': datain['payload_fields']['temperature']
}
return requests.post(request.host_url+"api/data/sensor", data=json.dumps(data), headers={"Content-type": "application/json", "apiKey": apiKey}).text