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 $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
|
|
|
|
55
|
1 |
|
$user, null, array('groups' => array('Detail')) |
56
|
|
|
); |
57
|
|
|
|
58
|
1 |
|
return $this->json( |
59
|
1 |
|
['user' => $json, 'X-AUTH-TOKEN' => $token] |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @Route("/user", name="user") |
65
|
|
|
* @Method("GET") |
66
|
|
|
* |
67
|
|
|
* @return JsonResponse |
68
|
|
|
*/ |
69
|
1 |
|
public function securityTestAction() |
70
|
|
|
{ |
71
|
1 |
|
return $this->json(['autorization' => 'works!']); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|