check status code on access token fetch
[shpub.git] / src / shpub / Command / Connect.php
index 0c86a8bac811e503bc26c9956220435203d7388a..02f60c7ae6a456a101c8b3cbbef5326596ffbc90 100644 (file)
@@ -16,6 +16,14 @@ class Command_Connect
 
     public function run($server, $user, $newKey, $force)
     {
+        $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
@@ -65,6 +73,7 @@ class Command_Connect
         }
         $this->cfg->hosts[$hostKey] = $host;
         $this->cfg->save();
+        echo "Server configuration $hostKey saved successfully.\n";
     }
 
     protected function fetchAccessToken(
@@ -89,6 +98,12 @@ class Command_Connect
             )
         );
         $res = $req->send();
+        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 ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
             Log::err('Wrong content type in auth verification response');
             exit(2);
@@ -130,9 +145,20 @@ class Command_Connect
 
     protected function getHttpServerData()
     {
-        //FIXME: get IP from SSH_CONNECTION
         $ip   = '127.0.0.1';
         $port = 12345;
+
+        if (isset($_SERVER['SSH_CONNECTION'])) {
+            $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
+            if (count($parts) >= 3) {
+                $ip = $parts[2];
+            }
+        }
+        if (strpos($ip, ':') !== false) {
+            //ipv6
+            $ip = '[' . $ip . ']';
+        }
+
         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
         $socketStr    = 'tcp://' . $ip . ':' . $port;
         return [$redirect_uri, $socketStr];