Completed
Pull Request — develop (#101)
by Boy
05:25 queued 02:43
created

SamlProvider   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 171
Duplicated Lines 30.41 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 18
c 5
b 1
f 0
lcom 1
cbo 9
dl 52
loc 171
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
B authenticate() 0 35 4
A supports() 0 4 1
B getInstitution() 27 27 4
B getCommonName() 0 25 4
B getEmail() 25 25 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\StepupSelfService\SelfServiceBundle\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\StepupMiddlewareClientBundle\Identity\Dto\Identity;
25
use Surfnet\StepupMiddlewareClientBundle\Uuid\Uuid;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Locale\PreferredLocaleProvider;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\Token\SamlToken;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Service\IdentityService;
29
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
30
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
31
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
32
33
class SamlProvider implements AuthenticationProviderInterface
34
{
35
    /**
36
     * @var \Surfnet\StepupSelfService\SelfServiceBundle\Service\IdentityService
37
     */
38
    private $identityService;
39
40
    /**
41
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary
42
     */
43
    private $attributeDictionary;
44
45
    /**
46
     * @var \Surfnet\StepupSelfService\SelfServiceBundle\Locale\PreferredLocaleProvider
47
     */
48
    private $preferredLocaleProvider;
49
50
    /**
51
     * @var \Psr\Log\LoggerInterface
52
     */
53
    private $logger;
54
55
    public function __construct(
56
        IdentityService $identityService,
57
        AttributeDictionary $attributeDictionary,
58
        PreferredLocaleProvider $preferredLocaleProvider,
59
        LoggerInterface $logger
60
    ) {
61
        $this->identityService = $identityService;
62
        $this->attributeDictionary = $attributeDictionary;
63
        $this->preferredLocaleProvider = $preferredLocaleProvider;
64
        $this->logger = $logger;
65
    }
66
67
    /**
68
     * @param  SamlToken $token
0 ignored issues
show
Documentation introduced by
Should the type for parameter $token not be TokenInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
69
     * @return TokenInterface|void
70
     */
71
    public function authenticate(TokenInterface $token)
72
    {
73
        $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...
74
75
        $nameId         = $translatedAssertion->getNameID();
76
        $institution    = $this->getInstitution($translatedAssertion);
77
        $email          = $this->getEmail($translatedAssertion);
78
        $commonName     = $this->getCommonName($translatedAssertion);
79
80
81
        $identity = $this->identityService->findByNameIdAndInstitution($nameId, $institution);
82
83
        if ($identity === null) {
84
            $identity = new Identity();
85
            $identity->id              = Uuid::generate();
86
            $identity->nameId          = $nameId;
87
            $identity->institution     = $institution;
88
            $identity->email           = $email;
89
            $identity->commonName      = $commonName;
90
            $identity->preferredLocale = $this->preferredLocaleProvider->providePreferredLocale();
91
92
            $this->identityService->createIdentity($identity);
93
        } elseif ($identity->email !== $email || $identity->commonName !== $commonName) {
94
            $identity->email = $email;
95
            $identity->commonName = $commonName;
96
97
            $this->identityService->updateIdentity($identity);
98
        }
99
100
        $authenticatedToken = new SamlToken(['ROLE_USER']);
101
102
        $authenticatedToken->setUser($identity);
103
104
        return $authenticatedToken;
105
    }
106
107
    public function supports(TokenInterface $token)
108
    {
109
        return $token instanceof SamlToken;
110
    }
111
112
    /**
113
     * @param AssertionAdapter $translatedAssertion
114
     * @return string
115
     */
116
    private function getCommonName(AssertionAdapter $translatedAssertion)
117
    {
118
        $commonNames = $translatedAssertion->getAttributeValue('commonName');
119
120
        if (empty($commonNames)) {
121
            throw new BadCredentialsException(
122
                'No commonName provided'
123
            );
124
        }
125
126
        if (count($commonNames) > 1) {
127
            $this->logger->warning('Multiple commonNames provided, picking first one', ['commonNamesCount' => count($commonNames)]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
128
        }
129
130
        $commonName = $commonNames[0];
131
132
        if (!is_string($commonName)) {
133
            $this->logger->warning('Received invalid commonName', ['commonNameCount' => count($commonName)]);
134
            throw new BadCredentialsException(
135
                'commonName is not a string'
136
            );
137
        }
138
139
        return $commonName;
140
    }
141
142
    /**
143
     * @param AssertionAdapter $translatedAssertion
144
     * @return string
145
     */
146 View Code Duplication
    private function getEmail(AssertionAdapter $translatedAssertion)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
    {
148
        $emails = $translatedAssertion->getAttributeValue('mail');
149
150
        if (empty($emails)) {
151
            throw new BadCredentialsException(
152
                'No schacHomeOrganization provided'
153
            );
154
        }
155
156
        if (count($emails) > 1) {
157
            $this->logger->warning('Multiple emails provided, picking first one', ['emailsCount' => count($emails)]);
158
        }
159
160
        $email = $emails[0];
161
162
        if (!is_string($email)) {
163
            $this->logger->warning('Received invalid email');
164
            throw new BadCredentialsException(
165
                'email is not a string'
166
            );
167
        }
168
169
        return $email;
170
    }
171
172
    /**
173
     * @param AssertionAdapter $translatedAssertion
174
     * @return string
175
     */
176 View Code Duplication
    private function getInstitution(AssertionAdapter $translatedAssertion)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
    {
178
        $institutions = $translatedAssertion->getAttributeValue('schacHomeOrganization');
179
180
        if (empty($institutions)) {
181
            throw new BadCredentialsException(
182
                'No schacHomeOrganization provided'
183
            );
184
        }
185
186
        if (count($institutions) > 1) {
187
            throw new BadCredentialsException(
188
                'Multiple schacHomeOrganizations provided'
189
            );
190
        }
191
192
        $institution = $institutions[0];
193
194
        if (!is_string($institution)) {
195
            $this->logger->warning('Received invalid schacHomeOrganization', ['schacHomeOrganization' => $institution]);
196
            throw new BadCredentialsException(
197
                'schacHomeOrganization is not a string'
198
            );
199
        }
200
201
        return $institution;
202
    }
203
}
204