forked from qvest-digital/loginsrv
/
github.go
66 lines (55 loc) · 1.69 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
package oauth2
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/tarent/loginsrv/model"
)
var githubAPI = "https://api.github.com"
func init() {
RegisterProvider(providerGithub)
}
// GithubUser is used for parsing the github response
type GithubUser struct {
Login string `json:"login,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
}
var providerGithub = Provider{
Name: "github",
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
GetUserInfo: func(token TokenInfo) (model.UserInfo, string, error) {
gu := GithubUser{}
url := fmt.Sprintf("%v/user?access_token=%v", githubAPI, token.AccessToken)
resp, err := http.Get(url)
if err != nil {
return model.UserInfo{}, "", err
}
defer resp.Body.Close()
if !strings.Contains(resp.Header.Get("Content-Type"), "application/json") {
return model.UserInfo{}, "", fmt.Errorf("wrong content-type on github get user info: %v", resp.Header.Get("Content-Type"))
}
if resp.StatusCode != 200 {
return model.UserInfo{}, "", fmt.Errorf("got http status %v on github get user info", resp.StatusCode)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return model.UserInfo{}, "", fmt.Errorf("error reading github get user info: %v", err)
}
err = json.Unmarshal(b, &gu)
if err != nil {
return model.UserInfo{}, "", fmt.Errorf("error parsing github get user info: %v", err)
}
return model.UserInfo{
Sub: gu.Login,
Picture: gu.AvatarURL,
Name: gu.Name,
Email: gu.Email,
Origin: "github",
}, string(b), nil
},
}