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.

401 lines
14 KiB

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