Completed
Pull Request — dev (#36)
by nonanerz
03:13
created

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 18.52%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 4
c 4
b 3
f 0
lcom 1
cbo 3
dl 0
loc 62
ccs 5
cts 27
cp 0.1852
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B loginAction() 0 43 3
A userAction() 0 4 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
            ->findOneBy(['email' => $userCredentials->getEmail()]);
34
35
        if (!$user) {
36
            throw new JsonHttpException(400, 'Bad credentials');
37
        }
38
39
        $result = $this->get('security.encoder_factory')
40
            ->getEncoder($user)
41
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
42
        if (!$result) {
43
            throw new JsonHttpException(400, 'Bad credentials');
44
        }
45
46
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
47
48
        $em = $this->getDoctrine()
49
            ->getManager();
50
        $user->setApiToken($token);
51
52
        $em->persist($user);
53
54
        $em->flush();
55
56
        $serializer = $this->get('serializer');
57
        $json = $serializer->normalize(
58
            $user,
59
            null,
60
            array('groups' => array('Short'))
61
        );
62
63
        return $this->json(
64
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
65
        );
66
    }
67
68
    /**
69
     * @Route("/user")
70
     * @Method({"GET"})
71
     */
72
    public function userAction()
73
    {
74
        return $this->json(['user' => $this->getUser()], 200, [], [AbstractNormalizer::GROUPS => ['Detail']]);
75
    }
76
}
77