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.

312 lines
11 KiB

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