NfgController::checkOtherPerson()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 4
nop 3
dl 0
loc 21
ccs 0
cts 20
cp 0
crap 20
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace PROCERGS\LoginCidadao\CoreBundle\Controller;
4
5
use LoginCidadao\CoreBundle\Model\PersonInterface;
6
use PROCERGS\LoginCidadao\CoreBundle\Entity\PersonMeuRS;
7
use PROCERGS\LoginCidadao\CoreBundle\Helper\NfgWsHelper;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Routing\Annotation\Route;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\RedirectResponse;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14
use PROCERGS\LoginCidadao\CoreBundle\Exception\NfgException;
15
use FOS\UserBundle\Event\FormEvent;
16
use FOS\UserBundle\FOSUserEvents;
17
use FOS\UserBundle\Event\FilterUserResponseEvent;
18
use FOS\UserBundle\Event\GetResponseUserEvent;
19
use PROCERGS\LoginCidadao\NfgBundle\Entity\NfgProfile;
20
use PROCERGS\LoginCidadao\CoreBundle\Helper\MeuRSHelper;
21
22
/**
23
 * @Route("/nfg-old")
24
 */
25
class NfgController extends Controller
26
{
27
28
    /**
29
     * @Route("/create", name="old_nfg_create")
30
     */
31
    public function createAction()
32
    {
33
        return $this->toNfg('nfg_url_auth', 'nfg_createback');
34
    }
35
36
    protected function toNfg($url, $callback, $useSession = false)
37
    {
38
        $nfg = $this->get('procergs_logincidadao.nfgws');
39
        $parm['accessid'] = $nfg->obterAccessID();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$parm was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parm = array(); before regardless.
Loading history...
40
        if ($useSession) {
41
            $this->getRequest()
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on PROCERGS\LoginCidadao\Co...ontroller\NfgController. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

41
            $this->/** @scrutinizer ignore-call */ 
42
                   getRequest()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
42
                ->getSession()
43
                ->set('ticketacessologin', $parm['accessid']);
44
        }
45
        $parm['urlretorno'] = $this->generateUrl(
46
            $callback,
47
            array(),
48
            UrlGeneratorInterface::ABSOLUTE_URL
49
        );
50
        // $url = $this->container->getParameter('nfg_url_auth') . '?' . http_build_query($parm);
51
        $url = $this->container->getParameter($url).'?accessid='.$parm['accessid'].'&urlretorno='.$parm['urlretorno'];
52
53
        //IE referer stuff, dont kill me
54
        return new Response(
55
            '<html><head><meta name="referrer" content="always"/></head><body><script type="text/javascript">document.location= "'.$url.'";</script></body></html>'
56
        );
57
    }
58
59
    /**
60
     * @Route("/create/back", name="old_nfg_createback")
61
     */
62
    public function createBackAction(Request $request)
63
    {
64
        /** @var MeuRSHelper $meursHelper */
65
        $meursHelper = $this->get('meurs.helper');
66
67
        $result1 = $this->checkAccessToken();
68
        $em = $this->getDoctrine()->getManager();
69
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
70
        if ($personRepo->findOneBy(
71
            array(
72
                'cpf' => $result1['CodCpf'],
73
            )
74
        )
75
        ) {
76
            throw new NfgException('nfg.cpf.already.used');
77
        }
78
        if ($personRepo->findOneBy(
79
            array(
80
                'email' => $result1['EmailPrinc'],
81
            )
82
        )
83
        ) {
84
            throw new NfgException('nfg.email.already.used');
85
        }
86
87
        $formFactory = $this->container->get('fos_user.registration.form.factory');
88
        $userManager = $this->container->get('fos_user.user_manager');
89
        $dispatcher = $this->container->get('event_dispatcher');
90
91
        $nfgProfile = $em->getRepository('PROCERGSNfgBundle:NfgProfile')->findOneBy(
92
            array(
93
                'cpf' => $result1['CodCpf'],
94
            )
95
        );
96
        if (!$nfgProfile) {
97
            $nfgProfile = new NfgProfile();
98
            $nfgProfile->setCpf($result1['CodCpf']);
99
        }
100
        $nfgProfile->setName($result1['NomeConsumidor']);
101
        $nfgProfile->setEmail($result1['EmailPrinc']);
102
103
        $user = $userManager->createUser();
104
        $user->setEnabled(true);
105
        $user->setPassword('');
106
        $user->setEmailConfirmedAt(new \DateTime());
107
        $user->setEmailExpiration(null);
108
        $user->setNfgAccessToken($result1['paccessid']);
109
        $user->setCpf($result1['CodCpf']);
110
        $user->setEmail($result1['EmailPrinc']);
111
        if ($result1['DtNasc']) {
112
            $user->setBirthdate(
113
                new \DateTime(
114
                    str_replace(
115
                        'T',
116
                        ' ',
117
                        $result1['DtNasc']
118
                    )
119
                )
120
            );
121
            $nfgProfile->setBirthdate($user->getBirthdate());
122
        }
123
        if (isset($result1['NroFoneContato'])) {
124
            $user->setMobile($result1['NroFoneContato']);
125
            $nfgProfile->setMobile($user->getMobile());
126
        }
127
        if ($result1['CodNivelAcesso']) {
128
            $nfgProfile->setAccessLvl($result1['CodNivelAcesso']);
129
        }
130
        $nome = explode(' ', $result1['NomeConsumidor']);
131
        $user->setFirstName(array_shift($nome));
132
        $user->setSurname(implode(' ', $nome));
133
134
        $em->persist($nfgProfile);
135
136
        $event = new GetResponseUserEvent($user, $request);
137
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
138
139
        if (null !== $event->getResponse()) {
140
            return $event->getResponse();
141
        }
142
143
        $form = $formFactory->createForm();
144
        $form->setData($user);
145
146
        $event = new FormEvent($form, $request);
147
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
148
149
        $userManager->updateUser($user);
150
151
        $personMeuRS = $meursHelper->getPersonMeuRS($user, true);
152
        $personMeuRS->setNfgProfile($nfgProfile);
153
        $em->persist($personMeuRS);
154
        $em->flush($personMeuRS);
155
156
        if (null === $response = $event->getResponse()) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $response is correct as $event->getResponse() targeting FOS\UserBundle\Event\FormEvent::getResponse() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
introduced by
The condition null === $response = $event->getResponse() is always true.
Loading history...
157
            $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
158
            $response = new RedirectResponse($url);
159
        }
160
161
        $dispatcher->dispatch(
162
            FOSUserEvents::REGISTRATION_COMPLETED,
163
            new FilterUserResponseEvent($user, $request, $response)
164
        );
165
166
        return $response;
167
    }
