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

SAMLController::acs()   C

Complexity

Conditions 9
Paths 10

Size

Total Lines 73
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 73
rs 5.9846
c 0
b 0
f 0
cc 9
eloc 41
nc 10
nop 0

How to fix   Long Method   

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\Control;
4
5
use Exception;
6
use OneLogin_Saml2_Error;
7
use SilverStripe\ActiveDirectory\Model\LDAPUtil;
8
use SilverStripe\Control\Controller;
9
use SilverStripe\Control\Director;
10
use SilverStripe\Control\Session;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Forms\Form;
13
use SilverStirpe\Security\Member;
14
use SilverStripe\Security\Security;
15
16
/**
17
 * Class SAMLController
18
 *
19
 * This controller handles serving metadata requests for the IdP, as well as handling
20
 * creating new users and logging them into SilverStripe after being authenticated at the IdP.
21
 *
22
 * @package activedirectory
23
 */
24
class SAMLController extends Controller
25
{
26
    /**
27
     * @var array
28
     */
29
    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...
30
        'index',
31
        'login',
32
        'logout',
33
        'acs',
34
        'sls',
35
        'metadata'
36
    ];
37
38
    /**
39
     * Assertion Consumer Service
40
     *
41
     * The user gets sent back here after authenticating with the IdP, off-site.
42
     * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate.
43
     *
44
     * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly
45
     * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows
46
     * LDAP side of this module to finish off loading Member data.
47
     *
48
     * @throws OneLogin_Saml2_Error
49
     */
50
    public function acs()
51
    {
52
        $auth = Injector::inst()->get('SilverStripe\\ActiveDirectory\\Helpers\\SAMLHelper')->getSAMLAuth();
53
        $auth->processResponse();
54
55
        $error = $auth->getLastErrorReason();
56
        if (!empty($error)) {
57
            $this->getLogger()->error($error);
58
            Form::messageForForm('SAMLLoginForm_LoginForm', "Authentication error: '{$error}'", 'bad');
0 ignored issues
show
Bug introduced by
The method messageForForm() does not seem to exist on object<SilverStripe\Forms\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
59
            Session::save();
60
            return $this->getRedirect();
61
        }
62
63
        if (!$auth->isAuthenticated()) {
64
            Form::messageForForm('SAMLLoginForm_LoginForm', _t('Member.ERRORWRONGCRED'), 'bad');
0 ignored issues
show
Bug introduced by
The method messageForForm() does not seem to exist on object<SilverStripe\Forms\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
65
            Session::save();
66
            return $this->getRedirect();
67
        }
68
69
        $decodedNameId = base64_decode($auth->getNameId());
70
        // check that the NameID is a binary string (which signals that it is a guid
71
        if (ctype_print($decodedNameId)) {
72
            Form::messageForForm('SAMLLoginForm_LoginForm', 'Name ID provided by IdP is not a binary GUID.', 'bad');
0 ignored issues
show
Bug introduced by
The method messageForForm() does not seem to exist on object<SilverStripe\Forms\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
            Session::save();
74
            return $this->getRedirect();
75
        }
76
77
        // transform the NameId to guid
78
        $guid = LDAPUtil::bin_to_str_guid($decodedNameId);
79
        if (!LDAPUtil::validGuid($guid)) {
80
            $errorMessage = "Not a valid GUID '{$guid}' recieved from server.";
81
            $this->getLogger()->error($errorMessage);
82
            Form::messageForForm('SAMLLoginForm_LoginForm', $errorMessage, 'bad');
0 ignored issues
show
Bug introduced by
The method messageForForm() does not seem to exist on object<SilverStripe\Forms\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
83
            Session::save();
84
            return $this->getRedirect();
85
        }
86
87
        // Write a rudimentary member with basic fields on every login, so that we at least have something
88
        // if LDAP synchronisation fails.
89
        $member = Member::get()->filter('GUID', $guid)->limit(1)->first();
90
        if (!($member && $member->exists())) {
91
            $member = new Member();
92
            $member->GUID = $guid;
93
        }
94
95
        $attributes = $auth->getAttributes();
96
97
        foreach ($member->config()->claims_field_mappings as $claim => $field) {
98
            if (!isset($attributes[$claim][0])) {
99
                $this->getLogger()->warn(
100
                    sprintf(
101
                        'Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, but wasn\'t passed through. Please check IdP claim rules.',
102
                        $claim
103
                    )
104
                );
105
106
                continue;
107
            }
108
109
            $member->$field = $attributes[$claim][0];
110
        }
111
112
        $member->SAMLSessionIndex = $auth->getSessionIndex();
113
114
        // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn.
115
        // The LDAP update will also write the Member record. We shouldn't write before
116
        // calling this, as any onAfterWrite hooks that attempt to update LDAP won't
117
        // have the Username field available yet for new Member records, and fail.
118
        // Both SAML and LDAP identify Members by the GUID field.
119
        $member->logIn();
120
121
        return $this->getRedirect();
122
    }
