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.

332 lines
11 KiB

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