Completed
Push — feature/add-institution-config... ( 9e78e8...c98478 )
by A.
03:02 queued 02:57
created

SamlProvider::authenticate()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 67
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 67
rs 6.6523
cc 8
eloc 35
nc 12
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 Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary;
22
use Surfnet\StepupRa\RaBundle\Exception\InconsistentStateException;
23
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
24
use Surfnet\StepupRa\RaBundle\Service\IdentityService;
25
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
26
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
27
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
28
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
29
30
class SamlProvider implements AuthenticationProviderInterface
31
{
32
    /**
33
     * @var \Surfnet\StepupRa\RaBundle\Service\IdentityService
34
     */
35
    private $identityService;
36
37
    /**
38
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary
39
     */
40
    private $attributeDictionary;
41
42
    /**
43
     * @var InstitutionConfigurationOptionsService
44
     */
45
    private $institutionConfigurationOptionsService;
46
47
    public function __construct(
48
        IdentityService $identityService,
49
        AttributeDictionary $attributeDictionary,
50
        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...
51
    ) {
52
        $this->identityService                        = $identityService;
53
        $this->attributeDictionary                    = $attributeDictionary;
54
        $this->institutionConfigurationOptionsService = $institutionConfigurationOptionsService;
55
    }
56
57
    /**
58
     * @param SamlToken|TokenInterface $token
59
     * @return TokenInterface|void
60
     */
61
    public function authenticate(TokenInterface $token)
62
    {
63
        $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...
64
65
        $nameId       = $translatedAssertion->getNameID();
66
        $institutions = $translatedAssertion->getAttributeValue('schacHomeOrganization');
67
68
        if (empty($institutions)) {
69
            throw new BadCredentialsException(
70
                'No schacHomeOrganization provided'
71
            );
72
        }
73
74
        if (count($institutions) > 1) {
75
            throw new BadCredentialsException(
76
                'Multiple schacHomeOrganizations provided'
77
            );
78
        }
79
80
        $identity = $this->identityService->findByNameIdAndInstitution($nameId, $institutions[0]);
81
82
        // if no identity can be found, we're done.
83
        if ($identity === null) {
84
            throw new BadCredentialsException(
85
                'Unable to find Identity matching the criteria. Has the identity been registered before?'
86
            );
87
        }
88
89
        $raCredentials = $this->identityService->getRaCredentials($identity);
90
91
        // if no credentials can be found, we're done.
92
        if (!$raCredentials) {
93
            throw new BadCredentialsException(
94
                'The Identity is not registered as (S)RA(A) and therefor does not have access to this application'
95
            );
96
        }
97
98
        // determine the role based on the credentials given
99
        $roles = [];
100
        if ($raCredentials->isSraa) {
101
            $roles[] = 'ROLE_SRAA';
102
        }
103
104
        if ($raCredentials->isRaa) {
105
            $roles[] = 'ROLE_RAA';
106
        } else {
107
            $roles[] = 'ROLE_RA';
108
        }
109
110
        $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...
111
            ->getInstitutionConfigurationOptionsFor($identity->institution);
112
113
        if ($institutionConfigurationOptions === null) {
114
            throw new InconsistentStateException(
115
                sprintf(
116
                    'No institution configuration options can be found for institution "%s"',
117
                    $identity->institution
118
                )
119
            );
120
        }
121
122
        // set the token
123
        $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...
124
        $authenticatedToken->setUser($identity);
125
126
        return $authenticatedToken;
127
    }
128
129
    public function supports(TokenInterface $token)
130
    {
131
        return $token instanceof SamlToken;
132
    }
133
}
134