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.

252 lines
9.3 KiB

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