Completed
Push — feature/fine-grained-authoriza... ( d683d5...7f3ff0 )
by Michiel
16s
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\ChangeRaManagementInstitutionCommand;
25
use Surfnet\StepupRa\RaBundle\Command\ChangeRaRoleCommand;
26
use Surfnet\StepupRa\RaBundle\Command\RetractRegistrationAuthorityCommand;
27
use Surfnet\StepupRa\RaBundle\Command\SearchRaCandidatesCommand;
28
use Surfnet\StepupRa\RaBundle\Form\Type\AmendRegistrationAuthorityInformationType;
29
use Surfnet\StepupRa\RaBundle\Form\Type\ChangeRaManagementInstitutionType;
30
use Surfnet\StepupRa\RaBundle\Form\Type\ChangeRaRoleType;
31
use Surfnet\StepupRa\RaBundle\Form\Type\CreateRaType;
32
use Surfnet\StepupRa\RaBundle\Form\Type\RetractRegistrationAuthorityType;
33
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaCandidatesType;
34
use Surfnet\StepupRa\RaBundle\Security\Authentication\Token\SamlToken;
35
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
36
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39
40
/**
41
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
42
 */
43
class RaManagementController extends Controller
44
{
45
    /**
46
     * @param Request $request
47
     * @return \Symfony\Component\HttpFoundation\Response
48
     */
49
    public function manageAction(Request $request)
50
    {
51
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
52
53
        $logger = $this->get('logger');
54
        $institution = $this->getUser()->institution;
55
56
        /**
57
         * @var SamlToken $token
58
         */
59
        $token  = $this->get('security.token_storage')->getToken();
60
        $logger->notice(sprintf('Loading overview of RA(A)s for institution "%s"', $institution));
61
62
        $raaSwitcherOptions = $this
63
            ->getInstitutionConfigurationOptionsService()
64
            ->getSelectRaaOptionsFor($institution);
65
66
        $raaSwitcherCommand = new ChangeRaManagementInstitutionCommand();
67
        $raaSwitcherCommand->raaManagementInstitution = $token->getRaManagementInstitution();
68
        $raaSwitcherCommand->availableInstitutions = $raaSwitcherOptions;
69
70
        $form = $this->createForm(ChangeRaManagementInstitutionType::class, $raaSwitcherCommand);
71
        $form->handleRequest($request);
72
73
        if ($form->isSubmitted()) {
74
            $token->changeRaaInstitutionScope($raaSwitcherCommand->raaManagementInstitution);
75
76
            $flashMessage = $this->get('translator')
77
                ->trans('ra.raa.changed_institution', ['%institution%' => $raaSwitcherCommand->raaManagementInstitution]);
78
            $this->get('session')->getFlashBag()->add('success', $flashMessage);
79
80
            $logger->notice(sprintf(
81
                'RAA "%s" successfully switched to institution "%s"',
82
                $this->getUser()->id,
83
                $raaSwitcherCommand->raaManagementInstitution
84
            ));
85
        }
86
87
        $searchQuery = (new RaListingSearchQuery($this->getUser()->institution, 1))
88
            ->setInstitution($this->getRaManagementInstitution())
89
            ->setOrderBy($request->get('orderBy', 'commonName'))
90
            ->setOrderDirection($request->get('orderDirection', 'asc'));
91
92
        $service = $this->getRaListingService();
93
        $raList = $service->search($searchQuery);
94
95
        $pagination = $this->getPaginator()->paginate(
96
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
97
            $raList->getCurrentPage(),
98
            $raList->getItemsPerPage()
99
        );
100
101
        $logger->notice(sprintf(
102
            'Created overview of "%d" RA(A)s for institution "%s"',
103
            $raList->getTotalItems(),
104
            $institution
105
        ));
106
107
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
108
        $raListings = $raList->getElements();
109
110
        return $this->render(
111
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
112
            [
113
                'raInstitutionSwitcher' => $form->createView(),
114
                'raList' => $raListings,
115
                'pagination' => $pagination,
116
            ]
117
        );
118
    }
119
120
    /**
121
     * @param Request $request
122
     * @return \Symfony\Component\HttpFoundation\Response
123
     */
124
    public function raCandidateSearchAction(Request $request)
125
    {
126
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
127
128
        $logger = $this->get('logger');
129
        $institution = $this->getUser()->institution;
130
131
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
132
133
        $command                   = new SearchRaCandidatesCommand();
134
        $command->actorInstitution = $institution;
135
        $command->institution      = $this->getRaManagementInstitution();
136
        $command->pageNumber       = (int) $request->get('p', 1);
137
        $command->orderBy          = $request->get('orderBy');
138
        $command->orderDirection   = $request->get('orderDirection');
139
140
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
141
        $form->handleRequest($request);
142
143
        $service = $this->getRaCandidateService();
144
        $raCandidateList = $service->search($command);
145
146
        $pagination = $this->getPaginator()->paginate(
147
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
148
            $raCandidateList->getCurrentPage(),
149
            $raCandidateList->getItemsPerPage()
150
        );
151
152
        $logger->notice(sprintf(
153
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
154
            $institution,
155
            $raCandidateList->getTotalItems()
156
        ));
157
158
        return $this->render(
159
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
160
            [
161
                'form'         => $form->createView(),
162
                'raCandidates' => $raCandidateList,
163
                'pagination'   => $pagination
164
            ]
165
        );
166
    }
167
168
    /**
169
     * @param Request $request
170
     * @return \Symfony\Component\HttpFoundation\Response
171
     */
172
    public function createRaAction(Request $request)
173
    {
174
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
175
        $logger = $this->get('logger');
176
177
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
178
        $identityId = $request->get('identityId');
179
        $raCandidate = $this->getRaCandidateService()->getRaCandidate($identityId, $this->getRaManagementInstitution());
180
181
        if (!$raCandidate) {
182
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
183
            throw new NotFoundHttpException();
184
        }
185
186
        $command                   = new AccreditCandidateCommand();
187
        $command->identityId       = $identityId;
188
        $command->institution      = $this->getRaManagementInstitution();
189
        $command->raInstitution    = $this->getUser()->institution;
190
191
        // todo: make choicelist configurable
192
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
193 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...
194
            $logger->debug('Accreditation form submitted, start processing command');
195
196
            $success = $this->getRaCandidateService()->accreditCandidate($command);
197
198
            if ($success) {
199
                $this->addFlash(
200
                    'success',
201
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
202
                );
203
204
                $logger->debug('Identity Accredited, redirecting to candidate overview');
205
                return $this->redirectToRoute('ra_management_ra_candidate_search');
206
            }
207
208
            $logger->debug('Identity Accreditation failed, adding error to form');
209
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
210
        }
211
212
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
213
            'raCandidate' => $raCandidate,
214
            'form'        => $form->createView()
215
        ]);
