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.

400 lines
14 KiB

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