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.

266 lines
9.9 KiB

10 years ago
8 years ago
8 years ago
  1. <?php
  2. function buildRedirectURI($params = array()) {
  3. return Config::$base_url . 'auth/callback?' . http_build_query($params);
  4. }
  5. function build_url($parsed_url) {
  6. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  7. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  8. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  9. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  10. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  11. $pass = ($user || $pass) ? "$pass@" : '';
  12. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  13. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  14. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  15. return "$scheme$user$pass$host$port$path$query$fragment";
  16. }
  17. $app->get('/', function($format='html') use($app) {
  18. $res = $app->response();
  19. $params = $app->request()->params();
  20. if (k($params, 'me')) {
  21. $app->redirect('/auth/start?'.http_build_query($params), 302);
  22. }
  23. ob_start();
  24. render('index', array(
  25. 'title' => 'Quill',
  26. 'meta' => '',
  27. 'authorizing' => false
  28. ));
  29. $html = ob_get_clean();
  30. $res->body($html);
  31. });
  32. $app->get('/auth/start', function() use($app) {
  33. $req = $app->request();
  34. $params = $req->params();
  35. // the "me" parameter is user input, and may be in a couple of different forms:
  36. // aaronparecki.com http://aaronparecki.com http://aaronparecki.com/
  37. if(!array_key_exists('me', $params) || !($me = IndieAuth\Client::normalizeMeURL($params['me']))) {
  38. $html = render('auth_error', array(
  39. 'title' => 'Sign In',
  40. 'error' => 'Invalid "me" Parameter',
  41. 'errorDescription' => 'The URL you entered, "<strong>' . $params['me'] . '</strong>" is not valid.'
  42. ));
  43. $app->response()->body($html);
  44. return;
  45. }
  46. if(k($params, 'redirect')) {
  47. $_SESSION['redirect_after_login'] = $params['redirect'];
  48. }
  49. $authorizationEndpoint = IndieAuth\Client::discoverAuthorizationEndpoint($me);
  50. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  51. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  52. if($tokenEndpoint && $micropubEndpoint && $authorizationEndpoint) {
  53. // Generate a "state" parameter for the request
  54. $state = IndieAuth\Client::generateStateParameter();
  55. $_SESSION['auth_state'] = $state;
  56. $scope = 'post';
  57. $cleanparams = $params;
  58. unset($cleanparams['me']);
  59. unset($cleanparams['redirect']);
  60. $authorizationURL = IndieAuth\Client::buildAuthorizationURL($authorizationEndpoint, $me, buildRedirectURI($cleanparams), Config::$base_url, $state, $scope);
  61. } else {
  62. $authorizationURL = false;
  63. }
  64. // If the user has already signed in before and has a micropub access token,
  65. // and the endpoints are all the same, skip the debugging screens and redirect
  66. // immediately to the auth endpoint.
  67. // This will still generate a new access token when they finish logging in.
  68. $user = ORM::for_table('users')->where('url', $me)->find_one();
  69. if($user && $user->micropub_access_token
  70. && $user->micropub_endpoint == $micropubEndpoint
  71. && $user->token_endpoint == $tokenEndpoint
  72. && $user->authorization_endpoint == $authorizationEndpoint
  73. && !array_key_exists('restart', $params)) {
  74. // TODO: fix this by caching the endpoints maybe in the session instead of writing them to the DB here.
  75. // Then remove the line below that blanks out the access token
  76. $user->micropub_endpoint = $micropubEndpoint;
  77. $user->authorization_endpoint = $authorizationEndpoint;
  78. $user->token_endpoint = $tokenEndpoint;
  79. $user->save();
  80. $app->redirect($authorizationURL, 301);
  81. } else {
  82. if(!$user)
  83. $user = ORM::for_table('users')->create();
  84. $user->url = $me;
  85. $user->date_created = date('Y-m-d H:i:s');
  86. $user->micropub_endpoint = $micropubEndpoint;
  87. $user->authorization_endpoint = $authorizationEndpoint;
  88. $user->token_endpoint = $tokenEndpoint;
  89. $user->micropub_access_token = ''; // blank out the access token if they attempt to sign in again
  90. $user->save();
  91. if (k($params, 'dontask') && $params['dontask']) {
  92. $app->redirect($authorizationURL, 302);
  93. }
  94. $html = render('auth_start', array(
  95. 'title' => 'Sign In',
  96. 'me' => $me,
  97. 'authorizing' => $me,
  98. 'meParts' => parse_url($me),
  99. 'tokenEndpoint' => $tokenEndpoint,
  100. 'micropubEndpoint' => $micropubEndpoint,
  101. 'authorizationEndpoint' => $authorizationEndpoint,
  102. 'authorizationURL' => $authorizationURL
  103. ));
  104. $app->response()->body($html);
  105. }
  106. });
  107. $app->get('/auth/callback', function() use($app) {
  108. $req = $app->request();
  109. $params = $req->params();
  110. // Double check there is a "me" parameter
  111. // Should only fail for really hacked up requests
  112. if(!array_key_exists('me', $params) || !($me = IndieAuth\Client::normalizeMeURL($params['me']))) {
  113. if(array_key_exists('me', $params))
  114. $error = 'The ID you entered, <strong>' . $params['me'] . '</strong> is not valid.';
  115. else
  116. $error = 'There was no "me" parameter in the callback.';
  117. $html = render('auth_error', array(
  118. 'title' => 'Auth Callback',
  119. 'error' => 'Invalid "me" Parameter',
  120. 'errorDescription' => $error
  121. ));
  122. $app->response()->body($html);
  123. return;
  124. }
  125. // If there is no state in the session, start the login again
  126. if(!array_key_exists('auth_state', $_SESSION)) {
  127. $app->redirect('/auth/start?me='.urlencode($params['me']));
  128. return;
  129. }
  130. if(!array_key_exists('code', $params) || trim($params['code']) == '') {
  131. $html = render('auth_error', array(
  132. 'title' => 'Auth Callback',
  133. 'error' => 'Missing authorization code',
  134. 'errorDescription' => 'No authorization code was provided in the request.'
  135. ));
  136. $app->response()->body($html);
  137. return;
  138. }
  139. // Verify the state came back and matches what we set in the session
  140. // Should only fail for malicious attempts, ok to show a not as nice error message
  141. if(!array_key_exists('state', $params)) {
  142. $html = render('auth_error', array(
  143. 'title' => 'Auth Callback',
  144. 'error' => 'Missing state parameter',
  145. 'errorDescription' => 'No state parameter was provided in the request. This shouldn\'t happen. It is possible this is a malicious authorization attempt.'
  146. ));
  147. $app->response()->body($html);
  148. return;
  149. }
  150. if($params['state'] != $_SESSION['auth_state']) {
  151. $html = render('auth_error', array(
  152. 'title' => 'Auth Callback',
  153. 'error' => 'Invalid state',
  154. '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.'
  155. ));
  156. $app->response()->body($html);
  157. return;
  158. }
  159. // Now the basic sanity checks have passed. Time to start providing more helpful messages when there is an error.
  160. // An authorization code is in the query string, and we want to exchange that for an access token at the token endpoint.
  161. // Discover the endpoints
  162. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  163. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  164. if($tokenEndpoint) {
  165. $token = IndieAuth\Client::getAccessToken($tokenEndpoint, $params['code'], $params['me'], buildRedirectURI(), Config::$base_url, k($params,'state'), true);
  166. } else {
  167. $token = array('auth'=>false, 'response'=>false);
  168. }
  169. $redirectToDashboardImmediately = false;
  170. // If a valid access token was returned, store the token info in the session and they are signed in
  171. if(k($token['auth'], array('me','access_token','scope'))) {
  172. $_SESSION['auth'] = $token['auth'];
  173. $_SESSION['me'] = $params['me'];
  174. $user = ORM::for_table('users')->where('url', $me)->find_one();
  175. if($user) {
  176. // Already logged in, update the last login date
  177. $user->last_login = date('Y-m-d H:i:s');
  178. // If they have logged in before and we already have an access token, then redirect to the dashboard now
  179. if($user->micropub_access_token)
  180. $redirectToDashboardImmediately = true;
  181. } else {
  182. // New user! Store the user in the database
  183. $user = ORM::for_table('users')->create();
  184. $user->url = $me;
  185. $user->date_created = date('Y-m-d H:i:s');
  186. }
  187. $user->micropub_endpoint = $micropubEndpoint;
  188. $user->micropub_access_token = $token['auth']['access_token'];
  189. $user->micropub_scope = $token['auth']['scope'];
  190. $user->micropub_response = $token['response'];
  191. $user->save();
  192. $_SESSION['user_id'] = $user->id();
  193. // Make a request to the micropub endpoint to discover the syndication targets and media endpoint if any.
  194. // Errors are silently ignored here. The user will be able to retry from the new post interface and get feedback.
  195. get_micropub_config($user);
  196. }
  197. unset($_SESSION['auth_state']);
  198. if($redirectToDashboardImmediately || k($params, 'dontask')) {
  199. if(k($_SESSION, 'redirect_after_login')) {
  200. $dest = $_SESSION['redirect_after_login'];
  201. unset($_SESSION['redirect_after_login']);
  202. $app->redirect($dest, 301);
  203. } else {
  204. $cleanparams = $params;
  205. unset($cleanparams['code']);
  206. unset($cleanparams['me']);
  207. unset($cleanparams['state']);
  208. $app->redirect('/new?' . http_build_query($cleanparams), 301);
  209. }
  210. } else {
  211. $html = render('auth_callback', array(
  212. 'title' => 'Sign In',
  213. 'me' => $me,
  214. 'authorizing' => $me,
  215. 'meParts' => parse_url($me),
  216. 'tokenEndpoint' => $tokenEndpoint,
  217. 'auth' => $token['auth'],
  218. 'response' => $token['response'],
  219. 'curl_error' => (array_key_exists('error', $token) ? $token['error'] : false),
  220. 'destination' => (k($_SESSION, 'redirect_after_login') ?: '/new')
  221. ));
  222. $app->response()->body($html);
  223. }
  224. });
  225. $app->get('/signout', function() use($app) {
  226. unset($_SESSION['auth']);
  227. unset($_SESSION['me']);
  228. unset($_SESSION['auth_state']);
  229. unset($_SESSION['user_id']);
  230. $app->redirect('/', 301);
  231. });