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.

263 lines
9.0 KiB

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