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.

338 lines
12 KiB

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