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

DefaultController::userAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 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