GitHub.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Overtrue\Socialite\Providers;
  3. use Overtrue\Socialite\User;
  4. class GitHub extends Base
  5. {
  6. public const NAME = 'github';
  7. protected array $scopes = ['read:user'];
  8. protected function getAuthUrl(): string
  9. {
  10. return $this->buildAuthUrlFromBase('https://github.com/login/oauth/authorize');
  11. }
  12. protected function getTokenUrl(): string
  13. {
  14. return 'https://github.com/login/oauth/access_token';
  15. }
  16. /**
  17. * @param string $token
  18. *
  19. * @return array
  20. * @throws \GuzzleHttp\Exception\GuzzleException
  21. */
  22. protected function getUserByToken(string $token): array
  23. {
  24. $userUrl = 'https://api.github.com/user';
  25. $response = $this->getHttpClient()->get(
  26. $userUrl,
  27. $this->createAuthorizationHeaders($token)
  28. );
  29. $user = json_decode($response->getBody(), true);
  30. if (in_array('user:email', $this->scopes)) {
  31. $user['email'] = $this->getEmailByToken($token);
  32. }
  33. return $user;
  34. }
  35. /**
  36. * @param string $token
  37. *
  38. * @return string
  39. */
  40. protected function getEmailByToken(string $token)
  41. {
  42. $emailsUrl = 'https://api.github.com/user/emails';
  43. try {
  44. $response = $this->getHttpClient()->get(
  45. $emailsUrl,
  46. $this->createAuthorizationHeaders($token)
  47. );
  48. } catch (\Throwable $e) {
  49. return '';
  50. }
  51. foreach (json_decode($response->getBody(), true) as $email) {
  52. if ($email['primary'] && $email['verified']) {
  53. return $email['email'];
  54. }
  55. }
  56. }
  57. protected function mapUserToObject(array $user): User
  58. {
  59. return new User([
  60. 'id' => $user['id'] ?? null,
  61. 'nickname' => $user['login'] ?? null,
  62. 'name' => $user['name'] ?? null,
  63. 'email' => $user['email'] ?? null,
  64. 'avatar' => $user['avatar_url'] ?? null,
  65. ]);
  66. }
  67. /**
  68. * @param string $token
  69. *
  70. * @return array
  71. */
  72. protected function createAuthorizationHeaders(string $token)
  73. {
  74. return [
  75. 'headers' => [
  76. 'Accept' => 'application/vnd.github.v3+json',
  77. 'Authorization' => sprintf('token %s', $token),
  78. ],
  79. ];
  80. }
  81. }