Completed
Push — master ( 72ecff...582962 )
by Damien
11:32
created

AbstractLogoutController::actionRequest()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 8.9048
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 */
6
7
namespace flipbox\saml\core\controllers\messages;
8
9
use craft\db\Table;
10
use flipbox\saml\core\helpers\MessageHelper;
11
use flipbox\saml\core\models\AbstractSettings;
12
use flipbox\saml\core\records\AbstractProvider;
13
use flipbox\saml\core\records\AbstractProviderIdentity;
14
use flipbox\saml\core\records\ProviderInterface;
15
use flipbox\saml\core\services\bindings\Factory;
16
use SAML2\LogoutRequest;
17
use SAML2\LogoutResponse;
18
use yii\web\HttpException;
19
20
/**
21
 * Class AbstractLogoutController
22
 * @package flipbox\saml\core\controllers\messages
23
 */
24
abstract class AbstractLogoutController extends AbstractController implements \flipbox\saml\core\EnsureSAMLPlugin
25
{
26
27
    protected $allowAnonymous = [
28
        'actionIndex',
29
        'actionRequest',
30
    ];
31
32
    public $enableCsrfValidation = false;
33
34
    /**
35
     * @return ProviderInterface
36
     */
37
    abstract protected function getRemoteProvider($uid = null);
38
39
    /**
40
     * @param \yii\base\Action $action
41
     * @return bool
42
     */
43
    public function beforeAction($action)
44
    {
45
        if (in_array(
46
            $action->actionMethod,
47
            [
48
                'actionIndex',
49
                'actionRequest',
50
            ]
51
        )) {
52
            return true;
53
        }
54
        return parent::beforeAction($action);
55
    }
56
57
58
    /**
59
     * @return \yii\web\Response
60
     * @throws HttpException
61
     * @throws \flipbox\saml\core\exceptions\InvalidMetadata
62
     * @throws \yii\base\ExitException
63
     * @throws \yii\base\InvalidConfigException
64
     */
65
    public function actionIndex()
66
    {
67
        $message = Factory::receive();
68
69
        $isRequest = $message instanceof LogoutRequest;
70
        $isResponse = $message instanceof LogoutResponse;
71
72
        if ((! $isRequest && ! $isResponse) ||
73
            $isResponse && $this->getPlugin()->getSession()->getRequestId() !== $message->getInResponseTo()) {
0 ignored issues
show
Documentation Bug introduced by
The method getSession does not exist on object<flipbox\saml\core\AbstractPlugin>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
74
            throw new HttpException(400, "Invalid request");
75
        }
76
77
        /** @var AbstractProvider $theirProvider */
78
        $theirProvider = $this->getPlugin()->getProvider()->findByEntityId(
79
            MessageHelper::getIssuer($message->getIssuer())
80
        )->one();
81
82
        /** @var AbstractProvider $ourProvider */
83
        $ourProvider = $this->getPlugin()->getProvider()->findOwn();
84
85
        if ($isRequest) {
86
            if (\Craft::$app->getUser()->isGuest) {
87
                $this->destroySpecifiedSession(
88
                    $message,
89
                    $theirProvider,
90
                    $this->getPlugin()->getSettings()
0 ignored issues
show
Bug introduced by
It seems like $this->getPlugin()->getSettings() can be null; however, destroySpecifiedSession() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
91
                );
92
            }
93
94
            /** @var LogoutResponse $response */
95
            $response = $this->getPlugin()->getLogoutResponse()->create(
96
                $message,
97
                $theirProvider,
98
                $ourProvider
99
            );
100
101
            /**
102
             * Add the request id to the the response.
103
             */
104
            $response->setInResponseTo($message->getId());
105
106
            \Craft::$app->user->logout(true);
107
            Factory::send($response, $theirProvider);
108
            \Craft::$app->end();
109
        }
110
111
        return $this->redirect(
112
            \Craft::$app->config->general->logoutPath
113
        );
114
    }
115
116
    /**
117
     * @param LogoutRequest $message
118
     * @param AbstractProvider $theirProvider
119
     * @throws \yii\db\Exception
120
     */
121
    protected function destroySpecifiedSession(
122
        LogoutRequest $message,
123
        AbstractProvider $theirProvider,
124
        AbstractSettings $settings
125
    ) {
126
        if (! $settings->sloDestroySpecifiedSessions) {
127
            return;
128
        }
129
130
        /** @var AbstractProviderIdentity $user */
131
        $user = $this->getPlugin()->getProviderIdentity()->findByNameId(
132
            $message->getNameId()->getValue(),
133
            $theirProvider
134
        )->one();
135
136
        if ($user) {
137
            \Craft::$app->getDb()->createCommand()
138
                ->delete(Table::SESSIONS, [
139
                    'userId' => $user->userId,
140
                ])
141
                ->execute();
142
        }
143
    }
144
145
146
    /**
147
     * @param null $uid
148
     * @throws \flipbox\saml\core\exceptions\InvalidMetadata
149
     * @throws \yii\base\ExitException
150
     * @throws \yii\base\InvalidConfigException
151
     */
152
    public function actionRequest($uid = null)
153
    {
154
        // Backwards compatibility with 1.0
155
        // The request shouldn't get here with a SAMLResponse
156
        if (\Craft::$app->request->getBodyParam('SAMLResponse')) {
157
            return $this->actionIndex();
158
        }
159
160
        /** @var AbstractProvider $theirProvider */
161
        $theirProvider = $this->getRemoteProvider($uid);
162
163
        /** @var AbstractProvider $ourProvider */
164
        $ourProvider = $this->getPlugin()->getProvider()->findOwn();
165
166
        $user = \Craft::$app->user->getIdentity();
167
168
        if (! $user || (
169
                $user &&
170
                ! $identity = $this->getPlugin()->getProviderIdentity()->findByUserAndProvider($user, $theirProvider)
171
            )
172
        ) {
173
            $saml = $this->getPlugin();
174
            $saml::warning('Logout not available. User is not logged in.');
175
            // Logout locally only
176
            return $this->redirect(
177
                \Craft::$app->config->general->logoutPath
178
            );
179
        }
180
181
        $logoutRequest = $this->getPlugin()->getLogoutRequest()->create(
182
            $theirProvider,
183
            $ourProvider,
184
            $identity,
0 ignored issues
show
Bug introduced by
The variable $identity does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
185
            \Craft::$app->config->general->getPostLogoutRedirect()
186
        );
187
188
        /**
189
         * Save id to session so we can validate the response.
190
         */
191
        $this->getPlugin()->getSession()->setRequestId($logoutRequest->getId());
0 ignored issues
show
Documentation Bug introduced by
The method getSession does not exist on object<flipbox\saml\core\AbstractPlugin>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
192
193
        Factory::send($logoutRequest, $theirProvider);
194
        \Craft::$app->end();
195
    }
196
}
197