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.

290 lines
10 KiB

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