-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDatabase.py
More file actions
406 lines (296 loc) · 13.4 KB
/
Database.py
File metadata and controls
406 lines (296 loc) · 13.4 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
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
#!python3
"""
2021-04-04 Version KJHass
- Get "requires_training" and "requires_payment" just once rather than
every time a card is checked
"""
# from standard library
import logging
import requests
import time
# our code
from CardType import CardType
class Database:
'''
A high level interface to the backend database
'''
def __init__(self, settings):
'''
Create a connection to the database specified
@param (dict)settings - a dictionary describing the database to connect to
'''
# insure a minimum configuration
if (not 'website' in settings or not 'bearer_token' in settings):
raise ValueError("Database configuration must at a minimum include the 'website', 'api', and 'bearer_token' keys")
self.api_url= f"{settings['website']}/api/box.php"
self.api_header = {"Authorization" : f"Bearer {settings['bearer_token']}"}
self.request_session = requests.Session()
self.request_session.headers.update(self.api_header)
def is_registered(self, mac_address):
'''
Determine if the portal box identified by the MAC address has been
registered with the database
@param (string)mac_address - the mac_address of the portal box to
check registration status of
'''
logging.debug(f"Checking if portal box with Mac Address {mac_address} is registered")
params = {
"mode" : "check_reg",
"mac_adr" : mac_address
}
response = self.request_session.get(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
# If we don't get a success status code, then return -1
logging.error(f"API error")
return -1
else:
response_details = response.json()
return int(response_details)
def register(self, mac_address):
'''
Register the portal box identified by the MAC address with the database
as an out of service device
'''
params = {
"mode" : "register",
"mac_adr" : mac_address
}
response = self.request_session.put(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
# If we don't get a success status code, then return -1
logging.error(f"API error")
return False
else:
return True
def get_equipment_profile(self, mac_address):
'''
Discover the equipment profile assigned to the Portal Box in the database
@return a tuple consisting of: (int)equipment id,
(int)equipment type id, (str)equipment type, (int)location id,
(str)location, (int)time limit in minutes, (int) allow proxy
'''
logging.debug("Querying database for equipment profile")
profile = (-1, -1, None, -1, None, -1, -1)
params = {
"mode" : "get_profile",
"mac_adr" : mac_address
}
response = self.request_session.get(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code == 200):
response_details = response.json()[0]
profile = (
int(response_details["id"]),
int(response_details["type_id"]),
response_details["name"][0],
int(response_details["location_id"]),
response_details["name"][1],
int(response_details["timeout"]),
int(response_details["allow_proxy"])
)
self.requires_training = int(response_details["requires_training"])
self.requires_payment = int(response_details["charge_policy"])
else:
raise Exception('Error checking if portalbox is registered')
return profile
def log_started_status(self, equipment_id):
'''
Logs that this portal box has started up
@param equipment_id: The ID assigned to the portal box
'''
logging.debug("Logging with the database that this portalbox has started up")
params = {
"mode" : "log_started_status",
"equipment_id" :equipment_id
}
response = self.request_session.post(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
#If we don't get a success status code, then return and unauthorized user
logging.error(f"API error")
def log_shutdown_status(self, equipment_id, card_id):
'''
Logs that this portal box is shutting down
@param equipment_id: The ID assigned to the portal box
@param card_id: The ID read from the card presented by the user use
or a falsy value if shutdown is not related to a card
'''
logging.debug("Logging with the database that this box has shutdown")
params = {
"mode" : "log_shutdown_status",
"equipment_id" : equipment_id,
"card_id" : card_id
}
response = self.request_session.post(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
# If we don't get a success status code, then return and unauthorized user
logging.error(f"API error")
def log_access_attempt(self, card_id, equipment_id, successful):
'''
Logs start time for user using a resource.
@param card_id: The ID read from the card presented by the user
@param equipment_id: The ID assigned to the portal box
@param successful: If login was successful (user is authorized)
'''
logging.debug("Logging with database an access attempt")
params = {
"mode" : "log_access_attempt",
"equipment_id" : equipment_id,
"card_id" : card_id,
"successful" : int(successful)
}
response = self.request_session.post(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
logging.debug(f"Took {response.elapsed.total_seconds()}")
if(response.status_code != 200):
#If we don't get a success status code, then return and unauthorized user
logging.error(f"API error")
def log_access_completion(self, card_id, equipment_id):
'''
Logs end time for user using a resource.
@param card_id: The ID read from the card presented by the user
@param equipment_id: The ID assigned to the portal box
'''
logging.debug("Logging with database an access completion")
params = {
"mode" : "log_access_completion",
"equipment_id" : equipment_id,
"card_id" : card_id
}
response = self.request_session.post(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
logging.debug(f"Took {response.elapsed.total_seconds()}")
if(response.status_code != 200):
#If we don't get a success status code, then return and unauthorized user
logging.error(f"API error")
def get_card_details(self, card_id, equipment_type_id):
'''
This function gets the persistent details about a card from the database, only connecting to it once
These are returned in a dictionary
Returns: {
"user_is_authorized": true/false //Whether or not the user is authorized for this equipment
"card_type": CardType //The type of card
"user_authority_level": int //Returns if the user is a normal user, trainer, or admin
}
'''
logging.debug("Starting to get user details for card with ID %d", card_id)
params = {
"mode" : "get_card_details",
"card_id" : card_id,
"equipment_id" : equipment_type_id
}
response = self.request_session.get(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
logging.debug(f"Took {response.elapsed.total_seconds()}")
if(response.status_code != 200):
#If we don't get a success status code, then return an unauthorized user
logging.error(f"API error")
details = {
"user_is_authorized": False,
"card_type" : CardType(-1),
"user_authority_level": 0
}
else:
response_details = response.json()[0]
if response_details["user_role"] == None:
response_details["user_role"] = 0
if response_details["card_type"] == None:
response_details["card_type"] = -1
details = {
"user_is_authorized": self.is_user_authorized_for_equipment_type(response_details),
"card_type" : CardType(int(response_details["card_type"])),
"user_authority_level": int(response_details["user_role"])
}
return details
def is_user_authorized_for_equipment_type(self, card_details):
'''
Check if card holder identified by card_id is authorized for the
equipment type identified by equipment_type_id
'''
is_authorized = False
balance = float(card_details["user_balance"])
user_auth = int(card_details["user_auth"])
if card_details["user_active"] == None:
return False
if int(card_details["user_active"]) != 1:
return False
if self.requires_training and self.requires_payment:
if balance > 0.0 and user_auth:
is_authorized = True
else:
is_authorized = False
elif self.requires_training and not self.requires_payment:
if user_auth:
is_authorized = True
else:
is_authorized = False
elif not self.requires_training and self.requires_payment:
if balance > 0.0:
is_authorized = True
else:
is_authorized = False
else:
is_authorized = True
return is_authorized
def get_user(self, card_id):
'''
Get details for the user identified by (card) id
@return, a tuple of name and email
'''
user = (None, None)
logging.debug(f"Getting user information from card ID: {id}")
params = {
"mode" : "get_user",
"card_id" : card_id
}
response = self.request_session.get(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
#If we don't get a succses status code, then return and unouthorized user
logging.error(f"API error")
else:
response_details = response.json()[0]
user = (
response_details["name"],
response_details["email"]
)
return user
def get_equipment_name(self, equipment_id):
'''
Gets the name of the equipment given the equipment id
@return, a string of the name
'''
logging.debug("Getting the equipment name")
params = {
"mode" : "get_equipment_name",
"equipment_id" : equipment_id
}
response = self.request_session.get(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
#If we don't get a success status code, then return and unauthorized user
logging.error(f"API error")
return "Unknown"
else:
response_details = response.json()[0]
return response_details["name"]
def record_ip(self, equipment_id, ip):
'''
Gets the name of the equipment given the equipment id
@return, a string of the name
'''
logging.debug("Getting the equipment name")
params = {
"mode" : "record_ip",
"equipment_id" : equipment_id,
"ip_address" : ip
}
response = self.request_session.post(self.api_url, params = params)
logging.debug(f"Got response from server\nstatus: {response.status_code}\nbody: {response.text}")
if(response.status_code != 200):
#If we don't get a succses status code, then return and unouthorized user
logging.error(f"API error")
return "Unknown"