Completed
Pull Request — dev (#24)
by
unknown
04:38
created

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 29.63%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 64
ccs 8
cts 27
cp 0.2963
rs 10
c 4
b 3
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A securityTestAction() 0 4 1
B loginAction() 0 43 3
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
14
class DefaultController extends JsonController
15
{
16
    /**
17
     * @param Request $request
18
     * @Route("/login", name="api_login")
19
     * @Method("POST")
20
     *
21
     * @return JsonResponse
22
     */
23 1
    public function loginAction(Request $request)
24
    {
25 1
        $userCredentials = new DtoUser();
26
27 1
        $form = $this->createForm(LoginType::class, $userCredentials);
28
29 1
        $this->handleJsonForm($form, $request);
30
31 1
        $user = $this->getDoctrine()->getRepository('AppBundle:User')
32 1
            ->findOneBy(['email' => $userCredentials->getEmail()]);
33
34 1
        if (!$user) {
35 1
            throw new JsonHttpException(400, 'Bad credentials');
36
        }
37
38
        $result = $this->get('security.encoder_factory')
39
            ->getEncoder($user)
40
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
41
        if (!$result) {
42
            throw new JsonHttpException(400, 'Bad credentials');
43
        }
44
45
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
46
47
        $em = $this->getDoctrine()
48
            ->getManager();
49
        $user->setApiToken($token);
50
51
        $em->persist($user);
52
53
        $em->flush();
54
55
        $serializer = $this->get('serializer');
56
        $json = $serializer->normalize(
57
            $user,
58
            null,
59
            array('groups' => array('Short'))
60
        );
61
62
        return $this->json(
63
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
64
        );
65
    }
66
67
    /**
68
     * @Route("/user", name="user")
69
     * @Method("GET")
70
     *
71
     * @return JsonResponse
72
     */
73
    public function securityTestAction()
74
    {
75
        return $this->json(['autorization' => 'works!']);
76
    }
77
}
78