Golang NewUserTag示例

说明

golang newusertag示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: github.com/juju/names

示例#1
文件: modelmanager_test.go 项目: pmatulis/juju

func (s *modelManagerSuite) TestListModelsDenied(c *gc.C) {
	user := names.NewUserTag("[email protected]")
	s.setAPIUser(c, user)
	other := names.NewUserTag("[email protected]")
	_, err := s.modelmanager.ListModels(params.Entity{other.String()})
	c.Assert(err, gc.ErrorMatches, "permission denied")
}

示例#2

func (s *modelInfoSuite) SetUpTest(c *gc.C) {
	s.BaseSuite.SetUpTest(c)
	s.authorizer = apiservertesting.FakeAuthorizer{
		Tag: names.NewUserTag("[email protected]"),
	}
	s.st = &mockState{
		uuid: coretesting.ModelTag.Id(),
	}
	s.st.model = &mockModel{
		owner: names.NewUserTag("[email protected]"),
		cfg:   coretesting.ModelConfig(c),
		life:  state.Dying,
		status: status.StatusInfo{
			Status: status.StatusDestroying,
			Since:  &time.Time{},
		},
		users: []*mockModelUser{{
			userName: "admin",
			access:   state.ModelAdminAccess,
		}, {
			userName:    "[email protected]",
			displayName: "Bob",
			access:      state.ModelReadAccess,
		}, {
			userName:    "[email protected]",
			displayName: "Charlotte",
			access:      state.ModelReadAccess,
		}},
	}
	var err error
	s.modelmanager, err = modelmanager.NewModelManagerAPI(s.st, &s.authorizer)
	c.Assert(err, jc.ErrorIsNil)
}

示例#3
文件: worker_test.go 项目: AlexisBruemmer/juju

func (s *Suite) TestMigration(c *gc.C) {
	masterClient := newStubMasterClient(s.stub)
	w := migrationmaster.New(masterClient)

	// Trigger migration.
	masterClient.watcher.changes <- migration.TargetInfo{
		ControllerTag: names.NewModelTag("uuid"),
		Addrs:         []string{"1.2.3.4:5"},
		CACert:        "cert",
		AuthTag:       names.NewUserTag("admin"),
		Password:      "secret",
	}

	// This error is temporary while migrationmaster is a WIP.
	runWorkerAndWait(c, w, "migration seen and aborted")

	// Observe that the migration was seen, the model exported, an API
	// connection to the target controller was made, the model was
	// imported and then the migration aborted.
	s.stub.CheckCalls(c, []jujutesting.StubCall{
		{"masterClient.Watch", nil},
		{"masterClient.Export", nil},
		{"apiOpen", []interface{}{&api.Info{
			Addrs:    []string{"1.2.3.4:5"},
			CACert:   "cert",
			Tag:      names.NewUserTag("admin"),
			Password: "secret",
		}, api.DefaultDialOpts()}},
		{"APICall:MigrationTarget.Import",
			[]interface{}{params.SerializedModel{Bytes: fakeSerializedModel}}},
		{"masterClient.SetPhase", []interface{}{migration.ABORT}},
		{"Connection.Close", nil},
	})
}

示例#4
文件: modelmigration_test.go 项目: makyo/juju

func (s *ModelMigrationSuite) SetUpTest(c *gc.C) {
	s.ConnSuite.SetUpTest(c)
	s.clock = coretesting.NewClock(time.Now().Truncate(time.Second))
	s.PatchValue(&state.GetClock, func() clock.Clock {
		return s.clock
	})

	// Create a hosted model to migrate.
	s.State2 = s.Factory.MakeModel(c, nil)
	s.AddCleanup(func(*gc.C) { s.State2.Close() })

	targetControllerTag := names.NewModelTag(utils.MustNewUUID().String())

	// Plausible migration arguments to test with.
	s.stdSpec = state.ModelMigrationSpec{
		InitiatedBy: names.NewUserTag("admin"),
		TargetInfo: migration.TargetInfo{
			ControllerTag: targetControllerTag,
			Addrs:         []string{"1.2.3.4:5555", "4.3.2.1:6666"},
			CACert:        "cert",
			AuthTag:       names.NewUserTag("user"),
			Password:      "password",
		},
	}
}

