Completed
Push — master ( 232009...3c190c )
by Robbie
14s
created

LDAPAuthenticator::fallbackAuthenticate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 4
nop 2
1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Authenticators;
4
5
use SilverStripe\ActiveDirectory\Forms\LDAPLoginForm;
6
use SilverStripe\ActiveDirectory\Services\LDAPService;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Control\Email\Email;
9
use SilverStripe\Control\HTTPRequest;
10
use SilverStripe\Core\Config\Config;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\ORM\ValidationResult;
13
use SilverStripe\Security\Authenticator;
14
use SilverStripe\Security\Member;
15
use SilverStripe\Security\MemberAuthenticator\MemberAuthenticator;
16
use Zend\Authentication\Result;
17
18
/**
19
 * Class LDAPAuthenticator
20
 *
21
 * Authenticate a user against LDAP, without the single sign-on component.
22
 *
23
 * See SAMLAuthenticator for further information.
24
 *
25
 * @package activedirectory
26
 */
27
class LDAPAuthenticator extends MemberAuthenticator
28
{
29
    /**
30
     * @var string
31
     */
32
    private $name = 'LDAP';
0 ignored issues
show
Unused Code introduced by
The property $name 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...
33
34
    /**
35
     * Set to 'yes' to indicate if this module should look up usernames in LDAP by matching the email addresses.
36
     *
37
     * CAVEAT #1: only set to 'yes' for systems that enforce email uniqueness.
38
     * Otherwise only the first LDAP user with matching email will be accessible.
39
     *
40
     * CAVEAT #2: this is untested for systems that use LDAP with principal style usernames (i.e. [email protected]).
41
     * The system will misunderstand emails for usernames with uncertain outcome.
42
     *
43
     * @var string 'no' or 'yes'
44
     */
45
    private static $allow_email_login = 'no';
0 ignored issues
show
Unused Code introduced by
The property $allow_email_login 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...
46
47
    /**
48
     * Set to 'yes' to fallback login attempts to {@link $fallback_authenticator}.
49
     * This will occur if LDAP fails to authenticate the user.
50
     *
51
     * @var string 'no' or 'yes'
52
     */
53
    private static $fallback_authenticator = 'no';
0 ignored issues
show
Unused Code introduced by
The property $fallback_authenticator 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
     * The class of {@link Authenticator} to use as the fallback authenticator.
57
     *
58
     * @var string
59
     */
60
    private static $fallback_authenticator_class = MemberAuthenticator::class;
0 ignored issues
show
Unused Code introduced by
The property $fallback_authenticator_class 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
     * @return string
64
     */
65
    public static function get_name()
66
    {
67
        return Config::inst()->get(self::class, 'name');
68
    }
69
70
    /**
71
     * @param Controller $controller
72
     * @return LDAPLoginForm
73
     */
74
    public static function get_login_form(Controller $controller)
75
    {
76
        return LDAPLoginForm::create($controller, LDAPAuthenticator::class, 'LoginForm');
77
    }
78
79
    /**
80
     * Performs the login, but will also create and sync the Member record on-the-fly, if not found.
81
     *
82
     * @param array $data
83
     * @param HTTPRequest $request
84
     * @param ValidationResult|null $result
85
     * @return null|Member
86
     */
87
    public function authenticate(array $data, HTTPRequest $request, ValidationResult &$result = null)
88
    {
89
        $result = $result ?: ValidationResult::create();
90
        /** @var LDAPService $service */
91
        $service = Injector::inst()->get(LDAPService::class);
92
        $login = trim($data['Login']);
93
        if (Email::is_valid_address($login)) {
94
            if (Config::inst()->get(self::class, 'allow_email_login') != 'yes') {
95
                $result->addError(
96
                    _t(
97
                        __CLASS__ . '.PLEASEUSEUSERNAME',
98
                        'Please enter your username instead of your email to log in.'
99
                    )
100
                );
101
                return null;
102
            }
103
            $username = $service->getUsernameByEmail($login);
104
105
            // No user found with this email.
106
            if (!$username) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $username of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
107
                if (Config::inst()->get(self::class, 'fallback_authenticator') === 'yes') {
108
                    if ($fallbackMember = $this->fallbackAuthenticate($data, $request)) {
109
                        {
110
                            return $fallbackMember;
111
                        }
112
                    }
113
                }
114
115
                $result->addError(_t(__CLASS__ . '.INVALIDCREDENTIALS', 'Invalid credentials'));
116
                return null;
117
            }
118
        } else {
119
            $username = $login;
120
        }
121
122
        $serviceAuthenticationResult = $service->authenticate($username, $data['Password']);
123
        $success = $serviceAuthenticationResult['success'] === true;
124
125
        if (!$success) {
126
            /*
127
             * Try the fallback method if admin or it failed for anything other than invalid credentials
128
             * This is to avoid having an unhandled exception error thrown by PasswordEncryptor::create_for_algorithm()
129
             */
130
            if (Config::inst()->get(self::class, 'fallback_authenticator') === 'yes') {
131
                if (!in_array($serviceAuthenticationResult['code'], [Result::FAILURE_CREDENTIAL_INVALID])
132
                    || $username === 'admin'
133
                ) {
134
                    if ($fallbackMember = $this->fallbackAuthenticate($data, $request)) {
135
                        return $fallbackMember;
136
                    }
137
                }
138
            }
139
140
            $result->addError($serviceAuthenticationResult['message']);
141
142
            return null;
143
        }
144
        $data = $service->getUserByUsername($serviceAuthenticationResult['identity']);
145
        if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
146
            $result->addError(
147
                _t(
148
                    __CLASS__ . '.PROBLEMFINDINGDATA',
149
                    'There was a problem retrieving your user data'
150
                )
151
            );
152
            return null;
153
        }
