"connect" works and stores token in config
[shpub.git] / src / shpub / Command / Connect.php
1 <?php
2 namespace shpub;
3
4 /**
5  * @link http://micropub.net/draft/
6  * @link http://indieweb.org/authorization-endpoint
7  */
8 class Command_Connect
9 {
10     public static $client_id = 'http://cweiske.de/shpub.htm';
11
12     public function __construct(Config $cfg)
13     {
14         $this->cfg = $cfg;
15     }
16
17     public function run($server, $user, $newKey, $force)
18     {
19         $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
20         if ($host->endpoints->incomplete()) {
21             $host->server = $server;
22             $this->discoverEndpoints($server, $host->endpoints);
23         }
24
25         list($redirect_uri, $socketStr) = $this->getHttpServerData();
26         $state = time();
27         echo "To authenticate, open the following URL:\n"
28             . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state)
29             . "\n";
30
31         $authParams = $this->startHttpServer($socketStr);
32         if ($authParams['state'] != $state) {
33             Log::err('Wrong "state" parameter value: ' . $authParams['state']);
34             exit(2);
35         }
36         $code    = $authParams['code'];
37         $userUrl = $authParams['me'];
38         $this->verifyAuthCode($host, $code, $state, $redirect_uri, $userUrl);
39
40         $accessToken = $this->fetchAccessToken(
41             $host, $userUrl, $code, $redirect_uri, $state
42         );
43
44         //all fine. update config
45         $host->user  = $userUrl;
46         $host->token = $accessToken;
47
48         if ($newKey != '') {
49             $hostKey = $newKey;
50         } else {
51             $hostKey = $this->cfg->getHostByName($server);
52             if ($hostKey === null) {
53                 $keyBase = parse_url($host->server, PHP_URL_HOST);
54                 $newKey  = $keyBase;
55                 $count = 0;
56                 while (isset($this->cfg->hosts[$newKey])) {
57                     $newKey = $keyBase . ++$count;
58                 }
59                 $hostKey = $newKey;
60             }
61         }
62         $this->cfg->hosts[$hostKey] = $host;
63         $this->cfg->save();
64     }
65
66     protected function fetchAccessToken(
67         $host, $userUrl, $code, $redirect_uri, $state
68     ) {
69         $req = new \HTTP_Request2($host->endpoints->token, 'POST');
70         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
71         $req->setBody(
72             http_build_query(
73                 [
74                     'me'           => $userUrl,
75                     'code'         => $code,
76                     'redirect_uri' => $redirect_uri,
77                     'client_id'    => static::$client_id,
78                     'state'        => $state,
79                 ]
80             )
81         );
82         $res = $req->send();
83         if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
84             Log::err('Wrong content type in auth verification response');
85             exit(2);
86         }
87         parse_str($res->getBody(), $tokenParams);
88         if (!isset($tokenParams['access_token'])) {
89             Log::err('"access_token" missing');
90             exit(2);
91         }
92
93         $accessToken = $tokenParams['access_token'];
94         return $accessToken;
95     }
96
97     protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state)
98     {
99         return $host->endpoints->authorization
100             . '?me=' . urlencode($user)
101             . '&client_id=' . urlencode(static::$client_id)
102             . '&redirect_uri=' . urlencode($redirect_uri)
103             . '&state=' . $state
104             . '&scope=post'
105             . '&response_type=code';
106     }
107
108     protected function getHost($keyOrServer, $force)
109     {
110         $host = new Config_Host();
111         $key = $this->cfg->getHostByName($keyOrServer);
112         if ($key !== null) {
113             $host = $this->cfg->hosts[$key];
114             if (!$force && $host->token != '') {
115                 Log::err('Token already available');
116                 return;
117             }
118         }
119         if ($host->endpoints === null) {
120             $host->endpoints = new Config_Endpoints();
121         }
122         return $host;
123     }
124
125     function discoverEndpoints($url, $cfg)
126     {
127         //TODO: discovery via link headers
128         $sx = simplexml_load_file($url);
129         if ($sx === false) {
130             Log::err('Error loading URL: ' . $url);
131             exit(1);
132         }
133         $sx->registerXPathNamespace('h', 'http://www.w3.org/1999/xhtml');
134
135         $auths = $sx->xpath(
136             '/h:html/h:head/h:link[@rel="authorization_endpoint" and @href]'
137         );
138         if (!count($auths)) {
139             Log::err('No authorization endpoint found');
140             exit(1);
141         }
142         $cfg->authorization = (string) $auths[0]['href'];
143
144         $tokens = $sx->xpath(
145             '/h:html/h:head/h:link[@rel="token_endpoint" and @href]'
146         );
147         if (!count($tokens)) {
148             Log::err('No token endpoint found');
149             exit(1);
150         }
151         $cfg->token = (string) $tokens[0]['href'];
152
153         $mps = $sx->xpath(
154             '/h:html/h:head/h:link[@rel="micropub" and @href]'
155         );
156         if (!count($mps)) {
157             Log::err('No micropub endpoint found');
158             exit(1);
159         }
160         $cfg->micropub = (string) $mps[0]['href'];
161     }
162
163     protected function getHttpServerData()
164     {
165         //FIXME: get IP from SSH_CONNECTION
166         $ip   = '127.0.0.1';
167         $port = 12345;
168         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
169         $socketStr    = 'tcp://' . $ip . ':' . $port;
170         return [$redirect_uri, $socketStr];
171     }
172
173     protected function verifyAuthCode($host, $code, $state, $redirect_uri, $me)
174     {
175         $req = new \HTTP_Request2($host->endpoints->authorization, 'POST');
176         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
177         $req->setBody(
178             http_build_query(
179                 [
180                     'code'         => $code,
181                     'state'        => $state,
182                     'client_id'    => static::$client_id,
183                     'redirect_uri' => $redirect_uri,
184                 ]
185             )
186         );
187         $res = $req->send();
188         if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
189             Log::err('Wrong content type in auth verification response');
190             exit(2);
191         }
192         parse_str($res->getBody(), $verifiedParams);
193         if (!isset($verifiedParams['me'])
194             || $verifiedParams['me'] !== $me
195         ) {
196             Log::err('Non-matching "me" values');
197             exit(2);
198         }
199     }
200
201     protected function startHttpServer($socketStr)
202     {
203         $responseOk = "HTTP/1.0 200 OK\r\n"
204             . "Content-Type: text/plain\r\n"
205             . "\r\n"
206             . "Ok. You may close this tab and return to the shell.\r\n";
207         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
208             . "Content-Type: text/plain\r\n"
209             . "\r\n"
210             . "Bad Request\r\n";
211
212         //5 minutes should be enough for the user to confirm
213         ini_set('default_socket_timeout', 60 * 5);
214         $server = stream_socket_server($socketStr, $errno, $errstr);
215         if (!$server) {
216             Log::err('Error starting HTTP server');
217             return false;
218         }
219
220         do {
221             $sock = stream_socket_accept($server);
222             if (!$sock) {
223                 Log::err('Error accepting socket connection');
224                 exit(1);
225             }
226
227             $headers = [];
228             $body    = null;
229             $content_length = 0;
230             //read request headers
231             while (false !== ($line = trim(fgets($sock)))) {
232                 if ('' === $line) {
233                     break;
234                 }
235                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
236                 if (preg_match($regex, $line, $matches)) {
237                     $content_length = (int) $matches[1];
238                 }
239                 $headers[] = $line;
240             }
241
242             // read content/body
243             if ($content_length > 0) {
244                 $body = fread($sock, $content_length);
245             }
246
247             // send response
248             list($method, $url, $httpver) = explode(' ', $headers[0]);
249             if ($method == 'GET') {
250                 $parts = parse_url($url);
251                 if (isset($parts['path']) && $parts['path'] == '/callback'
252                     && isset($parts['query'])
253                 ) {
254                     parse_str($parts['query'], $query);
255                     if (isset($query['code'])
256                         && isset($query['state'])
257                         && isset($query['me'])
258                     ) {
259                         fwrite($sock, $responseOk);
260                         fclose($sock);
261                         return $query;
262                     }
263                 }
264             }
265
266             fwrite($sock, $responseErr);
267             fclose($sock);
268         } while (true);
269     }
270 }
271 ?>