Completed
Push — master ( 7e1619...49fbee )
by
unknown
02:24
created

SecondFactorController::searchAction()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 48
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

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