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

LDAPMemberExtension::onBeforeWrite()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 8.8571
cc 5
eloc 9
nc 4
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.
46
     *
47
     * This requires setting write permissions on the user who talks to LDAP,
48
     * which is why it's disabled by default.
49
     *
50
     * Note that some constants must be configured in your environment file
51
     * for this to work:
52
     *
53
     * LDAP_DOMAIN - the base DN of the directory. e.g. "DN=mydomain,DC=com"
54
     * LDAP_NEW_USERS_OBJECT_CATEGORY - the type of object. e.g. "CN=Person,CN=Schema,DC=mydomain,DC=com"
55
     * LDAP_NEW_USERS_DN - where to place users in the directory. e.g. "OU=Users,DC=mydomain,DC=com"
56
     *
57
     * @var bool
58
     * @config
59
     */
60
    private static $reverse_sync_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $reverse_sync_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...
61
62
    /**
63
     * If enabled, new Member records written are also created as users in LDAP.
64
     *
65
     * This requires setting write permissions on the user who talks to LDAP,
66
     * which is why it's disabled by default.
67
     *
68
     * Please see {@link $reverse_sync_ldap} for constants that must be configured in
69
     * your environment file for this to work.
70
     *
71
     * @var bool
72
     * @config
73
     */
74
    private static $create_new_users_in_ldap = false;
0 ignored issues
show
Unused Code introduced by
The property $create_new_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
     * @var array
78
     */
79
    private static $dependencies = array(
0 ignored issues
show
Unused Code introduced by
The property $dependencies 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
        'ldapService' => '%$LDAPService',
81
    );
82
83
    /**
84
     * @param FieldList $fields
85
     */
86
    public function updateCMSFields(FieldList $fields)
87
    {
88
        // Redo LDAP metadata fields as read-only and move to LDAP tab.
89
        $ldapMetadata = array();
90
        $fields->replaceField('IsImportedFromLDAP', $ldapMetadata[] = new ReadonlyField(
91
            'IsImportedFromLDAP',
92
            _t('LDAPMemberExtension.ISIMPORTEDFROMLDAP', 'Is user imported from LDAP/AD?')
93
        ));
94
        $fields->replaceField('GUID', $ldapMetadata[] = new ReadonlyField('GUID'));
95
        $fields->replaceField('IsExpired', $ldapMetadata[] = new ReadonlyField(
96
            'IsExpired',
97
            _t('LDAPMemberExtension.ISEXPIRED', 'Has user\'s LDAP/AD login expired?'))
98
        );
99
        $fields->replaceField('LastSynced', $ldapMetadata[] = new ReadonlyField(
100
            'LastSynced',
101
            _t('LDAPMemberExtension.LASTSYNCED', 'Last synced'))
102
        );
103
        $fields->addFieldsToTab('Root.LDAP', $ldapMetadata);
104
105
        if ($this->owner->IsImportedFromLDAP && !$this->config()->reverse_sync_ldap) {
0 ignored issues
show
Bug introduced by
The method config() does not exist on LDAPMemberExtension. Did you maybe mean get_extra_config()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
106
            // Transform the automatically mapped fields into read-only. This doesn't
107
            // apply if reverse sync is enabled, as changing data locally can be written back.
108
            foreach ($this->owner->config()->ldap_field_mappings as $name) {
109
                $field = $fields->dataFieldByName($name);
110
                if (!empty($field)) {
111
                    // Set to readonly, but not disabled so that the data is still sent to the
112
                    // server and doesn't break Member_Validator
113
                    $field->setReadonly(true);
114
                    $field->setTitle($field->Title()._t('LDAPMemberExtension.IMPORTEDFIELD', ' (imported)'));
115
                }
116
            }
117
118
            // Display alert message at the top. This is not applicable if reverse sync is
119
            $message = _t(
120
                'LDAPMemberExtension.INFOIMPORTED',
121
                'This user is automatically imported from LDAP. '.
122
                    'Manual changes to imported fields will be removed upon sync.'
123
            );
124
            $fields->addFieldToTab(
125
                'Root.Main',
126
                new LiteralField(
127
                    'Info',
128
                    sprintf('<p class="message warning">%s</p>', $message)
129
                ),
130
                'FirstName'
131
            );
132
        }
133
    }
134
135
    public function validate(ValidationResult $validationResult)
136
    {
137
        if (!$this->owner->config()->create_new_users_in_ldap) {
138
            return;
139
        }
140
141
        // We allow empty Username for registration purposes, as we need to
142
        // create Member records with empty Username temporarily. Forms should explicitly
143
        // check for Username not being empty if they require it not to be.
144
        if (empty($this->owner->Username)) {
145
            return;
146
        }
147
148
        if (!preg_match('/^[a-z0-9\.]+$/', $this->owner->Username)) {
149
            $validationResult->error(
150
                'Username must only contain lowercase alphanumeric characters and dots.',
151
                'bad'
152
            );
153
            throw new ValidationException($validationResult);
154
        }
155
    }
156
157
    /**
158
     * Create the user in LDAP, provided this configuration is enabled
159
     * and a username was passed to a new Member record.
160
     *
161
     * Set a flag "Creating" so other extensions using on*() events can
162
     * detect whether it's in a state of being created, such as for
163
     * synchronising with other services when a user is being created
164
     * in LDAP for the first time.
165
     */
166
    public function onBeforeWrite()
167
    {
168
        $service = $this->ldapService;
0 ignored issues
show
Bug introduced by
The property ldapService does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
169
        if (!$service->enabled()) {
170
            return;
171
        }
172
        if (!$this->owner->config()->reverse_sync_ldap) {
173
            return;
174
        }
175
176
        if ($this->owner->Username && !$this->owner->IsImportedFromLDAP) {
177
            $service->createLDAPUser($this->owner);
178
            $this->owner->Creating = true;
179
        }
180
    }
181
182
    /**
183
     * Sync the local data with LDAP, and ensure local membership is also set in
184
     * LDAP too. This writes into LDAP, provided reverse sync is enabled.
185
     */
186
    public function onAfterWrite()
187
    {
188
        $service = $this->ldapService;
189
        if (!$service->enabled()) {
190
            return;
191
        }
192
        if (!$this->owner->config()->reverse_sync_ldap) {
193
            return;
194
        }
195
        if ($this->owner->IsImportedFromLDAP) {
196
            $this->service->updateLDAPFromMember($this->owner);
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean ldapService?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
197
            $this->service->updateLDAPGroupsForMember($this->owner);
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean ldapService?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
198
        }
199
200
        if (!$this->owner->Creating || !$this->owner->IsImportedFromLDAP) {
201
            return;
202
        }
203
204
        // muzdowski: Creation is entering the last phase. I have seen framework trying to ->write
205
        // twice in a row, resulting in an irrelevant error second time around. Mark creation
206
        // explicitly as done to prevent that.
207
        $this->owner->Creating = false;
208
    }
209
210
    /**
211
     * Triggered by {@link Member::logIn()} when successfully logged in,
212
     * this will update the Member record from AD data.
213
     */
214
    public function memberLoggedIn()
215
    {
216
        if ($this->owner->GUID) {
217
            $this->ldapService->updateMemberFromLDAP($this->owner);
218
        }
219
    }
220
}
221