SessionHandler.build_security_object()   F
last analyzed

Complexity

Conditions 12

Size

Total Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
dl 0
loc 71
rs 2.3748
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like SessionHandler.build_security_object() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
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