Passed
Push — master ( 3c190c...2857c2 )
by Robbie
03:26
created

LDAPMemberExtension   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 253
Duplicated Lines 13.04 %

Importance

Changes 0
Metric Value
dl 33
loc 253
rs 9.2
c 0
b 0
f 0
wmc 34

8 Methods

Rating   Name   Duplication   Size   Complexity  
B onAfterDelete() 15 15 5
A writeWithoutSync() 0 7 1
B onBeforeWrite() 16 16 6
B updateCMSFields() 0 53 8
B onAfterWrite() 0 14 5
A memberLoggedIn() 0 6 2
A validate() 0 15 4
A sync() 0 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace SilverStripe\LDAP\Extensions;
4
5
use Exception;
6
use SilverStripe\LDAP\Services\LDAPService;
7
use SilverStripe\Core\Injector\Injector;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\LiteralField;
10
use SilverStripe\Forms\ReadonlyField;
11
use SilverStripe\ORM\DataExtension;
12
use SilverStripe\ORM\ValidationResult;
13
use SilverStripe\ORM\ValidationException;
14
15
/**
16
 * Class LDAPMemberExtension.
17
 *
18
 * Adds mappings from AD attributes to SilverStripe {@link Member} fields.
19
 *
20
 * @package activedirectory
21
 */
22
class LDAPMemberExtension extends DataExtension
23
{
24
    /**
25
     * @var array
26
     */
27
    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...
28
        // Unique user identifier
29
        'GUID' => 'Varchar(50)',
30
        'Username' => 'Varchar(64)',
31
        'IsExpired' => 'Boolean',
32
        'LastSynced' => 'DBDatetime',
33
    ];
34
35
    /**
36
     * These fields are used by {@link LDAPMemberSync} to map specific AD attributes
37
     * to {@link Member} fields.
38
     *
39
     * @var array
40
     * @config
41
     */
42
    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...
43
        'givenname' => 'FirstName',
44
        'samaccountname' => 'Username',
45
        'sn' => 'Surname',
46
        'mail' => 'Email',
47
    ];
48
49
    /**
50
     * The location (relative to /assets) where to save thumbnailphoto data.
51
     *
52
     * @var string
53
     * @config
54
     */
55
    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...
56
57
    /**
58
     * When enabled, LDAP managed Member records (GUID flag)
59
     * have their data written back to LDAP on write, and synchronise
60
     * membership to groups mapped to LDAP.
61
     *
62
     * Keep in mind this will currently NOT trigger if there are no
63
     * field changes due to onAfterWrite in framework not being called
64
     * when there are no changes.
65
     *
66
     * This requires setting write permissions on the user configured in the LDAP
67
     * credentials, which is why this is disabled by default.
68
     *
69
     * @var bool
70
     * @config
71
     */
72
    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...
73
74
    /**
75
     * If enabled, Member records with a Username field have the user created in LDAP
76
     * on write.
77
     *
78
     * This requires setting write permissions on the user configured in the LDAP
79
     * credentials, which is why this is disabled by default.
80
     *
81
     * @var bool
82
     * @config
83
     */
84
    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...
85
86
    /**
87
     * If enabled, deleting Member records mapped to LDAP deletes the LDAP user.
88
     *
89
     * This requires setting write permissions on the user configured in the LDAP
90
     * credentials, which is why this is disabled by default.
91
     *
92
     * @var bool
93
     * @config
94
     */
95
    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...
96
97
    /**
98
     * @param FieldList $fields
99
     */
100
    public function updateCMSFields(FieldList $fields)
101
    {
102
        // Redo LDAP metadata fields as read-only and move to LDAP tab.
103
        $ldapMetadata = [];
104
        $fields->replaceField('GUID', $ldapMetadata[] = ReadonlyField::create('GUID'));
0 ignored issues
show
Bug introduced by
'GUID' of type string is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

104
        $fields->replaceField('GUID', $ldapMetadata[] = ReadonlyField::create(/** @scrutinizer ignore-type */ 'GUID'));
Loading history...
105
        $fields->replaceField(
106
            'IsExpired',
107
            $ldapMetadata[] = ReadonlyField::create(
108
                'IsExpired',
109
                _t(__CLASS__ . '.ISEXPIRED', 'Has user\'s LDAP/AD login expired?')
110
            )
111
        );
112
        $fields->replaceField(
113
            'LastSynced',
114
            $ldapMetadata[] = ReadonlyField::create(
115
                'LastSynced',
116
                _t(__CLASS__ . '.LASTSYNCED', 'Last synced')
117
            )
118
        );
119
        $fields->addFieldsToTab('Root.LDAP', $ldapMetadata);
120
121
        $message = '';
122
        if ($this->owner->GUID && $this->owner->config()->update_ldap_from_local) {
123
            $message = _t(
124
                __CLASS__ . '.CHANGEFIELDSUPDATELDAP',
125
                'Changing fields here will update them in LDAP.'
126
            );
127
        } elseif ($this->owner->GUID && !$this->owner->config()->update_ldap_from_local) {
128
            // Transform the automatically mapped fields into read-only. This doesn't
129
            // apply if updating LDAP from local is enabled, as changing data locally can be written back.
130
            foreach ($this->owner->config()->ldap_field_mappings as $name) {
131
                $field = $fields->dataFieldByName($name);
132
                if (!empty($field)) {
133
                    // Set to readonly, but not disabled so that the data is still sent to the
134
                    // server and doesn't break Member_Validator
135
                    $field->setReadonly(true);
136
                    $field->setTitle($field->Title()._t(__CLASS__ . '.IMPORTEDFIELD', ' (imported)'));
137
                }
138
            }
139
            $message = _t(
140
                __CLASS__ . '.INFOIMPORTED',
141
                'This user is automatically imported from LDAP. '.
142
                    'Manual changes to imported fields will be removed upon sync.'
143
            );
144
        }
145
        if ($message) {
146
            $fields->addFieldToTab(
147
                'Root.Main',
148
                LiteralField::create(
149
                    'Info',
150
                    sprintf('<p class="message warning">%s</p>', $message)
151
                ),
152
                'FirstName'
153
            );
154
        }
155
    }
