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

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 62
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
lcom 1
cbo 3
dl 0
loc 62
ccs 25
cts 27
cp 0.9259
rs 10
c 4
b 3
f 0

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