示例#1
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) ([]string, error) {
	var vres struct {
		Rows []struct {
			Value channels.TimedSet
		}
	}

	opts := map[string]interface{}{"stale": false, "key": user.Name()}
	if verr := context.Bucket.ViewCustom("sync_gateway", "role_access", opts, &vres); verr != nil {
		return nil, verr
	}
	// Boil the list of TimedSets down to a simple set of role names:
	all := map[string]bool{}
	for _, row := range vres.Rows {
		for name, _ := range row.Value {
			all[name] = true
		}
	}
	// Then turn that set into an array to return:
	values := make([]string, 0, len(all))
	for name, _ := range all {
		values = append(values, name)
	}
	return values, nil
}
示例#2
0
// Updates or creates a principal from a PrincipalConfig structure.
func updatePrincipal(dbc *db.DatabaseContext, 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 {
		user, err = authenticator.GetUser(internalUserName(*newInfo.Name))
		princ = user
	} else {
		princ, err = authenticator.GetRole(*newInfo.Name)
	}
	if err != nil {
		return
	}

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

	// Now update the Principal object from the properties in the request, first the channels:
	updatedChannels := princ.ExplicitChannels()
	if updatedChannels == nil {
		updatedChannels = ch.TimedSet{}
	}
	lastSeq, err := dbc.LastSequence()
	if err != nil {
		return
	}
	updatedChannels.UpdateAtSequence(newInfo.ExplicitChannels, lastSeq+1)
	princ.SetExplicitChannels(updatedChannels)

	// Then the roles:
	if isUser {
		user.SetEmail(newInfo.Email)
		if newInfo.Password != nil {
			user.SetPassword(*newInfo.Password)
		}
		user.SetDisabled(newInfo.Disabled)
		user.SetExplicitRoleNames(newInfo.ExplicitRoleNames)
	}

	// And finally save the Principal:
	err = authenticator.Save(princ)
	return
}
示例#3
0
func (listener *changeListener) NewWaiterWithChannels(chans base.Set, user auth.User) *changeWaiter {
	waitKeys := make([]string, 0, 5)
	for channel, _ := range chans {
		waitKeys = append(waitKeys, channelLogDocID(channel))
	}
	if user != nil {
		waitKeys = append(waitKeys, auth.UserKeyPrefix+user.Name())
		for _, role := range user.RoleNames() {
			waitKeys = append(waitKeys, auth.RoleKeyPrefix+role)
		}
	}
	return listener.NewWaiter(waitKeys)
}
示例#4
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()
}
示例#5
0
// Returns an HTTP 403 error if the User is not allowed to access any of the document's channels.
// A nil User means access control is disabled, so the function will return nil.
func AuthorizeAnyDocChannels(user *auth.User, channels ChannelMap) error {
	if user == nil {
		return nil
	} else if user.Channels != nil {
		for _, channel := range user.Channels {
			if channel == "*" {
				return nil
			}
			value, exists := channels[channel]
			if exists && value == nil {
				return nil // yup, it's in this channel
			}
		}
	}
	return user.UnauthError("You are not allowed to see this")
}
示例#6
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
}
示例#7
0
// POST /_session creates a login session and sets its cookie
func (h *handler) handleSessionPOST() error {
	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)
}
示例#8
0
// POST /_session creates a login session and sets its cookie
func (h *handler) handleSessionPOST() error {
	var params struct {
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	err := db.ReadJSONFromMIME(h.rq.Header, h.rq.Body, &params)
	if err != nil {
		return err
	}
	var user *auth.User
	user, err = h.context.auth.GetUser(params.Name)
	if err != nil {
		return err
	}
	if !user.Authenticate(params.Password) {
		user = nil
	}
	return h.makeSession(user)
}
示例#9
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("sync_gateway", "role_access", 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
}
示例#10
0
// Handles PUT or POST to /username
func putUser(r http.ResponseWriter, rq *http.Request, a *auth.Authenticator, username string) error {
	body, _ := ioutil.ReadAll(rq.Body)
	var user auth.User
	err := json.Unmarshal(body, &user)
	if err != nil {
		return err
	}
	if user.Channels == nil {
		return &base.HTTPError{http.StatusBadRequest, "Missing channels property"}
	}

	if rq.Method == "POST" {
		username = user.Name
		if username == "" {
			return &base.HTTPError{http.StatusBadRequest, "Missing name property"}
		}
	} else if user.Name == "" {
		user.Name = username
	} else if user.Name != username {
		return &base.HTTPError{http.StatusBadRequest, "Name mismatch (can't change name)"}
	}
	log.Printf("SaveUser: %v", user) //TEMP
	return a.SaveUser(&user)
}
示例#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(),
	}
}
示例#12
0
// Returns an HTTP 403 error if the User is not allowed to access any of the document's channels.
// A nil User means access control is disabled, so the function will return nil.
func AuthorizeAnyDocChannels(user auth.User, channels ChannelMap) error {
	if user == nil {
		return nil
	}
	for channel, removed := range channels {
		if removed == nil && user.CanSeeChannel(channel) {
			return nil
		}
	}
	if user.CanSeeChannel("*") {
		return nil // Doc is not in any channels, but user has all-access
	}
	return user.UnauthError("You are not allowed to see this")
}
示例#13
0
// Handles PUT and POST for a user or a role.
func (h *handler) updatePrincipal(name string, isUser bool) error {
	h.assertAdminOnly()
	// Unmarshal the request body into a PrincipalJSON struct:
	body, _ := ioutil.ReadAll(h.rq.Body)
	var newInfo PrincipalJSON
	var err error
	if err = json.Unmarshal(body, &newInfo); err != nil {
		return err
	}

	var princ auth.Principal
	var user auth.User
	if h.rq.Method == "POST" {
		// On POST, take the name from the "name" property in the request body:
		if newInfo.Name == nil {
			return &base.HTTPError{http.StatusBadRequest, "Missing name property"}
		}
		name = *newInfo.Name
	} else {
		// ON PUT, verify the name matches, if given:
		if newInfo.Name != nil && *newInfo.Name != name {
			return &base.HTTPError{http.StatusBadRequest, "Name mismatch (can't change name)"}
		}
	}

	// Get the existing principal, or if this is a POST make sure there isn't one:
	if isUser {
		user, err = h.db.Authenticator().GetUser(internalUserName(name))
		princ = user
	} else {
		princ, err = h.db.Authenticator().GetRole(name)
	}
	if err != nil {
		return err
	}

	status := http.StatusOK
	if princ == nil {
		// If user/role didn't exist already, instantiate a new one:
		status = http.StatusCreated
		if isUser {
			user, err = h.db.Authenticator().NewUser(internalUserName(name), "", nil)
			princ = user
		} else {
			princ, err = h.db.Authenticator().NewRole(name, nil)
		}
		if err != nil {
			return err
		}
	} else if h.rq.Method == "POST" {
		return &base.HTTPError{http.StatusConflict, "Already exists"}
	}

	// Now update the Principal object from the properties in the request, first the channels:
	updatedChannels := princ.ExplicitChannels()
	if updatedChannels == nil {
		updatedChannels = ch.TimedSet{}
	}
	updatedChannels.UpdateAtSequence(newInfo.ExplicitChannels, h.db.LastSequence()+1)
	princ.SetExplicitChannels(updatedChannels)

	// Then the roles:
	if isUser {
		user.SetEmail(newInfo.Email)
		if newInfo.Password != nil {
			user.SetPassword(*newInfo.Password)
		}
		user.SetDisabled(newInfo.Disabled)
		user.SetExplicitRoleNames(newInfo.ExplicitRoleNames)
	}

	// And finally save the Principal:
	if err = h.db.Authenticator().Save(princ); err != nil {
		return err
	}
	h.response.WriteHeader(status)
	return nil
}
示例#14
0
// Updates or creates a principal from a PrincipalConfig structure.
func updatePrincipal(dbc *db.DatabaseContext, 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 {
		user, err = authenticator.GetUser(internalUserName(*newInfo.Name))
		princ = user
	} else {
		princ, err = authenticator.GetRole(*newInfo.Name)
	}
	if err != nil {
		return
	}

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

	// Now update the Principal object from the properties in the request, first the channels:
	updatedChannels := princ.ExplicitChannels()
	if updatedChannels == nil {
		updatedChannels = ch.TimedSet{}
	}
	lastSeq, err := dbc.LastSequence()
	if err != nil {
		return
	}
	updatedChannels.UpdateAtSequence(newInfo.ExplicitChannels, lastSeq+1)
	princ.SetExplicitChannels(updatedChannels)

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

		// Convert the array of role strings into a TimedSet by reapplying the current sequences
		// for existing roles, and using the database's last sequence for any new roles.
		newRoles := ch.TimedSet{}
		oldRoles := user.ExplicitRoles()
		var currentSequence uint64
		for _, roleName := range newInfo.ExplicitRoleNames {
			since, found := oldRoles[roleName]
			if !found {
				if currentSequence == 0 {
					currentSequence, _ = dbc.LastSequence()
					if currentSequence == 0 {
						currentSequence = 1
					}
				}
				since = currentSequence
			}
			newRoles[roleName] = since
		}
		user.SetExplicitRoles(newRoles)
	}

	// And finally save the Principal:
	err = authenticator.Save(princ)
	return
}
示例#15
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 {
		if newInfo.Password != nil && len(*(newInfo.Password)) < 3 {
			err = base.HTTPErrorf(http.StatusBadRequest, "Passwords must be at least three 3 characters")
			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
	}

	// Update the persistent sequence number of this principal:
	nextSeq, err := dbc.sequences.nextSequence()
	if err != nil {
		return
	}
	princ.SetSequence(nextSeq)

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

	// 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.UpdateAtSequence(base.SetFromArray(newInfo.ExplicitRoleNames), nextSeq) {
			user.SetExplicitRoles(updatedRoles)
			changed = true
		}
	}

	// And finally save the Principal:
	if changed {
		err = authenticator.Save(princ)
	}
	return
}