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.

268 lines
9.2 KiB

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