示例#5
文件: watcher_test.go 项目: AlexisBruemmer/juju

func (s *migrationWatcherSuite) TestWatch(c *gc.C) {
	// Create a state server
	m, password := s.Factory.MakeMachineReturningPassword(c, &factory.MachineParams{
		Jobs:  []state.MachineJob{state.JobManageModel},
		Nonce: "noncey",
	})

	// Create a model to migrate.
	hostedState := s.Factory.MakeModel(c, nil)

	// Connect as a state server to the hosted environment.
	apiInfo := s.APIInfo(c)
	apiInfo.Tag = m.Tag()
	apiInfo.Password = password
	apiInfo.ModelTag = hostedState.ModelTag()
	apiInfo.Nonce = "noncey"

	apiConn, err := api.Open(apiInfo, api.DialOpts{})
	c.Assert(err, jc.ErrorIsNil)
	defer apiConn.Close()

	// Start watching for a migration.
	client := migrationmaster.NewClient(apiConn)
	w, err := client.Watch()
	c.Assert(err, jc.ErrorIsNil)
	defer func() {
		c.Assert(worker.Stop(w), jc.ErrorIsNil)
	}()

	// Should be no initial events.
	select {
	case _, ok := <-w.Changes():
		c.Fatalf("watcher sent unexpected change: (_, %v)", ok)
	case <-time.After(coretesting.ShortWait):
	}

	// Now create a migration.
	targetInfo := migration.TargetInfo{
		ControllerTag: names.NewModelTag(utils.MustNewUUID().String()),
		Addrs:         []string{"1.2.3.4:5"},
		CACert:        "trust me I'm an authority",
		AuthTag:       names.NewUserTag("dog"),
		Password:      "sekret",
	}
	_, err = hostedState.CreateModelMigration(state.ModelMigrationSpec{
		InitiatedBy: names.NewUserTag("someone"),
		TargetInfo:  targetInfo,
	})
	c.Assert(err, jc.ErrorIsNil)

	// Event with correct target details should be emitted.
	select {
	case reportedTargetInfo, ok := <-w.Changes():
		c.Assert(ok, jc.IsTrue)
		c.Assert(reportedTargetInfo, jc.DeepEquals, targetInfo)
	case <-time.After(coretesting.LongWait):
		c.Fatalf("watcher didn't emit an event")
	}
}

示例#6
文件: envuser_internal_test.go 项目: Pankov404/juju

func (s *internalEnvUserSuite) TestCreateEnvUserOpAndDoc(c *gc.C) {
	tag := names.NewUserTag("UserName")
	op, doc := createEnvUserOpAndDoc("ignored", tag, names.NewUserTag("ignored"), "ignored")

	c.Assert(op.Id, gc.Equals, "[email protected]")
	c.Assert(doc.ID, gc.Equals, "[email protected]")
	c.Assert(doc.UserName, gc.Equals, "[email protected]")
}

示例#7
文件: unshare_test.go 项目: exekias/juju

func (s *unshareSuite) TestPassesValues(c *gc.C) {
	sam := names.NewUserTag("sam")
	ralph := names.NewUserTag("ralph")

	_, err := s.run(c, "sam", "ralph")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(s.fake.removeUsers, jc.DeepEquals, []names.UserTag{sam, ralph})
}

示例#8
文件: modelmanager_test.go 项目: pmatulis/juju

