DaborySSOController.php-- 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use Exception;
  4. use App\Services\CallApiService;
  5. use App\Http\Controllers\Api\ApiController;
  6. class DaborySSOController
  7. {
  8. /**
  9. * @var CallApiService
  10. */
  11. private $callApiService;
  12. private $oauth2Info;
  13. private $target;
  14. public function __construct(CallApiService $callApiService)
  15. {
  16. $this->callApiService = $callApiService;
  17. }
  18. private function generate_string($strength = 32)
  19. {
  20. $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  21. $input_length = strlen($permitted_chars);
  22. $random_string = '';
  23. for ($i = 0; $i < $strength; $i++) {
  24. $random_character = $permitted_chars[mt_rand(0, $input_length - 1)];
  25. $random_string .= $random_character;
  26. }
  27. return $random_string;
  28. }
  29. public function redirectToProvider()
  30. {
  31. $this->oauth2Info = request('oauth2Info');
  32. $this->oauth2Info['ClientId'] = config('app.api.erp.ClientId');
  33. $this->oauth2Info['ClientSecret'] = config('app.api.erp.ClientSecret');
  34. $this->target = request('target');
  35. $host = request()->getSchemeAndHttpHost();
  36. $callback_uri = $host . "/dabory/ssologin/callback?target={$this->target}";
  37. session()->put('oauth2Info', $this->oauth2Info);
  38. session()->put('target', $this->target);
  39. $state = $this->generate_string();
  40. $url = $this->oauth2Info['AuthorizeUri'] . '?client_id=' . $this->oauth2Info['ClientId'] . '&redirect_uri=' . $callback_uri . '&response_type=code&scope=all&state=' . $state;
  41. return redirect()->away($url);
  42. }
  43. function getAccessToken($authorization_code)
  44. {
  45. $host = request()->getSchemeAndHttpHost();
  46. $callback_uri = $host . "/dabory/ssologin/callback?target={$this->target}";
  47. $authorization = base64_encode("{$this->oauth2Info['ClientId']}:{$this->oauth2Info['ClientSecret']}");
  48. $header = array("Authorization: Basic {$authorization}", "Content-Type: application/x-www-form-urlencoded");
  49. $content = "grant_type=authorization_code&code=$authorization_code&redirect_uri={$callback_uri}";
  50. $curl = curl_init();
  51. curl_setopt_array($curl, array(
  52. CURLOPT_URL => $this->oauth2Info['TokenUri'],
  53. CURLOPT_HTTPHEADER => $header,
  54. CURLOPT_SSL_VERIFYPEER => false,
  55. CURLOPT_RETURNTRANSFER => true,
  56. CURLOPT_POST => true,
  57. CURLOPT_POSTFIELDS => $content
  58. ));
  59. $response = curl_exec($curl);
  60. curl_close($curl);
  61. if ($response === false) {
  62. echo "Failed";
  63. echo curl_error($curl);
  64. echo "Failed";
  65. }
  66. return json_decode($response)->access_token;
  67. }
  68. // we can now use the access_token as much as we want to access protected resources
  69. function getResource($access_token)
  70. {
  71. $header = array("Authorization: Bearer {$access_token}");
  72. $curl = curl_init();
  73. curl_setopt_array($curl, array(
  74. CURLOPT_URL => $this->oauth2Info['UserInfoUri'],
  75. CURLOPT_HTTPHEADER => $header,
  76. CURLOPT_SSL_VERIFYPEER => false,
  77. CURLOPT_RETURNTRANSFER => true
  78. ));
  79. $response = curl_exec($curl);
  80. curl_close($curl);
  81. return json_decode($response, true);
  82. }
  83. /**
  84. * Handles redirecting off to the login provider
  85. *
  86. * @return array ['token' => array $token, 'profile' => \Hybridauth\User\Profile]
  87. */
  88. public function handleProviderCallback()
  89. {
  90. $code = filter_input(INPUT_GET, 'code');
  91. $token = $this->getAccessToken($code);
  92. $profile = $this->getResource($token);
  93. return [
  94. 'token' => $token,
  95. 'profile' => $profile
  96. ];
  97. }
  98. public function login()
  99. {
  100. $this->oauth2Info = session('oauth2Info');
  101. $this->oauth2Info['ClientId'] = config('app.api.erp.ClientId');
  102. $this->oauth2Info['ClientSecret'] = config('app.api.erp.ClientSecret');
  103. $this->target = session('target');
  104. session()->forget('oauth2Info');
  105. session()->forget('target');
  106. $loginRoute = request('target') == 'member' ? 'pro.auth.member-sso-login' : 'user-login';
  107. if (request('target') !== $this->target) {
  108. return redirect()->route($loginRoute);
  109. }
  110. try {
  111. $providerResponse = $this->handleProviderCallback();
  112. $userDetails = $providerResponse['profile'];
  113. if (!is_array($providerResponse))
  114. return redirect()->route($loginRoute);
  115. } catch (Exception $e) {
  116. return redirect()->route($loginRoute)->with(['mgs' => $e->getMessage()]);
  117. }
  118. if (request('target') == 'member') {
  119. $this->memberLogin($userDetails);
  120. return redirect()->to($this->oauth2Info['AfterMemberLoginUri']);
  121. } else {
  122. $this->usersLogin($userDetails);
  123. return redirect()->to($this->oauth2Info['AfterUsersLoginUri']);
  124. }
  125. // dd($this->oauth2Info);
  126. }
  127. public function memberLogin($userDetails)
  128. {
  129. $response = (new ApiController($this->callApiService))->callApi('member-sso-login', [
  130. 'Email' => $userDetails['user_id'],
  131. 'SsoBrand' => 'dabory',
  132. 'SsoSub' => $userDetails['sso_sub'],
  133. ]);
  134. if (isset($response['apiStatus'])) {
  135. return redirect()->route('pro.auth.member-sso-login')->with(['mgs' => $response['body']]);
  136. }
  137. session()->put('member', array_merge($response, ['is_member' => true, 'Ip' => request()->ip()]));
  138. }
  139. public function usersLogin($userDetails)
  140. {
  141. $response = (new ApiController($this->callApiService))->callApi('user-sso-login', [
  142. 'Email' => $userDetails['user_id'],
  143. 'SsoBrand' => 'dabory',
  144. 'SsoSub' => $userDetails['sso_sub'],
  145. ]);
  146. // dd($response);
  147. if (isset($response['apiStatus'])) {
  148. return redirect()->route('user-login')->with(['mgs' => $response['body']]);
  149. }
  150. session()->put('user', array_merge($response, ['is_member' => true, 'Ip' => request()->ip()]));
  151. // dd(session('user'));
  152. }
  153. public function logout(): \Illuminate\Http\RedirectResponse
  154. {
  155. session()->forget('user');
  156. session()->forget('member');
  157. session()->forget('GateToken');
  158. return redirect()->route('pro.auth.member-login');
  159. }
  160. }