5 * Connect to a micropub server to get an access token.
7 * @author Christian Weiske <cweiske@cweiske.de>
8 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
9 * @link http://cweiske.de/shpub.htm
10 * @link http://micropub.net/draft/
11 * @link http://indieweb.org/authorization-endpoint
15 public static $client_id = 'http://cweiske.de/shpub.htm';
17 public function __construct(Config $cfg)
22 public static function opts(\Console_CommandLine $optParser)
24 $cmd = $optParser->addCommand('connect');
25 $cmd->description = 'Obtain access token from a micropub server';
30 'long_name' => '--force-update',
31 'description' => 'Force token update if token already available',
32 'action' => 'StoreTrue',
40 'long_name' => '--scope',
41 'description' => 'Space-separated list of scopes to request'
42 . ' (default: create)',
43 'action' => 'StoreString',
44 'default' => 'create',
51 'description' => 'Server URL',
58 'description' => 'User URL',
65 'description' => 'Short name (key)',
70 public function run($server, $user, $newKey, $force, $scope)
72 $server = Validator::url($server, 'server');
74 //indieweb: homepage is your identity
77 $user = Validator::url($user, 'user');
80 $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
85 if ($host->endpoints->incomplete()) {
86 $host->server = $server;
87 $host->loadEndpoints();
90 list($redirect_uri, $socketStr) = $this->getHttpServerData();
93 "To authenticate, open the following URL:\n"
94 . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
97 $authParams = $this->startHttpServer($socketStr);
98 if ($authParams['state'] != $state) {
99 Log::err('Wrong "state" parameter value: ' . $authParams['state']);
102 $code = $authParams['code'];
103 $userUrl = $authParams['me'];
105 $accessToken = $this->fetchAccessToken(
106 $host, $userUrl, $code, $redirect_uri, $state
109 //all fine. update config
110 $host->user = $userUrl;
111 $host->token = $accessToken;
116 $hostKey = $this->cfg->getHostByName($server);
117 if ($hostKey === null) {
118 $keyBase = parse_url($host->server, PHP_URL_HOST);
121 while (isset($this->cfg->hosts[$newKey])) {
122 $newKey = $keyBase . ++$count;
127 $this->cfg->hosts[$hostKey] = $host;
129 Log::info("Server configuration $hostKey saved successfully.");
132 protected function fetchAccessToken(
133 $host, $userUrl, $code, $redirect_uri, $state
135 $req = new \HTTP_Request2($host->endpoints->token, 'POST');
136 if (version_compare(PHP_VERSION, '5.6.0', '<')) {
137 //correct ssl validation on php 5.5 is a pain, so disable
138 $req->setConfig('ssl_verify_host', false);
139 $req->setConfig('ssl_verify_peer', false);
141 $req->setHeader('Content-Type: application/x-www-form-urlencoded');
145 'grant_type' => 'authorization_code',
148 'redirect_uri' => $redirect_uri,
149 'client_id' => static::$client_id,
155 if (intval($res->getStatus() / 100) !== 2) {
156 Log::err('Failed to fetch access token');
157 Log::err('Server responded with HTTP status code ' . $res->getStatus());
158 Log::err($res->getBody());
161 if (Util::getMimeType($res) == 'application/x-www-form-urlencoded') {
162 parse_str($res->getBody(), $tokenParams);
163 } elseif (Util::getMimeType($res) == 'application/json') {
164 $tokenParams = json_decode($res->getBody(), true);
166 Log::err('Wrong content type in auth verification response');
169 if (!isset($tokenParams['access_token'])) {
170 Log::err('"access_token" missing');
174 $accessToken = $tokenParams['access_token'];
178 protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
180 $sep = strpos($host->endpoints->authorization, '?') === false
182 return $host->endpoints->authorization
183 . $sep . 'me=' . urlencode($user)
184 . '&client_id=' . urlencode(static::$client_id)
185 . '&redirect_uri=' . urlencode($redirect_uri)
186 . '&state=' . urlencode($state)
187 . '&scope=' . urlencode($scope)
188 . '&response_type=code';
191 protected function getHost($keyOrServer, $force)
193 $host = new Config_Host();
194 $key = $this->cfg->getHostByName($keyOrServer);
196 $host = $this->cfg->hosts[$key];
197 if (!$force && $host->token != '') {
198 Log::err('Token already available');
205 protected function getHttpServerData()
210 if (isset($_SERVER['SSH_CONNECTION'])) {
211 $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
212 if (count($parts) >= 3) {
216 if (strpos($ip, ':') !== false) {
218 $ip = '[' . $ip . ']';
221 $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
222 $socketStr = 'tcp://' . $ip . ':' . $port;
223 return [$redirect_uri, $socketStr];
226 protected function startHttpServer($socketStr)
228 $responseOk = "HTTP/1.0 200 OK\r\n"
229 . "Content-Type: text/plain\r\n"
231 . "Ok. You may close this tab and return to the shell.\r\n";
232 $responseErr = "HTTP/1.0 400 Bad Request\r\n"
233 . "Content-Type: text/plain\r\n"
237 //5 minutes should be enough for the user to confirm
238 ini_set('default_socket_timeout', 60 * 5);
239 $server = stream_socket_server($socketStr, $errno, $errstr);
241 Log::err('Error starting HTTP server');
246 $sock = stream_socket_accept($server);
248 Log::err('Error accepting socket connection');
255 //read request headers
256 while (false !== ($line = trim(fgets($sock)))) {
260 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
261 if (preg_match($regex, $line, $matches)) {
262 $content_length = (int) $matches[1];
268 if ($content_length > 0) {
269 $body = fread($sock, $content_length);
273 list($method, $url, $httpver) = explode(' ', $headers[0]);
274 if ($method == 'GET') {
275 $parts = parse_url($url);
276 if (isset($parts['path']) && $parts['path'] == '/callback'
277 && isset($parts['query'])
279 parse_str($parts['query'], $query);
280 if (isset($query['code'])
281 && isset($query['state'])
283 fwrite($sock, $responseOk);
290 fwrite($sock, $responseErr);