GraphQL Add dependency injection #2644

pull/2715/head
Angel Fernando Quiroz Campos 6 years ago
parent 3b9c5c75cd
commit f4d41383a5
  1. 11
      config/services.yaml
  2. 85
      src/ApiBundle/GraphQL/ApiGraphQLTrait.php
  3. 9
      src/ApiBundle/GraphQL/Mutation/RootMutation.php
  4. 9
      src/ApiBundle/GraphQL/Resolver/CourseResolver.php
  5. 8
      src/ApiBundle/GraphQL/Resolver/MessageResolver.php
  6. 9
      src/ApiBundle/GraphQL/Resolver/RootResolver.php
  7. 21
      src/ApiBundle/GraphQL/Resolver/UserResolver.php

@ -41,13 +41,12 @@ services:
arguments: arguments:
$debug: '%kernel.debug%' $debug: '%kernel.debug%'
Chamilo\ApiBundle\GraphQL\Resolver\: Chamilo\ApiBundle\GraphQL\:
resource: '../src/ApiBundle/GraphQL/Resolver' resource: '../src/ApiBundle/GraphQL/*'
tags: ['overblog_graphql.resolver'] exclude: '../src/ApiBundle/GraphQL/{Resources}'
tags: ['overblog_graphql.resolver', 'overblog_graphql.mutation']
Chamilo\ApiBundle\GraphQL\Mutation\: Doctrine\ORM\EntityManager: "@doctrine.orm.default_entity_manager"
resource: '../src/ApiBundle/GraphQL/Mutation'
tags: ['overblog_graphql.mutation']
sylius_settings: sylius_settings:
driver: doctrine/orm driver: doctrine/orm