168
169
    protected function checkAccessToken($voterRegistration = null)
170
    {
171
        $request = $this->getRequest();
172
        $paccessid = $request->get('paccessid');
173
        if (!$paccessid) {
174
            throw new NfgException('nfg.missing.token');
175
        }
176
        /** @var NfgWsHelper $nfg */
177
        $nfg = $this->get('procergs_logincidadao.nfgws');
178
        $nfg->setAccessToken($paccessid);
179
        if ($voterRegistration) {
180
            $nfg->setTituloEleitoral($voterRegistration);
181
        }
182
        $result1 = $nfg->consultaCadastro();
183
        if ($result1['CodSitRetorno'] != 1) {
184
            throw new NfgException($result1['MsgRetorno']);
185
        }
186
        if (!isset($result1['CodCpf'], $result1['NomeConsumidor'],
187
            $result1['EmailPrinc'])
188
        ) {
189
            throw new NfgException('nfg.missing.required.fields');
190
        }
191
        $result1['paccessid'] = $paccessid;
192
193
        return $result1;
194
    }
195
196
    /**
197
     * @Route("/login", name="old_nfg_login")
198
     */
199
    public function loginAction()
200
    {
201
        return $this->toNfg('nfg_url_login', 'nfg_loginback', true);
202
    }
203
204
    /**
205
     * @Route("/login/back", name="old_nfg_loginback")
206
     */
207
    public function loginBacktAction(Request $request)
