Completed
Push — feature/fga-raa-management ( ba16ff )
by
unknown
11:03
created

getInstitutionConfigurationOptionsService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
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\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
            ->setOrderBy($request->get('orderBy', 'commonName'))
89
            ->setOrderDirection($request->get('orderDirection', 'asc'));
90
91
        $service = $this->getRaListingService();
92
        $raList = $service->search($searchQuery);
93
94
        $pagination = $this->getPaginator()->paginate(
95
            $raList->getTotalItems() > 0 ? array_fill(0, $raList->getTotalItems(), 1) : [],
96
            $raList->getCurrentPage(),
97
            $raList->getItemsPerPage()
98
        );
99
100
        $logger->notice(sprintf(
101
            'Created overview of "%d" RA(A)s for institution "%s"',
102
            $raList->getTotalItems(),
103
            $institution
104
        ));
105
106
        /** @var \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\RaListing[] $raListings */
107
        $raListings = $raList->getElements();
108
109
        return $this->render(
110
            'SurfnetStepupRaRaBundle:RaManagement:manage.html.twig',
111
            [
112
                'raInstitutionSwitcher' => $form->createView(),
113
                'raList' => $raListings,
114
                'pagination' => $pagination,
115
            ]
116
        );
117
    }
118
119
    /**
120
     * @param Request $request
121
     * @return \Symfony\Component\HttpFoundation\Response
122
     */
123
    public function raCandidateSearchAction(Request $request)
124
    {
125
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
126
127
        $logger = $this->get('logger');
128
        $institution = $this->getUser()->institution;
129
130
        $logger->notice(sprintf('Searching for RaCandidates within institution "%s"', $institution));
131
132
        $command                   = new SearchRaCandidatesCommand();
133
        $command->actorInstitution = $institution;
134
        //$command->institution      = $institution;
135
        $command->pageNumber       = (int) $request->get('p', 1);
136
        $command->orderBy          = $request->get('orderBy');
137
        $command->orderDirection   = $request->get('orderDirection');
138
139
        $form = $this->createForm(SearchRaCandidatesType::class, $command, ['method' => 'get']);
140
        $form->handleRequest($request);
141
142
        $service = $this->getRaCandidateService();
143
        $raCandidateList = $service->search($command);
144
145
        $pagination = $this->getPaginator()->paginate(
146
            $raCandidateList->getTotalItems() > 0 ? array_fill(4, $raCandidateList->getTotalItems(), 1) : [],
147
            $raCandidateList->getCurrentPage(),
148
            $raCandidateList->getItemsPerPage()
149
        );
150
151
        $logger->notice(sprintf(
152
            'Searching for RaCandidates within institution "%s" yielded "%s" results',
153
            $institution,
154
            $raCandidateList->getTotalItems()
155
        ));
156
157
        return $this->render(
158
            'SurfnetStepupRaRaBundle:RaManagement:raCandidateOverview.html.twig',
159
            [
160
                'form'         => $form->createView(),
161
                'raCandidates' => $raCandidateList,
162
                'pagination'   => $pagination
163
            ]
164
        );
165
    }
166
167
    /**
168
     * @param Request $request
169
     * @return \Symfony\Component\HttpFoundation\Response
170
     */
171
    public function createRaAction(Request $request)
172
    {
173
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
174
        $logger = $this->get('logger');
175
176
        $logger->notice('Page for Accreditation of Identity to Ra or Raa requested');
177
        $identityId = $request->get('identityId');
178
        $raCandidate = $this->getRaCandidateService()->getRaCandidate($identityId, $this->getUser()->institution);
179
180
        if (!$raCandidate) {
181
            $logger->warning(sprintf('RaCandidate based on identity "%s" not found', $identityId));
182
            throw new NotFoundHttpException();
183
        }
184
185
        $command                   = new AccreditCandidateCommand();
186
        $command->identityId       = $identityId;
187
        $command->institution      = $this->getUser()->institution;
188
        $command->raInstitution    = $raCandidate->institution;
189
190
        // todo: make choicelist configurable
191
        $form = $this->createForm(CreateRaType::class, $command)->handleRequest($request);
192 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...
193
            $logger->debug('Accreditation form submitted, start processing command');
194
195
            $success = $this->getRaCandidateService()->accreditCandidate($command);
196
197
            if ($success) {
198
                $this->addFlash(
199
                    'success',
200
                    $this->get('translator')->trans('ra.management.create_ra.identity_accredited')
201
                );
202
203
                $logger->debug('Identity Accredited, redirecting to candidate overview');
204
                return $this->redirectToRoute('ra_management_ra_candidate_search');
205
            }
206
207
            $logger->debug('Identity Accreditation failed, adding error to form');
208
            $this->addFlash('error', 'ra.management.create_ra.error.middleware_command_failed');
209
        }
210
211
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:createRa.html.twig', [
212
            'raCandidate' => $raCandidate,
213
            'form'        => $form->createView()
214
        ]);
215
    }
216
217
    /**
218
     * @param Request $request
219
     * @param         $identityId
220
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
221
     */
222
    public function amendRaInformationAction(Request $request, $identityId)
