summaryrefslogtreecommitdiff
path: root/includes/GithubProvider.php
blob: 5639383ad5825be7dd76a134934d3e357bee5dd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

use League\OAuth2\Client\Provider\Github;
use League\OAuth2\Client\Token\AccessToken as AccessToken;

/**
 * A workaround for fetching the users email address if the user does not have a
 * public email address.
 */
class GithubProvider extends Github
{
    public function userDetails($response, AccessToken $token)
    {
        $user = parent::userDetails($response, $token);
        
        // Fetch the primary email address
        if (!$user->email) {
            $emails = $this->fetchUserEmails($token);
            $emails = json_decode($emails);
            $email  = null;
            
            foreach ($emails as $email) {
                if ($email->primary) {
                    $email = $email->email;
                    break;
                }
            }
            
            $user->email = $email;
        }
        
        return $user;
    }
    
    protected function fetchUserEmails(AccessToken $token)
    {
        $url = "https://api.github.com/user/emails?access_token={$token}";
        
        try {

            $client = $this->getHttpClient();
            $client->setBaseUrl($url);

            if ($this->headers) {
                $client->setDefaultOption('headers', $this->headers);
            }

            $request = $client->get()->send();
            $response = $request->getBody();

        } catch (BadResponseException $e) {
            // @codeCoverageIgnoreStart
            $raw_response = explode("\n", $e->getResponse());
            throw new IDPException(end($raw_response));
            // @codeCoverageIgnoreEnd
        }

        return $response;
    }
}