| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2015 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. |
| 4 |
| 5 package auth |
| 6 |
| 7 import ( |
| 8 "fmt" |
| 9 "net/http" |
| 10 |
| 11 "golang.org/x/net/context" |
| 12 |
| 13 "github.com/luci/luci-go/common/errors" |
| 14 "github.com/luci/luci-go/common/logging" |
| 15 "github.com/luci/luci-go/server/router" |
| 16 ) |
| 17 |
| 18 // Authenticate returns a middleware that performs authentication. |
| 19 // |
| 20 // This middleware either updates the context by injecting the authentication |
| 21 // state into it (enabling functions like CurrentIdentity and IsMember), or |
| 22 // aborts the request with an HTTP 401 or HTTP 500 error. |
| 23 // |
| 24 // Note that it passes through anonymous requests. CurrentIdentity returns |
| 25 // identity.AnonymousIdentity in this case. Use separate authorization layer to |
| 26 // further restrict the access, if necessary. |
| 27 func Authenticate(a *Authenticator) router.Middleware { |
| 28 return func(c *router.Context, next router.Handler) { |
| 29 ctx, err := a.Authenticate(c.Context, c.Request) |
| 30 switch { |
| 31 case errors.IsTransient(err): |
| 32 replyError(c.Context, c.Writer, 500, fmt.Sprintf("Transi
ent error during authentication - %s", err)) |
| 33 case err != nil: |
| 34 replyError(c.Context, c.Writer, 401, fmt.Sprintf("Authen
tication error - %s", err)) |
| 35 default: |
| 36 c.Context = ctx |
| 37 next(c) |
| 38 } |
| 39 } |
| 40 } |
| 41 |
| 42 // replyError logs the error and writes it to ResponseWriter. |
| 43 func replyError(c context.Context, rw http.ResponseWriter, code int, msg string)
{ |
| 44 logging.Errorf(c, "HTTP %d: %s", code, msg) |
| 45 http.Error(rw, msg, code) |
| 46 } |
| OLD | NEW |