Completed
Push — master ( 7a48ac...3c190c )
by Robbie
13:00
created

LDAPLostPasswordHandler::lostPasswordForm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Authenticators;
4
5
use SilverStripe\ActiveDirectory\Services\LDAPService;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Email\Email;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Core\Config\Config;
10
use SilverStripe\Core\Convert;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Forms\FieldList;
13
use SilverStripe\Forms\Form;
14
use SilverStripe\Forms\FormAction;
15
use SilverStripe\Forms\TextField;
16
use SilverStripe\ORM\FieldType\DBField;
17
use SilverStripe\Security\Member;
18
use SilverStripe\Security\MemberAuthenticator\LostPasswordForm;
19
use SilverStripe\Security\MemberAuthenticator\LostPasswordHandler;
20
use SilverStripe\Security\Security;
21
22
class LDAPLostPasswordHandler extends LostPasswordHandler
23
{
24
    /**
25
     * Since the logout and dologin actions may be conditionally removed, it's necessary to ensure these
26
     * remain valid actions regardless of the member login state.
27
     *
28
     * @var array
29
     * @config
30
     */
31
    private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $allowed_actions 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...
32
        'lostpassword',
33
        'LostPasswordForm',
34
        'passwordsent',
35
    ];
36
37
38
    /**
39
     * @param string $link The URL to recreate this request handler
40
     * @param LDAPAuthenticator $authenticator
41
     */
42
    public function __construct($link, LDAPAuthenticator $authenticator)
43
    {
44
        $this->link = $link;
0 ignored issues
show
Documentation introduced by
The property $link is declared private in SilverStripe\Security\Me...tor\LostPasswordHandler. Since you implemented __set(), maybe consider adding a @property or @property-write annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
45
        $this->authenticatorClass = get_class($authenticator);
46
        parent::__construct($link);
47
    }
48
49
    /**
50
     * Forgot password form handler method.
51
     *
52
     * Called when the user clicks on "I've lost my password".
53
     *
54
     * Extensions can use the 'forgotPassword' method to veto executing
55
     * the logic, by returning FALSE. In this case, the user will be redirected back
56
     * to the form without further action. It is recommended to set a message
57
     * in the form detailing why the action was denied.
58
     *
59
     * @param array $data Submitted data
60
     * @param LostPasswordForm $form
61
     * @return HTTPResponse
62
     */
63
    public function forgotPassword($data, $form)
64
    {
65
        /** @var Controller $controller */
66
        $controller = $form->getController();
67
68
        // No need to protect against injections, LDAPService will ensure that this is safe
69
        $login = trim($data['Login']);
70
71
        $service = Injector::inst()->get(LDAPService::class);
72
        if (Email::is_valid_address($login)) {
73
            if (Config::inst()->get(LDAPAuthenticator::class, 'allow_email_login') != 'yes') {
74
                $form->sessionMessage(
75
                    _t(
76
                        'SilverStripe\\ActiveDirectory\\Forms\\LDAPLoginForm.USERNAMEINSTEADOFEMAIL',
77
                        'Please enter your username instead of your email to get a password reset link.'
78
                    ),
79
                    'bad'
80
                );
81
                return $controller->redirect($controller->Link('lostpassword'));
82
            }
83
            $userData = $service->getUserByEmail($login);
84
        } else {
85
            $userData = $service->getUserByUsername($login);
86
        }
87
        // Avoid information disclosure by displaying the same status,
88
        // regardless whether the email address actually exists
89
        if (!isset($userData['objectguid'])) {
90
            return $controller->redirect($controller->Link('passwordsent/')
91
                . urlencode($data['Login']));
92
        }
93
94
        $member = Member::get()->filter('GUID', $userData['objectguid'])->limit(1)->first();
95
        // User haven't been imported yet so do that now
96 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...
97
            $member = new Member();
98
            $member->GUID = $userData['objectguid'];
99
        }
100
101
        // Update the users from LDAP so we are sure that the email is correct.
102
        // This will also write the Member record.
103
        $service->updateMemberFromLDAP($member, $userData, false);
104
105
        // Allow vetoing forgot password requests
106
        $results = $this->extend('forgotPassword', $member);
107
        if ($results && is_array($results) && in_array(false, $results, true)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results 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...
108
            return $controller->redirect('lostpassword');
109
        }