func (s *modelManagerSuite) TestListModelsForSelfLocalUser(c *gc.C) {
	// When the user's credentials cache stores the simple name, but the
	// api server converts it to a fully qualified name.
	user := names.NewUserTag("local-user")
	s.setAPIUser(c, names.NewUserTag("[email protected]"))
	result, err := s.modelmanager.ListModels(params.Entity{user.String()})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result.UserModels, gc.HasLen, 0)
}

示例#9
文件: modelmanager_test.go 项目: makyo/juju

func (s *modelManagerSuite) TestGrantToModelNoAccess(c *gc.C) {
	apiUser := names.NewUserTag("[email protected]")
	s.setAPIUser(c, apiUser)

	st := s.Factory.MakeModel(c, nil)
	defer st.Close()

	other := names.NewUserTag("[email protected]")
	err := s.grant(c, other, params.ModelReadAccess, st.ModelTag())
	c.Assert(err, gc.ErrorMatches, "permission denied")
}

示例#10
文件: unshare_test.go 项目: exekias/juju

func (s *unshareSuite) TestInit(c *gc.C) {
	wrappedCommand, unshareCmd := model.NewUnshareCommandForTest(s.fake)
	err := testing.InitCommand(wrappedCommand, []string{})
	c.Assert(err, gc.ErrorMatches, "no users specified")

	err = testing.InitCommand(wrappedCommand, []string{"not valid/0"})
	c.Assert(err, gc.ErrorMatches, `invalid username: "not valid/0"`)

	err = testing.InitCommand(wrappedCommand, []string{"[email protected]", "sam"})
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(unshareCmd.Users[0], gc.Equals, names.NewUserTag("[email protected]"))
	c.Assert(unshareCmd.Users[1], gc.Equals, names.NewUserTag("sam"))
}

示例#11
文件: unshare_test.go 项目: Pankov404/juju

func (s *unshareSuite) TestInit(c *gc.C) {
	unshareCmd := &environment.UnshareCommand{}
	err := testing.InitCommand(unshareCmd, []string{})
	c.Assert(err, gc.ErrorMatches, "no users specified")

	err = testing.InitCommand(unshareCmd, []string{"not valid/0"})
	c.Assert(err, gc.ErrorMatches, `invalid username: "not valid/0"`)

	err = testing.InitCommand(unshareCmd, []string{"[email protected]", "sam"})
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(unshareCmd.Users[0], gc.Equals, names.NewUserTag("[email protected]"))
	c.Assert(unshareCmd.Users[1], gc.Equals, names.NewUserTag("sam"))
}

示例#12
文件: modelmanager_test.go 项目: makyo/juju

func (s *modelManagerSuite) TestGrantToModelReadAccess(c *gc.C) {
	apiUser := names.NewUserTag("[email protected]")
	s.setAPIUser(c, apiUser)

	st := s.Factory.MakeModel(c, nil)
	defer st.Close()
	stFactory := factory.NewFactory(st)
	stFactory.MakeModelUser(c, &factory.ModelUserParams{
		User: apiUser.Canonical(), Access: state.ModelReadAccess})

	other := names.NewUserTag("[email protected]")
	err := s.grant(c, other, params.ModelReadAccess, st.ModelTag())
	c.Assert(err, gc.ErrorMatches, "permission denied")
}

示例#13

func (s *userManagerSuite) TestUserInfoUserExists(c *gc.C) {
	foobar := "foobar"
	fooTag := names.NewUserTag(foobar)
	user := s.Factory.MakeUser(factory.UserParams{Username: foobar, DisplayName: "Foo Bar"})

	args := params.Entities{
		Entities: []params.Entity{{Tag: fooTag.String()}},
	}
	results, err := s.usermanager.UserInfo(args)
	c.Assert(err, gc.IsNil)
	expected := params.UserInfoResults{
		Results: []params.UserInfoResult{
			{
				Result: ¶ms.UserInfo{
					Username:       "foobar",
					DisplayName:    "Foo Bar",
					CreatedBy:      "admin",
					DateCreated:    user.DateCreated(),
					LastConnection: user.LastConnection(),
				},
			},
		},
	}

	c.Assert(results, gc.DeepEquals, expected)
}

