forked from bitly/oauth2_proxy
-
Notifications
You must be signed in to change notification settings - Fork 9
/
gitlab.go
122 lines (107 loc) · 2.42 KB
/
gitlab.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package providers
import (
"log"
"net/http"
"net/url"
"path"
"strconv"
"github.com/ploxiln/oauth2_proxy/api"
)
type GitLabProvider struct {
*ProviderData
Groups []string
}
func NewGitLabProvider(p *ProviderData) *GitLabProvider {
p.ProviderName = "GitLab"
if p.LoginURL == nil || p.LoginURL.String() == "" {
p.LoginURL = &url.URL{
Scheme: "https",
Host: "gitlab.com",
Path: "/oauth/authorize",
}
}
if p.RedeemURL == nil || p.RedeemURL.String() == "" {
p.RedeemURL = &url.URL{
Scheme: "https",
Host: "gitlab.com",
Path: "/oauth/token",
}
}
if p.ValidateURL == nil || p.ValidateURL.String() == "" {
p.ValidateURL = &url.URL{
Scheme: "https",
Host: "gitlab.com",
Path: "/api/v4/user",
}
}
return &GitLabProvider{ProviderData: p}
}
func (p *GitLabProvider) SetGroups(groups []string) {
p.Groups = groups
if p.Scope == "" {
if len(groups) > 0 {
p.Scope = "api"
} else {
p.Scope = "read_user"
}
}
}
func (p *GitLabProvider) hasGroup(accessToken string) (bool, error) {
type groupsPage []struct {
FullPath string `json:"full_path"`
}
for pn := 1; pn <= 10; pn++ {
params := url.Values{
"access_token": {accessToken},
"per_page": {"100"},
"page": {strconv.Itoa(pn)},
}
endpoint := &url.URL{
Scheme: p.ValidateURL.Scheme,
Host: p.ValidateURL.Host,
Path: path.Join(p.ValidateURL.Path, "../groups"),
RawQuery: params.Encode(),
}
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return false, err
}
var groups groupsPage
err = api.RequestJson(req, &groups)
if err != nil {
return false, err
}
if len(groups) == 0 {
break
}
for _, group := range groups {
for _, g := range p.Groups {
if g == group.FullPath {
log.Printf("Found GitLab Group:%q", g)
return true, nil
}
}
}
}
return false, nil
}
func (p *GitLabProvider) GetEmailAddress(s *SessionState) (string, error) {
// if we require a Group, check that first
if len(p.Groups) > 0 {
if ok, err := p.hasGroup(s.AccessToken); err != nil || !ok {
return "", err
}
}
req, err := http.NewRequest("GET",
p.ValidateURL.String()+"?access_token="+s.AccessToken, nil)
if err != nil {
log.Printf("failed building request %s", err)
return "", err
}
json, err := api.Request(req)
if err != nil {
log.Printf("failed making request %s", err)
return "", err
}
return json.Get("email").String()
}