156
157
    /**
158
     * @param  ValidationResult
159
     * @throws ValidationException
160
     */
161
    public function validate(ValidationResult $validationResult)
162
    {
163
        // We allow empty Username for registration purposes, as we need to
164
        // create Member records with empty Username temporarily. Forms should explicitly
165
        // check for Username not being empty if they require it not to be.
166
        if (empty($this->owner->Username) || !$this->owner->config()->create_users_in_ldap) {
167
            return;
168
        }
169
170
        if (!preg_match('/^[a-z0-9\.]+$/', $this->owner->Username)) {
171
            $validationResult->addError(
172
                'Username must only contain lowercase alphanumeric characters and dots.',
173
                'bad'
174
            );
175
            throw new ValidationException($validationResult);
176
        }
177
    }
178
179
    /**
180
     * Create the user in LDAP, provided this configuration is enabled
181
     * and a username was passed to a new Member record.
182
     */
183 View Code Duplication
    public function onBeforeWrite()
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...
184
    {
185
        if ($this->owner->LDAPMemberExtension_NoSync) {
186
            return;
187
        }
188
189
        $service = Injector::inst()->get(LDAPService::class);
190
        if (!$service->enabled()
191
            || !$this->owner->config()->create_users_in_ldap
192
            || !$this->owner->Username
193
            || $this->owner->GUID
194
        ) {
195
            return;
196
        }
197
198
        $service->createLDAPUser($this->owner);
199
    }
200
201
    public function onAfterWrite()
202
    {
203
        if ($this->owner->LDAPMemberExtension_NoSync) {
204
            return;
205
        }
206
207
        $service = Injector::inst()->get(LDAPService::class);
208
        if (!$service->enabled() ||
209
            !$this->owner->config()->update_ldap_from_local ||
210
            !$this->owner->GUID
211
        ) {
212
            return;
213
        }
214
        $this->sync();
215
    }
216
217 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...
218
    {
219
        if ($this->owner->LDAPMemberExtension_NoSync) {
220
            return;
221
        }
222
223
        $service = Injector::inst()->get(LDAPService::class);
224
        if (!$service->enabled() ||
225
            !$this->owner->config()->delete_users_in_ldap ||
226
            !$this->owner->GUID
227
        ) {
228
            return;
229
        }
230
231
        $service->deleteLDAPMember($this->owner);
232
    }
233
234
    /**
235
     * Write DataObject without triggering this extension's hooks.
236
     *
237
     * @throws Exception
238
     */
239
    public function writeWithoutSync()
240
    {
241
        $this->owner->LDAPMemberExtension_NoSync = true;
242
        try {
243
            $this->owner->write();
244
        } finally {
245
            $this->owner->LDAPMemberExtension_NoSync = false;
246
        }
247
    }
248
249
    /**
250
     * Update the local data with LDAP, and ensure local membership is also set in
251
     * LDAP too. This writes into LDAP, provided that feature is enabled.
252
     */
253
    public function sync()
254
    {
255
        $service = Injector::inst()->get(LDAPService::class);
256
        if (!$service->enabled() ||
257
            !$this->owner->GUID
258
        ) {
259
            return;
260
        }
261
        $service->updateLDAPFromMember($this->owner);
262
        $service->updateLDAPGroupsForMember($this->owner);
263
    }
264
265
    /**
266
     * Triggered by {@link Member::logIn()} when successfully logged in,
267
     * this will update the Member record from AD data.
268
     */
269
    public function memberLoggedIn()
270
    {
271
        if ($this->owner->GUID) {
272
            Injector::inst()
273
                ->get(LDAPService::class)
274
                ->updateMemberFromLDAP($this->owner);
275
        }
276
    }
277
}
278