Completed
Pull Request — master (#64)
by Sean
03:46 queued 57s
created

LDAPMemberExtension::updateCMSFields()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 50
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 50
rs 6.3636
cc 8
eloc 32
nc 6
nop 1
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 = array(
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 = array(
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 with a Username field have the user created in LDAP
56
     * on write.
57
     *
58
     * This requires setting write permissions on the user configured in the LDAP
59
     * credentials, which is why this is disabled by default.
60
     *
61
     * Note that some constants must be configured in your environment file:
62
     * LDAP_NEW_USERS_DN - where to place users in the directory. e.g. "OU=Users,DC=mydomain,DC=com"
63
     *
64
     * @var bool
65
     * @config
66
     */
67
    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...
68
69
    /**
70
     * If enabled, deleting Member records mapped to LDAP deletes the LDAP user.
71
     *
72
     * This requires setting write permissions on the user configured in the LDAP
73
     * credentials, which is why this is disabled by default.
74
     *
75
     * @var bool
76
     * @config
77
     */
78
    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...
79
80
    /**
81
     * @param FieldList $fields
82
     */
83
    public function updateCMSFields(FieldList $fields)
84
    {
85
        // Redo LDAP metadata fields as read-only and move to LDAP tab.
86
        $ldapMetadata = array();
87
        $fields->replaceField('GUID', $ldapMetadata[] = new ReadonlyField('GUID'));
88
        $fields->replaceField('IsExpired', $ldapMetadata[] = new ReadonlyField(
89
            'IsExpired',
90
            _t('LDAPMemberExtension.ISEXPIRED', 'Has user\'s LDAP/AD login expired?'))
91
        );
92
        $fields->replaceField('LastSynced', $ldapMetadata[] = new ReadonlyField(
93
            'LastSynced',
94
            _t('LDAPMemberExtension.LASTSYNCED', 'Last synced'))
95
        );
96
        $fields->addFieldsToTab('Root.LDAP', $ldapMetadata);
97
98
        $message = '';
99
        if ($this->owner->GUID && $this->owner->config()->update_ldap_from_local) {
100
            $message = _t(
101
                'LDAPMemberExtension.CHANGEFIELDSUPDATELDAP',
102
                'Changing fields here will update them in LDAP.'
103
            );
104
        } elseif ($this->owner->GUID && !$this->owner->config()->update_ldap_from_local) {
105
            // Transform the automatically mapped fields into read-only. This doesn't
106
            // apply if updating LDAP from local is enabled, as changing data locally can be written back.
107
            foreach ($this->owner->config()->ldap_field_mappings as $name) {
108
                $field = $fields->dataFieldByName($name);
109
                if (!empty($field)) {
110
                    // Set to readonly, but not disabled so that the data is still sent to the
111
                    // server and doesn't break Member_Validator
112
                    $field->setReadonly(true);
113
                    $field->setTitle($field->Title()._t('LDAPMemberExtension.IMPORTEDFIELD', ' (imported)'));
114
                }
115
            }
116
            $message = _t(
117
                'LDAPMemberExtension.INFOIMPORTED',
118
                'This user is automatically imported from LDAP. '.
119
                    'Manual changes to imported fields will be removed upon sync.'
120
            );
121
        }
122
        if ($message) {
123
            $fields->addFieldToTab(
124
                'Root.Main',
125
                new LiteralField(
126
                    'Info',
127
                    sprintf('<p class="message warning">%s</p>', $message)
128
                ),
129
                'FirstName'
130
            );
131
        }
132
    }
133
134
    public function validate(ValidationResult $validationResult)
135
    {
136
        if (!$this->owner->config()->create_users_in_ldap) {
137
            return;
138
        }
139
140
        // We allow empty Username for registration purposes, as we need to
141
        // create Member records with empty Username temporarily. Forms should explicitly
142
        // check for Username not being empty if they require it not to be.
143
        if (empty($this->owner->Username)) {
144
            return;
145
        }
146
147
        if (!preg_match('/^[a-z0-9\.]+$/', $this->owner->Username)) {
148
            $validationResult->error(
149
                'Username must only contain lowercase alphanumeric characters and dots.',
150
                'bad'
151
            );
152
            throw new ValidationException($validationResult);
153
        }
154
    }
155
156
    /**
157
     * Create the user in LDAP, provided this configuration is enabled
158
     * and a username was passed to a new Member record.
159
     */
160
    public function onBeforeWrite()
161
    {
162
        $service = Injector::inst()->get('LDAPService');
163
        if (!$service->enabled()) {
164
            return;
165
        }
166
        if (!$this->owner->config()->create_users_in_ldap) {
167
            return;
168
        }
169
        if ($this->owner->Username && !$this->owner->GUID) {
170
            $service->createLDAPUser($this->owner);
171
        }
172
    }
173
174
    /**
175
     * Update the local data with LDAP, and ensure local membership is also set in
176
     * LDAP too. This writes into LDAP, provided that feature is enabled.
177
     */
178 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...
179
    {
180
        $service = Injector::inst()->get('LDAPService');
181
        if (!$service->enabled()) {
182
            return;
183
        }
184
        if (!$this->owner->config()->update_ldap_from_local) {
185
            return;
186
        }
187
        if ($this->owner->GUID) {
188
            $service->updateLDAPFromMember($this->owner);
189
            $service->updateLDAPGroupsForMember($this->owner);
190
        }
191
    }
192
193 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...
194
        $service = Injector::inst()->get('LDAPService');
195
        if (!$service->enabled()) {
196
            return;
197
        }
198
        if (!$this->owner->config()->delete_users_in_ldap) {
199
            return;
200
        }
201
        if ($this->owner->GUID) {
202
            $service->deleteLDAPMember($this->owner);
203
        }
204
    }
205
206
    /**
207
     * Triggered by {@link Member::logIn()} when successfully logged in,
208
     * this will update the Member record from AD data.
209
     */
210
    public function memberLoggedIn()
211
    {
212
        if ($this->owner->GUID) {
213
            Injector::inst()->get('LDAPService')->updateMemberFromLDAP($this->owner);
214
        }
215
    }
216
}
217