Failed Conditions
Push — issue#765 ( 54a2c2...25bda7 )
by Guilherme
09:33
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
        $view = $this->view($person)->setSerializationContext($this->getSerializationContext($scope));
65
66
        return $this->handleView($view);
67
    }
68
69
    /**
70
     * Waits for a change in the current user's profile.
71
     *
72
     * @ApiDoc(
73
     *   resource = true,
74
     *   description = "Waits for a change in the current user's profile.",
75
     *   output = {
76
     *     "class"="LoginCidadao\CoreBundle\Entity\Person",
77
     *     "groups" = {"public_profile"}
78
     *   },
79
     *   statusCodes = {
80
     *     200 = "Returned when successful",
81
     *     408 = "Returned when the request times out"
82
     *   }
83
     * )
84
     * @REST\Get("/wait/person/update")
85
     * @Audit\Loggable(type="SELECT")
86
     * @REST\View
87
     */
88
    public function waitPersonChangeAction(Request $request)
89
    {
90
        /** @var LongPollingUtils $longPolling */
91
        $longPolling = $this->get('long_polling');
92
93
        $user = $this->getUser();
94
        $updatedAt = \DateTime::createFromFormat('Y-m-d H:i:s', $request->get('updated_at'));
95
96
        if (!$updatedAt instanceof \DateTime) {
97
            $updatedAt = new \DateTime();
98
        }
99
100
        $callback = $longPolling->getEntityUpdateCheckerCallback($user, $updatedAt);
101
        $person = $longPolling->runTimeLimited($callback);
102
        $context = SerializationContext::create()->setGroups($this->getClientScope($user));
103
        $view = $this->view($person)->setSerializationContext($context);
104
105
        return $this->handleView($view);
106
    }
107
108
    /**
109
     * Generates and returns a logout key for the user.
110
     *
111
     * @ApiDoc(
112
     *   resource = true,
113
     *   description = "Generates and returns a logout key for the user.",
114
     *   output = {
115
     *     "class"="LoginCidadao\APIBundle\Entity\LogoutKey",
116
     *     "groups" = {"key"}
117
     *   },
118
     *   statusCodes = {
119
     *     200 = "Returned when successful"
120
     *   }
121
     * )
122
     * @REST\Route("/person/{id}/logout-key", methods={"PUT", "POST"})
123
     * @REST\View(templateVar="logoutKey")
124
     *
125
     * @throws NotFoundHttpException
126
     */
127
    public function getLogoutKeyAction($id)
128
    {
129
        /** @var OAuthToken $token */
130
        $token = $this->get('security.token_storage')->getToken();
131
        $accessToken = $this->getDoctrine()
132
            ->getRepository('LoginCidadaoOAuthBundle:AccessToken')
133
            ->findOneBy(['token' => $token->getToken()]);
134
        $client = $accessToken->getClient();
135
136
        $people = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
137
        $person = $people->find($id);
138
139
        if (!$person->hasAuthorization($client)) {
140
            throw new AccessDeniedException("Not authorized");
141
        }
142
143
        $logoutKey = new LogoutKey();
144
        $logoutKey->setPerson($person);
145
        $logoutKey->setClient($client);
146
        $logoutKey->setKey($logoutKey->generateKey());
147
148
        $em = $this->getDoctrine()->getManager();
149
        $em->persist($logoutKey);
150
        $em->flush();
151
152
        $result = [
153
            'key' => $logoutKey->getKey(),
154
            'url' => $this->generateUrl(
155
                'lc_logout_not_remembered_safe',
156
                ['key' => $logoutKey->getKey()],
157
                UrlGeneratorInterface::ABSOLUTE_URL
158
            ),
159
        ];
160
161
        return $result;
162
    }
163
}
164