208
    {
209
        /** @var MeuRSHelper $meursHelper */
210
        $meursHelper = $this->get('meurs.helper');
211
212
        $cpf = $request->get('cpf');
213
        $accessid = $request->get('accessid');
214
        $prsec = $request->get('prsec');
215
        if (null == $accessid || null == $cpf || null == $prsec) {
216
            throw new NfgException('nfg.corrupted.callback');
217
        }
218
        $sig = hash_hmac(
219
            'sha256',
220
            "$cpf$accessid",
221
            $this->container->getParameter('nfg_hmac_secret')
222
        );
223
        if (false == $sig || strcmp(strtoupper($sig), $prsec) !== 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $sig of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
224
            throw new NfgException('nfg.corrupted.callback');
225
        }
226
        if ($request->getSession()->get('ticketacessologin') != $accessid) {
227
            throw new NfgException('nfg.accessid.mismatch');
228
        }
229
        $cpf = str_pad($cpf, 11, "0", STR_PAD_LEFT);
230
        $em = $this->getDoctrine()->getManager();
231
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
232
        $user = $personRepo->findOneBy(
233
            array(
234
                'cpf' => $cpf,
235
            )
236
        );
237
238
        if ($user instanceof PersonInterface) {
239
            $personMeuRS = $meursHelper->getPersonMeuRS($user, true);
240
        } else {
241
            $personMeuRS = null;
242
        }
243
244
        if (!$user || !$personMeuRS->getNfgAccessToken()) {
245
            throw new NfgException('nfg.user.notfound');
246
        }
247
        $response = $this->redirect($this->generateUrl('lc_home'));
248
        try {
249
            $loginManager = $this->container->get('fos_user.security.login_manager');
250
            $firewallName = $this->container->getParameter('fos_user.firewall_name');
251
            $loginManager->loginUser($firewallName, $user, $response);
252
        } catch (AccountStatusException $ex) {
0 ignored issues
show
Bug introduced by
The type PROCERGS\LoginCidadao\Co...\AccountStatusException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
253
            // We simply do not authenticate users which do not pass the user
254
            // checker (not enabled, expired, etc.).
255
        }
256
257
        return $response;
258
    }
259
260
    /**
261
     * @Route("/bind", name="old_nfg_bind")
262
     */
263
    public function bindAction()
264
    {
265
        return $this->toNfg('nfg_url_auth', 'nfg_bindback');
266
    }
267
268
    /**
269
     * @Route("/bind/back", name="old_nfg_bindback")
270
     */
271
    public function bindBackAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

