forked from u5surf/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
312 lines (269 loc) · 8.66 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
stderr "errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/moov-io/auth/pkg/oauthdb"
moovhttp "github.com/moov-io/base/http"
"github.com/go-kit/kit/log"
"github.com/gorilla/mux"
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/errors"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/models"
"gopkg.in/oauth2.v3/server"
)
var (
errNoClientId = stderr.New("missing client_id")
)
type oauth struct {
manager *manage.Manager
clientStore *oauthdb.ClientStore
tokenStore oauth2.TokenStore
server *server.Server
logger log.Logger
}
func setupOAuthTokenStore(connStr string) (oauth2.TokenStore, error) {
if connStr == "" {
connStr = "file:oauth2_tokens.db"
}
return oauthdb.NewTokenStoreDB(connStr)
}
func setupOAuthClientStore(connStr string) (*oauthdb.ClientStore, error) {
if connStr == "" {
connStr = "file:oauth2_clients.db"
}
return oauthdb.NewClientStoreDB(connStr)
}
func setupOAuthServer(logger log.Logger, clientStore *oauthdb.ClientStore, tokenStore oauth2.TokenStore) (*oauth, error) {
out := &oauth{
logger: logger,
}
// Create our session manager
out.manager = manage.NewDefaultManager()
out.manager.MapTokenStorage(tokenStore)
out.tokenStore = tokenStore
// Defaults from (in vendor/)
// gopkg.in/oauth2.v3/manage/config.go
cfg := &manage.Config{
AccessTokenExp: 2 * time.Hour,
RefreshTokenExp: 24 * 3 * time.Hour,
IsGenerateRefresh: true,
}
out.manager.SetAuthorizeCodeTokenCfg(cfg)
out.manager.SetClientTokenCfg(cfg)
// Setup oauth2 clients database
out.clientStore = clientStore
out.manager.MapClientStorage(out.clientStore)
out.server = server.NewDefaultServer(out.manager)
out.server.SetAllowGetAccessRequest(true)
out.server.SetClientInfoHandler(server.ClientFormHandler)
out.server.SetInternalErrorHandler(func(err error) (re *errors.Response) {
logger.Log("internal-error", err.Error())
return
})
out.server.SetResponseErrorHandler(func(re *errors.Response) {
m := re.Error.Error()
if m == "server_error" || m == "unsupported_grant_type" {
return
}
logger.Log("response-error", m)
})
return out, nil
}
// addOAuthRoutes includes our oauth2 routes on the provided mux.Router
func addOAuthRoutes(r *mux.Router, o *oauth, logger log.Logger, auth authable) {
r.Methods("GET").Path("/oauth2/authorize").HandlerFunc(o.authorizeHandler)
r.Methods("GET").Path("/oauth2/clients").HandlerFunc(o.getClientsForUserId(auth))
r.Methods("POST").Path("/oauth2/client").HandlerFunc(o.createClientHandler(auth))
// Check token routes
if o.server.Config.AllowGetAccessRequest {
// only open up GET if the server config asks for it
r.Methods("GET").Path("/oauth2/token").HandlerFunc(o.tokenHandler(auth))
}
r.Methods("POST").Path("/oauth2/token").HandlerFunc(o.tokenHandler(auth))
}
// requestHasValidOAuthToken hooks into the go-oauth2 methods to validate
// a 'Bearer ...' Authorization header and the token.
func (o *oauth) requestHasValidOAuthToken(r *http.Request) (oauth2.TokenInfo, error) {
// We aren't using HandleAuthorizeRequest here because that assumes redirect_uri
// exists on the request. We're just checking for a valid token.
ti, err := o.server.ValidationBearerToken(r)
if err != nil {
authFailures.With("method", "oauth2").Add(1)
return nil, err
}
if ti.GetClientID() == "" {
authFailures.With("method", "oauth2").Add(1)
return nil, errNoClientId
}
return ti, nil
}
// authorizeHandler checks the request for appropriate oauth information
// and returns "200 OK" if the token is valid.
func (o *oauth) authorizeHandler(w http.ResponseWriter, r *http.Request) {
w = wrapResponseWriter(w, r, "oauth.authorizeHandler")
if _, err := o.requestHasValidOAuthToken(r); err != nil {
w.WriteHeader(http.StatusForbidden)
moovhttp.Problem(w, err)
return
}
// Passed token check, return "200 OK"
authSuccesses.With("method", "oauth2").Add(1)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}
// tokenHandler passes off the request down to our oauth2 library to
// generate a token (or return an error).
func (o *oauth) tokenHandler(auth authable) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w = wrapResponseWriter(w, r, "oauth.tokenHandler")
userId, err := extractUserId(auth, r)
if err != nil {
moovhttp.Problem(w, err)
return
}
// This block is copied from o.server.HandleTokenRequest
// We needed to inspect what's going on a bit.
gt, tgr, verr := o.server.ValidationTokenRequest(r)
if verr != nil {
moovhttp.Problem(w, verr)
return
}
ti, verr := o.server.GetAccessToken(gt, tgr)
if verr != nil {
moovhttp.Problem(w, verr)
return
}
data := o.server.GetTokenData(ti)
bs, err := json.Marshal(data)
if err != nil {
moovhttp.Problem(w, err)
return
}
// (end of copy)
// HandleTokenRequest currently returns nil even if the token request
// failed. That menas we can't clearly know if token generation passed or failed.
// We check ww.Code then, it'll be 0 if no WriteHeader calls were made.
if ww, ok := w.(*responseWriter); ok && ww.rec.Code == http.StatusOK {
tokenGenerations.Add(1)
// Set userId on the token and update in our DB.
ti.SetUserID(userId)
if err := o.tokenStore.Create(ti); err != nil {
moovhttp.InternalError(w, fmt.Errorf("unable to update OAuth token userId (%s): %v", userId, err))
return
}
w.Header().Set("X-User-Id", userId) // only on non-errors
}
// Write our response
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(bs)
}
}
// createClientHandler will create an oauth client for the authenticated user.
//
// This method extracts the user from the cookies in r.
func (o *oauth) createClientHandler(auth authable) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w = wrapResponseWriter(w, r, "oauth.createTokenHandler")
userId, err := auth.findUserId(extractCookie(r).Value)
if err != nil {
// user not found, return
w.WriteHeader(http.StatusForbidden)
return
}
// TODO(adam): don't create tokens if user hasn't gone through email verification
records, err := o.clientStore.GetByUserID(userId)
if err != nil && !strings.Contains(err.Error(), "not found") {
internalError(w, err)
return
}
if len(records) == 0 { // nothing found, so fake one
records = append(records, &models.Client{})
}
clients := make([]*models.Client, len(records))
for i := range records {
err = o.clientStore.DeleteByID(records[i].GetID())
if err != nil && !strings.Contains(err.Error(), "not found") {
internalError(w, err)
return
}
clients[i] = &models.Client{
ID: generateID()[:12],
Secret: generateID(),
Domain: Domain,
UserID: userId,
}
// Write client into oauth clients db.
if err := o.clientStore.Set(clients[i].GetID(), clients[i]); err != nil {
internalError(w, err)
return
}
}
// metrics
clientGenerations.Add(1)
// render back new clients
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var responseClients []*client
for i := range clients {
responseClients = append(responseClients, &client{
ClientID: clients[i].ID,
ClientSecret: clients[i].Secret,
Domain: clients[i].Domain,
})
}
if err := json.NewEncoder(w).Encode(responseClients); err != nil {
internalError(w, err)
return
}
}
}
type client struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Domain string `json:"domain"`
}
func (o *oauth) shutdown() error {
if o == nil || o.clientStore == nil {
return nil
}
return o.clientStore.Close()
}
func (o *oauth) getClientsForUserId(auth authable) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w = wrapResponseWriter(w, r, "oauth.getClientsForUserId")
userId, err := extractUserId(auth, r)
if err != nil {
w.WriteHeader(http.StatusForbidden)
return
}
clients, err := o.clientStore.GetByUserID(userId)
if err != nil {
internalError(w, err)
return
}
// render OAuth2 clients for user
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var responseClients []*client
for i := range clients {
responseClients = append(responseClients, &client{
ClientID: clients[i].GetID(),
ClientSecret: clients[i].GetSecret(),
Domain: clients[i].GetDomain(),
})
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(responseClients); err != nil {
internalError(w, err)
return
}
}
}