You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

347 lines
12 KiB

  1. <?php
  2. function buildRedirectURI() {
  3. return Config::$base_url . 'auth/callback';
  4. }
  5. function clientID($pebble=false) {
  6. if($pebble) {
  7. return Config::$base_url . 'pebble';
  8. } else {
  9. return trim(Config::$base_url, '/'); // remove trailing slash from client_id
  10. }
  11. }
  12. function build_url($parsed_url) {
  13. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  14. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  15. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  16. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  17. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  18. $pass = ($user || $pass) ? "$pass@" : '';
  19. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  20. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  21. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  22. return "$scheme$user$pass$host$port$path$query$fragment";
  23. }
  24. // Input: Any URL or string like "aaronparecki.com"
  25. // Output: Normlized URL (default to http if no scheme, force "/" path)
  26. // or return false if not a valid URL (has query string params, etc)
  27. function normalizeMeURL($url) {
  28. $me = parse_url($url);
  29. if(array_key_exists('path', $me) && $me['path'] == '')
  30. return false;
  31. // parse_url returns just "path" for naked domains
  32. if(count($me) == 1 && array_key_exists('path', $me)) {
  33. $me['host'] = $me['path'];
  34. unset($me['path']);
  35. }
  36. if(!array_key_exists('scheme', $me))
  37. $me['scheme'] = 'http';
  38. if(!array_key_exists('path', $me))
  39. $me['path'] = '/';
  40. // Invalid scheme
  41. if(!in_array($me['scheme'], array('http','https')))
  42. return false;
  43. // Invalid path
  44. // if($me['path'] != '/')
  45. // return false;
  46. // query and fragment not allowed
  47. if(array_key_exists('query', $me) || array_key_exists('fragment', $me))
  48. return false;
  49. return build_url($me);
  50. }
  51. function hostname($url) {
  52. return parse_url($url, PHP_URL_HOST);
  53. }
  54. function add_hcard_info($user, $hCard) {
  55. if($user && $hCard) {
  56. // Update the user's h-card info if present
  57. if(BarnabyWalters\Mf2\hasProp($hCard, 'name'))
  58. $user->name = BarnabyWalters\Mf2\getPlaintext($hCard, 'name');
  59. if(BarnabyWalters\Mf2\hasProp($hCard, 'photo'))
  60. $user->photo_url = BarnabyWalters\Mf2\getPlaintext($hCard, 'photo');
  61. }
  62. }
  63. $app->get('/', function($format='html') use($app) {
  64. $res = $app->response();
  65. ob_start();
  66. render('index', array(
  67. 'title' => 'Teacup',
  68. 'meta' => ''
  69. ));
  70. $html = ob_get_clean();
  71. $res->body($html);
  72. });
  73. $app->get('/auth/start', function() use($app) {
  74. $req = $app->request();
  75. $params = $req->params();
  76. // the "me" parameter is user input, and may be in a couple of different forms:
  77. // aaronparecki.com http://aaronparecki.com http://aaronparecki.com/
  78. // Normlize the value now (move this into a function in IndieAuth\Client later)
  79. if(!array_key_exists('me', $params) || !($me = normalizeMeURL($params['me']))) {
  80. $html = render('auth_error', array(
  81. 'title' => 'Sign In',
  82. 'error' => 'Invalid "me" Parameter',
  83. 'errorDescription' => 'The URL you entered, "<strong>' . $params['me'] . '</strong>" is not valid.'
  84. ));
  85. $app->response()->body($html);
  86. return;
  87. }
  88. $authorizationEndpoint = IndieAuth\Client::discoverAuthorizationEndpoint($me);
  89. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  90. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  91. $hCard = IndieAuth\Client::representativeHCard($me);
  92. // Generate a "state" parameter for the request
  93. $state = IndieAuth\Client::generateStateParameter();
  94. $_SESSION['auth_state'] = $state;
  95. // Store whether to return to the Pebble settings tab or the new post page after signing in
  96. if(array_key_exists('redirect', $params) && $params['redirect'] == 'settings') {
  97. $_SESSION['redirect_after_login'] = '/pebble/settings/finished';
  98. } else {
  99. $_SESSION['redirect_after_login'] = '/new';
  100. }
  101. $pebble = k($params, 'pebble');
  102. $_SESSION['pebble'] = $pebble;
  103. if($tokenEndpoint && $micropubEndpoint && $authorizationEndpoint) {
  104. $scope = 'post';
  105. $authorizationURL = IndieAuth\Client::buildAuthorizationURL($authorizationEndpoint, $me, buildRedirectURI(), clientID($pebble), $state, $scope);
  106. } else {
  107. $authorizationURL = IndieAuth\Client::buildAuthorizationURL('https://indieauth.com/auth', $me, buildRedirectURI(), clientID($pebble), $state);
  108. }
  109. // If the user has already signed in before and has a micropub access token, skip
  110. // the debugging screens and redirect immediately to the auth endpoint.
  111. // This will still generate a new access token when they finish logging in.
  112. $user = ORM::for_table('users')->where('url', hostname($me))->find_one();
  113. if($user && $user->access_token && !array_key_exists('restart', $params)) {
  114. add_hcard_info($user, $hCard);
  115. $user->micropub_endpoint = $micropubEndpoint;
  116. $user->authorization_endpoint = $authorizationEndpoint;
  117. $user->token_endpoint = $tokenEndpoint;
  118. $user->type = $micropubEndpoint ? 'micropub' : 'local';
  119. $user->save();
  120. $app->redirect($authorizationURL, 301);
  121. } else {
  122. if(!$user)
  123. $user = ORM::for_table('users')->create();
  124. add_hcard_info($user, $hCard);
  125. $user->url = hostname($me);
  126. $user->date_created = date('Y-m-d H:i:s');
  127. $user->micropub_endpoint = $micropubEndpoint;
  128. $user->authorization_endpoint = $authorizationEndpoint;
  129. $user->token_endpoint = $tokenEndpoint;
  130. $user->type = $micropubEndpoint ? 'micropub' : 'local';
  131. $user->save();
  132. $html = render('auth_start', array(
  133. 'title' => 'Sign In',
  134. 'me' => $me,
  135. 'authorizing' => $me,
  136. 'meParts' => parse_url($me),
  137. 'micropubUser' => $authorizationEndpoint && $tokenEndpoint && $micropubEndpoint,
  138. 'tokenEndpoint' => $tokenEndpoint,
  139. 'micropubEndpoint' => $micropubEndpoint,
  140. 'authorizationEndpoint' => $authorizationEndpoint,
  141. 'authorizationURL' => $authorizationURL
  142. ));
  143. $app->response()->body($html);
  144. }
  145. });
  146. $app->get('/auth/callback', function() use($app) {
  147. $req = $app->request();
  148. $params = $req->params();
  149. // Double check there is a "me" parameter
  150. // Should only fail for really hacked up requests
  151. if(!array_key_exists('me', $params) || !($me = normalizeMeURL($params['me']))) {
  152. $html = render('auth_error', array(
  153. 'title' => 'Auth Callback',
  154. 'error' => 'Invalid "me" Parameter',
  155. 'errorDescription' => 'The ID you entered, <strong>' . $params['me'] . '</strong> is not valid.'
  156. ));
  157. $app->response()->body($html);
  158. return;
  159. }
  160. // If there is no state in the session, start the login again
  161. if(!array_key_exists('auth_state', $_SESSION)) {
  162. $app->redirect('/auth/start?me='.urlencode($params['me']));
  163. return;
  164. }
  165. if(!array_key_exists('code', $params) || trim($params['code']) == '') {
  166. $html = render('auth_error', array(
  167. 'title' => 'Auth Callback',
  168. 'error' => 'Missing authorization code',
  169. 'errorDescription' => 'No authorization code was provided in the request.'
  170. ));
  171. $app->response()->body($html);
  172. return;
  173. }
  174. // Verify the state came back and matches what we set in the session
  175. // Should only fail for malicious attempts, ok to show a not as nice error message
  176. if(!array_key_exists('state', $params)) {
  177. $html = render('auth_error', array(
  178. 'title' => 'Auth Callback',
  179. 'error' => 'Missing state parameter',
  180. 'errorDescription' => 'No state parameter was provided in the request. This shouldn\'t happen. It is possible this is a malicious authorization attempt.'
  181. ));
  182. $app->response()->body($html);
  183. return;
  184. }
  185. if($params['state'] != $_SESSION['auth_state']) {
  186. $html = render('auth_error', array(
  187. 'title' => 'Auth Callback',
  188. 'error' => 'Invalid state',
  189. 'errorDescription' => 'The state parameter provided did not match the state provided at the start of authorization. This is most likely caused by a malicious authorization attempt.'
  190. ));
  191. $app->response()->body($html);
  192. return;
  193. }
  194. $pebble = k($_SESSION, 'pebble');
  195. // Now the basic sanity checks have passed. Time to start providing more helpful messages when there is an error.
  196. // An authorization code is in the query string, and we want to exchange that for an access token at the token endpoint.
  197. // Discover the endpoints
  198. $authorizationEndpoint = IndieAuth\Client::discoverAuthorizationEndpoint($me);
  199. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  200. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  201. $skipDebugScreen = false;
  202. if($tokenEndpoint) {
  203. // Exchange auth code for an access token
  204. $token = IndieAuth\Client::getAccessToken($tokenEndpoint, $params['code'], $params['me'], buildRedirectURI(), clientID($pebble), $params['state'], true);
  205. // If a valid access token was returned, store the token info in the session and they are signed in
  206. if(k($token['auth'], array('me','access_token','scope'))) {
  207. $_SESSION['auth'] = $token['auth'];
  208. $_SESSION['me'] = $params['me'];
  209. // TODO?
  210. // This client requires the "post" scope.
  211. // Make a request to the micropub endpoint to discover the syndication targets if any.
  212. // Errors are silently ignored here. The user will be able to retry from the new post interface and get feedback.
  213. // get_syndication_targets($user);
  214. }
  215. } else {
  216. // No token endpoint was discovered, instead, verify the auth code at the auth server or with indieauth.com
  217. // Never show the intermediate login confirmation page if we just authenticated them instead of got authorization
  218. $skipDebugScreen = true;
  219. if(!$authorizationEndpoint) {
  220. $authorizationEndpoint = 'https://indieauth.com/auth';
  221. }
  222. $token['auth'] = IndieAuth\Client::verifyIndieAuthCode($authorizationEndpoint, $params['code'], $params['me'], buildRedirectURI(), clientID($pebble), $params['state']);
  223. if(k($token['auth'], 'me')) {
  224. $token['response'] = ''; // hack becuase the verify call doesn't actually return the real response
  225. $token['auth']['scope'] = '';
  226. $token['auth']['access_token'] = '';
  227. $_SESSION['auth'] = $token['auth'];
  228. $_SESSION['me'] = $params['me'];
  229. }
  230. }
  231. // Verify the login actually succeeded
  232. if(!array_key_exists('me', $_SESSION)) {
  233. $html = render('auth_error', array(
  234. 'title' => 'Sign-In Failed',
  235. 'error' => 'Unable to verify the sign-in attempt',
  236. 'errorDescription' => ''
  237. ));
  238. $app->response()->body($html);
  239. return;
  240. }
  241. $user = ORM::for_table('users')->where('url', hostname($me))->find_one();
  242. if($user) {
  243. // Already logged in, update the last login date
  244. $user->last_login = date('Y-m-d H:i:s');
  245. // If they have logged in before and we already have an access token, then redirect to the dashboard now
  246. if($user->access_token)
  247. $skipDebugScreen = true;
  248. } else {
  249. // New user! Store the user in the database
  250. $user = ORM::for_table('users')->create();
  251. $user->url = hostname($me);
  252. $user->date_created = date('Y-m-d H:i:s');
  253. $user->last_login = date('Y-m-d H:i:s');
  254. }
  255. $user->micropub_endpoint = $micropubEndpoint;
  256. $user->access_token = $token['auth']['access_token'];
  257. $user->token_scope = $token['auth']['scope'];
  258. $user->token_response = $token['response'];
  259. $user->save();
  260. $_SESSION['user_id'] = $user->id();
  261. unset($_SESSION['auth_state']);
  262. if($skipDebugScreen) {
  263. $app->redirect($_SESSION['redirect_after_login'], 301);
  264. } else {
  265. $html = render('auth_callback', array(
  266. 'title' => 'Sign In',
  267. 'me' => $me,
  268. 'authorizing' => $me,
  269. 'meParts' => parse_url($me),
  270. 'tokenEndpoint' => $tokenEndpoint,
  271. 'auth' => $token['auth'],
  272. 'response' => $token['response'],
  273. 'curl_error' => (array_key_exists('error', $token) ? $token['error'] : false),
  274. 'redirect' => $_SESSION['redirect_after_login']
  275. ));
  276. $app->response()->body($html);
  277. }
  278. });
  279. $app->get('/signout', function() use($app) {
  280. unset($_SESSION['auth']);
  281. unset($_SESSION['me']);
  282. unset($_SESSION['auth_state']);
  283. unset($_SESSION['user_id']);
  284. $app->redirect('/', 301);
  285. });