-
-
Notifications
You must be signed in to change notification settings - Fork 617
/
oauth.go
207 lines (176 loc) · 5.6 KB
/
oauth.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package web
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/jsonq"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/oauth"
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
)
var (
systemProviders = []*models.OAuthConfig{
&models.OAuthConfig{
Provider: oauth.FacebookProvider,
DisplayName: "Facebook",
ProfileURL: "https://graph.facebook.com/me?fields=name,email",
ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),
ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),
Scope: "public_profile email",
AuthorizeURL: facebook.Endpoint.AuthURL,
TokenURL: facebook.Endpoint.TokenURL,
JSONUserIDPath: "id",
JSONNamePath: "name",
JSONEmailPath: "email",
},
&models.OAuthConfig{
Provider: oauth.GoogleProvider,
DisplayName: "Google",
ProfileURL: "https://www.googleapis.com/plus/v1/people/me",
ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),
ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),
Scope: "profile email",
AuthorizeURL: google.Endpoint.AuthURL,
TokenURL: google.Endpoint.TokenURL,
JSONUserIDPath: "id",
JSONNamePath: "displayName",
JSONEmailPath: "emails[0].value",
},
&models.OAuthConfig{
Provider: oauth.GitHubProvider,
DisplayName: "GitHub",
ProfileURL: "https://api.github.com/user",
ClientID: os.Getenv("OAUTH_GITHUB_CLIENTID"),
ClientSecret: os.Getenv("OAUTH_GITHUB_SECRET"),
Scope: "user:email",
AuthorizeURL: github.Endpoint.AuthURL,
TokenURL: github.Endpoint.TokenURL,
JSONUserIDPath: "id",
JSONNamePath: "name, login",
JSONEmailPath: "email",
},
}
)
//OAuthService implements real OAuth operations using Golang's oauth2 package
type OAuthService struct {
oauthBaseURL string
}
//NewOAuthService creates a new OAuthService
func NewOAuthService(oauthBaseURL string) *OAuthService {
return &OAuthService{
oauthBaseURL,
}
}
//GetAuthURL returns authentication url for given provider
func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string, error) {
config, err := s.getConfig(provider)
if err != nil {
return "", err
}
authURL, _ := url.Parse(config.AuthorizeURL)
parameters := url.Values{}
parameters.Add("client_id", config.ClientID)
parameters.Add("scope", config.Scope)
parameters.Add("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider))
parameters.Add("response_type", "code")
parameters.Add("state", redirect+"|"+identifier)
authURL.RawQuery = parameters.Encode()
return authURL.String(), nil
}
//GetProfile returns user profile based on provider and code
func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
config, err := s.getConfig(provider)
if err != nil {
return nil, err
}
exchange := (&oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: config.AuthorizeURL,
TokenURL: config.TokenURL,
},
RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider),
}).Exchange
oauthToken, err := exchange(oauth2.NoContext, code)
if err != nil {
return nil, errors.Wrap(err, "failed to exchange OAuth2 code with %s", provider)
}
bytes, err := s.doGet(config.ProfileURL, oauthToken.AccessToken)
if err != nil {
return nil, err
}
return s.ParseProfileResponse(string(bytes), config)
}
//ParseProfileResponse parses profile response into UserProfile model
func (s *OAuthService) ParseProfileResponse(body string, config *models.OAuthConfig) (*oauth.UserProfile, error) {
query := jsonq.New(body)
println(body)
profile := &oauth.UserProfile{
ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),
Name: strings.TrimSpace(query.String(config.JSONNamePath)),
Email: strings.TrimSpace(query.String(config.JSONEmailPath)),
}
if profile.ID == "" {
return nil, oauth.ErrUserIDRequired
}
if profile.Name == "" && profile.Email != "" {
parts := strings.Split(profile.Email, "@")
profile.Name = parts[0]
}
if profile.Name == "" {
profile.Name = "Anonymous"
}
if !validate.Email(profile.Email).Ok {
profile.Email = ""
}
return profile, nil
}
//ListProviders returns a list of all providers for current tenant
func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {
list := make([]*oauth.ProviderOption, 0)
for _, p := range systemProviders {
if p.ClientID != "" {
list = append(list, &oauth.ProviderOption{
Provider: p.Provider,
DisplayName: p.DisplayName,
URL: fmt.Sprintf("/oauth/%s", p.Provider),
})
}
}
return list, nil
}
func (s *OAuthService) doGet(url, accessToken string) ([]byte, error) {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
r, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to request GET %s", url)
}
if r.StatusCode != 200 {
return nil, errors.New("failed to request GET %s with status code %d and response %s", url, r.StatusCode, string(bytes))
}
return bytes, nil
}
func (s *OAuthService) getConfig(provider string) (*models.OAuthConfig, error) {
for _, p := range systemProviders {
if p.Provider == provider {
return p, nil
}
}
return nil, app.ErrNotFound
}