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.

326 lines
12 KiB

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