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.

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