forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
github.go
93 lines (77 loc) · 2.29 KB
/
github.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package github
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/RangelReale/osincli"
"github.com/golang/glog"
authapi "github.com/openshift/origin/pkg/auth/api"
"github.com/openshift/origin/pkg/auth/oauth/external"
)
const (
githubAuthorizeURL = "https://github.com/login/oauth/authorize"
githubTokenURL = "https://github.com/login/oauth/access_token"
githubUserApiURL = "https://api.github.com/user"
githubOauthScope = "user:email"
)
type provider struct {
clientID, clientSecret string
}
type githubUser struct {
ID uint64
Login string
Email string
Name string
}
func NewProvider(clientID, clientSecret string) external.Provider {
return provider{clientID, clientSecret}
}
// NewConfig implements external/interfaces/Provider.NewConfig
func (p provider) NewConfig() (*osincli.ClientConfig, error) {
config := &osincli.ClientConfig{
ClientId: p.clientID,
ClientSecret: p.clientSecret,
ErrorsInStatusCode: true,
SendClientSecretInParams: true,
AuthorizeUrl: githubAuthorizeURL,
TokenUrl: githubTokenURL,
Scope: githubOauthScope,
}
return config, nil
}
// AddCustomParameters implements external/interfaces/Provider.AddCustomParameters
func (p provider) AddCustomParameters(req *osincli.AuthorizeRequest) {
}
// GetUserIdentity implements external/interfaces/Provider.GetUserIdentity
func (p provider) GetUserIdentity(data *osincli.AccessData) (authapi.UserIdentityInfo, bool, error) {
req, _ := http.NewRequest("GET", githubUserApiURL, nil)
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", data.AccessToken))
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, false, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, false, err
}
userdata := githubUser{}
err = json.Unmarshal(body, &userdata)
if err != nil {
return nil, false, err
}
if userdata.ID == 0 {
return nil, false, errors.New("Could not retrieve GitHub id")
}
identity := &authapi.DefaultUserIdentityInfo{
UserName: fmt.Sprintf("%d", userdata.ID),
Extra: map[string]string{
"name": userdata.Name,
"login": userdata.Login,
"email": userdata.Email,
},
}
glog.V(4).Infof("Got identity=%#v", identity)
return identity, true, nil
}