示例#14
文件: factory.go 项目: pmatulis/juju

// MakeModelUser will create a modelUser with values defined by the params. For
// attributes of ModelUserParams that are the default empty values, some
// meaningful valid values are used instead. If params is not specified,
// defaults are used.
func (factory *Factory) MakeModelUser(c *gc.C, params *ModelUserParams) *state.ModelUser {
	if params == nil {
		params = &ModelUserParams{}
	}
	if params.User == "" {
		user := factory.MakeUser(c, &UserParams{NoModelUser: true})
		params.User = user.UserTag().Canonical()
	}
	if params.DisplayName == "" {
		params.DisplayName = uniqueString("display name")
	}
	if params.CreatedBy == nil {
		env, err := factory.st.Model()
		c.Assert(err, jc.ErrorIsNil)
		params.CreatedBy = env.Owner()
	}
	createdByUserTag := params.CreatedBy.(names.UserTag)
	modelUser, err := factory.st.AddModelUser(state.ModelUserSpec{
		User:        names.NewUserTag(params.User),
		CreatedBy:   createdByUserTag,
		DisplayName: params.DisplayName,
		ReadOnly:    params.ReadOnly,
	})
	c.Assert(err, jc.ErrorIsNil)
	return modelUser
}

示例#15
文件: useenvironment.go 项目: claudiu-coblis/juju

func (c *UseEnvironmentCommand) findMatchingEnvironment(ctx *cmd.Context, client UseEnvironmentAPI, creds configstore.APICredentials) (base.UserEnvironment, error) {

	var empty base.UserEnvironment

	envs, err := client.ListEnvironments(creds.User)
	if err != nil {
		return empty, errors.Annotate(err, "cannot list environments")
	}

	var owner string
	if c.Owner != "" {
		// The username always contains the provider aspect of the user.
		owner = names.NewUserTag(c.Owner).Username()
	}

	// If we have a UUID, we warn if the owner is different, but accept it.
	// We also trust that the environment UUIDs are unique
	if c.EnvUUID != "" {
		for _, env := range envs {
			if env.UUID == c.EnvUUID {
				if owner != "" && env.Owner != owner {
					ctx.Infof("Specified environment owned by %s, not %s", env.Owner, owner)
				}
				return env, nil
			}
		}
		return empty, errors.NotFoundf("matching environment")
	}

	var matches []base.UserEnvironment
	for _, env := range envs {
		match := env.Name == c.EnvName
		if match && owner != "" {
			match = env.Owner == owner
		}
		if match {
			matches = append(matches, env)
		}
	}

	// If there is only one match, that's the one.
	switch len(matches) {
	case 0:
		return empty, errors.NotFoundf("matching environment")
	case 1:
		return matches[0], nil
	}

	// We are going to return an error, but tell the user what the matches
	// were so they can make an informed decision. We are also going to assume
	// here that the resulting environment list has only one matching name for
	// each user. There are tests creating environments that enforce this.
	ctx.Infof("Multiple environments matched name %q:", c.EnvName)
	for _, env := range matches {
		ctx.Infof("  %s, owned by %s", env.UUID, env.Owner)
	}
	ctx.Infof("Please specify either the environment UUID or the owner to disambiguate.")

	return empty, errors.New("multiple environments matched")
}

示例#16
文件: model_test.go 项目: makyo/juju

func (s *ModelSuite) TestNewModelNonExistentLocalUser(c *gc.C) {
	cfg, _ := s.createTestEnvConfig(c)
	owner := names.NewUserTag("[email protected]")

	_, _, err := s.State.NewModel(state.ModelArgs{Config: cfg, Owner: owner})
	c.Assert(err, gc.ErrorMatches, `cannot create model: user "non-existent" not found`)
}

