OAuthClientCreateCommand.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Base\OAuthServerBundle\Command;
  3. use \Base\OAuthServerBundle\Entity\OAuthClient;
  4. use \FOS\OAuthServerBundle\Entity\ClientManager;
  5. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  6. use Symfony\Component\Console\Input\InputInterface;
  7. use Symfony\Component\Console\Output\OutputInterface;
  8. use Symfony\Component\Console\Input\InputOption;
  9. class OAuthClientCreateCommand extends ContainerAwareCommand
  10. {
  11. protected function configure()
  12. {
  13. $this
  14. ->setName('oauth:client:create')
  15. ->setDescription('Create OAuht client')
  16. ->setHelp('This command allows you to create an OAuth client')
  17. ->addOption(
  18. 'redirect_uri', null, InputOption::VALUE_REQUIRED, 'OAuth Redirect URI', 'http://127.0.0.1/ftth/app_dev.php/login_check'
  19. )
  20. ->addOption(
  21. 'client_id', null, InputOption::VALUE_OPTIONAL, 'OAuth Client random Id'
  22. )
  23. ->addOption(
  24. 'client_secret', null, InputOption::VALUE_OPTIONAL, 'OAuth Client random Secret'
  25. );
  26. }
  27. /**
  28. * @param InputInterface $input
  29. * @param OutputInterface $output
  30. */
  31. protected function execute(InputInterface $input, OutputInterface $output)
  32. {
  33. $redirectUri = $input->getOption('redirect_uri');
  34. $random = $input->getOption('client_id');
  35. $secret = $input->getOption('client_secret');
  36. $client = $this->createClient($redirectUri, $random, $secret);
  37. $output->writeln('#OAuth client successfully generated!');
  38. $output->writeln('<info>OAUTH_CLIENT_ID</info>=' . $client->getPublicId());
  39. $output->writeln('<info>OAUTH_CLIENT_SECRET</info>=' . $client->getSecret());
  40. }
  41. /**
  42. * @param string $redirectUri
  43. * @param string $random
  44. * @param string $secret
  45. *
  46. * @return OAuthClient
  47. */
  48. protected function createClient($redirectUri, $random = null, $secret = null)
  49. {
  50. /* @var $clientManager ClientManager */
  51. $clientManager = $this->getContainer()->get('fos_oauth_server.client_manager.default');
  52. $em = $this->getContainer()->get('doctrine')->getEntityManager();
  53. $client = $em->getRepository('BaseOAuthServerBundle:OAuthClient')->findOneByRedirectUri($redirectUri);
  54. if (!$client) {
  55. /* @var $client OAuthClient */
  56. $client = $clientManager->createClient();
  57. if ($random) {
  58. $client->setRandomId($random);
  59. }
  60. if ($secret) {
  61. $client->setSecret($secret);
  62. }
  63. $client->setRedirectUris(array(
  64. $redirectUri,
  65. ));
  66. $client->setAllowedGrantTypes(array_keys(OAuthClient::getGrantTypesChoices()));
  67. $clientManager->updateClient($client);
  68. }
  69. return $client;
  70. }
  71. }