SessionHandler   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 107
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 107
rs 10
c 2
b 0
f 0
wmc 20

8 Methods

Rating   Name   Duplication   Size   Complexity  
F build_security_object() 0 71 12
A session_ids() 0 2 1
A sessions() 0 2 1
A get_session() 0 7 2
A config() 0 2 1
A exists_session() 0 2 1
A __init__() 0 4 1
A destroy() 0 2 1
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
import logging
5
logger = logging.getLogger(__name__)
6
logger.debug("%s loaded", __name__)
7
8
import time # session timestamp
9
10
from doorpi.action.base import SingleAction
0 ignored issues
show
Unused Code introduced by Thomas
Unused SingleAction imported from doorpi.action.base
Loading history...
11
import doorpi
12
13
CONF_AREA_PREFIX = 'AREA_'
14
15
class SessionHandler:
16
17
    _Sessions = {}
18
19
    @property
20
    def config(self): return doorpi.DoorPi().config
21
22
    @property
23
    def session_ids(self): return self._Sessions.keys()
24
25
    @property
26
    def sessions(self): return self._Sessions
27
28
    def __init__(self):
29
        doorpi.DoorPi().event_handler.register_event('WebServerCreateNewSession', __name__)
30
        doorpi.DoorPi().event_handler.register_event('WebServerAuthUnknownUser', __name__)
31
        doorpi.DoorPi().event_handler.register_event('WebServerAuthWrongPassword', __name__)
32
33
    def destroy(self):
34
        doorpi.DoorPi().event_handler.unregister_source(__name__, True)
35
36
    __del__ = destroy
37
38
    def get_session(self, session_id):
39
        if session_id in self._Sessions:
40
            logger.trace('session %s found: %s', session_id, self._Sessions[session_id])
41
            return self._Sessions[session_id]
42
        else:
43
            logger.trace('no session with session id %s found', session_id)
44
            return None
45
46
    __call__ = get_session
47
48
    def exists_session(self, session_id):
49
        return session_id in self._Sessions
50
51
    def build_security_object(self, username, password, remote_client = ''):
52
        if not len(self.config.get_keys('User')):
53
            self.config.set_value(section = 'User', key = 'door', value = 'pi', password = True)
54
            self.config.set_value(section = 'Group', key = 'administrator', value = 'door')
55
            self.config.set_value(section = 'WritePermission', key = 'administrator', value = 'installer')
56
            self.config.set_value(section = 'AREA_installer', key = '.*', value = '')
57
58
        groups_with_write_permissions = self.config.get_keys('WritePermission')
59
        groups_with_read_permissions = self.config.get_keys('ReadPermission')
60
        groups = self.config.get_keys('Group')
61
        users = self.config.get_keys('User')
62
63
        if not username in users:
64
            doorpi.DoorPi().event_handler('WebServerAuthUnknownUser', __name__, {
65
                'username': username,
66
                'remote_client': remote_client
67
            })
68
            return None
69
70
        real_password = self.config.get('User', username, password = True)
71
        if real_password != password:
72
            doorpi.DoorPi().event_handler('WebServerAuthWrongPassword', __name__, {
73
                'username': username,
74
                'password': password,
75
                'remote_client': remote_client
76
            })
77
            return None
78
79
        web_session = dict(
80
            username = username,
81
            remote_client = remote_client,
82
            session_starttime = time.time(),
83
            readpermissions = [],
84
            writepermissions = [],
85
            groups = []
86
        )
87
88
        for group in groups:
89
            users_in_group = self.config.get_list('Group', group)
90
            if username in users_in_group: web_session['groups'].append(group)
91
92
        for group in groups_with_read_permissions:
93
            if group in web_session['groups']:
94
                modules = self.config.get_list('ReadPermission', group)
95
                for modul in modules:
96
                    web_session['readpermissions'].extend(
97
                        self.config.get_keys(CONF_AREA_PREFIX+modul)
98
                    )
99
100
        for group in groups_with_write_permissions:
101
            if group in web_session['groups']:
102
                modules = self.config.get_list('WritePermission', group)
103
                for modul in modules:
104
                    web_session['writepermissions'].extend(
105
                        self.config.get_keys(CONF_AREA_PREFIX+modul)
106
                    )
107
                    web_session['readpermissions'].extend(
108
                        self.config.get_keys(CONF_AREA_PREFIX+modul)
109
                    )
110
111
        web_session['readpermissions'] = list(set(web_session['readpermissions']))
112
        web_session['readpermissions'].sort()
113
        web_session['writepermissions'] = list(set(web_session['writepermissions']))
114
        web_session['writepermissions'].sort()
115
116
        doorpi.DoorPi().event_handler('WebServerCreateNewSession', __name__, {
117
            'session':  web_session
118
        })
119
120
        self._Sessions[web_session['username']] = web_session
121
        return web_session
122