示例#17
文件: apiclient_test.go 项目: snailwalker/juju

func (s *apiclientSuite) TestOpenFailsIfUsernameAndUseMacaroon(c *gc.C) {
	info := s.APIInfo(c)
	info.Tag = names.NewUserTag("foobar")
	info.UseMacaroons = true
	_, err := api.Open(info, api.DialOpts{})
	c.Assert(err, gc.ErrorMatches, "open should specifiy UseMacaroons or a username & password. Not both")
}

示例#18
文件: environdestroy_test.go 项目: kakamessi99/juju

func (s *destroyTwoEnvironmentsSuite) SetUpTest(c *gc.C) {
	s.JujuConnSuite.SetUpTest(c)
	_, err := s.State.AddUser("jess", "jess", "", "test")
	c.Assert(err, jc.ErrorIsNil)
	s.otherEnvOwner = names.NewUserTag("jess")
	s.otherState = factory.NewFactory(s.State).MakeEnvironment(c, &factory.EnvParams{
		Owner:   s.otherEnvOwner,
		Prepare: true,
		ConfigAttrs: jujutesting.Attrs{
			"state-server": false,
		},
	})
	s.AddCleanup(func(*gc.C) { s.otherState.Close() })

	// get the client for the other environment
	auth := apiservertesting.FakeAuthorizer{
		Tag:            s.otherEnvOwner,
		EnvironManager: false,
	}
	s.otherEnvClient, err = client.NewClient(s.otherState, common.NewResources(), auth)
	c.Assert(err, jc.ErrorIsNil)

	s.metricSender = &testMetricSender{}
	s.PatchValue(common.SendMetrics, s.metricSender.SendMetrics)
}

示例#19
文件: modelmanager_test.go 项目: pmatulis/juju

func (s *modelManagerSuite) TestListModelsForSelf(c *gc.C) {
	user := names.NewUserTag("[email protected]")
	s.setAPIUser(c, user)
	result, err := s.modelmanager.ListModels(params.Entity{user.String()})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result.UserModels, gc.HasLen, 0)
}

示例#20
文件: api.go 项目: kapilt/juju

// apiInfoConnect looks for endpoint on the given environment and
// tries to connect to it, sending the result on the returned channel.
func apiInfoConnect(store configstore.Storage, info configstore.EnvironInfo, apiOpen apiOpenFunc, stop <-chan struct{}) (apiState, error) {
	endpoint := info.APIEndpoint()
	if info == nil || len(endpoint.Addresses) == 0 {
		return nil, &infoConnectError{fmt.Errorf("no cached addresses")}
	}
	logger.Infof("connecting to API addresses: %v", endpoint.Addresses)
	var environTag names.Tag
	if endpoint.EnvironUUID != "" {
		// Note: we should be validating that EnvironUUID contains a
		// valid UUID.
		environTag = names.NewEnvironTag(endpoint.EnvironUUID)
	}
	username := info.APICredentials().User
	if username == "" {
		username = "admin"
	}
	apiInfo := &api.Info{
		Addrs:      endpoint.Addresses,
		CACert:     endpoint.CACert,
		Tag:        names.NewUserTag(username),
		Password:   info.APICredentials().Password,
		EnvironTag: environTag,
	}
	st, err := apiOpen(apiInfo, api.DefaultDialOpts())
	if err != nil {
		return nil, &infoConnectError{err}
	}
	return st, nil
}

示例#21
文件: client_test.go 项目: ktsakalozos/juju

