Completed
Pull Request — dev (#26)
by nonanerz
04:09
created

DefaultController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 91.67%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 4
c 4
b 3
f 0
lcom 1
cbo 6
dl 0
loc 60
ccs 22
cts 24
cp 0.9167
rs 10

2 Methods

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