223
    {
224
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
225
226
        $logger = $this->get('logger');
227
        $logger->notice(sprintf("Loading information amendment form for RA(A) '%s'", $identityId));
228
229
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
230
231
        if (!$raListing) {
232
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
233
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
234
        }
235
236
        $command = new AmendRegistrationAuthorityInformationCommand();
237
        $command->identityId = $raListing->identityId;
238
        $command->location = $this->getUser()->institution;
239
        $command->contactInformation = $raListing->contactInformation;
240
        // todo: institution
241
        $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...
242
243
        $form = $this->createForm(AmendRegistrationAuthorityInformationType::class, $command)->handleRequest($request);
244
        if ($form->isSubmitted() && $form->isValid()) {
245
            $logger->notice(sprintf("RA(A) '%s' information amendment form submitted, processing", $identityId));
246
247
            if ($this->get('ra.service.ra')->amendRegistrationAuthorityInformation($command)) {
248
                $this->addFlash('success', $this->get('translator')->trans('ra.management.amend_ra_info.info_amended'));
249
250
                $logger->notice(sprintf("RA(A) '%s' information successfully amended", $identityId));
251
                return $this->redirectToRoute('ra_management_manage');
252
            }
253
254
            $logger->notice(sprintf("Information of RA(A) '%s' failed to be amended, informing user", $identityId));
255
            $this->addFlash('error', 'ra.management.amend_ra_info.error.middleware_command_failed');
256
        }
257
258
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:amendRaInformation.html.twig', [
259
            'raListing' => $raListing,
260
            'form' => $form->createView(),
261
        ]);
262
    }
263
264
    /**
265
     * @param Request $request
266
     * @param         $identityId
267
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
268
     */
269
    public function changeRaRoleAction(Request $request, $identityId)
270
    {
271
        // todo: remove?
272
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
273
        $logger = $this->get('logger');
274
275
        $logger->notice(sprintf("Loading change Ra Role form for RA(A) '%s'", $identityId));
276
277
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
278
        if (!$raListing) {
279
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
280
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
281
        }
282
283
        $command              = new ChangeRaRoleCommand();
284
        $command->identityId  = $raListing->identityId;
285
        $command->institution = $this->getUser()->institution;
286
        $command->role        = $raListing->role;
287
288
        $form = $this->createForm(ChangeRaRoleType::class, $command)->handleRequest($request);
289
        if ($form->isSubmitted() && $form->isValid()) {
290
            $logger->notice(sprintf('RA(A) "%s" Change Role form submitted, processing', $identityId));
291
292
            if ($this->get('ra.service.ra')->changeRegistrationAuthorityRole($command)) {
293
                $logger->notice('Role successfully changed');
294
295
                $this->addFlash('success', $this->get('translator')->trans('ra.management.change_ra_role_changed'));
296
                return $this->redirectToRoute('ra_management_manage');
297
            }
298
299
            $logger->notice(sprintf('Role of RA(A) "%s" could not be changed, informing user', $identityId));
300
            $this->addFlash('error', 'ra.management.change_ra_role.middleware_command_failed');
301
        }
302
303
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:changeRaRole.html.twig', [
304
            'raListing' => $raListing,
305
            'form'      => $form->createView()
306
        ]);
307
    }
308
309
    /**
310
     * @param Request $request
311
     * @param         $identityId
312
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
313
     */
314
    public function retractRegistrationAuthorityAction(Request $request, $identityId)
315
    {
316
        $this->denyAccessUnlessGranted(['ROLE_RAA', 'ROLE_SRAA']);
317
        $logger = $this->get('logger');
318
319
        $logger->notice(sprintf("Loading retract registration authority form for RA(A) '%s'", $identityId));
320
321
        $raListing = $this->getRaListingService()->get($identityId, $this->getUser()->institution);
322
        if (!$raListing) {
323
            $logger->warning(sprintf("RA listing for identity ID '%s' not found", $identityId));
324
            throw new NotFoundHttpException(sprintf("RA listing for identity ID '%s' not found", $identityId));
325
        }
326
327
        $command = new RetractRegistrationAuthorityCommand();
328
        $command->identityId = $identityId;
329
        $command->institution = $this->getUser()->institution;
330
331
        $form = $this->createForm(RetractRegistrationAuthorityType::class, $command)->handleRequest($request);
332
        if ($form->isSubmitted() && $form->isValid()) {
333
            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...
334
                $logger->notice('Retraction of registration authority cancelled');
335
                return $this->redirectToRoute('ra_management_manage');
336
            }
337
338
            $logger->notice(sprintf('Confirmed retraction of RA credentials for identity "%s"', $identityId));
339
340
            if ($this->get('ra.service.ra')->retractRegistrationAuthority($command)) {
341
                $logger->notice(sprintf('Registration authority for identity "%s" retracted', $identityId));
342
343
                $this->addFlash('success', $this->get('translator')->trans('ra.management.retract_ra.success'));
344
                return $this->redirectToRoute('ra_management_manage');
345
            }
346
347
            $logger->notice(sprintf(
348
                'Could not retract Registration Authority credentials for identity "%s"',
349
                $identityId
350
            ));
351
            $this->addFlash('error', 'ra.management.retract_ra.middleware_command_failed');
352
        }
353
354
        return $this->render('SurfnetStepupRaRaBundle:RaManagement:confirmRetractRa.html.twig', [
355
            'raListing' => $raListing,
356
            'form'      => $form->createView()
357
        ]);
358
    }
359
360
    /**
361
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Service\RaListingService
362
     */
363
    private function getRaListingService()
364
    {
365
        return $this->get('surfnet_stepup_middleware_client.identity.service.ra_listing');
366
    }
367
368
    /**
369
     * @return \Surfnet\StepupRa\RaBundle\Service\RaCandidateService
370
     */
371
    private function getRaCandidateService()
372
    {
373
        return $this->get('ra.service.ra_candidate');
374
    }
375
376
    /**
377
     * @return InstitutionConfigurationOptionsService
378
     */
379
    private function getInstitutionConfigurationOptionsService()
380
    {
381
        return $this->get('ra.service.institution_configuration_options');
382
    }
383
384
    /**
385
     * @return \Knp\Component\Pager\Paginator
386
     */
387
    private function getPaginator()
388
    {
389
        return $this->get('knp_paginator');
390
    }
391
}
392