@ -3,17 +3,31 @@
namespace Chamilo\ApiBundle\GraphQL; namespace Chamilo\ApiBundle\GraphQL;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\UserBundle\Entity\User; use Chamilo\UserBundle\Entity\User;
use Doctrine\ORM\EntityManager;
use Firebase\JWT\JWT; use Firebase\JWT\JWT;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
/** /**
* Class Auth. * Trait ApiGraphQLTrait
*
* @package Chamilo\ApiBundle\GraphQL * @package Chamilo\ApiBundle\GraphQL
*/ */
class Auth trait ApiGraphQLTrait
{ {
use ContainerAwareTrait;
private $em;
/**
* ApiGraphQLTrait constructor.
*
* @param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/** /**
* @param string $username * @param string $username
* @param string $password * @param string $password
@ -22,16 +36,16 @@ class Auth
* *
* @return string * @return string
*/ */
public function getUserToken($username, $password): string private function getUserToken($username, $password): string
{ {
/** @var User $user */ /** @var User $user */
$user = Container::getUserManager()->findUserBy(['username' => $username]); $user = $this->em->getRepository('ChamiloUserBundle:User')->findOneBy(['username' => $username]);
if (!$user) { if (!$user) {
throw new \Exception(get_lang('NoUser')); throw new \Exception(get_lang('NoUser'));
} }
$encoder = Container::$container->get('chamilo_user.security.encoder'); $encoder = $this->container->get('chamilo_user.security.encoder');
$isValid = $encoder->isPasswordValid( $isValid = $encoder->isPasswordValid(
$user->getPassword(), $user->getPassword(),
$password, $password,
@ -42,7 +56,28 @@ class Auth
throw new \Exception(get_lang('InvalidId')); throw new \Exception(get_lang('InvalidId'));
} }
return self::generateToken($user->getId()); return self::encodeToken($user);
}
/**
* @param User $user
*
* @return string
*/
private function encodeToken(User $user): string
{
$secret = $this->container->getParameter('secret');
$time = time();
$payload = [
'iat' => $time,
'exp' => $time + (60 * 60 * 24),
'data' => [
'user' => $user->getId(),
],
];
return JWT::encode($payload, $secret, 'HS384');
} }
/** /**
@ -50,19 +85,20 @@ class Auth
* *
* @throws \Exception * @throws \Exception
*/ */
public static function checkAuthorization(\ArrayObject $context): void public function checkAuthorization(\ArrayObject $context): void
{ {
$header = Container::getRequest()->headers->get('Authorization'); $request = $this->container->get('request_stack')->getCurrentRequest();
$header = $request->headers->get('Authorization');
$token = str_replace(['Bearer ', 'bearer '], '', $header); $token = str_replace(['Bearer ', 'bearer '], '', $header);
if (empty($token)) { if (empty($token)) {
throw new \Exception(get_lang('NotAllowed')); throw new \Exception(get_lang('NotAllowed'));
} }
$tokenData = Auth::getTokenData($token); $tokenData = $this->decodeToken($token);
/** @var User $user */ /** @var User $user */
$user = Container::getUserManager()->find($tokenData['user']); $user = $this->em->find('ChamiloUserBundle:User', $tokenData['user']);
if (!$user) { if (!$user) {
throw new \Exception(get_lang('NotAllowed')); throw new \Exception(get_lang('NotAllowed'));
@ -71,35 +107,14 @@ class Auth
$context->offsetSet('user', $user); $context->offsetSet('user', $user);
} }
/**
* @param int $userId
*
* @return string
*/
private static function generateToken($userId): string
{
$secret = Container::$container->getParameter('secret');
$time = time();
$payload = [
'iat' => $time,
'exp' => $time + (60 * 60 * 24),
'data' => [
'user' => $userId,
],
];
return JWT::encode($payload, $secret, 'HS384');
}
/** /**
* @param string $token * @param string $token
* *
* @return array * @return array
*/ */
private static function getTokenData($token): array private function decodeToken($token): array
{ {
$secret = Container::$container->getParameter('secret'); $secret = $this->container->getParameter('secret');
$jwt = JWT::decode($token, $secret, ['HS384']); $jwt = JWT::decode($token, $secret, ['HS384']);
$data = (array) $jwt->data; $data = (array) $jwt->data;

@ -3,19 +3,22 @@
namespace Chamilo\ApiBundle\GraphQL\Mutation; namespace Chamilo\ApiBundle\GraphQL\Mutation;
use Chamilo\ApiBundle\GraphQL\Auth; use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Overblog\GraphQLBundle\Definition\Argument; use Overblog\GraphQLBundle\Definition\Argument;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface; use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\MutationInterface; use Overblog\GraphQLBundle\Definition\Resolver\MutationInterface;
use Overblog\GraphQLBundle\Error\UserError; use Overblog\GraphQLBundle\Error\UserError;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/** /**
* Class RootMutation. * Class RootMutation.
* *
* @package Chamilo\ApiBundle\GraphQL\Mutation * @package Chamilo\ApiBundle\GraphQL\Mutation
*/ */
class RootMutation implements MutationInterface, AliasedInterface class RootMutation implements MutationInterface, AliasedInterface, ContainerAwareInterface
{ {
use ApiGraphQLTrait;
/** /**
* Returns methods aliases. * Returns methods aliases.
* *
@ -39,7 +42,7 @@ class RootMutation implements MutationInterface, AliasedInterface
public function mutationAuthenticate(Argument $args) public function mutationAuthenticate(Argument $args)
{ {
try { try {
$token = Auth::getUserToken($args['username'], $args['password']); $token = $this->getUserToken($args['username'], $args['password']);
} catch (\Exception $exception) { } catch (\Exception $exception) {
throw new UserError(get_lang('NotAllowed')); throw new UserError(get_lang('NotAllowed'));
} }

@ -3,18 +3,21 @@
namespace Chamilo\ApiBundle\GraphQL\Resolver; namespace Chamilo\ApiBundle\GraphQL\Resolver;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\CoreBundle\Entity\Course; use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Framework\Container;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface; use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface; use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/** /**
* Class CourseResolver. * Class CourseResolver.
* *
* @package Chamilo\ApiBundle\GraphQL\Resolver * @package Chamilo\ApiBundle\GraphQL\Resolver
*/ */
class CourseResolver implements ResolverInterface, AliasedInterface class CourseResolver implements ResolverInterface, AliasedInterface, ContainerAwareInterface
{ {
use ApiGraphQLTrait;
/** /**
* Returns methods aliases. * Returns methods aliases.
* *
@ -49,7 +52,7 @@ class CourseResolver implements ResolverInterface, AliasedInterface
*/ */
public function resolveTeachers(Course $course) public function resolveTeachers(Course $course)
{ {
$courseRepo = Container::getEntityManager()->getRepository('ChamiloCoreBundle:Course'); $courseRepo = $this->em->getRepository('ChamiloCoreBundle:Course');
$teachers = $courseRepo $teachers = $courseRepo
->getSubscribedTeachers($course) ->getSubscribedTeachers($course)
->getQuery() ->getQuery()

@ -3,17 +3,21 @@
namespace Chamilo\ApiBundle\GraphQL\Resolver; namespace Chamilo\ApiBundle\GraphQL\Resolver;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\CoreBundle\Entity\Message; use Chamilo\CoreBundle\Entity\Message;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface; use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface; use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/** /**
* Class MessageResolver. * Class MessageResolver.
* *
* @package Chamilo\ApiBundle\GraphQL\Resolver * @package Chamilo\ApiBundle\GraphQL\Resolver
*/ */
class MessageResolver implements ResolverInterface, AliasedInterface class MessageResolver implements ResolverInterface, AliasedInterface, ContainerAwareInterface
{ {
use ApiGraphQLTrait;
/** /**
* Returns methods aliases. * Returns methods aliases.
* *
@ -47,7 +51,7 @@ class MessageResolver implements ResolverInterface, AliasedInterface
* *
* @return string * @return string
*/ */
public function resolveExcerpt($message, $length = 50) public function resolveExcerpt(Message $message, $length = 50)
{ {
$striped = strip_tags($message->getContent()); $striped = strip_tags($message->getContent());
$replaced = str_replace(["\r\n", "\n"], ' ', $striped); $replaced = str_replace(["\r\n", "\n"], ' ', $striped);

@ -3,19 +3,22 @@
namespace Chamilo\ApiBundle\GraphQL\Resolver; namespace Chamilo\ApiBundle\GraphQL\Resolver;
use Chamilo\ApiBundle\GraphQL\Auth; use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\UserBundle\Entity\User; use Chamilo\UserBundle\Entity\User;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface; use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface; use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface;
use Overblog\GraphQLBundle\Error\UserError; use Overblog\GraphQLBundle\Error\UserError;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/** /**
* Class RootResolver. * Class RootResolver.
* *
* @package Chamilo\ApiBundle\GraphQL\Resolver * @package Chamilo\ApiBundle\GraphQL\Resolver
*/ */
class RootResolver implements ResolverInterface, AliasedInterface class RootResolver implements ResolverInterface, AliasedInterface, ContainerAwareInterface
{ {
use ApiGraphQLTrait;
/** /**
* Returns methods aliases. * Returns methods aliases.
* *
@ -39,7 +42,7 @@ class RootResolver implements ResolverInterface, AliasedInterface
public function resolverViewer(\ArrayObject $context) public function resolverViewer(\ArrayObject $context)
{ {
try { try {
Auth::checkAuthorization($context); $this->checkAuthorization($context);
} catch (\Exception $exception) { } catch (\Exception $exception) {
throw new UserError($exception->getMessage()); throw new UserError($exception->getMessage());
} }

@ -3,26 +3,29 @@
namespace Chamilo\ApiBundle\GraphQL\Resolver; namespace Chamilo\ApiBundle\GraphQL\Resolver;
use Chamilo\ApiBundle\GraphQL\ApiGraphQLTrait;
use Chamilo\CoreBundle\Entity\Course; use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CoreBundle\Repository\MessageRepository; use Chamilo\CoreBundle\Repository\MessageRepository;
use Chamilo\UserBundle\Entity\User; use Chamilo\UserBundle\Entity\User;
use GraphQL\Error\UserError; use GraphQL\Error\UserError;
use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface; use Overblog\GraphQLBundle\Definition\Resolver\AliasedInterface;
use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface; use Overblog\GraphQLBundle\Definition\Resolver\ResolverInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/** /**
* Class UserResolver. * Class UserResolver.
* *
* @package Chamilo\ApiBundle\GraphQL\Resolver * @package Chamilo\ApiBundle\GraphQL\Resolver
*/ */
class UserResolver implements ResolverInterface, AliasedInterface class UserResolver implements ResolverInterface, AliasedInterface, ContainerAwareInterface
{ {
public const IMAGE_SIZE_TINY = 16; public const IMAGE_SIZE_TINY = 16;
public const IMAGE_SIZE_SMALL = 32; public const IMAGE_SIZE_SMALL = 32;
public const IMAGE_SIZE_MEDIUM = 64; public const IMAGE_SIZE_MEDIUM = 64;
public const IMAGE_SIZE_BIG = 128; public const IMAGE_SIZE_BIG = 128;
use ApiGraphQLTrait;
/** /**
* Returns methods aliases. * Returns methods aliases.
* *
@ -48,10 +51,10 @@ class UserResolver implements ResolverInterface, AliasedInterface
*/ */
public function resolveUserPicture(User $user, $size): string public function resolveUserPicture(User $user, $size): string
{ {
$assets = $this->container->get('templating.helper.assets');
$path = $user->getAvatarOrAnonymous((int) $size); $path = $user->getAvatarOrAnonymous((int) $size);
$url = Container::getAsset()->getUrl($path);
return $url; return $assets->getUrl($path);
} }
/** /**
@ -71,7 +74,7 @@ class UserResolver implements ResolverInterface, AliasedInterface
} }
/** @var MessageRepository $messageRepo */ /** @var MessageRepository $messageRepo */
$messageRepo = Container::getEntityManager()->getRepository('ChamiloCoreBundle:Message'); $messageRepo = $this->em->getRepository('ChamiloCoreBundle:Message');
$messages = $messageRepo->getFromLastOneReceived($user, (int) $lastId); $messages = $messageRepo->getFromLastOneReceived($user, (int) $lastId);
return $messages; return $messages;
@ -81,10 +84,6 @@ class UserResolver implements ResolverInterface, AliasedInterface
* @param User $user * @param User $user
* @param \ArrayObject $context * @param \ArrayObject $context
* *
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \Doctrine\ORM\TransactionRequiredException
*
* @return array * @return array
*/ */
public function resolveCourses(User $user, \ArrayObject $context) public function resolveCourses(User $user, \ArrayObject $context)
@ -98,11 +97,11 @@ class UserResolver implements ResolverInterface, AliasedInterface
$courses = []; $courses = [];
$coursesInfo = \CourseManager::get_courses_list_by_user_id($user->getId()); $coursesInfo = \CourseManager::get_courses_list_by_user_id($user->getId());
$em = Container::getEntityManager(); $coursesRepo = $this->em->getRepository('ChamiloCoreBundle:Course');
foreach ($coursesInfo as $courseInfo) { foreach ($coursesInfo as $courseInfo) {
/** @var Course $course */ /** @var Course $course */
$course = $em->find('ChamiloCoreBundle:Course', $courseInfo['real_id']); $course = $coursesRepo->find($courseInfo['real_id']);
if ($course) { if ($course) {
$courses[] = $course; $courses[] = $course;

Loading…
Cancel
Save