<?php
namespace App\Controller;
use App\Entity\User;
use App\Service\DairyOffice;
use JsonException;
use Psr\Container\{ContainerExceptionInterface, NotFoundExceptionInterface};
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\{Request, Response, Session\Session};
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\HttpClient\Exception\{ClientExceptionInterface,
DecodingExceptionInterface,
RedirectionExceptionInterface,
ServerExceptionInterface,
TransportExceptionInterface};
class UserController extends AbstractController
{
/**
* @Route("/security", name="security")
*/
public function index(): Response
{
return $this->render('security/index.html.twig', [
'controller_name' => 'UserController',
]);
}
/**
* @Route("/login", name="api_login")
* @param Request $request
*
* @return Response
* @throws ClientExceptionInterface
* @throws JsonException
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws DecodingExceptionInterface
*/
public function login(Request $request): Response
{
$req = $request->request;
$password = $req->get('password');
$username = $req->get('username');
$token = '';
$email = '';
$logged_in = false;
$user = new User($username, [ 'ROLE_BASE_USER' ], $email, $password);
$session = $this->container->get("session", function () {
$session = new Session();
$session->start();
return $session;
});
$session->set('user', $user);
$content = $user->callUserApi(
'https://authorize.dairyoffice.com/oauth2/token',
$username,
$password,
$this->getParameter('jwt.client_id'),
$this->getParameter('jwt.secret_key')
);
if (array_key_exists(0, $content) && ! $content[0]) {
if (array_key_exists(1, $content) && is_array($content[1])) {
$message = $content[1]['message'];
} else if (array_key_exists(1, $content) && is_array($content[1])) {
$message = $content[1];
} else {
$message = $content;
}
$this->addFlash( 'danger', $message );
} else {
$token = $content['access_token'];
$email = $content['email'];
$decodedJwtToken = json_decode(
base64_decode(str_replace('_', '/', str_replace(
'-',
'+',
explode('.', $token)[1]
))),
true,
512,
JSON_THROW_ON_ERROR
);
$user->setEmail($email)
->setUsername($decodedJwtToken['name'])
->setApiToken($token);
$logged_in = $decodedJwtToken['exp'] - microtime(true) > 0;
}
$do = new DairyOffice(['token' => $token]);
$data = $do->getDairyOfficeLinks();
return $this->render('default/index.html.twig', [
'data' => $data,
'user' => $user,
'logged_in' => $logged_in,
]);
}
/**
* @Route("/logout", name="api_logout")
*/
public function logout(): Response {
/** TODO: See about logging off from the API */
$session = $this->container->get("session", function () {
$session = new Session();
$session->invalidate();
return $session;
});
return $this->redirectToRoute('home');
}
}