github.com/go-kivik/kivik/v4@v4.3.2/session.go (about)

     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 kivik
    14  
    15  import (
    16  	"context"
    17  	"encoding/json"
    18  	"net/http"
    19  
    20  	"github.com/go-kivik/kivik/v4/driver"
    21  	internal "github.com/go-kivik/kivik/v4/int/errors"
    22  )
    23  
    24  // Session represents an authentication session.
    25  type Session struct {
    26  	// Name is the name of the authenticated user.
    27  	Name string
    28  	// Roles is a list of roles the user belongs to.
    29  	Roles []string
    30  	// AuthenticationMethod is the authentication method that was used for this
    31  	// session.
    32  	AuthenticationMethod string
    33  	// AuthenticationDB is the user database against which authentication was
    34  	// performed.
    35  	AuthenticationDB string
    36  	// AuthenticationHandlers is a list of authentication handlers configured on
    37  	// the server.
    38  	AuthenticationHandlers []string
    39  	// RawResponse is the raw JSON response sent by the server, useful for
    40  	// custom backends which may provide additional fields.
    41  	RawResponse json.RawMessage
    42  }
    43  
    44  // Ensure types are equal.
    45  var _ = Session(driver.Session{})
    46  
    47  // Session returns information about the currently authenticated user.
    48  func (c *Client) Session(ctx context.Context) (*Session, error) {
    49  	endQuery, err := c.startQuery()
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	defer endQuery()
    54  	if sessioner, ok := c.driverClient.(driver.Sessioner); ok {
    55  		session, err := sessioner.Session(ctx)
    56  		if err != nil {
    57  			return nil, err
    58  		}
    59  		ses := Session(*session)
    60  		return &ses, nil
    61  	}
    62  	return nil, &internal.Error{Status: http.StatusNotImplemented, Message: "kivik: driver does not support sessions"}
    63  }