271
    public function bindBackAction(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
272
    {
273
        $person = $this->getUser();
274
        $meuRSHelper = $this->getMeuRSHelper();
275
        if (!$person) {
276
            return $this->redirect($this->generateUrl('lc_home'));
277
        }
278
        $result1 = $this->checkAccessToken($meuRSHelper->getVoterRegistration($person));
279
        $em = $this->getDoctrine()->getManager();
280
        $personRepo = $em->getRepository('LoginCidadaoCoreBundle:Person');
281
282
        if ($person->getCpf()) {
283
            if ($person->getCpf() != $result1['CodCpf']) {
284
                $this->checkOtherPerson($result1, $em, $personRepo);
285
286
                $person->setCpf($result1['CodCpf']);
287
                // TODO: notify user
288
            }
289
        } else {
290
            $this->checkOtherPerson($result1, $em, $personRepo);
291
            $person->setCpf($result1['CodCpf']);
292
        }
293
294
        $nfgProfile = $em->getRepository('PROCERGSNfgBundle:NfgProfile')->findOneBy(
295
            array(
296
                'cpf' => $result1['CodCpf'],
297
            )
298
        );
299
        if (!$nfgProfile) {
300
            $nfgProfile = new NfgProfile();
301
            $nfgProfile->setCpf($result1['CodCpf']);
302
        }
303
        $nfgProfile->setName($result1['NomeConsumidor']);
304
        $nfgProfile->setEmail($result1['EmailPrinc']);
305
        if (isset($result1['DtNasc'])) {
306
            $nfgProfile->setBirthdate(
307
                new \DateTime(
308
                    str_replace(
309
                        'T',
310
                        ' ',
311
                        $result1['DtNasc']
312
                    )
313
                )
314
            );
315
            if (!$person->getBirthdate()) {
316
                $person->setBirthdate($nfgProfile->getBirthdate());
317
            }
318
        }
319
        if (isset($result1['NroFoneContato'])) {
320
            $nfgProfile->setMobile($result1['NroFoneContato']);
321
            if (!$person->getMobile()) {
322
                $person->setMobile($nfgProfile->getMobile());
323
            }
324
        }
325
        if ($result1['CodNivelAcesso']) {
326
            $nfgProfile->setAccessLvl($result1['CodNivelAcesso']);
327
        }
328
        if (isset($result1['CodSitTitulo'])) {
329
            $nfgProfile->setVoterRegistrationSit($result1['CodSitTitulo']);
330
            if (1 == $result1['CodSitTitulo']) {
331
                $nfgProfile->setVoterRegistration($meuRSHelper->getVoterRegistration($person));
332
            }
333
        }
334
        $em->persist($nfgProfile);
335
336
        $personMeuRS = $meuRSHelper->getPersonMeuRS($person);
337
        $personMeuRS->setNfgProfile($nfgProfile);
338
        $personMeuRS->setNfgAccessToken($result1['paccessid']);
339
        if (!$person->getFirstName() || !$person->getSurname()) {
340
            $nome = explode(' ', $result1['NomeConsumidor']);
341
            $person->setFirstName(array_shift($nome));
342
            $person->setSurname(implode(' ', $nome));
343
        }
344
345
        $this->container->get('fos_user.user_manager')->updateUser($person);
346
347
        return $this->redirect($this->generateUrl('lc_home'));
348
    }
349
350
    /**
351
     * @return MeuRSHelper
352
     */
353
    private function getMeuRSHelper()
354
    {
355
        return $this->get('meurs.helper');
356
    }
357
358
    protected function checkOtherPerson(&$result1, &$em, &$personRepo)
0 ignored issues
show
Unused Code introduced by
The parameter $em is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

358
    protected function checkOtherPerson(&$result1, /** @scrutinizer ignore-unused */ &$em, &$personRepo)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
359
    {
360
        $otherPerson = $personRepo->findOneBy(
361
            array(
362
                'cpf' => $result1['CodCpf'],
363
            )
364
        );
365
        if (!$otherPerson) {
366
            return;
367
        }
368
369
        if ($otherPerson->getNfgAccessToken()) {
370
            $this->solveConflict($result1, $otherPerson);
371
        } else {
372
            if ($result1['CodNivelAcesso'] == 1) {
373
                throw new NfgException(
374
                    'notification.nfg.already.cpf.but.weak',
375
                    NfgException::E_BIND
376
                );
377
            } else {
378
                $this->notifyAndClearCpfAndNfg($otherPerson);
379
            }
380
        }
381
    }
382
383
    private function solveConflict($thisPerson, Person $otherPerson)
384
    {
385
        $otherPersonNfg = $otherPerson->getNfgProfile();
386
        if ($otherPersonNfg->getAccessLvl() == 1) {
387
            if ($thisPerson['CodNivelAcesso'] == 1) {
388
                throw new NfgException(
389
                    'notification.nfg.already.bind.but.weak',
390
                    NfgException::E_BIND
391
                );
392
            } else {
393
                $this->notifyAndClearCpfAndNfg($otherPerson);
394
            }
395
        } else {
396
            throw new NfgException(
397
                'notification.nfg.already.bind',
398
                NfgException::E_BIND
399
            );
400
        }
401
    }
402
403
    private function notifyAndClearCpfAndNfg(Person $person)
404
    {
405
        $person->setCpf(null);
406
        $person->setNfgAccessToken(null);
407
        $person->setNfgProfile(null);
408
        //@TODO do no use updateUser
409
        $this->container->get('fos_user.user_manager')->updateUser($person);
410
        // TODO: notify user
411
    }
412
413
    /**
414
     * @Route("/unbind", name="old_nfg_unbind")
415
     */
416
    public function unbindAction()
417
    {
418
        $em = $this->getDoctrine()->getManager();
419
        $person = $this->getUser();
420
        $meuRSHelper = $this->getMeuRSHelper();
421
        $personMeuRS = $meuRSHelper->getPersonMeuRS($person);
0 ignored issues
show
Bug introduced by
It seems like $person can also be of type null; however, parameter $person of PROCERGS\LoginCidadao\Co...elper::getPersonMeuRS() does only seem to accept LoginCidadao\CoreBundle\Model\PersonInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

421
        $personMeuRS = $meuRSHelper->getPersonMeuRS(/** @scrutinizer ignore-type */ $person);
Loading history...
422
        if ($personMeuRS instanceof PersonMeuRS) {
0 ignored issues
show
introduced by
$personMeuRS is always a sub-type of PROCERGS\LoginCidadao\Co...ndle\Entity\PersonMeuRS.
Loading history...
423
            $personMeuRS->setNfgAccessToken(null);
424
            $personMeuRS->setNfgProfile(null);
425
            $em->persist($personMeuRS);
426
            $em->flush($personMeuRS);
427
            $this->container->get('fos_user.user_manager')->updateUser($person);
428
        }
429
430
        return $this->redirect($this->generateUrl('lc_home'));
431
    }
432
}
433