110
111
        if ($member) {
112
            /** @see MemberLoginForm::forgotPassword */
113
            $token = $member->generateAutologinTokenAndStoreHash();
114
            $e = Email::create()
115
                ->setSubject(
116
                    _t(
117
                        'Silverstripe\\Security\\Member.SUBJECTPASSWORDRESET',
118
                        'Your password reset link',
119
                        'Email subject'
120
                    )
121
                )
122
                ->setHTMLTemplate('SilverStripe\\Control\\Email\\ForgotPasswordEmail')
123
                ->setData($member)
124
                ->setData(['PasswordResetLink' => Security::getPasswordResetLink($member, $token)]);
125
            $e->setTo($member->Email);
126
            $e->send();
127
            return $controller->redirect($controller->Link('passwordsent/') . urlencode($data['Login']));
128
        } elseif ($data['Login']) {
129
            // Avoid information disclosure by displaying the same status,
130
            // regardless whether the email address actually exists
131
            return $controller->redirect($controller->Link('passwordsent/') . urlencode($data['Login']));
132
        } else {
133
            if (Config::inst()->get(LDAPAuthenticator::class, 'allow_email_login') === 'yes') {
134
                $form->sessionMessage(
135
                    _t(
136
                        'SilverStripe\\ActiveDirectory\\Forms\\LDAPLoginForm.ENTERUSERNAMEOREMAIL',
137
                        'Please enter your username or your email address to get a password reset link.'
138
                    ),
139
                    'bad'
140
                );
141
            } else {
142
                $form->sessionMessage(
143
                    _t(
144
                        'SilverStripe\\ActiveDirectory\\Forms\\LDAPLoginForm.ENTERUSERNAME',
145
                        'Please enter your username to get a password reset link.'
146
                    ),
147
                    'bad'
148
                );
149
            }
150
            return $controller->redirect($controller->Link('lostpassword'));
151
        }
152
    }
153
154
    /**
155
     * Factory method for the lost password form
156
     *
157
     * @return Form Returns the lost password form
158
     */
159
    public function lostPasswordForm()
160
    {
161
        $loginFieldLabel = (Config::inst()->get(LDAPAuthenticator::class, 'allow_email_login') === 'yes') ?
162
            _t('SilverStripe\\ActiveDirectory\\Forms\\LDAPLoginForm.USERNAMEOREMAIL', 'Username or email') :
163
            _t('SilverStripe\\ActiveDirectory\\Forms\\LDAPLoginForm.USERNAME', 'Username');
164
        $loginField = TextField::create('Login', $loginFieldLabel);
165
166
        $action = FormAction::create(
167
            'forgotPassword',
168
            _t('SilverStripe\\Security\\Security.BUTTONSEND', 'Send me the password reset link')
169
        );
170
        return LostPasswordForm::create(
171
            $this,
172
            $this->authenticatorClass,
173
            'LostPasswordForm',
174
            FieldList::create([$loginField]),
175
            FieldList::create([$action]),
176
            false
177
        );
178
    }
179
180
    public function lostpassword()
181
    {
182
        if (Config::inst()->get(LDAPAuthenticator::class, 'allow_email_login') === 'yes') {
183
            $message = _t(
184
                __CLASS__ . '.NOTERESETPASSWORDUSERNAMEOREMAIL',
185
                'Enter your username or your email address and we will send you a link with which '
186
                . 'you can reset your password'
187
            );
188
        } else {
189
            $message = _t(
190
                __CLASS__ . '.NOTERESETPASSWORDUSERNAME',
191
                'Enter your username and we will send you a link with which you can reset your password'
192
            );
193
        }
194
195
        return [
196
            'Content' => DBField::create_field('HTMLFragment', "<p>$message</p>"),
197
            'Form' => $this->lostPasswordForm(),
198
        ];
199
    }
200
201
    public function passwordsent()
202
    {
203
        $username = Convert::raw2xml(
204
            rawurldecode($this->getRequest()->param('OtherID'))
205
        );
206
        $username .= ($extension = $this->request->getExtension()) ? '.' . $extension : '';
207
208
        return [
209
            'Title' => _t(
210
                __CLASS__ . '.PASSWORDSENTHEADER',
211
                "Password reset link sent to '{username}'",
212
                ['username' => $username]
213
            ),
214
            'Content' =>
215
                _t(
216
                    __CLASS__ . '.PASSWORDSENTTEXT',
217
                    "Thank you! A reset link has been sent to '{username}', provided an account exists.",
218
                    ['username' => $username]
219
                ),
220
            'Username' => $username
221
        ];
222
    }
223
}
224