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.

353 lines
12KB

  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. $_SESSION['attempted_me'] = $me;
  85. $authorizationEndpoint = IndieAuth\Client::discoverAuthorizationEndpoint($me);
  86. $tokenEndpoint = IndieAuth\Client::discoverTokenEndpoint($me);
  87. $micropubEndpoint = IndieAuth\Client::discoverMicropubEndpoint($me);
  88. $hCard = IndieAuth\Client::representativeHCard($me);
  89. // Generate a "state" parameter for the request
  90. $state = IndieAuth\Client::generateStateParameter();
  91. $_SESSION['auth_state'] = $state;
  92. // Store whether to return to the Pebble settings tab or the new post page after signing in
  93. if(array_key_exists('redirect', $params) && $params['redirect'] == 'settings') {
  94. $_SESSION['redirect_after_login'] = '/pebble/settings/finished';
  95. } else {
  96. $_SESSION['redirect_after_login'] = '/new';
  97. }
  98. $pebble = k($params, 'pebble');
  99. $_SESSION['pebble'] = $pebble;
  100. if($tokenEndpoint && $micropubEndpoint && $authorizationEndpoint) {
  101. $scope = 'create';
  102. $authorizationURL = IndieAuth\Client::buildAuthorizationURL($authorizationEndpoint, $me, buildRedirectURI(), clientID($pebble), $state, $scope);
  103. $_SESSION['authorization_endpoint'] = $authorizationEndpoint;
  104. $_SESSION['micropub_endpoint'] = $micropubEndpoint;
  105. $_SESSION['token_endpoint'] = $tokenEndpoint;
  106. } else {
  107. $authorizationURL = IndieAuth\Client::buildAuthorizationURL('https://indieauth.com/auth', $me, buildRedirectURI(), clientID($pebble), $state);
  108. }
  109. // If the user has already signed in before and has a micropub access token, skip
  110. // the debugging screens and redirect immediately to the auth endpoint.
  111. // This will still generate a new access token when they finish logging in.
  112. $user = ORM::for_table('users')->where('url', hostname($me))->find_one();
  113. if($user && $user->access_token && !array_key_exists('restart', $params)) {
  114. add_hcard_info($user, $hCard);
  115. $user->micropub_endpoint = $micropubEndpoint;
  116. $user->authorization_endpoint = $authorizationEndpoint;
  117. $user->token_endpoint = $tokenEndpoint;
  118. $user->type = $micropubEndpoint ? 'micropub' : 'local';
  119. $user->save();
  120. $app->redirect($authorizationURL, 301);
  121. } else {
  122. if(!$user)
  123. $user = ORM::for_table('users')->create();
  124. add_hcard_info($user, $hCard);
  125. $user->url = hostname($me);
  126. $user->date_created = date('Y-m-d H:i:s');
  127. $user->micropub_endpoint = $micropubEndpoint;
  128. $user->authorization_endpoint = $authorizationEndpoint;
  129. $user->token_endpoint = $tokenEndpoint;
  130. $user->type = $micropubEndpoint ? 'micropub' : 'local';
  131. $user->save();
  132. render('auth_start', array(
  133. 'title' => 'Sign In',
  134. 'me' => $me,
  135. 'authorizing' => $me,
  136. 'meParts' => parse_url($me),
  137. 'micropubUser' => $authorizationEndpoint && $tokenEndpoint && $micropubEndpoint,
  138. 'tokenEndpoint' => $tokenEndpoint,
  139. 'micropubEndpoint' => $micropubEndpoint,
  140. 'authorizationEndpoint' => $authorizationEndpoint,
  141. 'authorizationURL' => $authorizationURL
  142. ));
  143. }
  144. });
  145. $app->get('/auth/callback', function() use($app) {
  146. $req = $app->request();
  147. $params = $req->params();
  148. // If there is no state in the session, start the login again
  149. if(!array_key_exists('auth_state', $_SESSION)) {
  150. render('auth_error', array(
  151. 'title' => 'Auth Callback',
  152. 'error' => 'Missing session state',
  153. 'errorDescription' => 'Something went wrong, please try signing in again, and make sure cookies are enabled for this domain.'
  154. ));
  155. return;
  156. }
  157. if(!array_key_exists('code', $params) || trim($params['code']) == '') {
  158. render('auth_error', array(
  159. 'title' => 'Auth Callback',
  160. 'error' => 'Missing authorization code',
  161. 'errorDescription' => 'No authorization code was provided in the request.'
  162. ));
  163. return;
  164. }
  165. // Verify the state came back and matches what we set in the session
  166. // Should only fail for malicious attempts, ok to show a not as nice error message
  167. if(!array_key_exists('state', $params)) {
  168. render('auth_error', array(
  169. 'title' => 'Auth Callback',
  170. 'error' => 'Missing state parameter',
  171. 'errorDescription' => 'No state parameter was provided in the request. This shouldn\'t happen. It is possible this is a malicious authorization attempt, or your authorization server failed to pass back the "state" parameter.'
  172. ));
  173. return;
  174. }
  175. if($params['state'] != $_SESSION['auth_state']) {
  176. 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. return;
  182. }
  183. if(!isset($_SESSION['attempted_me'])) {
  184. render('auth_error', [
  185. 'title' => 'Auth Callback',
  186. 'error' => 'Missing data',
  187. 'errorDescription' => 'We forgot who was logging in. It\'s possible you took too long to finish signing in, or something got mixed up by signing in in another tab.'
  188. ]);
  189. return;
  190. }
  191. $me = $_SESSION['attempted_me'];
  192. $pebble = k($_SESSION, 'pebble');
  193. // Now the basic sanity checks have passed. Time to start providing more helpful messages when there is an error.
  194. // An authorization code is in the query string, and we want to exchange that for an access token at the token endpoint.
  195. $authorizationEndpoint = isset($_SESSION['authorization_endpoint']) ? $_SESSION['authorization_endpoint'] : false;
  196. $tokenEndpoint = isset($_SESSION['token_endpoint']) ? $_SESSION['token_endpoint'] : false;
  197. $micropubEndpoint = isset($_SESSION['micropub_endpoint']) ? $_SESSION['micropub_endpoint'] : false;
  198. unset($_SESSION['authorization_endpoint']);
  199. unset($_SESSION['token_endpoint']);
  200. unset($_SESSION['micropub_endpoint']);
  201. $skipDebugScreen = false;
  202. if($tokenEndpoint) {
  203. // Exchange auth code for an access token
  204. $token = IndieAuth\Client::getAccessToken($tokenEndpoint, $params['code'], $me, buildRedirectURI(), clientID($pebble), true);
  205. // If a valid access token was returned, store the token info in the session and they are signed in
  206. if(k($token['auth'], array('me','access_token','scope'))) {
  207. // Double check that the domain of the returned "me" matches the expected
  208. if(parse_url($token['auth']['me'], PHP_URL_HOST) != parse_url($me, PHP_URL_HOST)) {
  209. render('auth_error', [
  210. 'title' => 'Error Signing In',
  211. 'error' => 'Invalid user',
  212. 'errorDescription' => 'The user URL that was returned in the access token did not match the domain of the user signing in.'
  213. ]);
  214. return;
  215. }
  216. $_SESSION['auth'] = $token['auth'];
  217. $_SESSION['me'] = $token['auth']['me'];
  218. }
  219. } else {
  220. // No token endpoint was discovered, instead, verify the auth code at the auth server or with indieauth.com
  221. // Never show the intermediate login confirmation page if we just authenticated them instead of got authorization
  222. $skipDebugScreen = true;
  223. if(!$authorizationEndpoint) {
  224. $authorizationEndpoint = 'https://indieauth.com/auth';
  225. }
  226. $token['auth'] = IndieAuth\Client::verifyIndieAuthCode($authorizationEndpoint, $params['code'], $me, buildRedirectURI(), clientID($pebble));
  227. if(k($token['auth'], 'me')) {
  228. $token['response'] = ''; // hack becuase the verify call doesn't actually return the real response
  229. $token['auth']['scope'] = '';
  230. $token['auth']['access_token'] = '';
  231. $_SESSION['auth'] = $token['auth'];
  232. $_SESSION['me'] = $params['me'];
  233. }
  234. }
  235. // Verify the login actually succeeded
  236. if(!k($token['auth'], 'me')) {
  237. render('auth_error', array(
  238. 'title' => 'Sign-In Failed',
  239. 'error' => 'Unable to verify the sign-in attempt',
  240. 'errorDescription' => ''
  241. ));
  242. return;
  243. }
  244. $user = ORM::for_table('users')->where('url', hostname($me))->find_one();
  245. if($user) {
  246. // Already logged in, update the last login date
  247. $user->last_login = date('Y-m-d H:i:s');
  248. // If they have logged in before and we already have an access token, then redirect to the dashboard now
  249. if($user->access_token)
  250. $skipDebugScreen = true;
  251. } else {
  252. // New user! Store the user in the database
  253. $user = ORM::for_table('users')->create();
  254. $user->url = hostname($me);
  255. $user->date_created = date('Y-m-d H:i:s');
  256. $user->last_login = date('Y-m-d H:i:s');
  257. }
  258. $user->micropub_endpoint = $micropubEndpoint;
  259. $user->access_token = $token['auth']['access_token'];
  260. $user->token_scope = $token['auth']['scope'];
  261. $user->token_response = $token['response'];
  262. $user->save();
  263. $_SESSION['user_id'] = $user->id();
  264. if($tokenEndpoint) {
  265. // Make a request to the micropub endpoint to discover the media endpoint if set.
  266. get_micropub_config($user);
  267. }
  268. unset($_SESSION['auth_state']);
  269. if($skipDebugScreen) {
  270. $app->redirect($_SESSION['redirect_after_login'], 301);
  271. } else {
  272. render('auth_callback', array(
  273. 'title' => 'Sign In',
  274. 'me' => $me,
  275. 'authorizing' => $me,
  276. 'meParts' => parse_url($me),
  277. 'tokenEndpoint' => $tokenEndpoint,
  278. 'auth' => $token['auth'],
  279. 'response' => $token['response'],
  280. 'curl_error' => (array_key_exists('error', $token) ? $token['error'] : false),
  281. 'redirect' => $_SESSION['redirect_after_login']
  282. ));
  283. }
  284. });
  285. $app->get('/signout', function() use($app) {
  286. unset($_SESSION['auth']);
  287. unset($_SESSION['me']);
  288. unset($_SESSION['auth_state']);
  289. unset($_SESSION['user_id']);
  290. $app->redirect('/', 301);
  291. });