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.

391 lines
14 KiB

9 years ago
  1. <?php
  2. use Abraham\TwitterOAuth\TwitterOAuth;
  3. function buildRedirectURI() {
  4. return Config::$base_url . 'auth/callback';
  5. }
  6. $app->get('/auth/start', function() use($app) {
  7. $req = $app->request();
  8. $params = $req->params();
  9. // the "me" parameter is user input, and may be in a couple of different forms:
  10. // aaronparecki.com http://aaronparecki.com http://aaronparecki.com/
  11. if(!array_key_exists('me', $params) || !($me = IndieAuth\Client::normalizeMeURL($params['me']))) {
  12. $html = render('auth_error', array(
  13. 'title' => 'Sign In',
  14. 'error' => 'Invalid "me" Parameter',
  15. 'errorDescription' => 'The URL you entered, "<strong>' . $params['me'] . '</strong>" is not valid.'
  16. ));
  17. $app->response()->body($html);
  18. return;
  19. }
  20. if(k($params, 'redirect')) {
  21. $_SESSION['redirect_after_login'] = $params['redirect'];
  22. }
  23. if(k($params, 'reply')) {
  24. $_SESSION['reply'] = $params['reply'];
  25. }
  26. $_SESSION['attempted_me'] = $me;
  27. $_SESSION['indieauth'] = [
  28. 'authorization_endpoint' => ($authorizationEndpoint=IndieAuth\Client::discoverAuthorizationEndpoint($me)),
  29. 'token_endpoint' => ($tokenEndpoint=IndieAuth\Client::discoverTokenEndpoint($me)),
  30. 'micropub_endpoint' => ($micropubEndpoint=IndieAuth\Client::discoverMicropubEndpoint($me)),
  31. ];
  32. $defaultScope = 'create update media';
  33. if($tokenEndpoint && $micropubEndpoint && $authorizationEndpoint) {
  34. // Generate a "state" parameter for the request
  35. $state = IndieAuth\Client::generateStateParameter();
  36. $_SESSION['auth_state'] = $state;
  37. $authorizationURL = IndieAuth\Client::buildAuthorizationURL($authorizationEndpoint, $me, buildRedirectURI(), Config::$base_url, $state, $defaultScope);
  38. } else {
  39. $authorizationURL = false;
  40. }
  41. // If the user has already signed in before and has a micropub access token,
  42. // and the endpoints are all the same, skip the debugging screens and redirect
  43. // immediately to the auth endpoint.
  44. // This will still generate a new access token when they finish logging in.
  45. $user = ORM::for_table('users')->where('url', $me)->find_one();
  46. if($user && $user->micropub_access_token
  47. && $user->micropub_endpoint == $micropubEndpoint
  48. && $user->token_endpoint == $tokenEndpoint
  49. && $user->authorization_endpoint == $authorizationEndpoint
  50. && !array_key_exists('restart', $params)) {
  51. // TODO: fix this by caching the endpoints maybe in the session instead of writing them to the DB here.
  52. // Then remove the line below that blanks out the access token
  53. $user->micropub_endpoint = $micropubEndpoint;
  54. $user->authorization_endpoint = $authorizationEndpoint;
  55. $user->token_endpoint = $tokenEndpoint;
  56. $user->save();
  57. // Request whatever scope was previously granted
  58. $authorizationURL = parse_url($authorizationURL);
  59. $authorizationURL['scope'] = $user->micropub_scope;
  60. $authorizationURL = http_build_url($authorizationURL);
  61. $app->redirect($authorizationURL, 302);
  62. } else {
  63. if(k($params, 'dontask') && $params['dontask']) {
  64. // Request whatever scope was previously granted
  65. $authorizationURL = parse_url($authorizationURL);
  66. $authorizationURL['scope'] = $user->micropub_scope ?: $defaultScope;
  67. $authorizationURL = http_build_url($authorizationURL);
  68. $_SESSION['dontask'] = 1;
  69. $app->redirect($authorizationURL, 302);
  70. }
  71. $html = render('auth_start', array(
  72. 'title' => 'Sign In',
  73. 'me' => $me,
  74. 'authorizing' => $me,
  75. 'meParts' => parse_url($me),
  76. 'tokenEndpoint' => $tokenEndpoint,
  77. 'micropubEndpoint' => $micropubEndpoint,
  78. 'authorizationEndpoint' => $authorizationEndpoint,
  79. 'authorizationURL' => $authorizationURL
  80. ));
  81. $app->response()->body($html);
  82. }
  83. });
  84. $app->get('/auth/redirect', function() use($app) {
  85. $req = $app->request();
  86. $params = $req->params();
  87. if(!isset($params['scope']))
  88. $params['scope'] = '';
  89. $authorizationURL = parse_url($params['authorization_url']);
  90. parse_str($authorizationURL['query'], $query);
  91. $query['scope'] = $params['scope'];
  92. $authorizationURL['query'] = http_build_query($query);
  93. $authorizationURL = http_build_url($authorizationURL);
  94. $app->redirect($authorizationURL);
  95. return;
  96. });
  97. $app->get('/auth/callback', function() use($app) {
  98. $req = $app->request();
  99. $params = $req->params();
  100. // If there is no state in the session, start the login again
  101. if(!array_key_exists('auth_state', $_SESSION)) {
  102. $html = render('auth_error', array(
  103. 'title' => 'Auth Callback',
  104. 'error' => 'Missing session state',
  105. 'errorDescription' => 'Something went wrong, please try signing in again, and make sure cookies are enabled for this domain.'
  106. ));
  107. $app->response()->body($html);
  108. return;
  109. }
  110. if(!array_key_exists('code', $params) || trim($params['code']) == '') {
  111. $html = render('auth_error', array(
  112. 'title' => 'Auth Callback',
  113. 'error' => 'Missing authorization code',
  114. 'errorDescription' => 'No authorization code was provided in the request.'
  115. ));
  116. $app->response()->body($html);
  117. return;
  118. }
  119. // Verify the state came back and matches what we set in the session
  120. // Should only fail for malicious attempts, ok to show a not as nice error message
  121. if(!array_key_exists('state', $params)) {
  122. $html = render('auth_error', array(
  123. 'title' => 'Auth Callback',
  124. 'error' => 'Missing state parameter',
  125. '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.'
  126. ));
  127. $app->response()->body($html);
  128. return;
  129. }
  130. if($params['state'] != $_SESSION['auth_state']) {
  131. $html = render('auth_error', array(
  132. 'title' => 'Auth Callback',
  133. 'error' => 'Invalid state',
  134. '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.'
  135. ));
  136. $app->response()->body($html);
  137. return;
  138. }
  139. if(!isset($_SESSION['attempted_me'])) {
  140. $html = render('auth_error', [
  141. 'title' => 'Auth Callback',
  142. 'error' => 'Missing data',
  143. '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.'
  144. ]);
  145. $app->response()->body($html);
  146. return;
  147. }
  148. $me = $_SESSION['attempted_me'];
  149. // Now the basic sanity checks have passed. Time to start providing more helpful messages when there is an error.
  150. // An authorization code is in the query string, and we want to exchange that for an access token at the token endpoint.
  151. // Discover the endpoints
  152. $micropubEndpoint = $_SESSION['indieauth']['micropub_endpoint'];
  153. $tokenEndpoint = $_SESSION['indieauth']['token_endpoint'];
  154. if($tokenEndpoint) {
  155. $token = IndieAuth\Client::getAccessToken($tokenEndpoint, $params['code'], $me, buildRedirectURI(), Config::$base_url, true);
  156. } else {
  157. $token = array('auth'=>false, 'response'=>false);
  158. }
  159. $redirectToDashboardImmediately = false;
  160. // If a valid access token was returned, store the token info in the session and they are signed in
  161. if(k($token['auth'], array('me','access_token','scope'))) {
  162. // Double check that the domain of the returned "me" matches the expected
  163. if(!\p3k\url\host_matches($token['auth']['me'], $me)) {
  164. $html = render('auth_error', [
  165. 'title' => 'Error Signing In',
  166. 'error' => 'Invalid user',
  167. 'errorDescription' => 'The user URL that was returned from the token endpoint (<code>'.$token['auth']['me'].'</code>) did not match the domain of the user signing in (<code>'.$me.'</code>).'
  168. ]);
  169. $app->response()->body($html);
  170. return;
  171. }
  172. $_SESSION['auth'] = $token['auth'];
  173. $_SESSION['me'] = $me = $token['auth']['me'];
  174. $user = ORM::for_table('users')->where('url', $me)->find_one();
  175. if($user) {
  176. // Already logged in, update the last login date
  177. $user->last_login = date('Y-m-d H:i:s');
  178. // If they have logged in before and we already have an access token, then redirect to the dashboard now
  179. if($user->micropub_access_token)
  180. $redirectToDashboardImmediately = true;
  181. } else {
  182. // New user! Store the user in the database
  183. $user = ORM::for_table('users')->create();
  184. $user->url = $me;
  185. $user->date_created = date('Y-m-d H:i:s');
  186. }
  187. $user->authorization_endpoint = $_SESSION['indieauth']['authorization_endpoint'];
  188. $user->token_endpoint = $tokenEndpoint;
  189. $user->micropub_endpoint = $micropubEndpoint;
  190. $user->micropub_access_token = $token['auth']['access_token'];
  191. $user->micropub_scope = $token['auth']['scope'];
  192. $user->micropub_response = $token['response'];
  193. $user->save();
  194. $_SESSION['user_id'] = $user->id();
  195. // Make a request to the micropub endpoint to discover the syndication targets and media endpoint if any.
  196. // Errors are silently ignored here. The user will be able to retry from the new post interface and get feedback.
  197. get_micropub_config($user, ['q'=>'config']);
  198. }
  199. unset($_SESSION['auth_state']);
  200. unset($_SESSION['attempted_me']);
  201. unset($_SESSION['indieauth']);
  202. if($redirectToDashboardImmediately || k($_SESSION, 'dontask')) {
  203. unset($_SESSION['dontask']);
  204. if(k($_SESSION, 'redirect_after_login')) {
  205. $dest = $_SESSION['redirect_after_login'];
  206. unset($_SESSION['redirect_after_login']);
  207. $app->redirect($dest, 302);
  208. } else {
  209. $query = [];
  210. if(k($_SESSION, 'reply')) {
  211. $query['reply'] = $_SESSION['reply'];
  212. unset($_SESSION['reply']);
  213. }
  214. $app->redirect('/new?' . http_build_query($query), 302);
  215. }
  216. } else {
  217. $tokenResponse = $token['response'];
  218. $parsed = @json_decode($tokenResponse);
  219. if($parsed)
  220. $tokenResponse = json_encode($parsed, JSON_PRETTY_PRINT+JSON_UNESCAPED_SLASHES);
  221. $html = render('auth_callback', array(
  222. 'title' => 'Sign In',
  223. 'me' => $me,
  224. 'authorizing' => $me,
  225. 'meParts' => parse_url($me),
  226. 'tokenEndpoint' => $tokenEndpoint,
  227. 'auth' => $token['auth'],
  228. 'response' => $tokenResponse,
  229. 'curl_error' => (array_key_exists('error', $token) ? $token['error'] : false),
  230. 'destination' => (k($_SESSION, 'redirect_after_login') ?: '/new')
  231. ));
  232. $app->response()->body($html);
  233. }
  234. });
  235. $app->get('/signout', function() use($app) {
  236. unset($_SESSION['auth']);
  237. unset($_SESSION['me']);
  238. unset($_SESSION['auth_state']);
  239. unset($_SESSION['user_id']);
  240. $app->redirect('/', 302);
  241. });
  242. $app->post('/auth/reset', function() use($app) {
  243. if($user=require_login($app, false)) {
  244. revoke_micropub_token($user->micropub_access_token, $user->token_endpoint);
  245. $user->authorization_endpoint = '';
  246. $user->token_endpoint = '';
  247. $user->micropub_endpoint = '';
  248. $user->authorization_endpoint = '';
  249. $user->micropub_media_endpoint = '';
  250. $user->micropub_scope = '';
  251. $user->micropub_access_token = '';
  252. $user->save();
  253. unset($_SESSION['auth']);
  254. unset($_SESSION['me']);
  255. unset($_SESSION['auth_state']);
  256. unset($_SESSION['user_id']);
  257. }
  258. $app->redirect('/', 302);
  259. });
  260. $app->post('/auth/twitter', function() use($app) {
  261. if($user=require_login($app, false)) {
  262. $params = $app->request()->params();
  263. // User just auth'd with twitter, store the access token
  264. $user->twitter_access_token = $params['twitter_token'];
  265. $user->twitter_token_secret = $params['twitter_secret'];
  266. $user->save();
  267. $app->response()['Content-type'] = 'application/json';
  268. $app->response()->body(json_encode(array(
  269. 'result' => 'ok'
  270. )));
  271. } else {
  272. $app->response()['Content-type'] = 'application/json';
  273. $app->response()->body(json_encode(array(
  274. 'result' => 'error'
  275. )));
  276. }
  277. });
  278. function getTwitterLoginURL(&$twitter) {
  279. $request_token = $twitter->oauth('oauth/request_token', [
  280. 'oauth_callback' => Config::$base_url . 'auth/twitter/callback'
  281. ]);
  282. $_SESSION['twitter_auth'] = $request_token;
  283. return $twitter->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]);
  284. }
  285. $app->get('/auth/twitter', function() use($app) {
  286. $params = $app->request()->params();
  287. if($user=require_login($app, false)) {
  288. // If there is an existing Twitter token, check if it is valid
  289. // Otherwise, generate a Twitter login link
  290. $twitter_login_url = false;
  291. if(array_key_exists('login', $params)) {
  292. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret);
  293. $twitter_login_url = getTwitterLoginURL($twitter);
  294. } else {
  295. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  296. $user->twitter_access_token, $user->twitter_token_secret);
  297. if($user->twitter_access_token) {
  298. if($twitter->get('account/verify_credentials')) {
  299. $app->response()['Content-type'] = 'application/json';
  300. $app->response()->body(json_encode(array(
  301. 'result' => 'ok'
  302. )));
  303. return;
  304. } else {
  305. // If the existing twitter token is not valid, generate a login link
  306. $twitter_login_url = getTwitterLoginURL($twitter);
  307. }
  308. } else {
  309. $twitter_login_url = getTwitterLoginURL($twitter);
  310. }
  311. }
  312. $app->response()['Content-type'] = 'application/json';
  313. $app->response()->body(json_encode(array(
  314. 'url' => $twitter_login_url
  315. )));
  316. } else {
  317. $app->response()['Content-type'] = 'application/json';
  318. $app->response()->body(json_encode(array(
  319. 'result' => 'error'
  320. )));
  321. }
  322. });
  323. $app->get('/auth/twitter/callback', function() use($app) {
  324. if($user=require_login($app)) {
  325. $params = $app->request()->params();
  326. $twitter = new TwitterOAuth(Config::$twitterClientID, Config::$twitterClientSecret,
  327. $_SESSION['twitter_auth']['oauth_token'], $_SESSION['twitter_auth']['oauth_token_secret']);
  328. $credentials = $twitter->oauth('oauth/access_token', ['oauth_verifier' => $params['oauth_verifier']]);
  329. $user->twitter_access_token = $credentials['oauth_token'];
  330. $user->twitter_token_secret = $credentials['oauth_token_secret'];
  331. $user->twitter_username = $credentials['screen_name'];
  332. $user->save();
  333. $app->redirect('/settings');
  334. }
  335. });