-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
95 lines (78 loc) · 2.12 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
94
95
package oauth
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type GithubAccessTokenRequest struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Code string `json:"code"`
}
type GithubUserResponse struct {
ID int `json:"id"`
Login string `json:"login"`
}
type GithubOauth struct{}
func (o *GithubOauth) LoginURL(cfg *OAuthConfig) string {
return fmt.Sprintf("https://github.com/login/oauth/authorize?client_id=%s", cfg.ClientID)
}
func (o *GithubOauth) RequestAccessToken(code string, cfg *OAuthConfig) (string, error) {
accessTokenReq := GithubAccessTokenRequest{
ClientID: cfg.ClientID,
ClientSecret: cfg.Secret,
Code: code,
}
data, err := json.Marshal(accessTokenReq)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(data))
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
tokenData := AccessTokenResponse{}
err = json.NewDecoder(resp.Body).Decode(&tokenData)
if err != nil {
return "", err
}
return tokenData.AccessToken, nil
}
func (o *GithubOauth) RequestUserInfo(access_token string, cfg *OAuthConfig) (*OauthUserInfo, error) {
// fetch user data
req, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
userData := GithubUserResponse{}
err = json.NewDecoder(resp.Body).Decode(&userData)
if err != nil {
return nil, err
}
external_id := strconv.Itoa(userData.ID)
info := OauthUserInfo{
Provider: ProviderTypeGithub,
Name: userData.Login,
ExternalID: external_id,
AvatarURL: fmt.Sprintf("https://github.com/%s.png", userData.Login),
}
return &info, nil
}