func (s *clientSuite) TestUnshareEnvironmentMissingUser(c *gc.C) {
	client := s.APIState.Client()
	user := names.NewUserTag("[email protected]")
	cleanup := api.PatchClientFacadeCall(client,
		func(request string, paramsIn interface{}, response interface{}) error {
			if users, ok := paramsIn.(params.ModifyEnvironUsers); ok {
				c.Assert(users.Changes, gc.HasLen, 1)
				c.Logf(string(users.Changes[0].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Logf(users.Changes[0].UserTag, gc.Equals, user.String())
			} else {
				c.Fatalf("wrong input structure")
			}
			if result, ok := response.(*params.ErrorResults); ok {
				err := ¶ms.Error{
					Message: "error message",
					Code:    params.CodeNotFound,
				}
				*result = params.ErrorResults{Results: []params.ErrorResult{{Error: err}}}
			} else {
				c.Fatalf("wrong input structure")
			}
			return nil
		},
	)
	defer cleanup()

	err := client.UnshareEnvironment(user)
	c.Assert(err, jc.ErrorIsNil)
	logMsg := fmt.Sprintf("WARNING juju.api environment was not previously shared with user %s", user.Username())
	c.Assert(c.GetTestLog(), jc.Contains, logMsg)
}

示例#22
文件: client_test.go 项目: ktsakalozos/juju

func (s *clientSuite) TestUnshareEnvironmentThreeUsers(c *gc.C) {
	client := s.APIState.Client()
	missingUser := s.Factory.MakeEnvUser(c, nil)
	localUser := s.Factory.MakeUser(c, nil)
	newUserTag := names.NewUserTag("[email protected]")
	cleanup := api.PatchClientFacadeCall(client,
		func(request string, paramsIn interface{}, response interface{}) error {
			if users, ok := paramsIn.(params.ModifyEnvironUsers); ok {
				c.Assert(users.Changes, gc.HasLen, 3)
				c.Assert(string(users.Changes[0].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[0].UserTag, gc.Equals, missingUser.UserTag().String())
				c.Assert(string(users.Changes[1].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[1].UserTag, gc.Equals, localUser.UserTag().String())
				c.Assert(string(users.Changes[2].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[2].UserTag, gc.Equals, newUserTag.String())
			} else {
				c.Log("wrong input structure")
				c.Fail()
			}
			if result, ok := response.(*params.ErrorResults); ok {
				err := ¶ms.Error{Message: "error unsharing user"}
				*result = params.ErrorResults{Results: []params.ErrorResult{{Error: err}, {Error: nil}, {Error: nil}}}
			} else {
				c.Log("wrong output structure")
				c.Fail()
			}
			return nil
		},
	)
	defer cleanup()

	err := client.UnshareEnvironment(missingUser.UserTag(), localUser.UserTag(), newUserTag)
	c.Assert(err, gc.ErrorMatches, "error unsharing user")
}

示例#23
文件: systemmanager_test.go 项目: ktsakalozos/juju

func (s *systemManagerSuite) TestAllEnvironments(c *gc.C) {
	admin := s.Factory.MakeUser(c, &factory.UserParams{Name: "foobar"})

	s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "owned", Owner: admin.UserTag()}).Close()
	remoteUserTag := names.NewUserTag("[email protected]")
	st := s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "user", Owner: remoteUserTag})
	defer st.Close()
	st.AddEnvironmentUser(admin.UserTag(), remoteUserTag, "Foo Bar")

	s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "no-access", Owner: remoteUserTag}).Close()

	response, err := s.systemManager.AllEnvironments()
	c.Assert(err, jc.ErrorIsNil)
	// The results are sorted.
	expected := []string{"dummyenv", "no-access", "owned", "user"}
	var obtained []string
	for _, env := range response.UserEnvironments {
		obtained = append(obtained, env.Name)
		stateEnv, err := s.State.GetEnvironment(names.NewEnvironTag(env.UUID))
		c.Assert(err, jc.ErrorIsNil)
		s.checkEnvironmentMatches(c, env.Environment, stateEnv)
	}
	c.Assert(obtained, jc.DeepEquals, expected)
}

示例#24
文件: environmentmanager.go 项目: claudiu-coblis/juju

