5 * @link http://micropub.net/draft/
6 * @link http://indieweb.org/authorization-endpoint
10 public static $client_id = 'http://cweiske.de/shpub.htm';
12 public function __construct(Config $cfg)
17 public function run($server, $user, $newKey, $force)
19 $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
20 if ($host->endpoints->incomplete()) {
21 $host->server = $server;
22 $this->discoverEndpoints($server, $host->endpoints);
25 list($redirect_uri, $socketStr) = $this->getHttpServerData();
27 echo "To authenticate, open the following URL:\n"
28 . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state)
31 $authParams = $this->startHttpServer($socketStr);
32 if ($authParams['state'] != $state) {
33 Log::err('Wrong "state" parameter value: ' . $authParams['state']);
36 $code = $authParams['code'];
37 $userUrl = $authParams['me'];
38 $this->verifyAuthCode($host, $code, $state, $redirect_uri, $userUrl);
40 $accessToken = $this->fetchAccessToken(
41 $host, $userUrl, $code, $redirect_uri, $state
44 //all fine. update config
45 $host->user = $userUrl;
46 $host->token = $accessToken;
51 $hostKey = $this->cfg->getHostByName($server);
52 if ($hostKey === null) {
53 $keyBase = parse_url($host->server, PHP_URL_HOST);
56 while (isset($this->cfg->hosts[$newKey])) {
57 $newKey = $keyBase . ++$count;
62 $this->cfg->hosts[$hostKey] = $host;
66 protected function fetchAccessToken(
67 $host, $userUrl, $code, $redirect_uri, $state
69 $req = new \HTTP_Request2($host->endpoints->token, 'POST');
70 $req->setHeader('Content-Type: application/x-www-form-urlencoded');
76 'redirect_uri' => $redirect_uri,
77 'client_id' => static::$client_id,
83 if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
84 Log::err('Wrong content type in auth verification response');
87 parse_str($res->getBody(), $tokenParams);
88 if (!isset($tokenParams['access_token'])) {
89 Log::err('"access_token" missing');
93 $accessToken = $tokenParams['access_token'];
97 protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state)
99 return $host->endpoints->authorization
100 . '?me=' . urlencode($user)
101 . '&client_id=' . urlencode(static::$client_id)
102 . '&redirect_uri=' . urlencode($redirect_uri)
105 . '&response_type=code';
108 protected function getHost($keyOrServer, $force)
110 $host = new Config_Host();
111 $key = $this->cfg->getHostByName($keyOrServer);
113 $host = $this->cfg->hosts[$key];
114 if (!$force && $host->token != '') {
115 Log::err('Token already available');
119 if ($host->endpoints === null) {
120 $host->endpoints = new Config_Endpoints();
125 function discoverEndpoints($url, $cfg)
127 //TODO: discovery via link headers
128 $sx = simplexml_load_file($url);
130 Log::err('Error loading URL: ' . $url);
133 $sx->registerXPathNamespace('h', 'http://www.w3.org/1999/xhtml');
136 '/h:html/h:head/h:link[@rel="authorization_endpoint" and @href]'
138 if (!count($auths)) {
139 Log::err('No authorization endpoint found');
142 $cfg->authorization = (string) $auths[0]['href'];
144 $tokens = $sx->xpath(
145 '/h:html/h:head/h:link[@rel="token_endpoint" and @href]'
147 if (!count($tokens)) {
148 Log::err('No token endpoint found');
151 $cfg->token = (string) $tokens[0]['href'];
154 '/h:html/h:head/h:link[@rel="micropub" and @href]'
157 Log::err('No micropub endpoint found');
160 $cfg->micropub = (string) $mps[0]['href'];
163 protected function getHttpServerData()
165 //FIXME: get IP from SSH_CONNECTION
168 $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
169 $socketStr = 'tcp://' . $ip . ':' . $port;
170 return [$redirect_uri, $socketStr];
173 protected function verifyAuthCode($host, $code, $state, $redirect_uri, $me)
175 $req = new \HTTP_Request2($host->endpoints->authorization, 'POST');
176 $req->setHeader('Content-Type: application/x-www-form-urlencoded');
182 'client_id' => static::$client_id,
183 'redirect_uri' => $redirect_uri,
188 if ($res->getHeader('content-type') != 'application/x-www-form-urlencoded') {
189 Log::err('Wrong content type in auth verification response');
192 parse_str($res->getBody(), $verifiedParams);
193 if (!isset($verifiedParams['me'])
194 || $verifiedParams['me'] !== $me
196 Log::err('Non-matching "me" values');
201 protected function startHttpServer($socketStr)
203 $responseOk = "HTTP/1.0 200 OK\r\n"
204 . "Content-Type: text/plain\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"
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);
216 Log::err('Error starting HTTP server');
221 $sock = stream_socket_accept($server);
223 Log::err('Error accepting socket connection');
230 //read request headers
231 while (false !== ($line = trim(fgets($sock)))) {
235 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
236 if (preg_match($regex, $line, $matches)) {
237 $content_length = (int) $matches[1];
243 if ($content_length > 0) {
244 $body = fread($sock, $content_length);
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'])
254 parse_str($parts['query'], $query);
255 if (isset($query['code'])
256 && isset($query['state'])
257 && isset($query['me'])
259 fwrite($sock, $responseOk);
266 fwrite($sock, $responseErr);