zend-blog-3-backend
115 строк · 3.1 Кб
1<?php
2/**
3* Created by PhpStorm.
4* User: morontt
5* Date: 17.06.15
6* Time: 1:23
7*/
8
9namespace App\Command;
10
11use App\Entity\SystemParameters;
12use App\OAuth2\Client\DropboxProvider;
13use App\Service\SystemParametersStorage;
14use Doctrine\ORM\ORMException;
15use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
16use Symfony\Component\Console\Command\Command;
17use Symfony\Component\Console\Input\InputInterface;
18use Symfony\Component\Console\Output\OutputInterface;
19use Symfony\Component\Console\Question\Question;
20
21class DropboxAuthCommand extends Command
22{
23/**
24* @var string
25*/
26private string $key;
27
28/**
29* @var string
30*/
31private string $secret;
32
33/**
34* @var SystemParametersStorage
35*/
36private SystemParametersStorage $storage;
37
38/**
39* @param SystemParametersStorage $storage
40* @param string $dropboxKey
41* @param string $dropboxSecret
42*/
43public function __construct(SystemParametersStorage $storage, string $dropboxKey, string $dropboxSecret)
44{
45parent::__construct();
46
47$this->key = $dropboxKey;
48$this->secret = $dropboxSecret;
49$this->storage = $storage;
50}
51
52protected function configure(): void
53{
54$this
55->setName('mtt:dropbox:auth')
56->setDescription('Dropbox command-line authorization');
57}
58
59/**
60* @param InputInterface $input
61* @param OutputInterface $output
62*
63* @throws IdentityProviderException
64* @throws ORMException
65*
66* @return int
67*/
68public function execute(InputInterface $input, OutputInterface $output): int
69{
70$provider = new DropboxProvider([
71'clientId' => $this->key,
72'clientSecret' => $this->secret,
73]);
74
75$authorizationUrl = $provider->getAuthorizationUrl();
76
77$output->writeln(sprintf("\n1. Go to: %s", $authorizationUrl));
78$output->writeln('2. Click <comment>"Allow"</comment> (you might have to log in first).');
79$output->writeln("3. Copy the authorization code.\n");
80
81$dialog = $this->getHelper('question');
82$question = new Question('Enter the authorization code here: ');
83$question->setValidator(function ($answer) {
84if (!trim($answer)) {
85throw new \RuntimeException('Empty code :(');
86}
87
88return $answer;
89});
90$question->setMaxAttempts(3);
91
92$authCode = trim($dialog->ask($input, $output, $question));
93
94$accessToken = $provider->getAccessToken('authorization_code', [
95'code' => $authCode,
96]);
97
98$output->writeln("\nAuthorization complete.");
99$output->writeln(sprintf('Access Token: <comment>%s</comment>', $accessToken->getToken()));
100
101$this->saveAccessToken($accessToken->getToken());
102
103return 0;
104}
105
106/**
107* @param string $accessToken
108*
109* @throws ORMException
110*/
111protected function saveAccessToken(string $accessToken): void
112{
113$this->storage->saveParameter(SystemParameters::DROPBOX_TOKEN, $accessToken, true);
114}
115}
116