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.

331 lines
12 KiB

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