Completed
Pull Request — develop (#188)
by Michiel
04:32 queued 02:14
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 Knp\Component\Pager\Paginator;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
23
use Surfnet\StepupRa\RaBundle\Command\ExportRaSecondFactorsCommand;
24
use Surfnet\StepupRa\RaBundle\Command\RevokeSecondFactorCommand;
25
use Surfnet\StepupRa\RaBundle\Command\SearchRaSecondFactorsCommand;
26
use Surfnet\StepupRa\RaBundle\Command\SearchSecondFactorAuditLogCommand;
27
use Surfnet\StepupRa\RaBundle\Form\Type\RevokeSecondFactorType;
28
use Surfnet\StepupRa\RaBundle\Form\Type\SearchRaSecondFactorsType;
29
use Surfnet\StepupRa\RaBundle\Security\Authorization\Context\InstitutionContext;
30
use Surfnet\StepupRa\RaBundle\Security\Authorization\Voter\AllowedInOtherInstitutionVoter;
31
use Surfnet\StepupRa\RaBundle\Service\InstitutionConfigurationOptionsService;
32
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36
37
/**
38
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) By making the Form Type classes explicit, MD now realizes couping
39
 *                                                 is to high.
40
 */
41
final class SecondFactorController extends Controller
42
{
43
    /**
44
     * @Template
45
     * @param Request $request
46
     * @return array|Response
47
     */
48
    public function searchAction(Request $request)
49
    {
50
        $this->denyAccessUnlessGranted(['ROLE_RA']);
51
52
        $identity = $this->getCurrentUser();
53
        $this->get('logger')->notice('Starting search for second factors');
54
55
        $institutionFilterOptions = $this
56
            ->getInstitutionConfigurationOptionsService()
57
            ->getAvailableInstitutionsFor($identity->institution);
58
59
        $command = new SearchRaSecondFactorsCommand();
60
        $command->actorInstitution = $identity->institution;
61
        $command->pageNumber = (int) $request->get('p', 1);
62
        $command->orderBy = $request->get('orderBy');
63
        $command->orderDirection = $request->get('orderDirection');
64
        
65
        // The options that will populate the institution filter choice list.
66
        $command->institutionFilterOptions = $institutionFilterOptions;
67
68
        $form = $this->createForm(SearchRaSecondFactorsType::class, $command, ['method' => 'get']);
69
        $form->handleRequest($request);
70
71
        $secondFactors = $this->getSecondFactorService()->search($command);
72
        $secondFactorCount = $secondFactors->getTotalItems();
73
74
        if ($form->isSubmitted() && $form->getClickedButton()->getName() == 'export') {
75
            $this->get('logger')->notice('Forwarding to export second factors action');
76
            return $this->forward('SurfnetStepupRaRaBundle:SecondFactor:export', ['command' => $command]);
77
        }
78
79
        /** @var Paginator $paginator */
80
        $paginator = $this->get('knp_paginator');
81
        $pagination = $paginator->paginate(
82
            $secondFactors->getElements(),
83
            $secondFactors->getCurrentPage(),
84
            $secondFactors->getItemsPerPage()
85
        );
86
87
        $revocationForm = $this->createForm(RevokeSecondFactorType::class, new RevokeSecondFactorCommand());
88
89
        $this->get('logger')->notice(sprintf(
90
            'Searching for second factors yielded "%d" results',
91
            $secondFactors->getTotalItems()
92
        ));
93
94
        return [
95
            'form'                  => $form->createView(),
96
            'revocationForm'        => $revocationForm->createView(),
97
            'secondFactors'         => $secondFactors,
98
            'pagination'            => $pagination,
99
            'numberOfSecondFactors' => $secondFactorCount,
100
            'orderBy'               => $command->orderBy,
101
            'orderDirection'        => $command->orderDirection ?: 'asc',
102
            'inverseOrderDirection' => $command->orderDirection === 'asc' ? 'desc' : 'asc',
103
        ];
104
    }
105
106
    public function exportAction(SearchRaSecondFactorsCommand $command)
107
    {
108
        $this->denyAccessUnlessGranted(['ROLE_RA']);
109
110
        $this->get('logger')->notice('Starting export of searched second factors');
111
112
        $identity = $this->getCurrentUser();
113
        $exportCommand = ExportRaSecondFactorsCommand::fromSearchCommand($command, $identity->institution);
114
115
        return $this->getSecondFactorService()->export($exportCommand);
116
    }
117
118
    /**
119
     * @param Request $request
120
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
121
     */
122 View Code Duplication
    public function revokeAction(Request $request)
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...
123
    {
124
        $this->denyAccessUnlessGranted(['ROLE_RA']);
125
126
        $logger = $this->get('logger');
127
128
        $logger->notice('Received request to revoke Second Factor');
129
130
        $command = new RevokeSecondFactorCommand();
131
        $command->currentUserId = $this->getCurrentUser()->id;
132
133
        $form = $this->createForm(RevokeSecondFactorType::class, $command);
134
        $form->handleRequest($request);
135
136
        $logger->info(sprintf(
137
            'Sending middleware request to revoke Second Factor "%s" belonging to "%s" on behalf of "%s"',
138
            $command->secondFactorId,
139
            $command->identityId,
140
            $command->currentUserId
141
        ));
142
143
        $translator = $this->get('translator');
144
        $flashBag = $this->get('session')->getFlashBag();
145
        if ($this->getSecondFactorService()->revoke($command)) {
146
            $logger->notice('Second Factor revocation Succeeded');
147
            $flashBag->add('success', $translator->trans('ra.second_factor.revocation.revoked'));
148
        } else {
149
            $logger->notice('Second Factor revocation Failed');
150
            $flashBag->add('error', $translator->trans('ra.second_factor.revocation.could_not_revoke'));
151
        }
152
153
        $logger->notice('Redirecting back to Second Factor Search Page');
154
155
        return $this->redirectToRoute('ra_second_factors_search');
156
    }
157
158
    /**
159
     * @param Request $request
160
     * @return Response
161
     */
162
    public function auditLogAction(Request $request)
163
    {
164
        $this->denyAccessUnlessGranted(['ROLE_RA']);
165
        $logger = $this->get('logger');
166
167
        $identityId = $request->get('identityId');
168
169
        $logger->notice(sprintf('Requested AuditLog for SecondFactors of identity "%s"', $identityId));
170
171
        $identity = $this->getIdentityService()->findById($identityId);
172
        if (!$identity) {
173
            $logger->notice(sprintf(
174
                'User with Identity "%s" requested non-existent identity "%s"',
175
                $this->getCurrentUser()->id,
176
                $identityId
177
            ));
178
179
            throw new NotFoundHttpException();
180
        }
181
182
        $institutionContext = new InstitutionContext($identity->institution, $this->getCurrentUser()->institution);
183
        if (!$this->isGranted(AllowedInOtherInstitutionVoter::VIEW_AUDITLOG, $institutionContext)) {
184
            $logger->warning(sprintf(
185
                'User with Identity "%s" (%s) requested Identity "%s" (%s) of another institution, denying access',
186
                $this->getCurrentUser()->id,
187
                $this->getCurrentUser()->institution,
188
                $identity->id,
189
                $identity->institution
190
            ));
191
192
            throw $this->createAccessDeniedException();
193
        }
194
195
        $logger->info(sprintf('Retrieving audit log for Identity "%s"', $identity->id));
196
197
        $command                 = new SearchSecondFactorAuditLogCommand();
198
        $command->identityId     = $identity->id;
199
        $command->institution    = $identity->institution;
200
        $command->pageNumber     = (int) $request->get('p', 1);
201
        $command->orderBy        = $request->get('orderBy', 'recordedOn');
202
        $command->orderDirection = $request->get('orderDirection', 'desc');
203
204
        $auditLog = $this->getAuditLogService()->getAuditlog($command);
205
206
        $pagination = $this->get('knp_paginator')->paginate(
207
            $auditLog->getTotalItems() > 0 ? array_fill(0, $auditLog->getTotalItems(), 1) : [],
208
            $auditLog->getCurrentPage(),
209
            $auditLog->getItemsPerPage()
210
        );
211
212
        $logger->notice(sprintf('Audit log yielded "%d" results, rendering page', $auditLog->getTotalItems()));
213
214
        return $this->render(
215
            'SurfnetStepupRaRaBundle:SecondFactor:auditLog.html.twig',
216
            [
217
                'pagination' => $pagination,
218
                'auditLog'   => $auditLog,
219
                'identity'   => $identity,
220
            ]
221
        );
222
    }
223
224
    /**
225
     * @return \Surfnet\StepupRa\RaBundle\Service\RaSecondFactorService
226
     */
227
    private function getSecondFactorService()
228
    {
229
        return $this->get('ra.service.ra_second_factor');
230
    }
231
232
    /**
233
     * @return \Surfnet\StepupRa\RaBundle\Service\IdentityService
234
     */
235
    private function getIdentityService()
236
    {
237
        return $this->get('ra.service.identity');
238
    }
239
240
    /**
241
     * @return \Surfnet\StepupRa\RaBundle\Service\AuditLogService
242
     */
243
    private function getAuditLogService()
244
    {
245
        return $this->get('ra.service.audit_log');
246
    }
247
248
    /**
249
     * @return \Surfnet\StepupMiddlewareClientBundle\Identity\Dto\Identity
250
     */
251
    private function getCurrentUser()
252
    {
253
        return $this->get('security.token_storage')->getToken()->getUser();
254
    }
255
256
    /**
257
     * @return InstitutionConfigurationOptionsService
258
     */
259
    private function getInstitutionConfigurationOptionsService()
260
    {
261
        return $this->get('ra.service.institution_configuration_options');
262
    }
263
}
264