Split off content type comments
[shpub.git] / src / shpub / Command / Connect.php
index 2e7e266ffe810ca7dba4f93f1ce54fbd2b5bb91b..e92077779c8abce3eb16d17d13649b1d26a53bec 100644 (file)
@@ -2,8 +2,13 @@
 namespace shpub;
 
 /**
- * @link http://micropub.net/draft/
- * @link http://indieweb.org/authorization-endpoint
+ * Connect to a micropub server to get an access token.
+ *
+ * @author  Christian Weiske <cweiske@cweiske.de>
+ * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
+ * @link    http://cweiske.de/shpub.htm
+ * @link    http://micropub.net/draft/
+ * @link    http://indieweb.org/authorization-endpoint
  */
 class Command_Connect
 {
@@ -14,19 +19,80 @@ class Command_Connect
         $this->cfg = $cfg;
     }
 
-    public function run($server, $user, $newKey, $force)
+    public static function opts(\Console_CommandLine $optParser)
     {
+        $cmd = $optParser->addCommand('connect');
+        $cmd->description = 'Obtain access token from a micropub server';
+        $cmd->addOption(
+            'force',
+            array(
+                'short_name'  => '-f',
+                'long_name'   => '--force-update',
+                'description' => 'Force token update if token already available',
+                'action'      => 'StoreTrue',
+                'default'     => false,
+            )
+        );
+        $cmd->addOption(
+            'scope',
+            array(
+                'short_name'  => '-s',
+                'long_name'   => '--scope',
+                'description' => 'Space-separated list of scopes to request'
+                    . ' (default: create)',
+                'action'      => 'StoreString',
+                'default'     => 'create',
+            )
+        );
+        $cmd->addArgument(
+            'server',
+            [
+                'optional'    => false,
+                'description' => 'Server URL',
+            ]
+        );
+        $cmd->addArgument(
+            'user',
+            [
+                'optional'    => true,
+                'description' => 'User URL',
+            ]
+        );
+        $cmd->addArgument(
+            'key',
+            [
+                'optional'    => true,
+                'description' => 'Short name (key)',
+            ]
+        );
+    }
+
+    public function run($server, $user, $newKey, $force, $scope)
+    {
+        $server = Validator::url($server, 'server');
+        if ($user === null) {
+            //indieweb: homepage is your identity
+            $user = $server;
+        } else {
+            $user = Validator::url($user, 'user');
+        }
+
         $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
+        if ($host === null) {
+            //already taken
+            return;
+        }
         if ($host->endpoints->incomplete()) {
             $host->server = $server;
-            $this->discoverEndpoints($server, $host->endpoints);
+            $host->loadEndpoints();
         }
 
         list($redirect_uri, $socketStr) = $this->getHttpServerData();
         $state = time();
-        echo "To authenticate, open the following URL:\n"
-            . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state)
-            . "\n";
+        Log::msg(
+            "To authenticate, open the following URL:\n"
+            . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
+        );
 
         $authParams = $this->startHttpServer($socketStr);
         if ($authParams['state'] != $state) {
@@ -35,7 +101,6 @@ class Command_Connect
         }
         $code    = $authParams['code'];
         $userUrl = $authParams['me'];
-        $this->verifyAuthCode($host, $code, $state, $redirect_uri, $userUrl);
 
         $accessToken = $this->fetchAccessToken(
             $host, $userUrl, $code, $redirect_uri, $state
@@ -61,16 +126,23 @@ class Command_Connect
         }
         $this->cfg->hosts[$hostKey] = $host;
         $this->cfg->save();
