Passed
Push — master ( 7438ce...69adc8 )
by Guilherme
01:29 queued 11s
created

PersonController::getCheckUpdateCallback()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 1
nop 3
dl 0
loc 23
ccs 0
cts 15
cp 0
crap 30
rs 8.5906
c 0
b 0
f 0
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\APIBundle\Controller;
12
13
use FOS\OAuthServerBundle\Security\Authentication\Token\OAuthToken;
14
use FOS\RestBundle\Controller\Annotations as REST;
15
use JMS\Serializer\SerializationContext;
16
use LoginCidadao\CoreBundle\LongPolling\LongPollingUtils;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
20
use LoginCidadao\CoreBundle\Model\PersonInterface;
21
use LoginCidadao\OAuthBundle\Model\ClientUser;
22
use LoginCidadao\APIBundle\Security\Audit\Annotation as Audit;
23
use LoginCidadao\APIBundle\Entity\LogoutKey;
24
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
26
27
class PersonController extends BaseController
28
{
29
30
    /**
31
     * Gets the currently authenticated user.
32
     *
33
     * The returned object contents will depend on the scope the user authorized.
34
     *
35
     * @ApiDoc(
36
     *   resource = true,
37
     *   description = "Gets the currently authenticated user.",
38
     *   output = {
39
     *     "class"="LoginCidadao\CoreBundle\Entity\Person",
40
     *     "groups" = {"public_profile"}
41
     *   },
42
     *   statusCodes = {
43
     *     200 = "Returned when successful"
44
     *   }
45
     * )
46
     * @REST\View(templateVar="person")
47
     * @REST\Get(defaults={"version": 2})
48
     * @Audit\Loggable(type="SELECT")
49
     * @throws NotFoundHttpException
50
     */
51
    public function getPersonAction()
52
    {
53
        $person = $this->getUser();
54
        if ($person instanceof PersonInterface) {
55
            $scope = $this->getClientScope($person);
56
        } else {
57
            if ($person instanceof ClientUser) {
58
                throw new AccessDeniedException("This is only available to a person's Access Token, not a client's.");
59
            } else {
60
                throw new AccessDeniedException();
61
            }
62
        }
63
64
        return $this->renderWithContext($person, $this->getSerializationContext($scope));
65
    }
66
67
    /**
68
     * Waits for a change in the current user's profile.
69
     *
70
     * @ApiDoc(
71
     *   resource = true,
72
     *   description = "Waits for a change in the current user's profile.",
73
     *   output = {
74
     *     "class"="LoginCidadao\CoreBundle\Entity\Person",
75
     *     "groups" = {"public_profile"}
76
     *   },
77
     *   statusCodes = {
78
     *     200 = "Returned when successful",
79
     *     408 = "Returned when the request times out"
80
     *   }
81
     * )
82
     * @REST\Get("/wait/person/update")
83
     * @Audit\Loggable(type="SELECT")
84
     * @REST\View
85
     */
86
    public function waitPersonChangeAction(Request $request)
87
    {
88
        /** @var LongPollingUtils $longPolling */
89
        $longPolling = $this->get('long_polling');
90
91
        $user = $this->getUser();
92
        $updatedAt = \DateTime::createFromFormat('Y-m-d H:i:s', $request->get('updated_at'));
93
94
        if (!$updatedAt instanceof \DateTime) {
95
            $updatedAt = new \DateTime();
96
        }
97
98
        $callback = $longPolling->getEntityUpdateCheckerCallback($user, $updatedAt);
99
        $person = $longPolling->runTimeLimited($callback);
100
101
        return $this->renderWithContext($person, $this->getSerializationContext($this->getClientScope($user)));
102
    }
103
104
    /**
105
     * Generates and returns a logout key for the user.
106
     *
107
     * @ApiDoc(
108
     *   resource = true,
109
     *   description = "Generates and returns a logout key for the user.",
110
     *   output = {
111
     *     "class"="LoginCidadao\APIBundle\Entity\LogoutKey",
112
     *     "groups" = {"key"}
113
     *   },
114
     *   statusCodes = {
115
     *     200 = "Returned when successful"
116
     *   }
117
     * )
118
     * @REST\Route("/person/{id}/logout-key", methods={"PUT", "POST"})
119
     * @REST\View(templateVar="logoutKey")
120
     *
121
     * @throws NotFoundHttpException
122
     */
123
    public function getLogoutKeyAction($id)
124
    {
125
        /** @var OAuthToken $token */
126
        $token = $this->get('security.token_storage')->getToken();
127
        $accessToken = $this->getDoctrine()
128
            ->getRepository('LoginCidadaoOAuthBundle:AccessToken')
129
            ->findOneBy(['token' => $token->getToken()]);
130
        $client = $accessToken->getClient();
131
132
        $people = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
133
        $person = $people->find($id);
134
135
        if (!$person->hasAuthorization($client)) {
136
            throw new AccessDeniedException("Not authorized");
137
        }
138
139
        $logoutKey = new LogoutKey();
140
        $logoutKey->setPerson($person);
141
        $logoutKey->setClient($client);
142
        $logoutKey->setKey($logoutKey->generateKey());
143
144
        $em = $this->getDoctrine()->getManager();
145
        $em->persist($logoutKey);
146
        $em->flush();
147
148
        $result = [
149
            'key' => $logoutKey->getKey(),
150
            'url' => $this->generateUrl(
151
                'lc_logout_not_remembered_safe',
152
                ['key' => $logoutKey->getKey()],
153
                UrlGeneratorInterface::ABSOLUTE_URL
154
            ),
155
        ];
156
157
        return $result;
158
    }
159
}
160