Completed
Push — feature/fine-grained-authoriza... ( 47d334...f68bce )
by Michiel
16s
created

RaManagementController::getIdentityInstitution()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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\Controller;
20
21
use Surfnet\StepupMiddlewareClient\Identity\Dto\RaListingSearchQuery;
22
use Surfnet\StepupRa\RaBundle\Command\AccreditCandidateCommand;
23
use Surfnet\StepupRa\RaBundle\Command\AmendRegistrationAuthorityInformationCommand;
24
use Surfnet\StepupRa\RaBundle\Command\ChangeRaRoleCommand;
25
use Surfnet\StepupRa\RaBundle\Command\RetractRegistrationAuthorityCommand;
26
use Surfnet\StepupRa\RaBundle\Command\SearchRaCandidatesCommand;
27
use Surfnet\StepupRa\RaBundle\Form\Type\AmendRegistrationAuthorityInformationType;
28
use Surfnet\StepupRa\RaBundle\Form\Type\ChangeRaRoleType;
29
use Surfnet\StepupRa\RaBundle\Form\Type\CreateRaType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\RetractRegistrationAuthorityType;
31
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaCandidatesType;
32
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
33
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
34
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
38
/**
39
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
40
 */
41
class RaManagementController extends Controller
42
{
43
    /**
44
     * @param Request $request
45
     * @return \Symfony\Component\HttpFoundation\Response
46
     */
47
    public function manageAction(Request $request)
48
    {
49
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
50
51
        $logger = $this->get('logger');
52
        $institution = $this->getUser()->institution;
53
        $logger->notice(sprintf('Loading overview of RA(A)s for institution "%s"', $institution));
54
55
        $searchQuery = (new RaListingSearchQuery($this->getIdentityInstitution(), 1))
56
            ->setInstitution($this->getRaManagementInstitution())
57
            ->setOrderBy($request->get('orderBy', 'commonName'))
58
            ->setOrderDirection($request->get('orderDirection', 'asc'));
59
60
        $service = $this->getRaListingService();
61
        $raList = $service->search($searchQuery);
62
63
        $pagination = $this->getPaginator()->paginate(
64
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
65
            $raList->getCurrentPage(),
66
            $raList->getItemsPerPage()
67
        );
68
69
        $logger->notice(sprintf(
70
            'Created overview of "%d" RA(A)s for institution "%s"',
71
            $raList->getTotalItems(),
72
            $institution
73
        ));
74
75
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
76
        $raListings = $raList->getElements();
77
78
        return $this->render(
79
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
80
            [
81
                'raList'     => $raListings,
82
                'pagination' => $pagination
83
            ]
84
        );
85
    }
86
87
    /**
88
     * @param Request $request
89
     * @return \Symfony\Component\HttpFoundation\Response
90
     */
91
    public function raCandidateSearchAction(Request $request)
92
    {
93
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
94
95
        $logger = $this->get('logger');
96
        $institution = $this->getUser()->institution;
97
98
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
99
100
        $command                   = new SearchRaCandidatesCommand();
101
        $command->actorInstitution = $this->getIdentityInstitution();
102
        $command->institution      = $this->getRaManagementInstitution();
103
        $command->pageNumber       = (int) $request->get('p', 1);
104
        $command->orderBy          = $request->get('orderBy');
105
        $command->orderDirection   = $request->get('orderDirection');
106
107
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
108
        $form->handleRequest($request);
109
110
        $service = $this->getRaCandidateService();
111
        $raCandidateList = $service->search($command);
112
113
        $pagination = $this->getPaginator()->paginate(
114
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
115
            $raCandidateList->getCurrentPage(),
116
            $raCandidateList->getItemsPerPage()
117
        );
118
119
        $logger->notice(sprintf(
120
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
121
            $institution,
122
            $raCandidateList->getTotalItems()
123
        ));
124
125
        return $this->render(
126
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
127
            [
128
                'form'         => $form->createView(),
129
                'raCandidates' => $raCandidateList,
130
                'pagination'   => $pagination
131
            ]
132
        );
133
    }
134
135
    /**
136
     * @param Request $request
137
     * @return \Symfony\Component\HttpFoundation\Response
138
     */
139
    public function createRaAction(Request $request)
140
    {
141
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
142
        $logger = $this->get('logger');
143
144
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
145
        $identityId = $request->get('identityId');
146
        $raCandidate = $this->getRaCandidateService()->getRaCandidate($identityId, $this->getIdentityInstitution());
147
148
        if (!$raCandidate) {
149
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
150
            throw new NotFoundHttpException();
151
        }
152
153
        $raaSwitcherOptions = $this
154
            ->getInstitutionConfigurationOptionsService()
155
            ->getAvailableSeleactRaaInstitutionsFor($this->getIdentityInstitution());
156
157
        $command                   = new AccreditCandidateCommand();
158
        $command->identityId       = $identityId;
159
        $command->institution      = $this->getIdentityInstitution();
160
        $command->raInstitution    = $this->getRaManagementInstitution();
161
        $command->availableInstitutions = $raaSwitcherOptions;
162
163
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
164 View Code Duplication
        if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
165
            $logger->debug('Accreditation form submitted, start processing command');
166
167
            $success = $this->getRaCandidateService()->accreditCandidate($command);
168
169
            if ($success) {
170
                $this->addFlash(
171
                    'success',
172
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
173
                );
174
175
                $logger->debug('Identity Accredited, redirecting to candidate overview');
176
                return $this->redirectToRoute('ra_management_ra_candidate_search');
177
            }
178
179
            $logger->debug('Identity Accreditation failed, adding error to form');
180
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
181
        }
182
183
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
184
            'raCandidate' => $raCandidate,
185
            'form'        => $form->createView()
186
        ]);