+        Log::info("Server configuration $hostKey saved successfully.");
     }
 
     protected function fetchAccessToken(
         $host, $userUrl, $code, $redirect_uri, $state
     ) {
         $req = new \HTTP_Request2($host->endpoints->token, 'POST');
+        if (version_compare(PHP_VERSION, '5.6.0', '<')) {
+            //correct ssl validation on php 5.5 is a pain, so disable
+            $req->setConfig('ssl_verify_host', false);
+            $req->setConfig('ssl_verify_peer', false);
+        }
         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
         $req->setBody(
             http_build_query(
                 [
+                    'grant_type'   => 'authorization_code',
                     'me'           => $userUrl,
                     'code'         => $code,
                     'redirect_uri' => $redirect_uri,
@@ -80,11 +152,20 @@ class Command_Connect
             )
         );
         $res = $req->send();
-        if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
+        if (intval($res->getStatus() / 100) !== 2) {
+            Log::err('Failed to fetch access token');
+            Log::err('Server responded with HTTP status code ' . $res->getStatus());
+            Log::err($res->getBody());
+            exit(2);
+        }
+        if (Util::getMimeType($res) == 'application/x-www-form-urlencoded') {
+            parse_str($res->getBody(), $tokenParams);
+        } elseif (Util::getMimeType($res) == 'application/json') {
+            $tokenParams = json_decode($res->getBody(), true);
+        } else {
             Log::err('Wrong content type in auth verification response');
             exit(2);
         }
-        parse_str($res->getBody(), $tokenParams);
         if (!isset($tokenParams['access_token'])) {
             Log::err('"access_token" missing');
             exit(2);
@@ -94,14 +175,14 @@ class Command_Connect
         return $accessToken;
     }
 
-    protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state)
+    protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
     {
         return $host->endpoints->authorization
             . '?me=' . urlencode($user)
             . '&client_id=' . urlencode(static::$client_id)
             . '&redirect_uri=' . urlencode($redirect_uri)
             . '&state=' . $state
-            . '&scope=post'
+            . '&scope=' . urlencode($scope)
             . '&response_type=code';
     }
 
@@ -116,88 +197,30 @@ class Command_Connect
                 return;
             }
         }
-        if ($host->endpoints === null) {
-            $host->endpoints = new Config_Endpoints();
-        }
         return $host;
     }
 
-    function discoverEndpoints($url, $cfg)
+    protected function getHttpServerData()
     {
-        //TODO: discovery via link headers
-        $sx = simplexml_load_file($url);
-        if ($sx === false) {
-            Log::err('Error loading URL: ' . $url);
-            exit(1);
-        }
-        $sx->registerXPathNamespace('h', 'http://www.w3.org/1999/xhtml');
-
-        $auths = $sx->xpath(
-            '/h:html/h:head/h:link[@rel="authorization_endpoint" and @href]'
-        );
-        if (!count($auths)) {
-            Log::err('No authorization endpoint found');
-            exit(1);
-        }
-        $cfg->authorization = (string) $auths[0]['href'];
+        $ip   = '127.0.0.1';
+        $port = 12345;
 
-        $tokens = $sx->xpath(
-            '/h:html/h:head/h:link[@rel="token_endpoint" and @href]'
-        );
-        if (!count($tokens)) {
-            Log::err('No token endpoint found');
-            exit(1);
+        if (isset($_SERVER['SSH_CONNECTION'])) {
+            $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
+            if (count($parts) >= 3) {
+                $ip = $parts[2];
+            }
         }
-        $cfg->token = (string) $tokens[0]['href'];
-
-        $mps = $sx->xpath(
-            '/h:html/h:head/h:link[@rel="micropub" and @href]'
-        );
-        if (!count($mps)) {
-            Log::err('No micropub endpoint found');
-            exit(1);
+        if (strpos($ip, ':') !== false) {
+            //ipv6
+            $ip = '[' . $ip . ']';
         }
-        $cfg->micropub = (string) $mps[0]['href'];
-    }
 
-    protected function getHttpServerData()
-    {
-        //FIXME: get IP from SSH_CONNECTION
-        $ip   = '127.0.0.1';
-        $port = 12345;
         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
         $socketStr    = 'tcp://' . $ip . ':' . $port;
         return [$redirect_uri, $socketStr];
     }
 
-    protected function verifyAuthCode($host, $code, $state, $redirect_uri, $me)
-    {
-        $req = new \HTTP_Request2($host->endpoints->authorization, 'POST');
-        $req->setHeader('Content-Type: application/x-www-form-urlencoded');
-        $req->setBody(
-            http_build_query(
-                [
-                    'code'         => $code,
-                    'state'        => $state,
-                    'client_id'    => static::$client_id,
-                    'redirect_uri' => $redirect_uri,
-                ]
-            )
-        );
-        $res = $req->send();
-        if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
-            Log::err('Wrong content type in auth verification response');
-            exit(2);
-        }
-        parse_str($res->getBody(), $verifiedParams);
-        if (!isset($verifiedParams['me'])
-            || $verifiedParams['me'] !== $me
-        ) {
-            Log::err('Non-matching "me" values');
-            exit(2);
-        }
-    }
-
     protected function startHttpServer($socketStr)
     {
         $responseOk = "HTTP/1.0 200 OK\r\n"