Completed
Push — master ( 197387...875417 )
by Damian
11s
created

LDAPAuthenticator::authenticate()   C

Complexity

Conditions 14
Paths 22

Size

Total Lines 76
Code Lines 45

Duplication

Lines 28
Ratio 36.84 %

Importance

Changes 0
Metric Value
dl 28
loc 76
rs 5.2661
c 0
b 0
f 0
cc 14
eloc 45
nc 22
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Authenticators;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Control\Email\Email;
7
use SilverStripe\Control\Session;
8
use SilverStripe\Core\Config\Config;
9
use SilverStripe\Core\Injector\Injector;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Security\Authenticator;
12
use SilverStripe\Security\Member;
13
14
/**
15
 * Class LDAPAuthenticator
16
 *
17
 * Authenticate a user against LDAP, without the single sign-on component.
18
 *
19
 * See SAMLAuthenticator for further information.
20
 *
21
 * @package activedirectory
22
 */
23
class LDAPAuthenticator extends Authenticator
24
{
25
    /**
26
     * @var string
27
     */
28
    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...
29
30
    /**
31
     * Set to 'yes' to indicate if this module should look up usernames in LDAP by matching the email addresses.
32
     *
33
     * CAVEAT #1: only set to 'yes' for systems that enforce email uniqueness.
34
     * Otherwise only the first LDAP user with matching email will be accessible.
35
     *
36
     * CAVEAT #2: this is untested for systems that use LDAP with principal style usernames (i.e. [email protected]).
37
     * The system will misunderstand emails for usernames with uncertain outcome.
38
     *
39
     * @var string 'no' or 'yes'
40
     */
41
    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...
42
43
    /**
44
     * Set to 'yes' to fallback login attempts to {@link $fallback_authenticator}.
45
     * This will occur if LDAP fails to authenticate the user.
46
     *
47
     * @var string 'no' or 'yes'
48
     */
49
    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...
50
51
    /**
52
     * The class of {@link Authenticator} to use as the fallback authenticator.
53
     *
54
     * @var string
55
     */
56
    private static $fallback_authenticator_class = 'SilverStripe\\Security\\MemberAuthenticator';
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...
57
58
    /**
59
     * @return string
60
     */
61
    public static function get_name()
62
    {
63
        return Config::inst()->get('SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator', 'name');
64
    }
65
66
    /**
67
     * @param Controller $controller
68
     * @return LDAPLoginForm
69
     */
70
    public static function get_login_form(Controller $controller)
71
    {
72
        return new LDAPLoginForm($controller, 'LoginForm');
0 ignored issues
show
Documentation introduced by
$controller is of type object<SilverStripe\Control\Controller>, but the function expects a object<SilverStripe\Acti...henticators\Controller>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
73
    }
74
75
    /**
76
     * Performs the login, but will also create and sync the Member record on-the-fly, if not found.
77
     *
78
     * @param array $data
79
     * @param Form $form
80
     * @return bool|Member|void
81
     * @throws HTTPResponse_Exception
82
     */
83
    public static function authenticate($data, Form $form = null)
84
    {
85
        $service = Injector::inst()->get('SilverStripe\\ActiveDirectory\\Services\\LDAPService');
86
        $login = trim($data['Login']);
87
        if (Email::is_valid_address($login)) {
88
            if (Config::inst()->get('SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator', 'allow_email_login') != 'yes') {
89
                $form->sessionMessage(
0 ignored issues
show
Bug introduced by
It seems like $form is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
90
                    _t(
91
                        'LDAPAuthenticator.PLEASEUSEUSERNAME',
92
                        'Please enter your username instead of your email to log in.'
93
                    ),
94
                    'bad'
95
                );
96
                return;
97
            }
98
99
            $username = $service->getUsernameByEmail($login);
100
101
            // No user found with this email.
102 View Code Duplication
            if (!$username) {
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...
103
                if (Config::inst()->get('SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator', 'fallback_authenticator') === 'yes') {
104
                    $fallbackMember = self::fallback_authenticate($data, $form);
105
                    if ($fallbackMember) {
106
                        return $fallbackMember;
107
                    }
108
                }
109
110
                $form->sessionMessage(_t('LDAPAuthenticator.INVALIDCREDENTIALS', 'Invalid credentials'), 'bad');
111
                return;
112
            }
113
        } else {
114
            $username = $login;
115
        }
116
117
        $result = $service->authenticate($username, $data['Password']);
118
        $success = $result['success'] === true;
119 View Code Duplication
        if (!$success) {
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...
120
            if (Config::inst()->get('SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator', 'fallback_authenticator') === 'yes') {
121
                $fallbackMember = self::fallback_authenticate($data, $form);
122
                if ($fallbackMember) {
123
                    return $fallbackMember;
124
                }
125
            }
126
127
            if ($form) {
128
                $form->sessionMessage($result['message'], 'bad');
129
            }
130
            return;
131
        }
132
133
        $data = $service->getUserByUsername($result['identity']);
134
        if (!$data) {
135
            if ($form) {
136
                $form->sessionMessage(
137
                    _t('LDAPAuthenticator.PROBLEMFINDINGDATA', 'There was a problem retrieving your user data'),
138
                    'bad'
139
                );
140
            }
141
            return;
142
        }
143
144
        // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
145
        $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
146 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...
147
            $member = new Member();
148
            $member->GUID = $data['objectguid'];
149
        }
150
151
        // Update the users from LDAP so we are sure that the email is correct.
152
        // This will also write the Member record.
153
        $service->updateMemberFromLDAP($member);
154
155
        Session::clear('BackURL');
156
157
        return $member;
158
    }
159
160
    /**
161
     * Try to authenticate using the fallback authenticator.
162
     *
163
     * @param array $data
164
     * @param null|Form $form
165
     * @return null|Member
166
     */
167
    protected static function fallback_authenticate($data, Form $form = null)
168
    {
169
        return call_user_func(
170
            [
171
                Config::inst()->get(
172
                    'SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator',
173
                    'fallback_authenticator_class'
174
                ),
175
                'authenticate'
176
            ],
177
            array_merge($data, ['Email' => $data['Login']]),
178
            $form
179
        );
180
    }
181
}
182