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:
$debug: '%kernel.debug%'
Chamilo\ApiBundle\GraphQL\Resolver\:
resource: '../src/ApiBundle/GraphQL/Resolver'
tags: ['overblog_graphql.resolver']
Chamilo\ApiBundle\GraphQL\:
resource: '../src/ApiBundle/GraphQL/*'
exclude: '../src/ApiBundle/GraphQL/{Resources}'
tags: ['overblog_graphql.resolver', 'overblog_graphql.mutation']
Chamilo\ApiBundle\GraphQL\Mutation\:
resource: '../src/ApiBundle/GraphQL/Mutation'
tags: ['overblog_graphql.mutation']
Doctrine\ORM\EntityManager: "@doctrine.orm.default_entity_manager"
sylius_settings:
driver: doctrine/orm

@ -3,17 +3,31 @@
namespace Chamilo\ApiBundle\GraphQL;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\UserBundle\Entity\User;
use Doctrine\ORM\EntityManager;
use Firebase\JWT\JWT;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
/**
* Class Auth.
*
* Trait ApiGraphQLTrait
* @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 $password
@ -22,16 +36,16 @@ class Auth
*
* @return string
*/
public function getUserToken($username, $password): string
private function getUserToken($username, $password): string
{
/** @var User $user */
$user = Container::getUserManager()->findUserBy(['username' => $username]);
$user = $this->em->getRepository('ChamiloUserBundle:User')->findOneBy(['username' => $username]);
if (!$user) {
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(
$user->getPassword(),
$password,
@ -42,7 +56,28 @@ class Auth
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
*/
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);
if (empty($token)) {
throw new \Exception(get_lang('NotAllowed'));
}
$tokenData = Auth::getTokenData($token);
$tokenData = $this->decodeToken($token);
/** @var User $user */
$user = Container::getUserManager()->find($tokenData['user']);
$user = $this->em->find('ChamiloUserBundle:User', $tokenData['user']);
if (!$user) {
throw new \Exception(get_lang('NotAllowed'));
@ -71,35 +107,14 @@ class Auth
$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
*
* @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']);
$data = (array) $jwt->data;

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

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

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

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

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

Loading…
Cancel
Save