Completed
Push — feature/export-raa-token-infor... ( 95b8f8 )
by
unknown
02:43
created

SecondFactorController   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 203
Duplicated Lines 17.24 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 14
dl 35
loc 203
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B searchAction() 0 46 6
A exportAction() 0 11 1
B revokeAction() 35 35 2
B auditLogAction() 0 60 4
A getSecondFactorService() 0 4 1
A getIdentityService() 0 4 1
A getAuditLogService() 0 4 1
A getCurrentUser() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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