chill-bundles/src/Bundle/ChillCalendarBundle/Command/AzureGetMachineAccessTokenCommand.php

83 lines
2.6 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\CalendarBundle\Command;
use Chill\CalendarBundle\Synchro\Connector\MSGraph\MachineTokenStorage;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use TheNetworg\OAuth2\Client\Provider\Azure;
use const PHP_URL_QUERY;
class AzureGetMachineAccessTokenCommand extends Command
{
private Azure $azure;
private ClientRegistry $clientRegistry;
private MachineTokenStorage $machineTokenStorage;
public function __construct(Azure $azure, ClientRegistry $clientRegistry, MachineTokenStorage $machineTokenStorage)
{
parent::__construct('chill:calendar:get-access-token');
$this->azure = $azure;
$this->clientRegistry = $clientRegistry;
$this->machineTokenStorage = $machineTokenStorage;
}
protected function configure()
{
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->azure->scope = ['https://graph.microsoft.com/.default'];
$authorizationUrl = explode('?', $this->azure->getAuthorizationUrl(['prompt' => 'consent']));
// replace the first part by the admin consent authorization url
$authorizationUrl[0] = strtr('https://login.microsoftonline.com/{tenant}/adminconsent', ['{tenant}' => $this->azure->tenant]);
$output->writeln('Go to the url');
$output->writeln(implode('?', $authorizationUrl));
$output->writeln('Authenticate as admin, and copy-paste the url you will reach');
// not necessary ?
$helper = $this->getHelper('question');
$question = new Question('Paste here the return url after you completed the admin consent');
$returnUrl = $helper->ask($input, $output, $question);
$keyValues = explode('&', parse_url($returnUrl, PHP_URL_QUERY));
$params = [];
foreach ($keyValues as $str) {
$strs = explode('=', $str);
$params[$strs[0]] = $strs[1];
}
dump($params);
$token = $this->azure->getAccessToken('client_credentials', [
'scope' => $this->azure->scope,
]);
$this->machineTokenStorage->storeToken($token);
$output->writeln('machine access token acquired and saved!');
return 0;
}
}