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.

286 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. $html = render('auth_error', array(
  132. 'title' => 'Auth Callback',
  133. 'error' => 'Invalid "me" Parameter',
  134. 'errorDescription' => 'The ID you entered, <strong>' . $params['me'] . '</strong> is not valid.'
  135. ));
  136. $app->response()->body($html);
  137. return;
  138. }
  139. // If there is no state in the session, start the login again
  140. if(!array_key_exists('auth_state', $_SESSION)) {
  141. $app->redirect('/auth/start?me='.urlencode($params['me']));
  142. return;
  143. }
  144. if(!array_key_exists('code', $params) || trim($params['code']) == '') {
  145. $html = render('auth_error', array(
  146. 'title' => 'Auth Callback',
  147. 'error' => 'Missing authorization code',
  148. 'errorDescription' => 'No authorization code was provided in the request.'
  149. ));
  150. $app->response()->body($html);
  151. return;
  152. }
  153. // Verify the state came back and matches what we set in the session
  154. // Should only fail for malicious attempts, ok to show a not as nice error message
  155. if(!array_key_exists('state', $params)) {
  156. $html = render('auth_error', array(
  157. 'title' => 'Auth Callback',
  158. 'error' => 'Missing state parameter',
  159. 'errorDescription' => 'No state parameter was provided in the request. This shouldn\'t happen. It is possible this is a malicious authorization attempt.'
  160. ));
  161. $app->response()->body($html);
  162. return;
  163. }
  164. if($params['state'] != $_SESSION['auth_state']) {
  165. $html = render('auth_error', array(
  166. 'title' => 'Auth Callback',
  167. 'error' => 'Invalid state',
  168. '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.'
  169. ));
  170. $app->response()->body($html);
  171. return;
  172. }
  173. // Now the basic sanity checks have passed. Time to start providing more helpful messages when there is an error.
  174. // An authorization code is in the query string, and we want to exchange that for an access token at the token endpoint.
  175. // Discover the endpoints
  176. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  177. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  178. if($tokenEndpoint) {
  179. $token = IndieAuth\Client::getAccessToken($tokenEndpoint, $params['code'], $params['me'], buildRedirectURI(), Config::$base_url, k($params,'state'), true);
  180. } else {
  181. $token = array('auth'=>false, 'response'=>false);
  182. }
  183. $redirectToDashboardImmediately = false;
  184. // If a valid access token was returned, store the token info in the session and they are signed in
  185. if(k($token['auth'], array('me','access_token','scope'))) {
  186. $_SESSION['auth'] = $token['auth'];
  187. $_SESSION['me'] = $params['me'];
  188. $user = ORM::for_table('users')->where('url', $me)->find_one();
  189. if($user) {
  190. // Already logged in, update the last login date
  191. $user->last_login = date('Y-m-d H:i:s');
  192. // If they have logged in before and we already have an access token, then redirect to the dashboard now
  193. if($user->micropub_access_token)
  194. $redirectToDashboardImmediately = true;
  195. } else {
  196. // New user! Store the user in the database
  197. $user = ORM::for_table('users')->create();
  198. $user->url = $me;
  199. $user->date_created = date('Y-m-d H:i:s');
  200. }
  201. $user->micropub_endpoint = $micropubEndpoint;
  202. $user->micropub_access_token = $token['auth']['access_token'];
  203. $user->micropub_scope = $token['auth']['scope'];
  204. $user->micropub_response = $token['response'];
  205. $user->save();
  206. $_SESSION['user_id'] = $user->id();
  207. // Make a request to the micropub endpoint to discover the syndication targets if any.
  208. // Errors are silently ignored here. The user will be able to retry from the new post interface and get feedback.
  209. get_syndication_targets($user);
  210. }
  211. unset($_SESSION['auth_state']);
  212. if($redirectToDashboardImmediately) {
  213. if(k($_SESSION, 'redirect_after_login')) {
  214. $dest = $_SESSION['redirect_after_login'];
  215. unset($_SESSION['redirect_after_login']);
  216. $app->redirect($dest, 301);
  217. } else {
  218. $app->redirect('/new', 301);
  219. }
  220. } else {
  221. $html = render('auth_callback', array(
  222. 'title' => 'Sign In',
  223. 'me' => $me,
  224. 'authorizing' => $me,
  225. 'meParts' => parse_url($me),
  226. 'tokenEndpoint' => $tokenEndpoint,
  227. 'auth' => $token['auth'],
  228. 'response' => $token['response'],
  229. 'curl_error' => (array_key_exists('error', $token) ? $token['error'] : false),
  230. 'destination' => (k($_SESSION, 'redirect_after_login') ?: '/new')
  231. ));
  232. $app->response()->body($html);
  233. }
  234. });
  235. $app->get('/signout', function() use($app) {
  236. unset($_SESSION['auth']);
  237. unset($_SESSION['me']);
  238. unset($_SESSION['auth_state']);
  239. unset($_SESSION['user_id']);
  240. $app->redirect('/', 301);
  241. });