Completed
Pull Request — dev (#39)
by nonanerz
04:41
created

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 64
ccs 26
cts 28
cp 0.9286
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B loginAction() 0 43 3
A userAction() 0 6 1
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\DTO\DtoUser;
6
use AppBundle\Exception\JsonHttpException;
7
use AppBundle\Form\LoginType;
8
use Mcfedr\JsonFormBundle\Controller\JsonController;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\Routing\Annotation\Route;
13
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
14
15
class DefaultController extends JsonController
16
{
17
    /**
18
     * @param Request $request
19
     * @Route("/login", name="api_login")
20
     * @Method("POST")
21
     *
22
     * @return JsonResponse
23
     */
24 1
    public function loginAction(Request $request)
25
    {
26 1
        $userCredentials = new DtoUser();
27
28 1
        $form = $this->createForm(LoginType::class, $userCredentials);
29
30 1
        $this->handleJsonForm($form, $request);
31
32 1
        $user = $this->getDoctrine()->getRepository('AppBundle:User')
33 1
            ->findOneBy(['email' => $userCredentials->getEmail()]);
34
35 1
        if (!$user) {
36
            throw new JsonHttpException(400, 'Bad credentials');
37
        }
38
39 1
        $result = $this->get('security.encoder_factory')
40 1
            ->getEncoder($user)
41 1
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
42 1
        if (!$result) {
43
            throw new JsonHttpException(400, 'Bad credentials');
44
        }
45
46 1
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
47
48 1
        $em = $this->getDoctrine()
49 1
            ->getManager();
50 1
        $user->setApiToken($token);
51
52 1
        $em->persist($user);
53
54 1
        $em->flush();
55
56 1
        $serializer = $this->get('serializer');
57 1
        $json = $serializer->normalize(
58
            $user,
59 1
            null,
60 1
            array('groups' => array('Short'))
61
        );
62
63 1
        return $this->json(
64 1
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
65
        );
66
    }
67
68
    /**
69
     * @Route("/user")
70
     * @Method({"GET"})
71
     */
72 1
    public function userAction()
73
    {
74 1
        $this->get('app.email_notification')->sendNotification('[email protected]');
75
76 1
        return $this->json(['user' => $this->getUser()], 200, [], [AbstractNormalizer::GROUPS => ['Detail']]);
77
    }
78
}
79