Completed
Push — master ( d21da7...883721 )
by Daan van
03:11
created

SamlProvider::getInstitution()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 14

Duplication

Lines 27
Ratio 100 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 27
loc 27
rs 8.5806
cc 4
eloc 14
nc 4
nop 1
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 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...
117
    {
118
        $institutions = $translatedAssertion->getAttributeValue('schacHomeOrganization');
119
120
        if (empty($institutions)) {
121
            throw new BadCredentialsException(
122
                'No schacHomeOrganization provided'
123
            );
124
        }
125
126
        if (count($institutions) > 1) {
127
            throw new BadCredentialsException(
128
                'Multiple schacHomeOrganizations provided in SAML Assertion'
129
            );
130
        }
131
132
        $institution = $institutions[0];
133
134
        if (!is_string($institution)) {
135
            $this->logger->warning('Received invalid schacHomeOrganization', ['schacHomeOrganizationType' => gettype($institution)]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 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...
136
            throw new BadCredentialsException(
137
                'schacHomeOrganization is not a string'
138
            );
139
        }
140
141
        return $institution;
142
    }
143
144
    /**
145
     * @param AssertionAdapter $translatedAssertion
146
     * @return string
147
     */
148 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...
149
    {
150
        $emails = $translatedAssertion->getAttributeValue('mail');
151
152
        if (empty($emails)) {
153
            throw new BadCredentialsException(
154
                'No schacHomeOrganization provided'
155
            );
156
        }
157
158
        if (count($emails) > 1) {
159
            throw new BadCredentialsException(
160
                'Multiple email values provided in SAML Assertion'
161
            );
162
        }
163
164
        $email = $emails[0];
165
166
        if (!is_string($email)) {
167
            $this->logger->warning('Received invalid email', ['emailType' => gettype($email)]);
168
            throw new BadCredentialsException(
169
                'email is not a string'
170
            );
171
        }
172
173
        return $email;
174
    }
175
176
    /**
177
     * @param AssertionAdapter $translatedAssertion
178
     * @return string
179
     */
180 View Code Duplication
    private function getCommonName(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...
181
    {
182
        $commonNames = $translatedAssertion->getAttributeValue('commonName');
183
184
        if (empty($commonNames)) {
185
            throw new BadCredentialsException(
186
                'No commonName provided'
187
            );
188
        }
189
190
        if (count($commonNames) > 1) {
191
            throw new BadCredentialsException(
192
                'Multiple commonName values provided in SAML Assertion'
193
            );
194
        }
195
196
        $commonName = $commonNames[0];
197
198
        if (!is_string($commonName)) {
199
            $this->logger->warning('Received invalid commonName', ['commonNameType' => gettype($commonName)]);
200
            throw new BadCredentialsException(
201
                'commonName is not a string'
202
            );
203
        }
204
205
        return $commonName;
206
    }
207
}
208