<?php
namespace App\Api\Authentication;
use App\Entity\User;
use App\Entity\UserStation;
use Doctrine\Persistence\ManagerRegistry;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\View\View;
use Lexik\Bundle\JWTAuthenticationBundle\DependencyInjection\Security\Factory\JWTAuthenticatorFactory;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Validator\Constraints\JsonValidator;
use Symfony\Config\LexikJwtAuthenticationConfig;
class TokenController extends AbstractFOSRestController {
private ManagerRegistry $doctrine;
private UserPasswordHasherInterface $userPasswordHasher;
private JWTTokenManagerInterface $encoder;
private $logger;
public function __construct(ManagerRegistry $doctrine, UserPasswordHasherInterface $userPasswordHasher,
JWTTokenManagerInterface $encoder, LoggerInterface $logger) {
$this->doctrine = $doctrine;
$this->userPasswordHasher = $userPasswordHasher;
$this->encoder = $encoder;
$this->logger = $logger;
}
/**
* @Route("/login",methods={"POST"}, name="token")
* @throws JWTEncodeFailureException
*/
public function newToken(Request $request){
$em = $this->doctrine->getManager();
$username = $request->get('username');
$data = json_decode($request->getContent(), true);
$username = $data['username'];
/** @var User $user */
$user = $em->getRepository(User::class)->findOneBy([
'username' => $username
]);
if(!$user){
$data = [
'error' => 'Wrong username '.$username.' - or password'
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
$isValid = $this->userPasswordHasher->isPasswordValid($user, $data['password']);
if(!$isValid){
$data = [
'error' => 'Wrong username or password'
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
/** @var UserStation $station */
$station = $em->getRepository(UserStation::class)->findOneBy([
'isActive' => true,
'user' => $user
]);
// $token = $this->encoder->create($user);
$token = $this->encoder->createFromPayload($user,[
'username' => $user->getUsername(),
'user_id' => $user->getId(),
'exp' => time() + (3600 * 4)
]);
$data = [
'token' => $token,
'username' => $user->getUsername(),
'full_name' => $user->getPerson()->__toString(),
'station' => $station->getStation()->getStationName(),
'station_id' => $station->getStation()->getId(),
'roles' => $user->getRoles(),
];
return new JsonResponse($data, Response::HTTP_OK);
}
/**
* @Method("POST")
* @Route("/sign-up/check", name="signup_check")
*/
public function signUpCount(){
$em = $this->doctrine->getManager();
$users = $em->getRepository(User::class)->findAll();
if(count($users) > 0) {
$view = new View('Data found', Response::HTTP_OK);
return $view;
}
$view = new View('No Data Found', Response::HTTP_FORBIDDEN);
return $view;
}
/**
* @Method("POST")
* @Route("/login/check", name="token_check")
* @Security("is_granted('ROLE_LECTURER','ROLE_WEB_USER')")
*/
public function isLoggedIn(){
return true;
}
/**
* @Method("GET")
* @Route("/make_user", name="user_update")
*/
public function updateUser(){
$em = $this->doctrine->getManager();
$user = $em->getRepository(User::class)->findOneBy([
'id' => 1
]);
if(!$user)
$user = new User();
$user->setCreatedAt(new \DateTime());
$user->setPassword($this->get('security.password_encoder')->encodePassword($user, 'mirage'));
$user->setCreatedBy(null);
$user->setUsername("samuel");
$user->setRoles(['ROLE_WEB_USER']);
$em->persist($user);
$em->flush();
return new Response($user);
}
/**
* @Route("/login/invoices",methods={"POST"}, name="test")
*/
public function timsApi(Request $request){
$content = $request->getContent();
$this->logger->info($content);
$this->logger->info($request->headers);
// foreach ($request->headers as $index => $header) {
//
// }
if($this->json_validator($content)){
$this->logger->info("AWESOME");
}else{
$this->logger->info("REALLY");
}
// json_decode($content, true);
return new Response("OK");
}
function json_validator($data): bool
{
if (!empty($data)) {
return is_string($data) &&
is_array(json_decode($data, true)) ? true : false;
}
return false;
}
}