Completed
Push — master ( 1fe696...91c058 )
by Damien
04:44
created

AssertionTrait::getFirstAssertion()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 0
cts 13
cp 0
rs 8.8177
c 0
b 0
f 0
cc 6
nc 6
nop 1
crap 42
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 */
6
7
namespace flipbox\saml\sp\services\login;
8
9
use flipbox\saml\core\exceptions\InvalidMessage;
10
use flipbox\saml\core\helpers\SecurityHelper;
11
use flipbox\saml\core\records\AbstractProvider;
12
use flipbox\saml\sp\Saml;
13
use SAML2\Assertion as SamlAssertion;
14
use SAML2\EncryptedAssertion;
15
use SAML2\Response as SamlResponse;
16
17
trait AssertionTrait
18
{
19
    private $firstDecryptedAssertion;
20
21
    /**
22
     * @param SamlResponse $response
23
     * @return SamlAssertion
24
     * @throws InvalidMessage
25
     */
26
    public function getFirstAssertion(SamlResponse $response)
27
    {
28
29
        /** @var AbstractProvider $ownProvider */
30
        $ownProvider = Saml::getInstance()->getProvider()->findOwn();
31
32
        // grab the first one
33
        $assertion = $response->getAssertions()[0];
34
35
        // decrypt if needed
36
        if ($ownProvider->keychain &&
37
            $assertion instanceof EncryptedAssertion &&
38
            is_null($this->firstDecryptedAssertion)
39
        ) {
40
            $assertion = SecurityHelper::decryptAssertion(
41
                $assertion,
42
                $ownProvider->keychain->getDecryptedCertificate()
43
            );
44
45
            // only do this once
46
            $this->firstDecryptedAssertion = $assertion;
47
        }
48
49
50
        if (! isset($assertion)) {
51
            throw new InvalidMessage("Invalid message. No assertions found in response.");
52
        }
53
54
        return $this->firstDecryptedAssertion ?: $assertion;
55
    }
56
}
57