Mirror of Quill
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.

376 lines
13 KiB

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