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.

343 lines
12 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. $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. });