Completed
Pull Request — dev (#26)
by nonanerz
03:06
created

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 92.59%

Importance

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

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\User;
6
use AppBundle\Form\LoginType;
7
use Mcfedr\JsonFormBundle\Controller\JsonController;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
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
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 User();
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 1
            ->findOneBy(['email' => $userCredentials->getEmail()]);
34
35 1
        if (!$user) {
36
            return $this->json(['message' => 'Bad credentials'], 401);
37
        }
38
39 1
        $result = $this->get('security.encoder_factory')
40 1
            ->getEncoder($user)
41 1
            ->isPasswordValid($user->getPassword(), $userCredentials->getPassword(), null);
42 1
        if (!$result) {
43
            return $this->json(['message' => 'Bad credentials'], 401);
44
        }
45
46 1
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
47
48 1
        $em = $this->getDoctrine()
49 1
            ->getManager();
50 1
        $user->setApiToken($token);
51
52 1
        $em->persist($user);
53
54 1
        $em->flush();
55
56 1
        $serializer = $this->get('serializer');
57 1
        $json = $serializer->normalize(
58
            $user,
59 1
            null,
60 1
            array('groups' => array('Detail'))
61
        );
62
63 1
        return $this->json(
64 1
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
65
        );
66
    }
67
68
    /**
69
     * @Route("/user", name="user")
70
     * @Method("GET")
71
     *
72
     * @return JsonResponse
73
     */
74 1
    public function securityTestAction()
75
    {
76 1
        return $this->json(['autorization' => 'works!']);
77
    }
78
}
79