//Couchdb returns updated AuthSession tokens
181831
func (ca *CookieAuth) UpdateAuth(resp *http.Response) {
	for _, cookie := range resp.Cookies() {
		if cookie.Name == "AuthSession" {
			ca.UpdatedAuthToken = cookie.Value
		}
	}
}
1138507
func (doc *Document) updateDocument(oldBody []byte, newBody []byte) ([]byte, error) {

	var oldBodyMap map[string]interface{}
	var newBodyMap map[string]interface{}
	err := json.Unmarshal(oldBody, &oldBodyMap)
	if err != nil {
		return nil, errors.New("Unmarshalling error " + err.Error())
	}

	err = json.Unmarshal(newBody, &newBodyMap)
	if err != nil {
		return nil, errors.New("Unmarshalling error " + err.Error())
	}

	// Update old data with new contents.
	for newKey, newValue := range newBodyMap {
		oldBodyMap[newKey] = newValue
	}

	oldBodyMap["_rev"] = doc.Rev
	// do the update operation.
	newData, err := json.Marshal(oldBodyMap)
	if err != nil {
		return nil, errors.New("Marshalling error of new value in couch " + err.Error())
	}
	return newData, nil
}
814180
func CreateSystemDatabasesIfNotExist(couchInstance *CouchInstance) error {

	dbName := "_users"
	systemCouchDBDatabase := CouchDatabase{CouchInstance: couchInstance, DBName: dbName, IndexWarmCounter: 1}
	err := systemCouchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error calling CouchDB CreateDatabaseIfNotExist() for system dbName: %s, error: %s", dbName, err)
		return err
	}

	dbName = "_replicator"
	systemCouchDBDatabase = CouchDatabase{CouchInstance: couchInstance, DBName: dbName, IndexWarmCounter: 1}
	err = systemCouchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error calling CouchDB CreateDatabaseIfNotExist() for system dbName: %s, error: %s", dbName, err)
		return err
	}
	if couchInstance.conf.CreateGlobalChangesDB {
		dbName = "_global_changes"
		systemCouchDBDatabase = CouchDatabase{CouchInstance: couchInstance, DBName: dbName, IndexWarmCounter: 1}
		err = systemCouchDBDatabase.CreateDatabaseIfNotExist()
		if err != nil {
			logger.Errorf("Error calling CouchDB CreateDatabaseIfNotExist() for system dbName: %s, error: %s", dbName, err)
			return err
		}
	}
	return nil

}
1295119
func (c *Client) UpdateSession(req session.UpdateRequest) error {
	if err := req.Check(); err != nil {
		return trace.Wrap(err)
	}
	_, err := c.PutJSON(c.Endpoint("namespaces", req.Namespace, "sessions", string(req.ID)), updateSessionReq{Update: req})
	return trace.Wrap(err)
}
1252452
func GetAuthDBSnapshot(c context.Context, id string) (*protocol.AuthDB, error) {
	report := durationReporter(c, getSnapshotDuration)
	logging.Debugf(c, "Fetching AuthDB snapshot from the datastore")
	defer logging.Debugf(c, "AuthDB snapshot fetched")

	c = ds.WithoutTransaction(defaultNS(c))
	snap := Snapshot{ID: id}
	switch err := ds.Get(c, &snap); {
	case err == ds.ErrNoSuchEntity:
		report("ERROR_NO_SNAPSHOT")
		return nil, err // not transient
	case err != nil:
		report("ERROR_TRANSIENT")
		return nil, transient.Tag.Apply(err)
	}

	db, err := service.InflateAuthDB(snap.AuthDBDeflated)
	if err != nil {
		report("ERROR_INFLATION")
		return nil, err
	}

	report("SUCCESS")
	return db, nil
}
792761
func (d *driver) getAuthSession() (session *napping.Session, err error) {
	e := ApiError{}

	s := napping.Session{
		Userinfo: d.creds,
		Client:   d.httpClient,
	}

	url := d.url + loginUri

	resp, err := s.Get(url, nil, nil, &e)

	if err != nil {
		return
	}

	token := resp.HttpResponse().Header.Get("X-SDS-AUTH-TOKEN")

	h := http.Header{}

	h.Set("X-SDS-AUTH-TOKEN", token)

	session = &napping.Session{
		Client: d.httpClient,
		Header: &h,
	}

	return
}
10263
func ConnectBucket(serverURL, poolName, bucketName string,
	auth couchbase.AuthHandler) (Bucket, error) {
	var bucket *couchbase.Bucket
	var err error

	if auth != nil {
		bucket, err = couchbase.ConnectWithAuthAndGetBucket(serverURL, poolName, bucketName, auth)
	} else {
		bucket, err = couchbase.GetBucket(serverURL, poolName, bucketName)
	}
	if err != nil {
		return nil, err
	}
	if bucket == nil {
		return nil, fmt.Errorf("unknown bucket,"+
			" serverURL: %s, bucketName: %s", serverURL, bucketName)
	}

	return &bucketWrapper{b: bucket}, nil
}
1072379
func (dbclient *CouchDatabase) ListIndex() ([]*IndexResult, error) {

	//IndexDefinition contains the definition for a couchdb index
	type indexDefinition struct {
		DesignDocument string          `json:"ddoc"`
		Name           string          `json:"name"`
		Type           string          `json:"type"`
		Definition     json.RawMessage `json:"def"`
	}

	//ListIndexResponse contains the definition for listing couchdb indexes
	type listIndexResponse struct {
		TotalRows int               `json:"total_rows"`
		Indexes   []indexDefinition `json:"indexes"`
	}

	dbName := dbclient.DBName
	logger.Debug("[%s] Entering ListIndex()", dbName)

	indexURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, _, err := dbclient.handleRequest(http.MethodGet, "ListIndex", indexURL, nil, "", "", maxRetries, true, nil, "_index")
	if err != nil {
		return nil, err
	}
	defer closeResponseBody(resp)

	//handle as JSON document
	jsonResponseRaw, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(err, "error reading response body")
	}

	var jsonResponse = &listIndexResponse{}

	err2 := json.Unmarshal(jsonResponseRaw, jsonResponse)
	if err2 != nil {
		return nil, errors.Wrap(err2, "error unmarshalling json data")
	}

	var results []*IndexResult

	for _, row := range jsonResponse.Indexes {

		//if the DesignDocument does not begin with "_design/", then this is a system
		//level index and is not meaningful and cannot be edited or deleted
		designDoc := row.DesignDocument
		s := strings.SplitAfterN(designDoc, "_design/", 2)
		if len(s) > 1 {
			designDoc = s[1]

			//Add the index definition to the results
			var addIndexResult = &IndexResult{DesignDocument: designDoc, Name: row.Name, Definition: fmt.Sprintf("%s", row.Definition)}
			results = append(results, addIndexResult)
		}

	}

	logger.Debugf("[%s] Exiting ListIndex()", dbclient.DBName)

	return results, nil

}
995795
func CreateConnectionDefinition(couchDBAddress, username, password string, maxRetries,
	maxRetriesOnStartup int, requestTimeout time.Duration, createGlobalChangesDB bool) (*CouchConnectionDef, error) {

	logger.Debugf("Entering CreateConnectionDefinition()")

	connectURL := &url.URL{
		Host:   couchDBAddress,
		Scheme: "http",
	}

	//parse the constructed URL to verify no errors
	finalURL, err := url.Parse(connectURL.String())
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, errors.Wrapf(err, "error parsing connect URL: %s", connectURL)
	}

	logger.Debugf("Created database configuration  URL=[%s]", finalURL.String())
	logger.Debugf("Exiting CreateConnectionDefinition()")

	//return an object containing the connection information
	return &CouchConnectionDef{finalURL.String(), username, password, maxRetries,
		maxRetriesOnStartup, requestTimeout, createGlobalChangesDB}, nil

}
602590
func (t *Store) UpdateUserToken(token string, source TokenSource) {
	t.l.Lock()
	t.userToken = token
	t.userTokenSource = source
	t.l.Unlock()
}
119332
func NewAuthenticatedSession(user, password string) (*Client, error) {
	client, err := NewClient()
	if err != nil {
		return nil, err
	}

	if err := client.Authenticate(user, password); err != nil {
		return nil, err
	}

	return client, nil
}
298595
func (r *Reference) Auth(token string) *Reference {
	r.token = token

	return r
}
1251673
func (d *DNSProvider) updateTxtRecord(fqdn, token, txt string, clear bool) error {
	u, _ := url.Parse("https://www.do.de/api/letsencrypt")

	query := u.Query()
	query.Set("token", token)
	query.Set("domain", dns01.UnFqdn(fqdn))

	// api call differs per set/delete
	if clear {
		query.Set("action", "delete")
	} else {
		query.Set("value", txt)
	}

	u.RawQuery = query.Encode()

	response, err := d.config.HTTPClient.Get(u.String())
	if err != nil {
		return err
	}
	defer response.Body.Close()

	bodyBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}

	var r apiResponse
	err = json.Unmarshal(bodyBytes, &r)
	if err != nil {
		return fmt.Errorf("request to change TXT record for do.de returned the following invalid json (%s); used url [%s]", string(bodyBytes), u)
	}

	body := string(bodyBytes)
	if !r.Success {
		return fmt.Errorf("request to change TXT record for do.de returned the following error result (%s); used url [%s]", body, u)
	}
	return nil
}
31493
func (s *server) UpdateSession(req UpdateRequest) error {
	if err := req.Check(); err != nil {
		return trace.Wrap(err)
	}

	key := activeKey(req.Namespace, string(req.ID))

	// Try several times, then give up
	for i := 0; i < sessionUpdateAttempts; i++ {
		item, err := s.bk.Get(context.TODO(), key)
		if err != nil {
			return trace.Wrap(err)
		}

		var session Session
		if err := json.Unmarshal(item.Value, &session); err != nil {
			return trace.Wrap(err)
		}

		if req.TerminalParams != nil {
			session.TerminalParams = *req.TerminalParams
		}
		if req.Active != nil {
			session.Active = *req.Active
		}
		if req.Parties != nil {
			session.Parties = *req.Parties
		}
		newValue, err := json.Marshal(session)
		if err != nil {
			return trace.Wrap(err)
		}
		newItem := backend.Item{
			Key:     key,
			Value:   newValue,
			Expires: s.clock.Now().UTC().Add(s.activeSessionTTL),
		}

		_, err = s.bk.CompareAndSwap(context.TODO(), *item, newItem)
		if err != nil {
			if trace.IsCompareFailed(err) || trace.IsConnectionProblem(err) {
				s.clock.Sleep(sessionUpdateRetryPeriod)
				continue
			}
			return trace.Wrap(err)
		} else {
			return nil
		}
	}
	return trace.ConnectionProblem(nil, "failed concurrently update the session")
}
274629
func (conn *Connection) GetUser(username string, userData interface{},
	auth Auth) (string, error) {
	userDb := conn.SelectDB("_users", auth)
	namestring := "org.couchdb.user:" + username
	return userDb.Read(namestring, &userData, nil)
}
223432
func (aug *AuthUserGroup) AuthGroup(db XODB) (*AuthGroup, error) {
	return AuthGroupByID(db, aug.GroupID)
}
649092
func (dbclient *CouchDatabase) GetDatabaseInfo() (*DBInfo, *DBReturn, error) {

	connectURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, nil, errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, couchDBReturn, err := dbclient.handleRequest(http.MethodGet, "GetDatabaseInfo", connectURL, nil, "", "", maxRetries, true, nil)
	if err != nil {
		return nil, couchDBReturn, err
	}
	defer closeResponseBody(resp)

	dbResponse := &DBInfo{}
	decodeErr := json.NewDecoder(resp.Body).Decode(&dbResponse)
	if decodeErr != nil {
		return nil, nil, errors.Wrap(decodeErr, "error decoding response body")
	}

	// trace the database info response
	logger.Debugw("GetDatabaseInfo()", "dbResponseJSON", dbResponse)

	return dbResponse, couchDBReturn, nil

}