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.

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