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.

177 lines
5.6 KiB

9 years ago
9 years ago
9 years ago
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Laravel\Lumen\Routing\Controller as BaseController;
  4. use Illuminate\Http\Request;
  5. use GuzzleHttp;
  6. use DB;
  7. class IndieAuth extends BaseController
  8. {
  9. private function _redirectURI() {
  10. return env('BASE_URL') . 'auth/callback';
  11. }
  12. public function start(Request $request) {
  13. $me = \IndieAuth\Client::normalizeMeURL($request->input('me'));
  14. if(!$me) {
  15. return view('auth/error', ['error' => 'Invalid URL']);
  16. }
  17. $state = \IndieAuth\Client::generateStateParameter();
  18. if(preg_match('/https?:\/\/github\.com\/[^ \/]+/', $me)) {
  19. $authorizationURL = 'https://github.com/login/oauth/authorize'
  20. . '?client_id=' . env('GITHUB_ID')
  21. . '&state=' . $state;
  22. session([
  23. 'auth_state' => $state,
  24. 'attempted_me' => $me,
  25. ]);
  26. } else {
  27. $authorizationEndpoint = \IndieAuth\Client::discoverAuthorizationEndpoint($me);
  28. session([
  29. 'auth_state' => $state,
  30. 'attempted_me' => $me,
  31. 'authorization_endpoint' => $authorizationEndpoint,
  32. ]);
  33. // If the user specified only an authorization endpoint, use that
  34. if(!$authorizationEndpoint) {
  35. // Otherwise, fall back to indieauth.com
  36. $authorizationEndpoint = env('DEFAULT_AUTH_ENDPOINT');
  37. }
  38. $authorizationURL = \IndieAuth\Client::buildAuthorizationURL($authorizationEndpoint, $me, $this->_redirectURI(), env('BASE_URL'), $state);
  39. }
  40. return redirect($authorizationURL);
  41. }
  42. public function callback(Request $request) {
  43. if(!session('auth_state') || !session('attempted_me')) {
  44. return view('auth/error', ['error' => 'Missing state information. Start over.']);
  45. }
  46. if($request->input('error')) {
  47. return view('auth/error', ['error' => $request->input('error')]);
  48. }
  49. if(session('auth_state') != $request->input('state')) {
  50. return view('auth/error', ['error' => 'State did not match. Start over.']);
  51. }
  52. if(session('authorization_endpoint')) {
  53. $authorizationEndpoint = session('authorization_endpoint');
  54. } else {
  55. $authorizationEndpoint = env('DEFAULT_AUTH_ENDPOINT');
  56. }
  57. $token = \IndieAuth\Client::verifyIndieAuthCode($authorizationEndpoint, $request->input('code'), session('attempted_me'), $this->_redirectURI(), env('BASE_URL'));
  58. if($token && array_key_exists('me', $token)) {
  59. session()->flush();
  60. session(['me' => $token['me']]);
  61. $this->_userLoggedIn($token['me']);
  62. }
  63. return redirect('/');
  64. }
  65. public function github(Request $request) {
  66. if(!session('auth_state') || !session('attempted_me')) {
  67. return view('auth/error', ['error' => 'Missing state information. Start over.']);
  68. }
  69. if($request->input('error')) {
  70. return view('auth/error', ['error' => $request->input('error')]);
  71. }
  72. if(session('auth_state') != $request->input('state')) {
  73. return view('auth/error', ['error' => 'State did not match. Start over.']);
  74. }
  75. if(!$request->input('code')) {
  76. return view('auth/error', ['error' => 'An unknown error occurred']);
  77. }
  78. $client = new GuzzleHttp\Client([
  79. 'http_errors' => false
  80. ]);
  81. $res = $client->post('https://github.com/login/oauth/access_token', [
  82. 'form_params' => [
  83. 'client_id' => env('GITHUB_ID'),
  84. 'client_secret' => env('GITHUB_SECRET'),
  85. // 'redirect_uri' => env('BASE_URL') . 'auth/github',
  86. 'code' => $request->input('code'),
  87. 'state' => session('auth_state')
  88. ],
  89. 'headers' => [
  90. 'Accept' => 'application/json'
  91. ]
  92. ]);
  93. if($res->getStatusCode() == 200) {
  94. $body = $res->getBody();
  95. $data = json_decode($body);
  96. if($data) {
  97. if(property_exists($data, 'access_token')) {
  98. // Now check the username of the user that just logged in
  99. $res = $client->get('https://api.github.com/user', [
  100. 'headers' => [
  101. 'Authorization' => 'token ' . $data->access_token
  102. ]
  103. ]);
  104. if($res->getStatusCode() == 200) {
  105. $data = json_decode($res->getBody());
  106. if(property_exists($data, 'login')) {
  107. session()->flush();
  108. $me = 'https://github.com/' . $data->login;
  109. session(['me' => $me]);
  110. $this->_userLoggedIn($me);
  111. return redirect('/');
  112. } else {
  113. return view('auth/error', ['error' => 'Login failed']);
  114. }
  115. } else {
  116. return view('auth/error', ['error' => 'Login failed']);
  117. }
  118. } else {
  119. $err = '';
  120. if(property_exists($data, 'error_description')) {
  121. $err = ': ' . $data->error_description;
  122. }
  123. return view('auth/error', ['error' => 'Login failed' . $err]);
  124. }
  125. } else {
  126. return view('auth/error', ['error' => 'Error parsing response body from GitHub']);
  127. }
  128. } else {
  129. return view('auth/error', ['error' => 'Could not verify login from GitHub: ' . $res->getBody()]);
  130. }
  131. }
  132. private function _userLoggedIn($url) {
  133. // Create the user record if it doesn't exist yet
  134. $user = DB::table('users')->where('url','=',$url)->first();
  135. if($user) {
  136. DB::update('UPDATE users SET last_login = ?', [date('Y-m-d H:i:s')]);
  137. session(['user_id' => $user->id]);
  138. } else {
  139. $user_id = DB::table('users')->insertGetId([
  140. 'url' => $url,
  141. 'created_at' => date('Y-m-d H:i:s'),
  142. 'last_login' => date('Y-m-d H:i:s'),
  143. ]);
  144. session(['user_id' => $user_id]);
  145. }
  146. }
  147. public function logout(Request $request) {
  148. session()->flush();
  149. return redirect('/');
  150. }
  151. }