216
    }
217
218
    /**
219
     * @param Request $request
220
     * @param         $identityId
221
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
222
     */
223
    public function amendRaInformationAction(Request $request, $identityId)
224
    {
225
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
226
227
        $logger = $this->get('logger');
228
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
229
230
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
231
232
        if (!$raListing) {
233
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
234
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
235
        }
236
237
        $command = new AmendRegistrationAuthorityInformationCommand();
238
        $command->identityId = $raListing->identityId;
239
        $command->location = $this->getUser()->institution;
240
        $command->contactInformation = $raListing->contactInformation;
241
        // todo: institution
242
        $command->institution = $raListing->institution;
0 ignored issues
show
Bug introduced by
The property institution does not seem to exist in Surfnet\StepupRa\RaBundl...orityInformationCommand.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
243
244
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
245
        if ($form->isSubmitted() && $form->isValid()) {
246
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
247
248
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
249
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
250
251
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
252
                return $this->redirectToRoute('ra_management_manage');
253
            }
254
255
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
256
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
257
        }
258
259
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
260
            'raListing' => $raListing,
261
            'form' => $form->createView(),
262
        ]);
263
    }
264
265
    /**
266
     * @param Request $request
267
     * @param         $identityId
268
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
269
     */
270
    public function changeRaRoleAction(Request $request, $identityId)
271
    {
272
        // todo: remove?
273
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
274
        $logger = $this->get('logger');
275
276
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
277
278
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
279
        if (!$raListing) {
280
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
281
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
282
        }
283
284
        $command              = new ChangeRaRoleCommand();
285
        $command->identityId  = $raListing->identityId;
286
        $command->institution = $this->getUser()->institution;
287
        $command->role        = $raListing->role;
288
289
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
290
        if ($form->isSubmitted() && $form->isValid()) {
291
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
292
293
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
294
                $logger->notice('Role successfully changed');
295
296
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
297
                return $this->redirectToRoute('ra_management_manage');
298
            }
299
300
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
301
            $this->addFlash('error', 'ra.management.change_ra_role.middleware_command_failed');
302
        }
303
304
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
305
            'raListing' => $raListing,
306
            'form'      => $form->createView()
307
        ]);
308
    }
309
310
    /**
311
     * @param Request $request
312
     * @param         $identityId
313
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
314
     */
315
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
316
    {
317
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
318
        $logger = $this->get('logger');
319
320
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
321
322
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
323
        if (!$raListing) {
324
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
325
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
326
        }
327
328
        $command = new RetractRegistrationAuthorityCommand();
329
        $command->identityId = $identityId;
330
        $command->institution = $this->getUser()->institution;
331
332
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
333
        if ($form->isSubmitted() && $form->isValid()) {
334
            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...
335
                $logger->notice('Retraction of registration authority cancelled');
336
                return $this->redirectToRoute('ra_management_manage');
337
            }
338
339
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
340
341
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
342
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
343
344
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
345
                return $this->redirectToRoute('ra_management_manage');
346
            }
347
348
            $logger->notice(sprintf(
349
                'Could not retract Registration Authority credentials for identity "%s"',
350
                $identityId
351
            ));
352
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
353
        }
354
355
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
356
            'raListing' => $raListing,
357
            'form'      => $form->createView()
358
        ]);
359
    }
360
361
    /**
362
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
363
     */
364
    private function getRaListingService()
365
    {
366
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
367
    }
368
369
    /**
370
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
371
     */
372
    private function getRaCandidateService()
373
    {
374
        return $this->get('ra.service.ra_candidate');
375
    }
376
377
    /**
378
     * @return InstitutionConfigurationOptionsService
379
     */
380
    private function getInstitutionConfigurationOptionsService()
381
    {
382
        return $this->get('ra.service.institution_configuration_options');
383
    }
384
385
    /**
386
     * @return \Knp\Component\Pager\Paginator
387
     */
388
    private function getPaginator()
389
    {
390
        return $this->get('knp_paginator');
391
    }
392
393
    /**
394
     * @return string
395
     */
396
    private function getRaManagementInstitution()
397
    {
398
        /**
399
         * @var SamlToken $token
400
         */
401
        $token  = $this->get('security.token_storage')->getToken();
402
        return $token->getRaManagementInstitution();
403
    }
404
}
405