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

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 84%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 4
c 4
b 3
f 0
lcom 1
cbo 6
dl 0
loc 66
ccs 21
cts 25
cp 0.84
rs 10

2 Methods

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