src/Api/Authentication/TokenController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Api\Authentication;
  3. use App\Entity\User;
  4. use App\Entity\UserStation;
  5. use Doctrine\Persistence\ManagerRegistry;
  6. use FOS\RestBundle\Controller\AbstractFOSRestController;
  7. use FOS\RestBundle\Controller\Annotations\Route;
  8. use FOS\RestBundle\View\View;
  9. use Lexik\Bundle\JWTAuthenticationBundle\DependencyInjection\Security\Factory\JWTAuthenticatorFactory;
  10. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  11. use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
  12. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  20. use Symfony\Component\Serializer\Encoder\JsonDecode;
  21. use Symfony\Component\Validator\Constraints\JsonValidator;
  22. use Symfony\Config\LexikJwtAuthenticationConfig;
  23. class TokenController extends AbstractFOSRestController {
  24. private ManagerRegistry $doctrine;
  25. private UserPasswordHasherInterface $userPasswordHasher;
  26. private JWTTokenManagerInterface $encoder;
  27. private $logger;
  28. public function __construct(ManagerRegistry $doctrine, UserPasswordHasherInterface $userPasswordHasher,
  29. JWTTokenManagerInterface $encoder, LoggerInterface $logger) {
  30. $this->doctrine = $doctrine;
  31. $this->userPasswordHasher = $userPasswordHasher;
  32. $this->encoder = $encoder;
  33. $this->logger = $logger;
  34. }
  35. /**
  36. * @Route("/login",methods={"POST"}, name="token")
  37. * @throws JWTEncodeFailureException
  38. */
  39. public function newToken(Request $request){
  40. $em = $this->doctrine->getManager();
  41. $username = $request->get('username');
  42. $data = json_decode($request->getContent(), true);
  43. $username = $data['username'];
  44. /** @var User $user */
  45. $user = $em->getRepository(User::class)->findOneBy([
  46. 'username' => $username
  47. ]);
  48. if(!$user){
  49. $data = [
  50. 'error' => 'Wrong username '.$username.' - or password'
  51. ];
  52. return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
  53. }
  54. $isValid = $this->userPasswordHasher->isPasswordValid($user, $data['password']);
  55. if(!$isValid){
  56. $data = [
  57. 'error' => 'Wrong username or password'
  58. ];
  59. return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
  60. }
  61. /** @var UserStation $station */
  62. $station = $em->getRepository(UserStation::class)->findOneBy([
  63. 'isActive' => true,
  64. 'user' => $user
  65. ]);
  66. // $token = $this->encoder->create($user);
  67. $token = $this->encoder->createFromPayload($user,[
  68. 'username' => $user->getUsername(),
  69. 'user_id' => $user->getId(),
  70. 'exp' => time() + (3600 * 4)
  71. ]);
  72. $data = [
  73. 'token' => $token,
  74. 'username' => $user->getUsername(),
  75. 'full_name' => $user->getPerson()->__toString(),
  76. 'station' => $station->getStation()->getStationName(),
  77. 'station_id' => $station->getStation()->getId(),
  78. 'roles' => $user->getRoles(),
  79. ];
  80. return new JsonResponse($data, Response::HTTP_OK);
  81. }
  82. /**
  83. * @Method("POST")
  84. * @Route("/sign-up/check", name="signup_check")
  85. */
  86. public function signUpCount(){
  87. $em = $this->doctrine->getManager();
  88. $users = $em->getRepository(User::class)->findAll();
  89. if(count($users) > 0) {
  90. $view = new View('Data found', Response::HTTP_OK);
  91. return $view;
  92. }
  93. $view = new View('No Data Found', Response::HTTP_FORBIDDEN);
  94. return $view;
  95. }
  96. /**
  97. * @Method("POST")
  98. * @Route("/login/check", name="token_check")
  99. * @Security("is_granted('ROLE_LECTURER','ROLE_WEB_USER')")
  100. */
  101. public function isLoggedIn(){
  102. return true;
  103. }
  104. /**
  105. * @Method("GET")
  106. * @Route("/make_user", name="user_update")
  107. */
  108. public function updateUser(){
  109. $em = $this->doctrine->getManager();
  110. $user = $em->getRepository(User::class)->findOneBy([
  111. 'id' => 1
  112. ]);
  113. if(!$user)
  114. $user = new User();
  115. $user->setCreatedAt(new \DateTime());
  116. $user->setPassword($this->get('security.password_encoder')->encodePassword($user, 'mirage'));
  117. $user->setCreatedBy(null);
  118. $user->setUsername("samuel");
  119. $user->setRoles(['ROLE_WEB_USER']);
  120. $em->persist($user);
  121. $em->flush();
  122. return new Response($user);
  123. }
  124. /**
  125. * @Route("/login/invoices",methods={"POST"}, name="test")
  126. */
  127. public function timsApi(Request $request){
  128. $content = $request->getContent();
  129. $this->logger->info($content);
  130. $this->logger->info($request->headers);
  131. // foreach ($request->headers as $index => $header) {
  132. //
  133. // }
  134. if($this->json_validator($content)){
  135. $this->logger->info("AWESOME");
  136. }else{
  137. $this->logger->info("REALLY");
  138. }
  139. // json_decode($content, true);
  140. return new Response("OK");
  141. }
  142. function json_validator($data): bool
  143. {
  144. if (!empty($data)) {
  145. return is_string($data) &&
  146. is_array(json_decode($data, true)) ? true : false;
  147. }
  148. return false;
  149. }
  150. }