Completed
Pull Request — master (#64)
by Sean
04:53 queued 02:10
created

LDAPMemberExtension::memberLoggedIn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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