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.

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