Completed
Pull Request — master (#30)
by
unknown
03:43
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.59%

Importance

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

2 Methods

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