Completed
Push — master ( 7f018f...75cfb8 )
by A.
07:23 queued 03:02
created

SamlProvider::authenticate()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 57
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
c 5
b 0
f 2
dl 0
loc 57
rs 8.7433
cc 6
eloc 31
nc 10
nop 1

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
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupRa\RaBundle\Security\Authentication\Provider;
20
21
use Psr\Log\LoggerInterface;
22
use Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary;
23
use Surfnet\SamlBundle\SAML2\Response\AssertionAdapter;
24
use Surfnet\StepupRa\RaBundle\Exception\InconsistentStateException;
25
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
26
use Surfnet\StepupRa\RaBundle\Service\IdentityService;
27
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
28
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
29
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
30
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
31
32
class SamlProvider implements AuthenticationProviderInterface
33
{
34
    /**
35
     * @var \Surfnet\StepupRa\RaBundle\Service\IdentityService
36
     */
37
    private $identityService;
38
39
    /**
40
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary
41
     */
42
    private $attributeDictionary;
43
44
    /**
45
     * @var InstitutionConfigurationOptionsService
46
     */
47
    private $institutionConfigurationOptionsService;
48
49
    /**
50
     * @var LoggerInterface
51
     */
52
    private $logger;
53
54
    public function __construct(
55
        IdentityService $identityService,
56
        AttributeDictionary $attributeDictionary,
57
        InstitutionConfigurationOptionsService $institutionConfigurationOptionsService,
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptionsService exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
58
        LoggerInterface $logger
59
    ) {
60
        $this->identityService                        = $identityService;
61
        $this->attributeDictionary                    = $attributeDictionary;
62
        $this->institutionConfigurationOptionsService = $institutionConfigurationOptionsService;
63
        $this->logger                                 = $logger;
64
    }
65
66
    /**
67
     * @param SamlToken|TokenInterface $token
68
     * @return TokenInterface|void
69
     */
70
    public function authenticate(TokenInterface $token)
71
    {
72
        $translatedAssertion = $this->attributeDictionary->translate($token->assertion);
0 ignored issues
show
Bug introduced by
Accessing assertion on the interface Symfony\Component\Securi...on\Token\TokenInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
73
74
        $nameId      = $translatedAssertion->getNameID();
75
        $institution = $this->getSingleStringValue('schacHomeOrganization', $translatedAssertion);
76
77
        $identity = $this->identityService->findByNameIdAndInstitution($nameId, $institution);
78
79
        // if no identity can be found, we're done.
80
        if ($identity === null) {
81
            throw new BadCredentialsException(
82
                'Unable to find Identity matching the criteria. Has the identity been registered before?'
83
            );
84
        }
85
86
        $raCredentials = $this->identityService->getRaCredentials($identity);
87
88
        // if no credentials can be found, we're done.
89
        if (!$raCredentials) {
90
            throw new BadCredentialsException(
91
                'The Identity is not registered as (S)RA(A) and therefor does not have access to this application'
92
            );
93
        }
94
95
        // determine the role based on the credentials given
96
        $roles = [];
97
        if ($raCredentials->isSraa) {
98
            $roles[] = 'ROLE_SRAA';
99
        }
100
101
        if ($raCredentials->isRaa) {
102
            $roles[] = 'ROLE_RAA';
103
        } else {
104
            $roles[] = 'ROLE_RA';
105
        }
106
107
        $institutionConfigurationOptions = $this->institutionConfigurationOptionsService
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptions exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
108
            ->getInstitutionConfigurationOptionsFor($identity->institution);
109
110
        if ($institutionConfigurationOptions === null) {
111
            throw new InconsistentStateException(
112
                sprintf(
113
                    'InstitutionConfigurationOptions for institution "%s" '
114
                    . 'must exist but cannot be found after authenticating Identity "%s"',
115
                    $identity->institution,
116
                    $identity->id
117
                )
118
            );
119
        }
120
121
        // set the token
122
        $authenticatedToken = new SamlToken($token->getLoa(), $roles, $institutionConfigurationOptions);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Securi...on\Token\TokenInterface as the method getLoa() does only exist in the following implementations of said interface: Surfnet\StepupRa\RaBundl...ication\Token\SamlToken.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
123
        $authenticatedToken->setUser($identity);
124
125
        return $authenticatedToken;
126
    }
127
128
    private function getSingleStringValue($attribute, AssertionAdapter $translatedAssertion)
129
    {
130
        $values = $translatedAssertion->getAttributeValue($attribute);
131
132
        if (empty($values)) {
133
            throw new BadCredentialsException(sprintf('Missing value for required attribute "%s"', $attribute));
134
        }
135
136
        // see https://www.pivotaltracker.com/story/show/121296389
137
        if (count($values) > 1) {
138
            $this->logger->warning(sprintf(
139
                'Found "%d" values for attribute "%s", using first value',
140
                count($values),
141
                $attribute
142
            ));
143
        }
144
145
        $value = reset($values);
146
147
        if (!is_string($value)) {
148
            $message = sprintf(
149
                'First value of attribute "%s" must be a string, "%s" given',
150
                $attribute,
151
                is_object($value) ? get_class($value) : gettype($value)
152
            );
153
154
            $this->logger->warning($message);
155
156
            throw new BadCredentialsException($message);
157
        }
158
159
        return $value;
160
    }
161
162
    public function supports(TokenInterface $token)
163
    {
164
        return $token instanceof SamlToken;
165
    }
166
}
167