Completed
Pull Request — master (#81)
by Sean
05:56 queued 03:13
created

LDAPMemberExtension::generateLDAPUsername()   D

Complexity

Conditions 9
Paths 18

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 33
rs 4.909
cc 9
eloc 18
nc 18
nop 0
1
<?php
2
/**
3
 * Class LDAPMemberExtension.
4
 *
5
 * Adds mappings from AD attributes to SilverStripe {@link Member} fields.
6
 */
7
class LDAPMemberExtension extends DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
{
9
    /**
10
     * @var array
11
     */
12
    private static $db = [
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
        // Unique user identifier, same field is used by SAMLMemberExtension
14
        'GUID' => 'Varchar(50)',
15
        'Username' => 'Varchar(64)',
16
        'IsExpired' => 'Boolean',
17
        'LastSynced' => 'SS_Datetime',
18
    ];
19
20
    /**
21
     * These fields are used by {@link LDAPMemberSync} to map specific AD attributes
22
     * to {@link Member} fields.
23
     *
24
     * @var array
25
     * @config
26
     */
27
    private static $ldap_field_mappings = [
0 ignored issues
show
Unused Code introduced by
The property $ldap_field_mappings is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        'givenname' => 'FirstName',
29
        'samaccountname' => 'Username',
30
        'sn' => 'Surname',
31
        'mail' => 'Email',
32
    ];
33
34
    /**
35
     * The location (relative to /assets) where to save thumbnailphoto data.
36
     *
37
     * @var string
38
     * @config
39
     */
40
    private static $ldap_thumbnail_path = 'Uploads';
0 ignored issues
show
Unused Code introduced by
The property $ldap_thumbnail_path is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
41
42
    /**
43
     * When enabled, LDAP managed Member records (GUID flag)
44
     * have their data written back to LDAP on write.
45
     *
46
     * This requires setting write permissions on the user configured in the LDAP
47
     * credentials, which is why this is disabled by default.
48
     *
49
     * @var bool
50
     * @config
51
     */
52
    private static $update_ldap_from_local = false;
0 ignored issues
show
Unused Code introduced by
The property $update_ldap_from_local is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
54
    /**
55
     * If enabled, Member records are created in LDAP on write.
56
     *
57
     * This requires setting write permissions on the user configured in the LDAP
58
     * credentials, which is why this is disabled by default.
59
     *
60
     * @var bool
61
     * @config
62
     */
63
    private static $create_users_in_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $create_users_in_ldap is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
64
65
    /**
66
     * If enabled, deleting Member records mapped to LDAP deletes the LDAP user.
67
     *
68
     * This requires setting write permissions on the user configured in the LDAP
69
     * credentials, which is why this is disabled by default.
70
     *
71
     * @var bool
72
     * @config
73
     */
74
    private static $delete_users_in_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $delete_users_in_ldap is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
75
76
    /**
77
     * @param FieldList $fields
78
     */
79
    public function updateCMSFields(FieldList $fields)
80
    {
81
        // Redo LDAP metadata fields as read-only and move to LDAP tab.
82
        $ldapMetadata = [];
83
        $fields->replaceField('GUID', $ldapMetadata[] = new ReadonlyField('GUID'));
84
        $fields->replaceField('IsExpired', $ldapMetadata[] = new ReadonlyField(
85
            'IsExpired',
86
            _t('LDAPMemberExtension.ISEXPIRED', 'Has user\'s LDAP/AD login expired?'))
87
        );
88
        $fields->replaceField('LastSynced', $ldapMetadata[] = new ReadonlyField(
89
            'LastSynced',
90
            _t('LDAPMemberExtension.LASTSYNCED', 'Last synced'))
91
        );
92
        $fields->addFieldsToTab('Root.LDAP', $ldapMetadata);
93
94
        $message = '';
95
        if ($this->owner->GUID && $this->owner->config()->update_ldap_from_local) {
96
            $message = _t(
97
                'LDAPMemberExtension.CHANGEFIELDSUPDATELDAP',
98
                'Changing fields here will update them in LDAP.'
99
            );
100
        } elseif ($this->owner->GUID && !$this->owner->config()->update_ldap_from_local) {
101
            // Transform the automatically mapped fields into read-only. This doesn't
102
            // apply if updating LDAP from local is enabled, as changing data locally can be written back.
103
            foreach ($this->owner->config()->ldap_field_mappings as $name) {
104
                $field = $fields->dataFieldByName($name);
105
                if (!empty($field)) {
106
                    // Set to readonly, but not disabled so that the data is still sent to the
107
                    // server and doesn't break Member_Validator
108
                    $field->setReadonly(true);
109
                    $field->setTitle($field->Title()._t('LDAPMemberExtension.IMPORTEDFIELD', ' (imported)'));
110
                }
111
            }
112
            $message = _t(
113
                'LDAPMemberExtension.INFOIMPORTED',
114
                'This user is automatically imported from LDAP. '.
115
                    'Manual changes to imported fields will be removed upon sync.'
116
            );
117
        }
118
        if ($message) {
119
            $fields->addFieldToTab(
120
                'Root.Main',
121
                new LiteralField(
122
                    'Info',
123
                    sprintf('<p class="message warning">%s</p>', $message)
124
                ),
125
                'FirstName'
126
            );
127
        }
128
    }
129
130
    public function validate(ValidationResult $validationResult)
131
    {
132
        // We allow empty Username for registration purposes, as we need to
133
        // create Member records with empty Username temporarily. Forms should explicitly
134
        // check for Username not being empty if they require it not to be.
135
        if (!$this->owner->config()->create_users_in_ldap) {
136
            return;
137
        }
138
139
        if (!preg_match('/^[a-z0-9\.]+$/', $this->owner->Username)) {
140
            $validationResult->error(
141
                'Username must only contain lowercase alphanumeric characters and dots.',
142
                'bad'
143
            );
144
            throw new ValidationException($validationResult);
145
        }
146
    }
147
148
    /**
149
     * Generate a username for the user based on their name and/or email
150
     * @return string
151
     */
152
    public function generateLDAPUsername()
153
    {
154
        $service = Injector::inst()->get('LDAPService');
155
        if (!$service->enabled()) {
156
            return;
157
        }
158
159
        if (!$this->owner->FirstName && !$this->owner->Surname && !$this->owner->Email) {
160
            throw new ValidationException('Please ensure first name, surname, and email are set');
161
        }
162
163
        // Prepare the base string based on first name and surname.
164
        $baseArray = [];
165
        if ($this->owner->FirstName) $baseArray[] = strtolower($this->owner->FirstName);
166
        if ($this->owner->Surname) $baseArray[] = strtolower($this->owner->Surname);
167
        $baseUsername = implode('.', $baseArray);
168
169
        // Fallback to the first part of email.
170
        if (!$baseUsername) $baseUsername = preg_replace('/@.*/', '', $this->owner->Email);
171
172
        // Sanitise so it passes LDAP validator.
173
        $baseUsername = preg_replace('/[^a-z0-9\.]/', '', $baseUsername);
174
175
        // Ensure uniqueness.
176
        $suffix = 0;
177
        $tryUsername = $baseUsername;
178
        while ($service->getUserByUsername($tryUsername)) {
179
            $suffix++;
180
            $tryUsername = sprintf('%s%d', $baseUsername, $suffix);
181
        }
182
183
        return $tryUsername;
184
    }
185
186
    /**
187
     * Create the user in LDAP, provided this configuration is enabled
188
     * and a username was passed to a new Member record.
189
     */
190
    public function onBeforeWrite()
191
    {
192
        $service = Injector::inst()->get('LDAPService');
193
        if (
194
            !$service->enabled() ||
195
            !$this->owner->config()->create_users_in_ldap ||
196
            $this->owner->GUID
197
        ) {
198
            return;
199
        }
200
201
        // If a username wasn't provided, generate one
202
        if (!$this->owner->Username) {
203
            $this->owner->Username = $this->generateLDAPUsername();
204
        }
205
206
        $service->createLDAPUser($this->owner);
207
    }
208
209
    /**
210
     * Update the local data with LDAP, and ensure local membership is also set in
211
     * LDAP too. This writes into LDAP, provided that feature is enabled.
212
     */
213 View Code Duplication
    public function onAfterWrite()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
    {
215
        $service = Injector::inst()->get('LDAPService');
216
        if (
217
            !$service->enabled() ||
218
            !$this->owner->config()->update_ldap_from_local ||
219
            !$this->owner->GUID
220
        ) {
221
            return;
222
        }
223
224
        $service->updateLDAPFromMember($this->owner);
225
        $service->updateLDAPGroupsForMember($this->owner);
226
    }
227
228 View Code Duplication
    public function onAfterDelete() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
229
        $service = Injector::inst()->get('LDAPService');
230
        if (
231
            !$service->enabled() ||
232
            !$this->owner->config()->delete_users_in_ldap ||
233
            !$this->owner->GUID
234
        ) {
235
            return;
236
        }
237
238
        $service->deleteLDAPMember($this->owner);
239
    }
240
241
    /**
242
     * Triggered by {@link Member::logIn()} when successfully logged in,
243
     * this will update the Member record from AD data.
244
     */
245
    public function memberLoggedIn()
246
    {
247
        if ($this->owner->GUID) {
248
            Injector::inst()->get('LDAPService')->updateMemberFromLDAP($this->owner);
249
        }
250
    }
251
}
252