1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 // Package auth manages authorization and authentication for kivikd. 14 package auth 15 16 import ( 17 "encoding/json" 18 "net/http" 19 20 "github.com/go-kivik/kivik/v4/x/kivikd/authdb" 21 ) 22 23 // Handler is an auth handler. 24 type Handler interface { 25 // MethodName identifies the handler. It is only called once on server 26 // start up. 27 MethodName() string 28 // Authenticate authenticates the HTTP request. On success, a user context 29 // must be returned. Any error will immediately terminate the authentication 30 // process, returning an error to the client. In particular, this means that 31 // an "unauthorized" error must not be returned if fallthrough is intended. 32 // If a response is sent, execution does not continue. This allows handlers 33 // to expose their own API endpoints (for example, the default cookie auth 34 // handler adds POST /_session and DELETE /_session handlers). 35 Authenticate(http.ResponseWriter, *http.Request) (*authdb.UserContext, error) 36 } 37 38 // Session represents an authenticated session. 39 type Session struct { 40 AuthMethod string 41 AuthDB string 42 Handlers []string 43 User *authdb.UserContext 44 } 45 46 // MarshalJSON satisfies the json.Marshaler interface. 47 func (s *Session) MarshalJSON() ([]byte, error) { 48 user := s.User 49 if user == nil { 50 user = &authdb.UserContext{} 51 } 52 result := map[string]interface{}{ 53 "info": map[string]interface{}{ 54 "authenticated": s.AuthMethod, 55 "authentication_db": s.AuthDB, 56 "authentication_handlers": s.Handlers, 57 }, 58 "ok": true, 59 "userCtx": user, 60 } 61 return json.Marshal(result) 62 } 63