| 1 | package authmodel |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | |
| 7 | "github.com/sassoftware/relic/v7/config" |
| 8 | "github.com/sassoftware/relic/v7/internal/zhttp" |
| 9 | "github.com/sassoftware/relic/v7/lib/audit" |
| 10 | ) |
| 11 | |
| 12 | type ctxKey int |
| 13 | |
| 14 | var ctxKeyUserInfo ctxKey = 1 |
| 15 | |
| 16 | type Authenticator interface { |
| 17 | Authenticate(req *http.Request) (UserInfo, error) |
| 18 | } |
| 19 | |
| 20 | type UserInfo interface { |
| 21 | // Allowed checks whether the named key is visible to the current user |
| 22 | Allowed(*config.KeyConfig) bool |
| 23 | // AuditContext amends an audit record with the authenticated user's name |
| 24 | // and other relevant details |
| 25 | AuditContext(info *audit.Info) |
| 26 | } |
| 27 | |
| 28 | // New creates an authenticator based on the provided server configuration |
| 29 | func New(conf *config.Config) (Authenticator, error) { |
| 30 | switch { |
| 31 | case conf.Server.PolicyURL != "": |
| 32 | return newPolicyAuthenticator(conf) |
| 33 | default: |
| 34 | return &CertificateAuth{Config: conf}, nil |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Middleware checks each request for authentication. If successful, the user's |
| 39 | // information is appended to the log context and request context. If not, an |
| 40 | // error is returned and the inner handler is skipped. |
| 41 | func Middleware(a Authenticator) func(http.Handler) http.Handler { |
| 42 | return func(next http.Handler) http.Handler { |
| 43 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 44 | info, err := a.Authenticate(r) |
| 45 | if err != nil { |
| 46 | if h, ok := err.(http.Handler); ok { |
| 47 | h.ServeHTTP(w, r) |
| 48 | } else { |
| 49 | zhttp.WriteUnhandledError(w, r, err, "") |
| 50 | } |
| 51 | return |
| 52 | } else if info == nil { |
| 53 | panic("authenticator returned nil without an error") |
| 54 | } |
| 55 | ctx := r.Context() |
| 56 | ctx = context.WithValue(ctx, ctxKeyUserInfo, info) |
| 57 | r = r.WithContext(ctx) |
| 58 | next.ServeHTTP(w, r) |
| 59 | }) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // RequestInfo returns information about the calling user |
| 64 | func RequestInfo(req *http.Request) UserInfo { |
| 65 | info, ok := req.Context().Value(ctxKeyUserInfo).(UserInfo) |
| 66 | if !ok { |
| 67 | // middleware should guarantee this is always present, otherwise |
| 68 | // something is seriously wrong |
| 69 | panic("userinfo missing from request context") |
| 70 | } |
| 71 | return info |
| 72 | } |