-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
373 lines (313 loc) · 9.23 KB
/
handlers.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"errors"
"fmt"
"log"
"encoding/json"
"net/http"
"github.com/gorilla/context"
"github.com/paulrosania/go-validation"
"github.com/paulrosania/registrar/storage"
)
type HandlerFunc func(*Context, http.ResponseWriter) error
func writeError(w http.ResponseWriter, err error) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
log.Print(err)
switch err := err.(type) {
case *OAuthError:
err.Write(w)
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "{\"error_description\": %q}\n", err)
}
}
func writeJson(w http.ResponseWriter, o interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
buf, err := json.Marshal(o)
if err != nil {
writeError(w, NewOAuthError("internal_server_error", err.Error()))
return
}
fmt.Fprintln(w, string(buf))
}
func readOneFormValue(r *http.Request, key string) (val string, err error) {
val, err = readOneFormValueOptional(r, key)
if val == "" && err == nil {
return "", NewOAuthError("invalid_request", fmt.Sprintf("missing required parameter %q", key))
}
return
}
func readOneFormValueOptional(r *http.Request, key string) (val string, err error) {
vals := r.PostForm[key]
switch len(vals) {
case 1:
return vals[0], nil
case 0:
return "", nil
default:
return "", NewOAuthError("invalid_request", fmt.Sprintf("multiple parameters for %q", key))
}
}
// GET /.well-known/openid-configuration
func OpenIdConfigurationHandler(ctx *Context, w http.ResponseWriter) error {
baseUrl := ctx.Server.config.Server.BaseUrl
cfg := map[string]interface{}{
"issuer": baseUrl,
"authorization_endpoint": baseUrl + "/auth",
"token_endpoint": baseUrl + "/token",
"userinfo_endpoint": baseUrl + "/userinfo",
"revocation_endpoint": baseUrl + "/revoke",
"jwks_uri": baseUrl + "/certs",
"scopes_supported": []string{
"openid",
"email",
"profile"},
"response_types_supported": []string{
"code",
"token",
"id_token",
"code token",
"code id_token",
"code token id_token",
"none"},
"id_token_signing_alg_values_supported": []string{"RS256"},
"token_endpoint_auth_methods_supported": []string{"client_secret_basic"},
"subject_types_supported": []string{"public"},
"grant_types_supported": []string{
"authorization_code",
"implicit",
},
"claims_supported": []string{
"aud",
"email",
"email_verified",
"exp",
"family_name",
"given_name",
"iat",
"iss",
"locale",
"name",
"picture",
"sub",
},
}
writeJson(w, cfg)
return nil
}
// GET /userinfo
func UserinfoHandler(ctx *Context, w http.ResponseWriter) error {
// TODO: return valid userinfo response (sub is required)
if u, ok := context.GetOk(ctx.Request, CurrentPrincipal); ok {
writeJson(w, u)
} else {
return errors.New("failed to retrieve user")
}
return nil
}
func setCORSHeaders(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*") // TODO: this is a security flaw (needs to be fixed to wherever the proxy lives)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Max-Age", "3600") // (seconds)
}
func OptionsHandler(ctx *Context, w http.ResponseWriter) error {
setCORSHeaders(w)
return nil
}
// POST /accounts
func CreateAccountHandler(ctx *Context, w http.ResponseWriter) error {
setCORSHeaders(w)
params := new(storage.UserParams)
err := json.NewDecoder(ctx.Request.Body).Decode(params)
if err != nil {
return NewOAuthError("invalid_request", err.Error())
}
v := validation.NewMultiValidator()
v.Assert(params.Email != "", "email", "must provide a email")
v.Assert(params.Password != "", "password", "must provide a password")
if v.Valid() {
user, err := ctx.Server.store.Users.New(params)
if err == storage.ErrNotUnique {
err := NewOAuthError("invalid_request", "validation failed")
err.Meta["fields"] = map[string][]string{
"email": []string{"email address taken"},
}
return err
} else if err != nil {
return NewOAuthError("invalid_request", err.Error())
}
writeJson(w, user)
} else {
err := NewOAuthError("invalid_request", "validation failed")
err.Meta["fields"] = v.Errors()
return err
}
return nil
}
// GET /client
func ClientHandler(ctx *Context, w http.ResponseWriter) error {
if c, ok := context.GetOk(ctx.Request, CurrentPrincipal); ok {
writeJson(w, c)
} else {
return errors.New("failed to retrieve client")
}
return nil
}
// POST /clients
func NewClientHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
err := r.ParseForm()
if err != nil {
return NewOAuthError("invalid_request", err.Error())
}
name, err := readOneFormValue(r, "name")
if err != nil {
return err
}
client, err := ctx.Server.store.Apps.New(name, "", "", "", "secret")
if err != nil {
return NewOAuthError("invalid_request", err.Error())
}
writeJson(w, client)
return nil
}
// POST /token
func TokenHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
err := r.ParseForm()
if err != nil {
return NewOAuthError("invalid_request", err.Error())
}
grantType, err := readOneFormValue(r, "grant_type")
if err != nil {
return err
}
switch grantType {
case "authorization_code":
return authorizationCodeGrantHandler(ctx, w)
case "client_credentials":
return clientCredentialsGrantHandler(ctx, w)
case "password":
return passwordGrantHandler(ctx, w)
case "refresh_token":
return refreshTokenGrantHandler(ctx, w)
}
return NewOAuthError("unsupported_grant_type", fmt.Sprintf("unsupported grant type %q", grantType))
}
func authorizationCodeGrantHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
app := context.Get(r, CurrentPrincipal).(*storage.Application)
code, err := readOneFormValue(r, "code")
if err != nil {
return err
}
redirectUri, err := readOneFormValue(r, "redirect_uri")
if err != nil {
return err
}
resp, err := ctx.Server.store.Apps.ExchangeAuthCode(app, code, redirectUri)
if err != nil {
return err
}
writeJson(w, resp)
return nil
}
func clientCredentialsGrantHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
app := context.Get(r, CurrentPrincipal).(*storage.Application)
scope, err := readOneFormValueOptional(r, "scope")
if err != nil {
return err
}
token, err := ctx.Server.store.Apps.Authorize(app, scope)
if err != nil {
return err
}
writeJson(w, TokenResponse{
AccessToken: token.Token,
TokenType: token.Type,
ExpiresIn: 3600,
Scope: scope,
})
return nil
}
func passwordGrantHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
app := context.Get(r, CurrentPrincipal).(*storage.Application)
username, err := readOneFormValue(r, "username")
if err != nil {
return err
}
password, err := readOneFormValue(r, "password")
if err != nil {
return err
}
scope, err := readOneFormValueOptional(r, "scope")
if err != nil {
return err
}
user, err := ctx.Server.store.Users.FindByCredentials(username, password)
if err != nil {
return NewOAuthError("access_denied", "invalid username/password")
}
seconds := 3600
issuer := ctx.Server.config.OpenID.Issuer
accessToken := NewJWT(issuer, app.ClientId, user.Email, seconds)
refreshToken, err := ctx.Server.store.Users.Authorize(user.Id, app.Id, scope, true)
if err != nil {
return NewOAuthError("internal_server_error", "could not authorize client")
}
signedAccessToken, err := ctx.Server.SignJWT(accessToken)
if err != nil {
return NewOAuthError("internal_server_error", "could not authorize client")
}
resp := &TokenResponse{
AccessToken: signedAccessToken,
RefreshToken: refreshToken,
ExpiresIn: seconds,
TokenType: "bearer",
}
writeJson(w, resp)
return nil
}
func refreshTokenGrantHandler(ctx *Context, w http.ResponseWriter) error {
r := ctx.Request
app := context.Get(r, CurrentPrincipal).(*storage.Application)
refreshToken, err := readOneFormValue(r, "refresh_token")
if err != nil {
return err
}
scope, err := readOneFormValueOptional(r, "scope")
if err != nil {
return err
}
// TODO: actually need to load up old refresh token, check scope against scope param
// if scope param is empty, use refresh token scope
// if scope param includes scopes not granted to refresh token, fail (invalid_request)
// otherwise, use scope param
user, err := ctx.Server.store.Users.FindByRefreshToken(app.Id, refreshToken)
if err != nil {
log.Printf("refresh failed: %s", err)
return NewOAuthError("invalid_grant", "refresh token is invalid or expired")
} else if user == nil {
log.Println("refresh failed: user not found with matching valid refresh token for specified client")
return NewOAuthError("invalid_grant", "refresh token is invalid or expired")
}
seconds := 3600
issuer := ctx.Server.config.OpenID.Issuer
accessToken := NewJWT(issuer, app.ClientId, user.Email, seconds)
signedAccessToken, err := ctx.Server.SignJWT(accessToken)
if err != nil {
return NewOAuthError("internal_server_error", "could not authorize client")
}
resp := &TokenResponse{
AccessToken: signedAccessToken,
RefreshToken: refreshToken,
ExpiresIn: seconds,
Scope: scope, // FIXME: BUG!
TokenType: "bearer",
}
writeJson(w, resp)
return nil
}