Failed Conditions
Push — issue#702_rs ( ed72a1...cdafcf )
by Guilherme
07:33
created

DefaultController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 147
rs 10
c 0
b 0
f 0
wmc 15

6 Methods

Rating   Name   Duplication   Size   Complexity  
A dashboardAction() 0 22 1
B contactAction() 0 28 4
A helpAction() 0 3 1
A indexAction() 0 3 1
A getEmail() 0 12 1
C safeLogoutIfNotRememberedAction() 0 44 7
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\CoreBundle\Controller;
12
13
use LoginCidadao\APIBundle\Entity\ActionLogRepository;
14
use LoginCidadao\CoreBundle\Model\PersonInterface;
15
use LoginCidadao\CoreBundle\Model\SupportMessage;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
19
use Symfony\Component\Security\Core\User\UserInterface;
20
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
23
use LoginCidadao\CoreBundle\Entity\SentEmail;
24
use LoginCidadao\APIBundle\Entity\LogoutKey;
25
use Symfony\Component\Translation\TranslatorInterface;
26
27
class DefaultController extends Controller
28
{
29
30
    /**
31
     * @Route("/help", name="lc_help")
32
     * @Template()
33
     */
34
    public function helpAction()
35
    {
36
        return $this->render('LoginCidadaoCoreBundle:Info:help.html.twig');
37
    }
38
39
    /**
40
     * @Route("/contact/{correlationId}", defaults={"correlationId" = null}, name="lc_contact")
41
     * @Template()
42
     * @codeCoverageIgnore
43
     */
44
    public function contactAction(Request $request, $correlationId = null)
45
    {
46
        $person = $this->getUser() instanceof PersonInterface ? $this->getUser() : null;
47
48
        $data = new SupportMessage($person);
49
        $data->setExtra('Correlation Id', $correlationId);
50
51
        $form = $this->createForm('contact_form_type', $data, ['loggedIn' => $person instanceof PersonInterface]);
52
        $form->handleRequest($request);
53
54
        /** @var TranslatorInterface $translator */
55
        $translator = $this->get('translator');
56
        $message = $translator->trans('contact.form.sent');
57
58
        if ($form->isValid()) {
59
            $email = $this->getEmail($data, $translator);
60
            $swiftMail = $email->getSwiftMail();
61
            if ($this->get('mailer')->send($swiftMail)) {
62
                $em = $this->getDoctrine()->getManager();
63
                $em->persist($email);
64
                $em->flush();
65
                $this->get('session')->getFlashBag()->add('success', $message);
66
            }
67
68
            return $this->redirectToRoute('lc_contact');
69
        }
70
71
        return $this->render('LoginCidadaoCoreBundle:Info:contact.html.twig', ['form' => $form->createView()]);
72
    }
73
74
    /**
75
     * @Route("/dashboard", name="lc_dashboard")
76
     * @Template()
77
     */
78
    public function dashboardAction()
79
    {
80
        // badges
81
        $badgesHandler = $this->get('badges.handler');
82
        $badges = $badgesHandler->getAvailableBadges();
83
        $userBadges = $badgesHandler->evaluate($this->getUser())->getBadges();
84
85
        // logs
86
        $em = $this->getDoctrine()->getManager();
87
88
        /** @var ActionLogRepository $logRepo */
89
        $logRepo = $em->getRepository('LoginCidadaoAPIBundle:ActionLog');
90
        $logs['logins'] = $logRepo->findLoginsByPerson($this->getUser(), 5);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$logs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $logs = array(); before regardless.
Loading history...
91
        $logs['activity'] = $logRepo->getActivityLogsByTarget($this->getUser(), 4);
92
93
        $defaultClientUid = $this->container->getParameter('oauth_default_client.uid');
94
95
        return array(
96
            'allBadges' => $badges,
97
            'userBadges' => $userBadges,
98
            'logs' => $logs,
99
            'defaultClientUid' => $defaultClientUid,
100
        );
101
    }
102
103
    /**
104
     * @Route("/logout/if-not-remembered/{key}", name="lc_logout_not_remembered_safe")
105
     * @Template()
106
     */
107
    public function safeLogoutIfNotRememberedAction(Request $request, $key)
108
    {
109
        $em = $this->getDoctrine()->getManager();
110
        $logoutKeys = $em->getRepository('LoginCidadaoAPIBundle:LogoutKey');
111
        $logoutKey = $logoutKeys->findActiveByKey($key);
112
113
        if (!($logoutKey instanceof LogoutKey)) {
114
            throw new AccessDeniedException("Invalid logout key.");
115
        }
116
117
        $result['logged_out'] = false;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.
Loading history...
118
        if ($this->getUser() instanceof UserInterface) {
119
            if ($request->cookies->has($this->getParameter('session.remember_me.name'))) {
120
                $result = array('logged_out' => false);
121
            } else {
122
                $this->get("request")->getSession()->invalidate();
123
                $this->get("security.token_storage")->setToken(null);
124
                $result['logged_out'] = true;
125
            }
126
        } else {
127
            $result['logged_out'] = true;
128
        }
129
130
        $response = new JsonResponse();
131
        $userAgent = $request->headers->get('User-Agent');
132
        if (preg_match('/(?i)msie [1-9]/', $userAgent)) {
133
            $response->headers->set('Content-Type', 'text/json');
134
        }
135
136
        $client = $logoutKey->getClient();
137
        $em->remove($logoutKey);
138
        $em->flush();
139
140
        $redirectUrl = $request->get('redirect_url');
141
        if ($redirectUrl !== null) {
142
            $host = parse_url($redirectUrl, PHP_URL_HOST);
143
            if ($client->ownsDomain($host)) {
144
                return $this->redirect($redirectUrl);
145
            } else {
146
                $result['error'] = "Invalid redirect_url domain. It doesn't appear to belong to {$client->getName()}";
147
            }
148
        }
149
150
        return $response->setData($result);
151
    }
152
153
    /**
154
     * @Route("/_home", name="lc_index")
155
     * @Template()
156
     */
157
    public function indexAction(Request $request, $lastUsername)
158
    {
159
        ['last_username' => $lastUsername];
160
    }
161
162
    private function getEmail(SupportMessage $supportMessage, TranslatorInterface $translator)
163
    {
164
        $message = $supportMessage->getFormattedMessage($translator);
165
166
        $email = (new SentEmail())
167
            ->setType('contact-mail')
168
            ->setSubject('Fale conosco - '.$supportMessage->getName())
169
            ->setSender($supportMessage->getEmail())
170
            ->setReceiver($this->container->getParameter('contact_form.email'))
171
            ->setMessage($message);
172
173
        return $email;
174
    }
175
}
176