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