Completed
Push — master ( 5f169a...f49b23 )
by Louis
14s
created

DefaultController::refreshAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace KI\UserBundle\Controller;
4
5
use KI\CoreBundle\Controller\BaseController;
6
use KI\UserBundle\Entity\Achievement;
7
use KI\UserBundle\Event\AchievementCheckEvent;
8
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
14
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
16
class DefaultController extends BaseController
17
{
18
    public function setContainer(ContainerInterface $container = null)
19
    {
20
        parent::setContainer($container);
21
        $this->initialize('User', 'User');
22
    }
23
24
    /**
25
     * @ApiDoc(
26
     *  description="Retourne les utilisateurs étant connectés et si le KI est ouvert",
27
     *  parameters={
28
     *   {
29
     *    "name"="delay",
30
     *    "dataType"="integer",
31
     *    "required"=false,
32
     *    "description"="Temps de l'intervalle considéré en minutes (30 minutes par défaut)"
33
     *   }
34
     *  },
35
     *  statusCodes={
36
     *   200="Requête traitée avec succès",
37
     *   401="Une authentification est nécessaire pour effectuer cette action",
38
     *   403="Pas les droits suffisants pour effectuer cette action",
39
     *   404="Ressource non trouvée",
40
     *   503="Service temporairement indisponible ou en maintenance",
41
     *  },
42
     *  section="Utilisateurs"
43
     * )
44
     * @Route("/refresh")
45
     * @Method("GET")
46
     */
47
    public function refreshAction(Request $request)
48
    {
49
        $delay = $request->query->has('delay') ? (int)$request->query->get('delay') : 30;
50
        $clubRepo = $this->manager->getRepository('KIUserBundle:Club');
51
52
        return $this->json([
53
                                'online' => $this->repository->getOnlineUsers($delay),
54
                                'open' => $clubRepo->findOneBySlug('ki')->getOpen()
55
                           ]);
56
    }
57
58
59
    /**
60
     * @ApiDoc(
61
     *  description="Envoie un mail permettant de reset le mot de passe",
62
     *  requirements={
63
     *   {
64
     *    "name"="username",
65
     *    "dataType"="string",
66
     *    "description"="Le nom d'utilisateur"
67
     *   }
68
     *  },
69
     *  statusCodes={
70
     *   204="Requête traitée avec succès mais pas d’information à renvoyer",
71
     *   401="Mauvaise combinaison username/password ou champ nom rempli",
72
     *   404="Ressource non trouvée",
73
     *   503="Service temporairement indisponible ou en maintenance",
74
     *  },
75
     *  section="Général"
76
     * )
77
     * @Route("/resetting/request")
78
     * @Method("POST")
79
     */
80
    public function resettingAction(Request $request)
81
    {
82
        if (!$request->request->has('username'))
83
            throw new BadRequestHttpException('Aucun nom d\'utilisateur fourni');
84
85
        $manager = $this->getDoctrine()->getManager();
86
        $repo = $manager->getRepository('KIUserBundle:User');
87
        $user = $repo->findOneByUsername($request->request->get('username'));
0 ignored issues
show
Bug introduced by
The method findOneByUsername() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
88
89
        if ($user) {
90
            if ($user->hasRole('ROLE_ADMISSIBLE'))
91
                return $this->json(null, 403);
92
93
            $token = $this->get('ki_user.service.token')->getToken($user);
94
            $message = \Swift_Message::newInstance()
95
                ->setSubject('Réinitialisation du mot de passe')
96
                ->setFrom('[email protected]')
97
                ->setTo($user->getEmail())
98
                ->setBody($this->renderView('KIUserBundle::resetting.txt.twig', ['token' => $token, 'name' => $user->getFirstName()]));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
99
            $this->get('mailer')->send($message);
100
101
            $dispatcher = $this->container->get('event_dispatcher');
102
            $achievementCheck = new AchievementCheckEvent(Achievement::PASSWORD, $user);
103
            $dispatcher->dispatch('upont.achievement', $achievementCheck);
104
105
            return $this->json(null, 204);
106
        } else
107
            throw new NotFoundHttpException('Utilisateur non trouvé');
108
    }
109
110
    /**
111
     * @ApiDoc(
112
     *  description="Reset son mot de passe à partir du mail",
113
     *  requirements={
114
     *   {
115
     *    "name"="password",
116
     *    "dataType"="string",
117
     *    "description"="Le mot de passe"
118
     *   },
119
     *   {
120
     *    "name"="check",
121
     *    "dataType"="string",
122
     *    "description"="Le mot de passe une seconde fois (confirmation)"
123
     *   }
124
     *  },
125
     *  statusCodes={
126
     *   204="Requête traitée avec succès mais pas d’information à renvoyer",
127
     *   401="Mauvaise combinaison username/password ou champ nom rempli",
128
     *   404="Ressource non trouvée",
129
     *   503="Service temporairement indisponible ou en maintenance",
130
     *  },
131
     *  section="Général"
132
     * )
133
     * @Route("/resetting/token/{token}")
134
     * @Method("POST")
135
     */
136
    public function resettingTokenAction(Request $request, $token)
137
    {
138
        if (!$request->request->has('password') || !$request->request->has('check'))
139
            throw new BadRequestHttpException('Champs password/check non rempli(s)');
140
141
        $manager = $this->getDoctrine()->getManager();
142
        $repo = $manager->getRepository('KIUserBundle:User');
143
        $user = $repo->findOneByToken($token);
0 ignored issues
show
Bug introduced by
The method findOneByToken() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
144
145
        if ($user) {
146
            if ($user->hasRole('ROLE_ADMISSIBLE'))
147
                return $this->json(null, 403);
148
149
            $username = $user->getUsername();
150
151
            // Pour changer le mot de passe on doit passer par le UserManager
152
            $userManager = $this->get('fos_user.user_manager');
153
            $user = $userManager->findUserByUsername($username);
154
155
156
            if ($request->request->get('password') != $request->request->get('check'))
157
                throw new BadRequestHttpException('Mots de passe non identiques');
158
159
            $user->setPlainPassword($request->request->get('password'));
160
            $userManager->updateUser($user, true);
161
162
            return $this->json(null, 204);
163
        } else
164
            throw new NotFoundHttpException('Utilisateur non trouvé');
165
    }
166
}
167