// ListEnvironments returns the environments that the specified user
// has access to in the current server.  Only that state server owner
// can list environments for any user (at this stage).  Other users
// can only ask about their own environments.
func (c *Client) ListEnvironments(user string) ([]base.UserEnvironment, error) {
	var environments params.UserEnvironmentList
	if !names.IsValidUser(user) {
		return nil, errors.Errorf("invalid user name %q", user)
	}
	entity := params.Entity{names.NewUserTag(user).String()}
	err := c.facade.FacadeCall("ListEnvironments", entity, &environments)
	if err != nil {
		return nil, errors.Trace(err)
	}
	result := make([]base.UserEnvironment, len(environments.UserEnvironments))
	for i, env := range environments.UserEnvironments {
		owner, err := names.ParseUserTag(env.OwnerTag)
		if err != nil {
			return nil, errors.Annotatef(err, "OwnerTag %q at position %d", env.OwnerTag, i)
		}
		result[i] = base.UserEnvironment{
			Name:           env.Name,
			UUID:           env.UUID,
			Owner:          owner.Username(),
			LastConnection: env.LastConnection,
		}
	}
	return result, nil
}

示例#25
文件: factory.go 项目: claudiu-coblis/juju

// MakeUser will create a user with values defined by the params.
// For attributes of UserParams that are the default empty values,
// some meaningful valid values are used instead.
// If params is not specified, defaults are used.
func (factory *Factory) MakeUser(c *gc.C, params *UserParams) *state.User {
	if params == nil {
		params = &UserParams{}
	}
	if params.Name == "" {
		params.Name = uniqueString("username")
	}
	if params.DisplayName == "" {
		params.DisplayName = uniqueString("display name")
	}
	if params.Password == "" {
		params.Password = "password"
	}
	if params.Creator == nil {
		env, err := factory.st.Environment()
		c.Assert(err, jc.ErrorIsNil)
		params.Creator = env.Owner()
	}
	creatorUserTag := params.Creator.(names.UserTag)
	user, err := factory.st.AddUser(
		params.Name, params.DisplayName, params.Password, creatorUserTag.Name())
	c.Assert(err, jc.ErrorIsNil)
	if !params.NoEnvUser {
		_, err := factory.st.AddEnvironmentUser(user.UserTag(), names.NewUserTag(user.CreatedBy()), params.DisplayName)
		c.Assert(err, jc.ErrorIsNil)
	}
	if params.Disabled {
		err := user.Disable()
		c.Assert(err, jc.ErrorIsNil)
	}
	return user
}

示例#26
文件: migration_test.go 项目: AlexisBruemmer/juju

func (s *ImportSuite) TestStreamCharmsTools(c *gc.C) {
	model := description.NewModel(description.ModelArgs{
		Owner: names.NewUserTag("me"),
	})
	model.AddService(description.ServiceArgs{
		Tag:      names.NewServiceTag("magic"),
		CharmURL: "local:trusty/magic",
	})
	model.AddService(description.ServiceArgs{
		Tag:      names.NewServiceTag("magic"),
		CharmURL: "cs:trusty/postgresql-42",
	})

	uploader := &fakeUploader{charms: make(map[string]string)}
	config := migration.UploadBinariesConfig{
		State:            &fakeStateStorage{},
		Model:            model,
		Target:           &fakeAPIConnection{},
		GetCharmUploader: func(api.Connection) migration.CharmUploader { return uploader },
		GetToolsUploader: func(target api.Connection) migration.ToolsUploader { return &noOpUploader{} },
		GetStateStorage:  func(migration.UploadBackend) storage.Storage { return &fakeCharmsStorage{} },
		GetCharmStoragePath: func(_ migration.UploadBackend, u *charm.URL) (string, error) {
			return "/path/for/" + u.String(), nil
		},
	}
	err := migration.UploadBinaries(config)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(uploader.charms, jc.DeepEquals, map[string]string{
		"local:trusty/magic":      "fake file at /path/for/local:trusty/magic",
		"cs:trusty/postgresql-42": "fake file at /path/for/cs:trusty/postgresql-42",
	})
}

