Base.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. namespace Overtrue\Socialite\Providers;
  3. use GuzzleHttp\Client as GuzzleClient;
  4. use GuzzleHttp\Psr7\Stream;
  5. use Overtrue\Socialite\Config;
  6. use Overtrue\Socialite\Contracts\ProviderInterface;
  7. use Overtrue\Socialite\Exceptions\AuthorizeFailedException;
  8. use Overtrue\Socialite\Exceptions\MethodDoesNotSupportException;
  9. use Overtrue\Socialite\User;
  10. abstract class Base implements ProviderInterface
  11. {
  12. public const NAME = null;
  13. protected ?string $state = null;
  14. protected Config $config;
  15. protected ?string $redirectUrl;
  16. protected array $parameters = [];
  17. protected array $scopes = [];
  18. protected string $scopeSeparator = ',';
  19. protected GuzzleClient $httpClient;
  20. protected array $guzzleOptions = [];
  21. protected int $encodingType = PHP_QUERY_RFC1738;
  22. protected string $expiresInKey = 'expires_in';
  23. protected string $accessTokenKey = 'access_token';
  24. protected string $refreshTokenKey = 'refresh_token';
  25. public function __construct(array $config)
  26. {
  27. $this->config = new Config($config);
  28. // set scopes
  29. if ($this->config->has('scopes') && is_array($this->config->get('scopes'))) {
  30. $this->scopes = $this->getConfig()->get('scopes');
  31. } else if ($this->config->has('scope') && is_string($this->getConfig()->get('scope'))) {
  32. $this->scopes = array($this->getConfig()->get('scope'));
  33. }
  34. // normalize 'client_id'
  35. if (!$this->config->has('client_id')) {
  36. $id = $this->config->get('app_id');
  37. if (null != $id) {
  38. $this->config->set('client_id', $id);
  39. }
  40. }
  41. // normalize 'client_secret'
  42. if (!$this->config->has('client_secret')) {
  43. $secret = $this->config->get('app_secret');
  44. if (null != $secret) {
  45. $this->config->set('client_secret', $secret);
  46. }
  47. }
  48. // normalize 'redirect_url'
  49. if (!$this->config->has('redirect_url')) {
  50. $this->config->set('redirect_url', $this->config->get('redirect'));
  51. }
  52. $this->redirectUrl = $this->config->get('redirect_url');
  53. }
  54. abstract protected function getAuthUrl(): string;
  55. abstract protected function getTokenUrl(): string;
  56. abstract protected function getUserByToken(string $token): array;
  57. abstract protected function mapUserToObject(array $user): User;
  58. /**
  59. * @param string|null $redirectUrl
  60. *
  61. * @return string
  62. */
  63. public function redirect(?string $redirectUrl = null): string
  64. {
  65. if (!empty($redirectUrl)) {
  66. $this->withRedirectUrl($redirectUrl);
  67. }
  68. return $this->getAuthUrl();
  69. }
  70. /**
  71. * @param string $code
  72. *
  73. * @return \Overtrue\Socialite\User
  74. * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
  75. * @throws \GuzzleHttp\Exception\GuzzleException
  76. */
  77. public function userFromCode(string $code): User
  78. {
  79. $tokenResponse = $this->tokenFromCode($code);
  80. $user = $this->userFromToken($tokenResponse[$this->accessTokenKey]);
  81. return $user->setRefreshToken($tokenResponse[$this->refreshTokenKey] ?? null)
  82. ->setExpiresIn($tokenResponse[$this->expiresInKey] ?? null)
  83. ->setTokenResponse($tokenResponse);
  84. }
  85. /**
  86. * @param string $token
  87. *
  88. * @return \Overtrue\Socialite\User
  89. */
  90. public function userFromToken(string $token): User
  91. {
  92. $user = $this->getUserByToken($token);
  93. return $this->mapUserToObject($user)->setProvider($this)->setRaw($user)->setAccessToken($token);
  94. }
  95. /**
  96. * @param string $code
  97. *
  98. * @return array
  99. * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException|\GuzzleHttp\Exception\GuzzleException
  100. */
  101. public function tokenFromCode(string $code): array
  102. {
  103. $response = $this->getHttpClient()->post(
  104. $this->getTokenUrl(),
  105. [
  106. 'form_params' => $this->getTokenFields($code),
  107. 'headers' => [
  108. 'Accept' => 'application/json',
  109. ],
  110. ]
  111. );
  112. return $this->normalizeAccessTokenResponse($response->getBody()->getContents());
  113. }
  114. /**
  115. * @param string $refreshToken
  116. *
  117. * @throws \Overtrue\Socialite\Exceptions\MethodDoesNotSupportException
  118. */
  119. public function refreshToken(string $refreshToken)
  120. {
  121. throw new MethodDoesNotSupportException('refreshToken does not support.');
  122. }
  123. /**
  124. * @param string $redirectUrl
  125. *
  126. * @return $this|\Overtrue\Socialite\Contracts\ProviderInterface
  127. */
  128. public function withRedirectUrl(string $redirectUrl): ProviderInterface
  129. {
  130. $this->redirectUrl = $redirectUrl;
  131. return $this;
  132. }
  133. /**
  134. * @param string $state
  135. *
  136. * @return \Overtrue\Socialite\Contracts\ProviderInterface
  137. */
  138. public function withState(string $state): ProviderInterface
  139. {
  140. $this->state = $state;
  141. return $this;
  142. }
  143. /**
  144. * @param array $scopes
  145. *
  146. * @return $this
  147. */
  148. public function scopes(array $scopes): self
  149. {
  150. $this->scopes = $scopes;
  151. return $this;
  152. }
  153. /**
  154. * @param array $parameters
  155. *
  156. * @return $this
  157. */
  158. public function with(array $parameters): self
  159. {
  160. $this->parameters = $parameters;
  161. return $this;
  162. }
  163. public function getConfig(): Config
  164. {
  165. return $this->config;
  166. }
  167. /**
  168. * @param string $scopeSeparator
  169. *
  170. * @return self
  171. */
  172. public function withScopeSeparator(string $scopeSeparator): self
  173. {
  174. $this->scopeSeparator = $scopeSeparator;
  175. return $this;
  176. }
  177. public function getClientId(): ?string
  178. {
  179. return $this->config->get('client_id');
  180. }
  181. public function getClientSecret(): ?string
  182. {
  183. return $this->config->get('client_secret');
  184. }
  185. public function getHttpClient(): GuzzleClient
  186. {
  187. return $this->httpClient ?? new GuzzleClient($this->guzzleOptions);
  188. }
  189. /**
  190. * @param array $config
  191. *
  192. * @return \Overtrue\Socialite\Contracts\ProviderInterface
  193. */
  194. public function setGuzzleOptions($config = []): ProviderInterface
  195. {
  196. $this->guzzleOptions = $config;
  197. return $this;
  198. }
  199. public function getGuzzleOptions(): array
  200. {
  201. return $this->guzzleOptions;
  202. }
  203. /**
  204. * @param array $scopes
  205. * @param string $scopeSeparator
  206. *
  207. * @return string
  208. */
  209. protected function formatScopes(array $scopes, $scopeSeparator): string
  210. {
  211. return implode($scopeSeparator, $scopes);
  212. }
  213. /**
  214. * @param string $code
  215. *
  216. * @return array
  217. */
  218. protected function getTokenFields(string $code): array
  219. {
  220. return [
  221. 'client_id' => $this->getClientId(),
  222. 'client_secret' => $this->getClientSecret(),
  223. 'code' => $code,
  224. 'redirect_uri' => $this->redirectUrl,
  225. ];
  226. }
  227. /**
  228. * @param string $url
  229. *
  230. * @return string
  231. */
  232. protected function buildAuthUrlFromBase(string $url): string
  233. {
  234. $query = $this->getCodeFields() + ($this->state ? ['state' => $this->state] : []);
  235. return $url . '?' . \http_build_query($query, '', '&', $this->encodingType);
  236. }
  237. protected function getCodeFields(): array
  238. {
  239. $fields = array_merge(
  240. [
  241. 'client_id' => $this->getClientId(),
  242. 'redirect_uri' => $this->redirectUrl,
  243. 'scope' => $this->formatScopes($this->scopes, $this->scopeSeparator),
  244. 'response_type' => 'code',
  245. ],
  246. $this->parameters
  247. );
  248. if ($this->state) {
  249. $fields['state'] = $this->state;
  250. }
  251. return $fields;
  252. }
  253. /**
  254. * @param array|string $response
  255. *
  256. * @return mixed
  257. * @return array
  258. * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
  259. *
  260. */
  261. protected function normalizeAccessTokenResponse($response): array
  262. {
  263. if ($response instanceof Stream) {
  264. $response->rewind();
  265. $response = $response->getContents();
  266. }
  267. if (\is_string($response)) {
  268. $response = json_decode($response, true) ?? [];
  269. }
  270. if (!\is_array($response)) {
  271. throw new AuthorizeFailedException('Invalid token response', [$response]);
  272. }
  273. if (empty($response[$this->accessTokenKey])) {
  274. throw new AuthorizeFailedException('Authorize Failed: ' . json_encode($response, JSON_UNESCAPED_UNICODE), $response);
  275. }
  276. return $response + [
  277. 'access_token' => $response[$this->accessTokenKey],
  278. 'refresh_token' => $response[$this->refreshTokenKey] ?? null,
  279. 'expires_in' => \intval($response[$this->expiresInKey] ?? 0),
  280. ];
  281. }
  282. }