// AddEnvironmentUser adds a new user to the database. func (st *State) AddEnvironmentUser(user, createdBy names.UserTag, displayName string) (*EnvironmentUser, error) { // Ensure local user exists in state before adding them as an environment user. if user.Provider() == names.LocalProvider { if _, err := st.User(user.Name()); err != nil { return nil, errors.Annotate(err, fmt.Sprintf("user %q does not exist locally", user.Name())) } } // Ensure local createdBy user exists. if createdBy.Provider() == names.LocalProvider { if _, err := st.User(createdBy.Name()); err != nil { return nil, errors.Annotate(err, fmt.Sprintf("createdBy user %q does not exist locally", createdBy.Name())) } } username := user.Username() envuuid := st.EnvironTag().Id() id := envUserID(envuuid, username) envUser := &EnvironmentUser{ st: st, doc: envUserDoc{ ID: id, EnvUUID: envuuid, UserName: username, DisplayName: displayName, CreatedBy: createdBy.Username(), DateCreated: nowToTheSecond(), }} ops := []txn.Op{{ C: envUsersC, Id: id, Assert: txn.DocMissing, Insert: &envUser.doc, }} err := st.runTransaction(ops) if err == txn.ErrAborted { err = errors.New("env user already exists") } if err != nil { return nil, errors.Trace(err) } return envUser, nil }