187
    }
188
189
    /**
190
     * @param Request $request
191
     * @param string  $identityId
192
     * @param string  $institution
193
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
194
     */
195
    public function amendRaInformationAction(Request $request, $identityId, $institution)
196
    {
197
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
198
199
        $logger = $this->get('logger');
200
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
201
202
        $raListing = $this->getRaListingService()->get($identityId, $institution);
203
204
        if (!$raListing) {
205
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
206
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
207
        }
208
209
        $command = new AmendRegistrationAuthorityInformationCommand();
210
        $command->identityId = $raListing->identityId;
211
        $command->location = $this->getUser()->institution;
212
        $command->contactInformation = $raListing->contactInformation;
213
        $command->institution = $institution;
214
215
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
216
        if ($form->isSubmitted() && $form->isValid()) {
217
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
218
219
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
220
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
221
222
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
223
                return $this->redirectToRoute('ra_management_manage');
224
            }
225
226
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
227
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
228
        }
229
230
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
231
            'raListing' => $raListing,
232
            'form' => $form->createView(),
233
        ]);
234
    }
235
236
    /**
237
     * @param Request $request
238
     * @param         $identityId
239
     * @param         $institution
240
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
241
     */
242
    public function changeRaRoleAction(Request $request, $identityId, $institution)
243
    {
244
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
245
        $logger = $this->get('logger');
246
247
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
248
249
        $raListing = $this->getRaListingService()->get($identityId, $institution);
250
        if (!$raListing) {
251
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
252
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
253
        }
254
255
        $command              = new ChangeRaRoleCommand();
256
        $command->identityId  = $raListing->identityId;
257
        $command->institution = $this->getRaManagementInstitution();
258
        $command->role        = $institution;
259
260
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
261
        if ($form->isSubmitted() && $form->isValid()) {
262
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
263
264
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
265
                $logger->notice('Role successfully changed');
266
267
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
268
                return $this->redirectToRoute('ra_management_manage');
269
            }
270
271
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
272
            $this->addFlash('error', 'ra.management.change_ra_role.middleware_command_failed');
273
        }
274
275
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
276
            'raListing' => $raListing,
277
            'form'      => $form->createView()
278
        ]);
279
    }
280
281
    /**
282
     * @param Request $request
283
     * @param         $identityId
284
     * @param         $institution
285
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
286
     */
287
    public function retractRegistrationAuthorityAction(Request $request, $identityId, $institution)
288
    {
289
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
290
        $logger = $this->get('logger');
291
292
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
293
294
        $raListing = $this->getRaListingService()->get($identityId, $institution);
295
        if (!$raListing) {
296
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
297
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
298
        }
299
300
        $command = new RetractRegistrationAuthorityCommand();
301
        $command->identityId = $identityId;
302
        $command->institution = $institution;
303
304
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
305
        if ($form->isSubmitted() && $form->isValid()) {
306
            if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

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...
307
                $logger->notice('Retraction of registration authority cancelled');
308
                return $this->redirectToRoute('ra_management_manage');
309
            }
310
311
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
312
313
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
314
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
315
316
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
317
                return $this->redirectToRoute('ra_management_manage');
318
            }
319
320
            $logger->notice(sprintf(
321
                'Could not retract Registration Authority credentials for identity "%s"',
322
                $identityId
323
            ));
324
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
325
        }
326
327
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
328
            'raListing' => $raListing,
329
            'form'      => $form->createView()
330
        ]);
331
    }
332
333
    /**
334
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
335
     */
336
    private function getRaListingService()
337
    {
338
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
339
    }
340
341
    /**
342
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
343
     */
344
    private function getRaCandidateService()
345
    {
346
        return $this->get('ra.service.ra_candidate');
347
    }
348
349
    /**
350
     * @return InstitutionConfigurationOptionsService
351
     */
352
    private function getInstitutionConfigurationOptionsService()
353
    {
354
        return $this->get('ra.service.institution_configuration_options');
355
    }
356
357
    /**
358
     * @return \Knp\Component\Pager\Paginator
359
     */
360
    private function getPaginator()
361
    {
362
        return $this->get('knp_paginator');
363
    }
364
365
    /**
366
     * @return string
367
     */
368
    private function getRaManagementInstitution()
369
    {
370
        return $this->getUser()->institution;
371
    }
372
373
    /**
374
     * @return string
375
     */
376
    private function getIdentityInstitution()
377
    {
378
        /**
379
         * @var SamlToken $token
380
         */
381
        $token  = $this->get('security.token_storage')->getToken();
382
        return $token->getIdentityOriginalInstitution();
383
    }
384
}
385