154
155
        // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
156
        $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
157 View Code Duplication
        if (!($member && $member->exists())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
158
            $member = new Member();
159
            $member->GUID = $data['objectguid'];
160
        }
161
162
        // Update the users from LDAP so we are sure that the email is correct.
163
        // This will also write the Member record.
164
        $service->updateMemberFromLDAP($member, $data);
0 ignored issues
show
Compatibility introduced by
$member of type object<SilverStripe\ORM\DataObject> is not a sub-type of object<SilverStripe\Security\Member>. It seems like you assume a child class of the class SilverStripe\ORM\DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
165
166
        $request->getSession()->clear('BackURL');
167
168
        return $member;
169
    }
170
171
    /**
172
     * Try to authenticate using the fallback authenticator.
173
     *
174
     * @param array $data
175
     * @param HTTPRequest $request
176
     * @return null|Member
177
     */
178
    protected function fallbackAuthenticate($data, HTTPRequest $request)
179
    {
180
        // Set Email from Login
181
        if (array_key_exists('Login', $data) && !array_key_exists('Email', $data)) {
182
            $data['Email'] = $data['Login'];
183
        }
184
        $authenticatorClass = Config::inst()->get(self::class, 'fallback_authenticator_class');
185
        if ($authenticator = Injector::inst()->get($authenticatorClass)) {
186
            $result = call_user_func(
187
                [
188
                    $authenticator,
189
                    'authenticate'
190
                ],
191
                $data,
192
                $request
193
            );
194
            return $result;
195
        }
196
    }
197
198
    public function getLoginHandler($link)
199
    {
200
        return LDAPLoginHandler::create($link, $this);
201
    }
202
203
    public function supportedServices()
204
    {
205
        $result = Authenticator::LOGIN | Authenticator::LOGOUT | Authenticator::RESET_PASSWORD;
206
207
        if ((bool)LDAPService::config()->get('allow_password_change')) {
208
            $result |= Authenticator::CHANGE_PASSWORD;
209
        }
210
        return $result;
211
    }
212
213
    public function getLostPasswordHandler($link)
214
    {
215
        return LDAPLostPasswordHandler::create($link, $this);
216
    }
217
218
    /**
219
     * @param string $link
220
     * @return LDAPChangePasswordHandler
221
     */
222
    public function getChangePasswordHandler($link)
223
    {
224
        return LDAPChangePasswordHandler::create($link, $this);
225
    }
226
}
227