Ejemplo n.º 1
0
// Cleans up the Value property, and removes rows that aren't visible to the current user
func filterViewResult(input walrus.ViewResult, user auth.User) (result walrus.ViewResult) {
	checkChannels := false
	var visibleChannels ch.TimedSet
	if user != nil {
		visibleChannels = user.InheritedChannels()
		checkChannels = !visibleChannels.Contains("*")
	}
	result.TotalRows = input.TotalRows
	result.Rows = make([]*walrus.ViewRow, 0, len(input.Rows)/2)
	for _, row := range input.Rows {
		value := row.Value.([]interface{})
		// value[0] is the array of channels; value[1] is the actual value
		if !checkChannels || channelsIntersect(visibleChannels, value[0].([]interface{})) {
			// Add this row:
			stripSyncProperty(row)
			result.Rows = append(result.Rows, &walrus.ViewRow{
				Key:   row.Key,
				Value: value[1],
				ID:    row.ID,
				Doc:   row.Doc,
			})
		}
	}
	return
}
Ejemplo n.º 2
0
// POST /_session creates a login session and sets its cookie
func (h *handler) handleSessionPOST() error {
	// CORS not allowed for login #115 #762
	originHeader := h.rq.Header["Origin"]
	if len(originHeader) > 0 {
		matched := ""
		if h.server.config.CORS != nil {
			matched = matchedOrigin(h.server.config.CORS.LoginOrigin, originHeader)
		}
		if matched == "" {
			return base.HTTPErrorf(http.StatusBadRequest, "No CORS")
		}
	}

	var params struct {
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	err := h.readJSONInto(&params)
	if err != nil {
		return err
	}
	var user auth.User
	user, err = h.db.Authenticator().GetUser(params.Name)
	if err != nil {
		return err
	}

	if user != nil && !user.Authenticate(params.Password) {
		user = nil
	}
	return h.makeSession(user)
}
Ejemplo n.º 3
0
func (h *handler) makeSession(user auth.User) error {
	if user == nil {
		return base.HTTPErrorf(http.StatusUnauthorized, "Invalid login")
	}
	h.user = user
	auth := h.db.Authenticator()
	session, err := auth.CreateSession(user.Name(), kDefaultSessionTTL)
	if err != nil {
		return err
	}
	cookie := auth.MakeSessionCookie(session)
	cookie.Path = "/" + h.db.Name + "/"
	http.SetCookie(h.response, cookie)
	return h.respondWithSessionInfo()
}
Ejemplo n.º 4
0
// Creates a session with TTL and adds to the response.  Does NOT return the session info response.
func (h *handler) makeSessionWithTTL(user auth.User, expiry time.Duration) (sessionID string, err error) {
	if user == nil {
		return "", base.HTTPErrorf(http.StatusUnauthorized, "Invalid login")
	}
	h.user = user
	auth := h.db.Authenticator()
	session, err := auth.CreateSession(user.Name(), expiry)
	if err != nil {
		return "", err
	}
	cookie := auth.MakeSessionCookie(session)
	base.AddDbPathToCookie(h.rq, cookie)
	http.SetCookie(h.response, cookie)
	return session.ID, nil
}
Ejemplo n.º 5
0
func (listener *changeListener) NewWaiterWithChannels(chans base.Set, user auth.User) *changeWaiter {
	waitKeys := make([]string, 0, 5)
	for channel, _ := range chans {
		waitKeys = append(waitKeys, channel)
	}
	var userKeys []string
	if user != nil {
		userKeys = []string{auth.UserKeyPrefix + user.Name()}
		for role, _ := range user.RoleNames() {
			userKeys = append(userKeys, auth.RoleKeyPrefix+role)
		}
		waitKeys = append(waitKeys, userKeys...)
	}
	waiter := listener.NewWaiter(waitKeys)
	waiter.userKeys = userKeys
	return waiter
}
Ejemplo n.º 6
0
// Cleans up the Value property, and removes rows that aren't visible to the current user
func filterViewResult(input sgbucket.ViewResult, user auth.User, applyChannelFiltering bool) (result sgbucket.ViewResult) {
	hasStarChannel := false
	var visibleChannels ch.TimedSet
	if user != nil {
		visibleChannels = user.InheritedChannels()
		hasStarChannel = !visibleChannels.Contains("*")
		if !applyChannelFiltering {
			return // this is an error
		}
	}
	result.TotalRows = input.TotalRows
	result.Rows = make([]*sgbucket.ViewRow, 0, len(input.Rows)/2)
	for _, row := range input.Rows {
		if applyChannelFiltering {
			value, ok := row.Value.([]interface{})
			if ok {
				// value[0] is the array of channels; value[1] is the actual value
				if !hasStarChannel || channelsIntersect(visibleChannels, value[0].([]interface{})) {
					// Add this row:
					stripSyncProperty(row)
					result.Rows = append(result.Rows, &sgbucket.ViewRow{
						Key:   row.Key,
						Value: value[1],
						ID:    row.ID,
						Doc:   row.Doc,
					})
				}
			}
		} else {
			// Add the raw row:
			stripSyncProperty(row)
			result.Rows = append(result.Rows, &sgbucket.ViewRow{
				Key:   row.Key,
				Value: row.Value,
				ID:    row.ID,
				Doc:   row.Doc,
			})
		}

	}
	result.TotalRows = len(result.Rows)
	return
}
Ejemplo n.º 7
0
// Formats session response similar to what is returned by CouchDB
func (h *handler) formatSessionResponse(user auth.User) db.Body {

	var name *string
	allChannels := channels.TimedSet{}

	if user != nil {
		userName := user.Name()
		if userName != "" {
			name = &userName
		}
		allChannels = user.Channels()
	}

	// Return a JSON struct similar to what CouchDB returns:
	userCtx := db.Body{"name": name, "channels": allChannels}
	handlers := []string{"default", "cookie"}
	response := db.Body{"ok": true, "userCtx": userCtx, "authentication_handlers": handlers}
	return response

}
Ejemplo n.º 8
0
// Recomputes the set of roles a User has been granted access to by sync() functions.
// This is part of the ChannelComputer interface defined by the Authenticator.
func (context *DatabaseContext) ComputeRolesForUser(user auth.User) (channels.TimedSet, error) {
	var vres struct {
		Rows []struct {
			Value channels.TimedSet
		}
	}

	opts := map[string]interface{}{"stale": false, "key": user.Name()}
	if verr := context.Bucket.ViewCustom(DesignDocSyncGateway, ViewRoleAccess, opts, &vres); verr != nil {
		return nil, verr
	}
	// Merge the TimedSets from the view result:
	var result channels.TimedSet
	for _, row := range vres.Rows {
		if result == nil {
			result = row.Value
		} else {
			result.Add(row.Value)
		}
	}
	return result, nil
}
Ejemplo n.º 9
0
func (h *handler) getUserFromSessionRequestBody() (auth.User, error) {

	var params struct {
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	err := h.readJSONInto(&params)
	if err != nil {
		return nil, err
	}

	var user auth.User
	user, err = h.db.Authenticator().GetUser(params.Name)
	if err != nil {
		return nil, err
	}

	if user != nil && !user.Authenticate(params.Password) {
		user = nil
	}
	return user, err
}
Ejemplo n.º 10
0
// POST /_session creates a login session and sets its cookie
func (h *handler) handleSessionPOST() error {
	if len(h.rq.Header["Origin"]) > 0 {
		// CORS not allowed for login #115
		return base.HTTPErrorf(http.StatusBadRequest, "No CORS")
	}
	var params struct {
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	err := h.readJSONInto(&params)
	if err != nil {
		return err
	}
	var user auth.User
	user, err = h.db.Authenticator().GetUser(params.Name)
	if err != nil {
		return err
	}

	if !user.Authenticate(params.Password) {
		user = nil
	}
	return h.makeSession(user)
}
Ejemplo n.º 11
0
// Creates a userCtx object to be passed to the sync function
func makeUserCtx(user auth.User) map[string]interface{} {
	if user == nil {
		return nil
	}
	return map[string]interface{}{
		"name":     user.Name(),
		"roles":    user.RoleNames(),
		"channels": user.InheritedChannels().AllChannels(),
	}
}
Ejemplo n.º 12
0
// Updates or creates a principal from a PrincipalConfig structure.
func (dbc *DatabaseContext) UpdatePrincipal(newInfo PrincipalConfig, isUser bool, allowReplace bool) (replaced bool, err error) {
	// Get the existing principal, or if this is a POST make sure there isn't one:
	var princ auth.Principal
	var user auth.User
	authenticator := dbc.Authenticator()
	if isUser {
		isValid, reason := newInfo.IsPasswordValid(dbc.AllowEmptyPassword)
		if !isValid {
			err = base.HTTPErrorf(http.StatusBadRequest, reason)
			return
		}
		user, err = authenticator.GetUser(*newInfo.Name)
		princ = user
	} else {
		princ, err = authenticator.GetRole(*newInfo.Name)
	}
	if err != nil {
		return
	}

	changed := false
	replaced = (princ != nil)
	if !replaced {
		// If user/role didn't exist already, instantiate a new one:
		if isUser {
			user, err = authenticator.NewUser(*newInfo.Name, "", nil)
			princ = user
		} else {
			princ, err = authenticator.NewRole(*newInfo.Name, nil)
		}
		if err != nil {
			return
		}
		changed = true
	} else if !allowReplace {
		err = base.HTTPErrorf(http.StatusConflict, "Already exists")
		return
	}

	updatedChannels := princ.ExplicitChannels()
	if updatedChannels == nil {
		updatedChannels = ch.TimedSet{}
	}
	if !updatedChannels.Equals(newInfo.ExplicitChannels) {
		changed = true
	}

	var updatedRoles ch.TimedSet

	// Then the user-specific fields like roles:
	if isUser {
		if newInfo.Email != user.Email() {
			user.SetEmail(newInfo.Email)
			changed = true
		}
		if newInfo.Password != nil {
			user.SetPassword(*newInfo.Password)
			changed = true
		}
		if newInfo.Disabled != user.Disabled() {
			user.SetDisabled(newInfo.Disabled)
			changed = true
		}

		updatedRoles = user.ExplicitRoles()
		if updatedRoles == nil {
			updatedRoles = ch.TimedSet{}
		}
		if !updatedRoles.Equals(base.SetFromArray(newInfo.ExplicitRoleNames)) {
			changed = true
		}

	}

	// And finally save the Principal:
	if changed {
		// Update the persistent sequence number of this principal (only allocate a sequence when needed - issue #673):
		nextSeq := uint64(0)
		if dbc.writeSequences() {
			var err error
			nextSeq, err = dbc.sequences.nextSequence()
			if err != nil {
				return replaced, err
			}
			princ.SetSequence(nextSeq)
		}

		// Now update the Principal object from the properties in the request, first the channels:
		if updatedChannels.UpdateAtSequence(newInfo.ExplicitChannels, nextSeq) {
			princ.SetExplicitChannels(updatedChannels)
		}

		if isUser {
			if updatedRoles.UpdateAtSequence(base.SetFromArray(newInfo.ExplicitRoleNames), nextSeq) {
				user.SetExplicitRoles(updatedRoles)
			}
		}
		err = authenticator.Save(princ)
	}
	return
}