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.

404 lines
14 KiB

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