Mirror of Quill
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

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