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

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 92%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 4
c 4
b 3
f 0
lcom 1
cbo 5
dl 0
loc 63
ccs 23
cts 25
cp 0.92
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A securityTestAction() 0 4 1
B loginAction() 0 41 3
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\User;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\Routing\Annotation\Route;
11
12
class DefaultController extends Controller
13
{
14
    /**
15
16
     * @param Request $request
17
     * @Route("/login", name="api_login")
18
     * @Method("POST")
19
     *
20
     * @return JsonResponse
21
     */
22 1
    public function loginAction(Request $request)
23
    {
24 1
        $data = json_decode($request->getContent(), true);
25
        /**
26
         * @var User
27
         */
28 1
        $user = $this->getDoctrine()->getRepository('AppBundle:User')
29 1
            ->findOneBy(['email' => $data['email']]);
30
31 1
        if (!$user) {
32
            return $this->json(['message' => 'Bad credentials'], 401);
33
        }
34
35 1
        $result = $this->get('security.encoder_factory')
36 1
            ->getEncoder($user)
37 1
            ->isPasswordValid($user->getPassword(), $data['password'], null);
38 1
        if (!$result) {
39
            return $this->json(['message' => 'Bad credentials'], 401);
40
        }
41
42 1
        $token = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
43
44 1
        $em = $this->getDoctrine()
45 1
            ->getManager();
46 1
        $user->setApiToken($token);
47
48 1
        $em->persist($user);
49
50 1
        $em->flush();
51
52 1
        $serializer = $this->get('serializer');
53 1
        $json = $serializer->normalize(
54
            $user,
55 1
            null,
56 1
            array('groups' => array('Detail'))
57
        );
58
59 1
        return $this->json(
60 1
            ['user' => $json, 'X-AUTH-TOKEN' => $token]
61
        );
62
    }
63
64
    /**
65
     * @Route("/user", name="user")
66
     * @Method("GET")
67
     *
68
     * @return JsonResponse
69
     */
70 1
    public function securityTestAction()
71
    {
72 1
        return $this->json(['autorization' => 'works!']);
73
    }
74
}
75