14287: Refactor controller to use strong types in API handlers.
[arvados.git] / sdk / go / auth / handlers.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package auth
6
7 import (
8         "context"
9         "net/http"
10 )
11
12 type contextKey string
13
14 var ContextKeyCredentials contextKey = "credentials"
15
16 // LoadToken wraps the next handler, adding credentials to the request
17 // context so subsequent handlers can access them efficiently via
18 // CredentialsFromRequest.
19 func LoadToken(next http.Handler) http.Handler {
20         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21                 if _, ok := r.Context().Value(ContextKeyCredentials).(*Credentials); !ok {
22                         r = r.WithContext(context.WithValue(r.Context(), ContextKeyCredentials, CredentialsFromRequest(r)))
23                 }
24                 next.ServeHTTP(w, r)
25         })
26 }
27
28 // RequireLiteralToken wraps the next handler, rejecting any request
29 // that doesn't supply the given token. If the given token is empty,
30 // RequireLiteralToken returns next (i.e., no auth checks are
31 // performed).
32 func RequireLiteralToken(token string, next http.Handler) http.Handler {
33         if token == "" {
34                 return next
35         }
36         return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
37                 c := CredentialsFromRequest(r)
38                 if len(c.Tokens) == 0 {
39                         http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
40                         return
41                 }
42                 for _, t := range c.Tokens {
43                         if t == token {
44                                 next.ServeHTTP(w, r)
45                                 return
46                         }
47                 }
48                 http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
49         })
50 }