123
124
    /**
125
     * Generate this SP's metadata. This is needed for intialising the SP-IdP relationship.
126
     * IdP is instructed to call us back here to establish the relationship. IdP may also be configured
127
     * to hit this endpoint periodically during normal operation, to check the SP availability.
128
     */
129
    public function metadata()
130
    {
131
        try {
132
            $auth = Injector::inst()->get('SilverStripe\\ActiveDirectory\\Helpers\\SAMLHelper')->getSAMLAuth();
133
            $settings = $auth->getSettings();
134
            $metadata = $settings->getSPMetadata();
135
            $errors = $settings->validateMetadata($metadata);
136
            if (empty($errors)) {
137
                header('Content-Type: text/xml');
138
                echo $metadata;
139
            } else {
140
                throw new \OneLogin_Saml2_Error(
141
                    'Invalid SP metadata: ' . implode(', ', $errors),
142
                    \OneLogin_Saml2_Error::METADATA_SP_INVALID
143
                );
144
            }
145
        } catch (Exception $e) {
146
            $this->getLogger()->error($e->getMessage());
147
            echo $e->getMessage();
148
        }
149
    }
150
151
    /**
152
     * @return SS_HTTPResponse
153
     */
154
    protected function getRedirect()
155
    {
156
        // Absolute redirection URLs may cause spoofing
157 View Code Duplication
        if (Session::get('BackURL') && Director::is_site_url(Session::get('BackURL'))) {
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
            return $this->redirect(Session::get('BackURL'));
159
        }
160
161
        // Spoofing attack, redirect to homepage instead of spoofing url
162 View Code Duplication
        if (Session::get('BackURL') && !Director::is_site_url(Session::get('BackURL'))) {
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...
163
            return $this->redirect(Director::absoluteBaseURL());
0 ignored issues
show
Security Bug introduced by
It seems like \SilverStripe\Control\Director::absoluteBaseURL() targeting SilverStripe\Control\Director::absoluteBaseURL() can also be of type false; however, SilverStripe\Control\Controller::redirect() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
164
        }
165
166
        // If a default login dest has been set, redirect to that.
167
        if (Security::config()->default_login_dest) {
168
            return $this->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest);
169
        }
170
171
        // fallback to redirect back to home page
172
        return $this->redirect(Director::absoluteBaseURL());
0 ignored issues
show
Security Bug introduced by
It seems like \SilverStripe\Control\Director::absoluteBaseURL() targeting SilverStripe\Control\Director::absoluteBaseURL() can also be of type false; however, SilverStripe\Control\Controller::redirect() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
173
    }
174
175
    /**
176
     * Get a logger
177
     *
178
     * @return Psr\Log\LoggerInterface
179
     */
180
    public function getLogger()
181
    {
182
        return Injector::inst()->get('Logger');
183
    }
184
}
185