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.

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