Completed
Push — master ( 7401b1...7c15e2 )
by Damien
09:56
created

AssertionTrait::getAssertions()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 13
cp 0
rs 9.1608
c 0
b 0
f 0
cc 5
nc 4
nop 1
crap 30
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 $decryptedAssertions = [];
20
21
    /**
22
     * @param SamlResponse $response
23
     * @return SamlAssertion
24
     * @throws InvalidMessage
25
     */
26
    public function getFirstAssertion(SamlResponse $response)
27
    {
28
29
30
        $assertions = $this->getAssertions($response);
31
32
        if (! count($assertions)) {
33
            throw new InvalidMessage("Invalid message. No assertions found in response.");
34
        }
35
36
        return $assertions[0];
37
    }
38
39
    /**
40
     * @param SamlResponse $response
41
     * @return mixed
42
     * @throws \Exception
43
     */
44
    public function getAssertions(SamlResponse $response)
45
    {
46
        /** @var AbstractProvider $ownProvider */
47
        $ownProvider = Saml::getInstance()->getProvider()->findOwn();
48
49
        // is there a cache already?
50
        if (count($this->decryptedAssertions)) {
51
            return $this->decryptedAssertions;
52
        }
53
54
        // grab the first one
55
        foreach ($response->getAssertions() as $assertion) {
56
            if ($ownProvider->keychain &&
57
                $assertion instanceof EncryptedAssertion
58
            ) {
59
                $assertion = SecurityHelper::decryptAssertion(
60
                    $assertion,
61
                    $ownProvider->keychain->getDecryptedKey()
62
                );
63
64
                $this->decryptedAssertions[] = $assertion;
65
            } else {
66
                $this->decryptedAssertions[] = $assertion;
67
            }
68
        }
69
70
        return $this->decryptedAssertions;
71
    }
72
}
73