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.

330 lines
12 KiB

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