示例#27

func (c *UserInfoCommand) Run(ctx *cmd.Context) (err error) {
	client, err := getUserInfoAPI(c)
	if err != nil {
		return err
	}
	defer client.Close()
	username := c.Username
	if username == "" {
		// No username given, get current user
		store, err := configstore.Default()
		if err != nil {
			return err
		}
		info, err := store.ReadInfo(c.EnvName)
		if err != nil {
			return err
		}
		username = info.APICredentials().User
	}
	userTag := names.NewUserTag(username)
	result, err := client.UserInfo(userTag.Id())
	if err != nil {
		return err
	}
	info := UserInfo{
		Username:       result.Result.Username,
		DisplayName:    result.Result.DisplayName,
		DateCreated:    result.Result.DateCreated.String(),
		LastConnection: result.Result.LastConnection.String(),
	}
	if err = c.out.Write(ctx, info); err != nil {
		return err
	}
	return nil
}

示例#28
文件: usermanager_test.go 项目: imoapps/juju

func (s *userManagerSuite) TestBlockEnableUser(c *gc.C) {
	alex := s.Factory.MakeUser(c, &factory.UserParams{Name: "alex"})
	barb := s.Factory.MakeUser(c, &factory.UserParams{Name: "barb", Disabled: true})

	args := params.Entities{
		Entities: []params.Entity{
			{alex.Tag().String()},
			{barb.Tag().String()},
			{names.NewLocalUserTag("ellie").String()},
			{names.NewUserTag("[email protected]").String()},
			{"not-a-tag"},
		}}

	s.BlockAllChanges(c, "TestBlockEnableUser")
	_, err := s.usermanager.EnableUser(args)
	// Check that the call is blocked
	s.AssertBlocked(c, err, "TestBlockEnableUser")

	err = alex.Refresh()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(alex.IsDisabled(), jc.IsFalse)

	err = barb.Refresh()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(barb.IsDisabled(), jc.IsTrue)
}

示例#29
文件: modelmanager_test.go 项目: pmatulis/juju

func (s *modelManagerSuite) TestNewAPIAcceptsClient(c *gc.C) {
	anAuthoriser := s.authoriser
	anAuthoriser.Tag = names.NewUserTag("[email protected]")
	endPoint, err := modelmanager.NewModelManagerAPI(s.State, s.resources, anAuthoriser)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(endPoint, gc.NotNil)
}

示例#30
文件: controller_test.go 项目: pmatulis/juju

func (s *controllerSuite) TestAllModels(c *gc.C) {
	admin := s.Factory.MakeUser(c, &factory.UserParams{Name: "foobar"})

	s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "owned", Owner: admin.UserTag()}).Close()
	remoteUserTag := names.NewUserTag("[email protected]")
	st := s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "user", Owner: remoteUserTag})
	defer st.Close()
	st.AddModelUser(state.ModelUserSpec{
		User:        admin.UserTag(),
		CreatedBy:   remoteUserTag,
		DisplayName: "Foo Bar"})

	s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "no-access", Owner: remoteUserTag}).Close()

	response, err := s.controller.AllModels()
	c.Assert(err, jc.ErrorIsNil)
	// The results are sorted.
	expected := []string{"dummymodel", "no-access", "owned", "user"}
	var obtained []string
	for _, env := range response.UserModels {
		obtained = append(obtained, env.Name)
		stateEnv, err := s.State.GetModel(names.NewModelTag(env.UUID))
		c.Assert(err, jc.ErrorIsNil)
		s.checkEnvironmentMatches(c, env.Model, stateEnv)
	}
	c.Assert(obtained, jc.DeepEquals, expected)
}

展开阅读全文