-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorizer.py
105 lines (85 loc) · 3.41 KB
/
authorizer.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
import asyncio
from copy import deepcopy
from datetime import datetime
from comms import create_comms
from database import read_acl_data
class Authorizer:
def __init__(self):
self.name = "authorizer"
self.comms = create_comms(self.name)
self.hours = None
self.rfids = None
self.authorities = ['/open']
self.load_acl_data()
def load_acl_data(self):
""" Load or reload the access control data """
new_data = read_acl_data()
self.hours = new_data['hours']
self.rfids = new_data['rfids']
def command_handler(self, request):
commands = request.pop('permissions')
for cmd in commands:
if cmd.get('perm') == '/reload':
self.load_acl_data()
self.comms.logger.warning("Reloading ACL data")
def lookup(self, permission, ctx):
""" Looks up the requested permission using data in the provided
context. Returns True if there's a match, false otherwise.
"""
if "identity" not in ctx:
raise ValueError("Request Missing Identity")
# Check that the requested ID is in the known RFIDs
identity = ctx.pop('identity')
self.comms.logger.info(f"attempt for: {identity}")
if identity not in self.rfids:
return False
# If RFID is known, check access rules
rules = self.rfids[identity]
allowed_hours = self.hours[rules['access_times']]
start_time, end_time = map(int, allowed_hours)
this_hour = datetime.now().hour # local time, not UTC
# this_hour is before the endtime since end_time is the label of the
# hour a user should not have access.
if ((start_time <= this_hour) and (this_hour < end_time)):
return True
# attempted access outside allowed rules
return False
def grant_permissions(self, request):
for i, perm_req in enumerate(request['permissions']):
grant = False
perm = perm_req['perm']
ctx = perm_req['ctx']
if perm in self.authorities:
try:
grant = self.lookup(perm, ctx)
except Exception as e:
grant = False
ctx = {"error": f"{e}"}
self.comms.logger.error(f"{e}")
request['permissions'][i]['grant'] = grant
async def process(self):
self.comms.start()
while True:
request = await self.comms.in_q.get()
# create and send out response
response = deepcopy(request)
response['code'] = 0
response['msg'] = "OK"
response.pop('permissions')
await self.comms.out_q.put(response)
target_id = request['target_id']
self.comms.logger.info(f"Got request for {target_id}")
# Targetting me, handle it and continue
if target_id == self.name:
self.command_handler(request)
continue
req_grant = deepcopy(request)
if target_id == 'front_door_latch':
self.grant_permissions(req_grant)
self.comms.logger.debug(f"sent request: {req_grant}")
await self.comms.request(target_id, req_grant)
if __name__ == "__main__":
auth = Authorizer()
loop = asyncio.get_event_loop()
loop.create_task(auth.process())
loop.run_forever()