Completed
Push — develop ( 784583...9a84aa )
by Michiel
02:05 queued 10s
created

RaManagementController::changeRaRoleAction()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
c 0
b 0
f 0
rs 8.9848
cc 5
nc 4
nop 2
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->getUser()->institution, 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 = $institution;
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->getRaManagementInstitution());
147
148
        if (!$raCandidate) {
149
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
150
            throw new NotFoundHttpException();
151
        }
152
153
        /**
154
         * @var SamlToken $token
155
         */
156
        $token  = $this->get('security.token_storage')->getToken();
157
        $raaSwitcherOptions = $this
158
            ->getInstitutionConfigurationOptionsService()
159
            ->getAvailableSeleactRaaInstitutionsFor($token->getIdentityInstitution());
160
161
        $command                   = new AccreditCandidateCommand();
162
        $command->identityId       = $identityId;
163
        $command->institution      = $this->getRaManagementInstitution();
164
        $command->raInstitution    = $this->getUser()->institution;
165
        $command->availableInstitutions = $raaSwitcherOptions;
166
167
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
168 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...
169
            $logger->debug('Accreditation form submitted, start processing command');
170
171
            $success = $this->getRaCandidateService()->accreditCandidate($command);
172
173
            if ($success) {
174
                $this->addFlash(
175
                    'success',
176
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
177
                );
178
179
                $logger->debug('Identity Accredited, redirecting to candidate overview');
180
                return $this->redirectToRoute('ra_management_ra_candidate_search');
181
            }
182
183
            $logger->debug('Identity Accreditation failed, adding error to form');
184
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
185
        }
186
187
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
188
            'raCandidate' => $raCandidate,
189
            'form'        => $form->createView()
190
        ]);
191
    }
192
193
    /**
194
     * @param Request $request
195
     * @param         $identityId
196
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
197
     */
198
    public function amendRaInformationAction(Request $request, $identityId)
199
    {
200
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
201
202
        $logger = $this->get('logger');
203
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
204
205
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
206
207
        if (!$raListing) {
208
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
209
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
210
        }
211
212
        $command = new AmendRegistrationAuthorityInformationCommand();
213
        $command->identityId = $raListing->identityId;
214
        $command->location = $this->getUser()->institution;
215
        $command->contactInformation = $raListing->contactInformation;
216
        $command->institution = $this->getRaManagementInstitution();
217
218
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
219
        if ($form->isSubmitted() && $form->isValid()) {
220
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
221
222
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
223
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
224
225
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
226
                return $this->redirectToRoute('ra_management_manage');
227
            }
228
229
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
230
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
231
        }
232
233
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
234
            'raListing' => $raListing,
235
            'form' => $form->createView(),
236
        ]);
237
    }
238
239
    /**
240
     * @param Request $request
241
     * @param         $identityId
242
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
243
     */
244
    public function changeRaRoleAction(Request $request, $identityId)
245
    {
246
        // todo: remove?
247
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
248
        $logger = $this->get('logger');
249
250
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
251
252
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
253
        if (!$raListing) {
254
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
255
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
256
        }
257
258
        $command              = new ChangeRaRoleCommand();
259
        $command->identityId  = $raListing->identityId;
260
        $command->institution = $this->getUser()->institution;
261
        $command->role        = $raListing->role;
262
263
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
264
        if ($form->isSubmitted() && $form->isValid()) {
265
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
266
267
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
268
                $logger->notice('Role successfully changed');
269
270
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
271
                return $this->redirectToRoute('ra_management_manage');
272
            }
273
274
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
275
            $this->addFlash('error', 'ra.management.change_ra_role.middleware_command_failed');
276
        }
277
278
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
279
            'raListing' => $raListing,
280
            'form'      => $form->createView()
281
        ]);
282
    }
283
284
    /**
285
     * @param Request $request
286
     * @param         $identityId
287
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
288
     */
289
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
290
    {
291
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
292
        $logger = $this->get('logger');
293
294
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
295
296
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
297
        if (!$raListing) {
298
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
299
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
300
        }
301
302
        $command = new RetractRegistrationAuthorityCommand();
303
        $command->identityId = $identityId;
304
        $command->institution = $this->getUser()->institution;
305
306
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
307
        if ($form->isSubmitted() && $form->isValid()) {
308
            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...
309
                $logger->notice('Retraction of registration authority cancelled');
310
                return $this->redirectToRoute('ra_management_manage');
311
            }
312
313
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
314
315
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
316
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
317
318
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
319
                return $this->redirectToRoute('ra_management_manage');
320
            }
321
322
            $logger->notice(sprintf(
323
                'Could not retract Registration Authority credentials for identity "%s"',
324
                $identityId
325
            ));
326
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
327
        }
328
329
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
330
            'raListing' => $raListing,
331
            'form'      => $form->createView()
332
        ]);
333
    }
334
335
    /**
336
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
337
     */
338
    private function getRaListingService()
339
    {
340
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
341
    }
342
343
    /**
344
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
345
     */
346
    private function getRaCandidateService()
347
    {
348
        return $this->get('ra.service.ra_candidate');
349
    }
350
351
    /**
352
     * @return InstitutionConfigurationOptionsService
353
     */
354
    private function getInstitutionConfigurationOptionsService()
355
    {
356
        return $this->get('ra.service.institution_configuration_options');
357
    }
358
359
    /**
360
     * @return \Knp\Component\Pager\Paginator
361
     */
362
    private function getPaginator()
363
    {
364
        return $this->get('knp_paginator');
365
    }
366
367
    /**
368
     * @return string
369
     */
370
    private function getRaManagementInstitution()
371
    {
372
        return $this->getUser()->institution;
373
    }
374
}
375