Completed
Push — master ( 3253a7...22cbe7 )
by Matěj
23s queued 10s
created

UserLDAP.get_ldap_config_id()   A

Complexity

Conditions 2

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 19
rs 10
c 0
b 0
f 0
cc 2
nop 2
1
# -*- coding: utf-8 -*-
2
import re
3
4
from nextcloud.base import WithRequester
5
6
7
class UserLDAP(WithRequester):
8
    API_URL = "/ocs/v2.php/apps/user_ldap/api/v1/config"
9
    SUCCESS_CODE = 200
10
11
    CONFIG_KEYS = [
12
        "ldapHost",
13
        "ldapPort",
14
        "ldapBackupHost",
15
        "ldapBackupPort",
16
        "ldapBase",
17
        "ldapBaseUsers",
18
        "ldapBaseGroups",
19
        "ldapAgentName",
20
        "ldapAgentPassword",
21
        "ldapTLS",
22
        "turnOffCertCheck",
23
        "ldapUserDisplayName",
24
        "ldapGidNumber",
25
        "ldapUserFilterObjectclass",
26
        "ldapUserFilterGroups",
27
        "ldapUserFilter",
28
        "ldapUserFilterMode",
29
        "ldapGroupFilter",
30
        "ldapGroupFilterMode",
31
        "ldapGroupFilterObjectclass",
32
        "ldapGroupFilterGroups",
33
        "ldapGroupMemberAssocAttr",
34
        "ldapGroupDisplayName",
35
        "ldapLoginFilter",
36
        "ldapLoginFilterMode",
37
        "ldapLoginFilterEmail",
38
        "ldapLoginFilterUsername",
39
        "ldapLoginFilterAttributes",
40
        "ldapQuotaAttribute",
41
        "ldapQuotaDefault",
42
        "ldapEmailAttribute",
43
        "ldapCacheTTL",
44
        "ldapUuidUserAttribute",
45
        "ldapUuidGroupAttribute",
46
        "ldapOverrideMainServer",
47
        "ldapConfigurationActive",
48
        "ldapAttributesForUserSearch",
49
        "ldapAttributesForGroupSearch",
50
        "ldapExperiencedAdmin",
51
        "homeFolderNamingRule",
52
        "hasMemberOfFilterSupport",
53
        "useMemberOfToDetectMembership",
54
        "ldapExpertUsernameAttr",
55
        "ldapExpertUUIDUserAttr",
56
        "ldapExpertUUIDGroupAttr",
57
        "lastJpegPhotoLookup",
58
        "ldapNestedGroups",
59
        "ldapPagingSize",
60
        "turnOnPasswordChange",
61
        "ldapDynamicGroupMemberURL",
62
        "ldapDefaultPPolicyDN",
63
    ]
64
65
    def create_ldap_config(self):
66
        """ Create a new and empty LDAP configuration """
67
        return self.requester.post()
68
69
    def get_ldap_config_id(self, idx=1):
70
        """
71
        The LDAP config ID is a string.
72
        Given the number of the config file, return the corresponding string ID
73
        if the configuration exists.
74
75
        Args:
76
            idx: The index of the configuration.
77
                 If a single configuration exists on the server from the beginning,
78
                 it is going to have index of 1.
79
80
        Returns:
81
            Configuration string or None
82
        """
83
        config_id = f"s{idx:02d}"
84
        config = self.get_ldap_config(config_id)
85
        if config.is_ok:
86
            return config_id
87
        return None
88
89
    def get_ldap_lowest_existing_config_id(self, lower_bound=1, upper_bound=10):
90
        """
91
        Given (inclusive) lower and upper bounds, try to guess an existing LDAP config ID
92
        that corresponds to an index within those bounds.
93
94
        Args:
95
            lower_bound: The lowest index of the configuration possible.
96
            upper_bound: The greatest index of the configuration possible.
97
98
        Returns:
99
            Configuration string or None
100
        """
101
        for idx in range(lower_bound, upper_bound + 1):
102
            config_id = self.get_ldap_config_id(idx)
103
            if config_id:
104
                return config_id
105
106
    def get_ldap_config(self, config_id, show_password=None):
107
        """
108
        Get all keys and values of the specified LDAP configuration
109
110
        Args:
111
            config_id (str): User LDAP config id
112
            show_password (int): 0 or 1 whether to return the password in clear text (default 0)
113
114
        Returns:
115
116
        """
117
        params = dict(showPassword=show_password)
118
        return self.requester.get(config_id, params=params)
119
120
    def edit_ldap_config(self, config_id, data):
121
        """
122
        Update a configuration with the provided values
123
124
        You can find list of all config keys in get_ldap_config method response or in
125
        Nextcloud docs
126
127
        Args:
128
            config_id (str): User LDAP config id
129
            data (dict): config values to update
130
131
        Returns:
132
133
        """
134
        prepared_data = {'configData[{}]'.format(key): value for key, value in data.items()}
135
        return self.requester.put(config_id, data=prepared_data)
136
137
    def ldap_cache_flush(self, config_id):
138
        """
139
        Flush the cache, so the fresh LDAP DB data is used.
140
141
        Implementation detail:
142
        This is performed by a fake update of LDAP cache TTL
143
        as indicated by
144
145
        Args:
146
            config_id (str): User LDAP config id
147
        """
148
        cache_val = self.get_ldap_cache_ttl(config_id)
149
        self.set_ldap_cache_ttl(config_id, cache_val)
150
151
    def delete_ldap_config(self, config_id):
152
        """
153
        Delete a given LDAP configuration
154
155
        Args:
156
            config_id (str): User LDAP config id
157
158
        Returns:
159
160
        """
161
        return self.requester.delete(config_id)
162
163
164
for ldap_key in UserLDAP.CONFIG_KEYS:
165
    key_name = re.sub('ldap', '', ldap_key)
166
    key_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', key_name).lower()
167
168
    # create and add getter method
169
    getter_name = "get_ldap_{}".format(key_name)
170
171
    def getter_method(param):
172
        def getter(self, config_id):
173
            res = self.get_ldap_config(config_id)
174
            data = res.data
175
            return data[param]
176
        getter.__name__ = getter_name
177
        return getter
178
179
    setattr(UserLDAP, getter_name, getter_method(ldap_key))
180
181
    # create and add setter method
182
    setter_name = "set_ldap_{}".format(key_name)
183
184
    def setter_method(param):
185
        def setter(self, config_id, value):
186
            res = self.edit_ldap_config(config_id, data={param: value})
187
            return res
188
        setter.__name__ = setter_name
189
        return setter
190
191
    setattr(UserLDAP, setter_name, setter_method(ldap_key))
192