当前位置: 首页>>代码示例>>Golang>>正文


Golang permission.Context函数代码示例

本文整理汇总了Golang中github.com/tsuru/tsuru/permission.Context函数的典型用法代码示例。如果您正苦于以下问题:Golang Context函数的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: getEnv

func getEnv(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	var variables []string
	if r.Body != nil {
		defer r.Body.Close()
		err := json.NewDecoder(r.Body).Decode(&variables)
		if err != nil && err != io.EOF {
			return err
		}
	}
	appName := r.URL.Query().Get(":app")
	var u *auth.User
	var err error
	a, err := getAppFromContext(appName, r)
	if err != nil {
		return err
	}
	if !t.IsAppToken() {
		u, err = t.User()
		if err != nil {
			return err
		}
		rec.Log(u.Email, "get-env", "app="+appName, fmt.Sprintf("envs=%s", variables))
		allowed := permission.Check(t, permission.PermAppReadEnv,
			append(permission.Contexts(permission.CtxTeam, a.Teams),
				permission.Context(permission.CtxApp, a.Name),
				permission.Context(permission.CtxPool, a.Pool),
			)...,
		)
		if !allowed {
			return permission.ErrUnauthorized
		}
	}
	return writeEnvVars(w, &a, variables...)
}
开发者ID:Endika,项目名称:tsuru,代码行数:34,代码来源:app.go

示例2: listContainersHandler

func listContainersHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	address := r.URL.Query().Get(":address")
	if address != "" {
		node, err := mainDockerProvisioner.Cluster().GetNode(address)
		if err != nil {
			return err
		}
		hasAccess := permission.Check(t, permission.PermNodeRead,
			permission.Context(permission.CtxPool, node.Metadata["pool"]))
		if !hasAccess {
			return permission.ErrUnauthorized
		}
		containerList, err := mainDockerProvisioner.listContainersByHost(address)
		if err != nil {
			return err
		}
		return json.NewEncoder(w).Encode(containerList)
	}
	appName := r.URL.Query().Get(":appname")
	a, err := app.GetByName(appName)
	if err != nil {
		return err
	}
	hasAccess := permission.Check(t, permission.PermNodeRead,
		permission.Context(permission.CtxPool, a.Pool))
	if !hasAccess {
		return permission.ErrUnauthorized
	}
	containerList, err := mainDockerProvisioner.listContainersByApp(appName)
	if err != nil {
		return err
	}
	return json.NewEncoder(w).Encode(containerList)
}
开发者ID:reoring,项目名称:tsuru,代码行数:34,代码来源:handlers.go

示例3: appDelete

func appDelete(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	u, err := t.User()
	if err != nil {
		return err
	}
	a, err := getAppFromContext(r.URL.Query().Get(":app"), r)
	if err != nil {
		return err
	}
	canDelete := permission.Check(t, permission.PermAppDelete,
		append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...,
	)
	if !canDelete {
		return permission.ErrUnauthorized
	}
	rec.Log(u.Email, "app-delete", "app="+a.Name)
	keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
	defer keepAliveWriter.Stop()
	writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
	err = app.Delete(&a, writer)
	if err != nil {
		writer.Encode(tsuruIo.SimpleJsonMessage{Error: err.Error()})
	}
	return nil
}
开发者ID:Endika,项目名称:tsuru,代码行数:28,代码来源:app.go

示例4: TestNewWithPermission

func (s *S) TestNewWithPermission(c *check.C) {
	evt, err := New(&Opts{
		Target: Target{Type: "app", Value: "myapp"},
		Kind:   permission.PermAppUpdateEnvSet,
		Owner:  s.token,
		Allowed: Allowed(permission.PermAppReadEvents,
			permission.Context(permission.CtxApp, "myapp"), permission.Context(permission.CtxTeam, "myteam")),
	})
	c.Assert(err, check.IsNil)
	expected := &Event{eventData: eventData{
		ID:             eventID{Target: Target{Type: "app", Value: "myapp"}},
		UniqueID:       evt.UniqueID,
		Target:         Target{Type: "app", Value: "myapp"},
		Kind:           Kind{Type: KindTypePermission, Name: "app.update.env.set"},
		Owner:          Owner{Type: OwnerTypeUser, Name: s.token.GetUserName()},
		Running:        true,
		StartTime:      evt.StartTime,
		LockUpdateTime: evt.LockUpdateTime,
		Allowed: AllowedPermission{
			Scheme:   permission.PermAppReadEvents.FullName(),
			Contexts: []permission.PermissionContext{permission.Context(permission.CtxApp, "myapp"), permission.Context(permission.CtxTeam, "myteam")},
		},
	}}
	c.Assert(evt, check.DeepEquals, expected)
	evts, err := All()
	c.Assert(err, check.IsNil)
	c.Assert(evts, check.HasLen, 1)
	evts[0].StartTime = expected.StartTime
	evts[0].LockUpdateTime = expected.LockUpdateTime
	c.Assert(&evts[0], check.DeepEquals, expected)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:31,代码来源:event_test.go

示例5: TestEventInfoPermission

func (s *EventSuite) TestEventInfoPermission(c *check.C) {
	token := customUserWithPermission(c, "myuser", permission.Permission{
		Scheme:  permission.PermAppRead,
		Context: permission.Context(permission.CtxTeam, s.team.Name),
	})
	evt, err := event.New(&event.Opts{
		Target:  event.Target{Type: event.TargetTypeApp, Value: "aha"},
		Owner:   s.token,
		Kind:    permission.PermAppDeploy,
		Allowed: event.Allowed(permission.PermAppReadEvents, permission.Context(permission.CtxTeam, s.team.Name)),
	})
	c.Assert(err, check.IsNil)
	u := fmt.Sprintf("/events/%s", evt.UniqueID.Hex())
	request, err := http.NewRequest("GET", u, nil)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+token.GetValue())
	recorder := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	var result event.Event
	err = json.Unmarshal(recorder.Body.Bytes(), &result)
	c.Assert(err, check.IsNil)
	c.Assert(result.Kind, check.DeepEquals, evt.Kind)
	c.Assert(result.Target, check.DeepEquals, evt.Target)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:26,代码来源:event_test.go

示例6: BaseTokenPermission

func BaseTokenPermission(t Token) ([]permission.Permission, error) {
	if t.IsAppToken() {
		// TODO(cezarsa): Improve handling of app tokens. These permissions
		// listed here are the ones required by deploy-agent and legacy tsuru-
		// unit-agent.
		return []permission.Permission{
			{
				Scheme:  permission.PermAppUpdateUnitRegister,
				Context: permission.Context(permission.CtxApp, t.GetAppName()),
			},
			{
				Scheme:  permission.PermAppUpdateLog,
				Context: permission.Context(permission.CtxApp, t.GetAppName()),
			},
			{
				Scheme:  permission.PermAppUpdateUnitStatus,
				Context: permission.Context(permission.CtxApp, t.GetAppName()),
			},
			{
				Scheme:  permission.PermAppReadDeploy,
				Context: permission.Context(permission.CtxApp, t.GetAppName()),
			},
		}, nil
	}
	user, err := t.User()
	if err != nil {
		return nil, err
	}
	return user.Permissions()
}
开发者ID:zhenruyan,项目名称:tsuru,代码行数:30,代码来源:token.go

示例7: TestListUsersWithPermissions

func (s *S) TestListUsersWithPermissions(c *check.C) {
	u1 := User{Email: "[email protected]", Password: "123"}
	err := u1.Create()
	c.Assert(err, check.IsNil)
	u2 := User{Email: "[email protected]", Password: "123"}
	err = u2.Create()
	c.Assert(err, check.IsNil)
	r1, err := permission.NewRole("r1", "app", "")
	c.Assert(err, check.IsNil)
	err = r1.AddPermissions("app.update.env", "app.deploy")
	c.Assert(err, check.IsNil)
	err = u1.AddRole("r1", "myapp1")
	c.Assert(err, check.IsNil)
	err = u2.AddRole("r1", "myapp2")
	c.Assert(err, check.IsNil)
	users, err := ListUsersWithPermissions(permission.Permission{
		Scheme:  permission.PermAppDeploy,
		Context: permission.Context(permission.CtxApp, "myapp1"),
	})
	c.Assert(err, check.IsNil)
	c.Assert(users, check.HasLen, 1)
	c.Assert(users[0].Email, check.Equals, u1.Email)
	users, err = ListUsersWithPermissions(permission.Permission{
		Scheme:  permission.PermAppDeploy,
		Context: permission.Context(permission.CtxApp, "myapp2"),
	})
	c.Assert(err, check.IsNil)
	c.Assert(users, check.HasLen, 1)
	c.Assert(users[0].Email, check.Equals, u2.Email)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:30,代码来源:user_test.go

示例8: TestDissociateRoleNotAuthorized

func (s *S) TestDissociateRoleNotAuthorized(c *check.C) {
	role, err := permission.NewRole("test", "team")
	c.Assert(err, check.IsNil)
	err = role.AddPermissions("app.create")
	c.Assert(err, check.IsNil)
	otherToken := customUserWithPermission(c, "user2")
	otherUser, err := otherToken.User()
	c.Assert(err, check.IsNil)
	err = otherUser.AddRole(role.Name, "myteam")
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("/roles/test/user/%s?context=myteam", otherToken.GetUserName())
	req, err := http.NewRequest("DELETE", url, nil)
	c.Assert(err, check.IsNil)
	token := customUserWithPermission(c, "user1", permission.Permission{
		Scheme:  permission.PermRoleUpdateDissociate,
		Context: permission.Context(permission.CtxGlobal, ""),
	}, permission.Permission{
		Scheme:  permission.PermAppCreate,
		Context: permission.Context(permission.CtxTeam, "otherteam"),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	recorder := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(recorder, req)
	c.Assert(err, check.IsNil)
	c.Assert(recorder.Code, check.Equals, http.StatusForbidden)
	c.Assert(recorder.Body.String(), check.Equals, "User not authorized to use permission app.create(team myteam)\n")
	otherUser, err = otherToken.User()
	c.Assert(err, check.IsNil)
	c.Assert(otherUser.Roles, check.HasLen, 1)
}
开发者ID:Endika,项目名称:tsuru,代码行数:32,代码来源:permission_test.go

示例9: unsetCName

func unsetCName(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	cnames := r.URL.Query()["cname"]
	if len(cnames) == 0 {
		msg := "You must provide the cname."
		return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
	}
	u, err := t.User()
	if err != nil {
		return err
	}
	appName := r.URL.Query().Get(":app")
	a, err := getAppFromContext(appName, r)
	if err != nil {
		return err
	}
	allowed := permission.Check(t, permission.PermAppUpdateCnameRemove,
		append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...,
	)
	if !allowed {
		return permission.ErrUnauthorized
	}
	rec.Log(u.Email, "remove-cname", "app="+appName, "cnames="+strings.Join(cnames, ", "))
	if err = a.RemoveCName(cnames...); err == nil {
		return nil
	}
	if err.Error() == "Invalid cname" {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
	}
	return err
}
开发者ID:pedrosnk,项目名称:tsuru,代码行数:33,代码来源:app.go

示例10: changePlan

func changePlan(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	var plan app.Plan
	err := json.NewDecoder(r.Body).Decode(&plan)
	if err != nil {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: "unable to parse request body",
		}
	}
	a, err := getAppFromContext(r.URL.Query().Get(":app"), r)
	if err != nil {
		return err
	}
	allowed := permission.Check(t, permission.PermAppUpdatePlan,
		append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...,
	)
	if !allowed {
		return permission.ErrUnauthorized
	}
	keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
	defer keepAliveWriter.Stop()
	writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
	err = a.ChangePlan(plan.Name, writer)
	if err == app.ErrPlanNotFound {
		writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
		return err
	}
	return err
}
开发者ID:Endika,项目名称:tsuru,代码行数:32,代码来源:plan.go

示例11: TestPoolListHandlerWithPermissionToDefault

func (s *S) TestPoolListHandlerWithPermissionToDefault(c *check.C) {
	team := auth.Team{Name: "angra"}
	err := s.conn.Teams().Insert(team)
	c.Assert(err, check.IsNil)
	perms := []permission.Permission{
		{
			Scheme:  permission.PermAppCreate,
			Context: permission.Context(permission.CtxGlobal, ""),
		},
		{
			Scheme:  permission.PermPoolUpdate,
			Context: permission.Context(permission.CtxGlobal, ""),
		},
	}
	token := userWithPermission(c, perms...)
	pool := provision.Pool{Name: "pool1", Teams: []string{team.Name}}
	opts := provision.AddPoolOptions{Name: pool.Name, Default: pool.Default}
	err = provision.AddPool(opts)
	c.Assert(err, check.IsNil)
	err = provision.AddTeamsToPool(pool.Name, pool.Teams)
	c.Assert(err, check.IsNil)
	defer provision.RemovePool(pool.Name)
	req, err := http.NewRequest("GET", "/pools", nil)
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	err = poolList(rec, req, token)
	c.Assert(err, check.IsNil)
	var pools []provision.Pool
	err = json.NewDecoder(rec.Body).Decode(&pools)
	c.Assert(err, check.IsNil)
	c.Assert(pools, check.HasLen, 2)
	c.Assert(pools[0].Name, check.Equals, "test1")
	c.Assert(pools[1].Name, check.Equals, "pool1")
}
开发者ID:pedrosnk,项目名称:tsuru,代码行数:34,代码来源:pool_test.go

示例12: restart

func restart(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	process := r.URL.Query().Get("process")
	w.Header().Set("Content-Type", "text")
	u, err := t.User()
	if err != nil {
		return err
	}
	appName := r.URL.Query().Get(":app")
	a, err := getAppFromContext(appName, r)
	if err != nil {
		return err
	}
	allowed := permission.Check(t, permission.PermAppUpdateRestart,
		append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...,
	)
	if !allowed {
		return permission.ErrUnauthorized
	}
	rec.Log(u.Email, "restart", "app="+appName)
	keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
	defer keepAliveWriter.Stop()
	writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
	err = a.Restart(process, writer)
	if err != nil {
		writer.Encode(tsuruIo.SimpleJsonMessage{Error: err.Error()})
		return err
	}
	return nil
}
开发者ID:Endika,项目名称:tsuru,代码行数:32,代码来源:app.go

示例13: appChangePool

func appChangePool(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	u, err := t.User()
	if err != nil {
		return err
	}
	a, err := getAppFromContext(r.URL.Query().Get(":app"), r)
	if err != nil {
		return err
	}
	allowed := permission.Check(t, permission.PermAppUpdatePool,
		append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...,
	)
	if !allowed {
		return permission.ErrUnauthorized
	}
	defer r.Body.Close()
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: fmt.Sprintf("Unable to decode body: %s", err.Error()),
		}
	}
	pool := string(data)
	rec.Log(u.Email, "app-change-pool", "app="+r.URL.Query().Get(":app"), "pool="+pool)
	return a.ChangePool(pool)
}
开发者ID:Endika,项目名称:tsuru,代码行数:30,代码来源:app.go

示例14: deployDataToEvent

func deployDataToEvent(data *DeployData) error {
	var evt event.Event
	evt.UniqueID = data.ID
	evt.Target = event.Target{Type: event.TargetTypeApp, Value: data.App}
	evt.Owner = event.Owner{Type: event.OwnerTypeUser, Name: data.User}
	evt.Kind = event.Kind{Type: event.KindTypePermission, Name: permission.PermAppDeploy.FullName()}
	evt.StartTime = data.Timestamp
	evt.EndTime = data.Timestamp.Add(data.Duration)
	evt.Error = data.Error
	evt.Log = data.Log
	evt.RemoveDate = data.RemoveDate
	a, err := GetByName(data.App)
	if err == nil {
		evt.Allowed = event.Allowed(permission.PermAppReadEvents, append(permission.Contexts(permission.CtxTeam, a.Teams),
			permission.Context(permission.CtxApp, a.Name),
			permission.Context(permission.CtxPool, a.Pool),
		)...)
	} else {
		evt.Allowed = event.Allowed(permission.PermAppReadEvents)
	}
	startOpts := DeployOptions{
		Commit: data.Commit,
		Origin: data.Origin,
	}
	var otherData map[string]string
	if data.Diff != "" {
		otherData = map[string]string{"diff": data.Diff}
	}
	endData := map[string]string{"image": data.Image}
	err = evt.RawInsert(startOpts, otherData, endData)
	if mgo.IsDup(err) {
		return nil
	}
	return err
}
开发者ID:tsuru,项目名称:tsuru,代码行数:35,代码来源:deploy.go

示例15: addNodeHandler

// addNodeHandler can provide an machine and/or register a node address.
// If register flag is true, it will just register a node.
// It checks if node address is valid and accessible.
func addNodeHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	params, err := unmarshal(r.Body)
	if err != nil {
		return err
	}
	if templateName, ok := params["template"]; ok {
		params, err = iaas.ExpandTemplate(templateName)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
		}
	}
	pool := params["pool"]
	if pool == "" {
		w.WriteHeader(http.StatusBadRequest)
		return json.NewEncoder(w).Encode(map[string]string{"error": "pool is required"})
	}
	if !permission.Check(t, permission.PermNodeCreate, permission.Context(permission.CtxPool, pool)) {
		return permission.ErrUnauthorized
	}
	isRegister, _ := strconv.ParseBool(r.URL.Query().Get("register"))
	if !isRegister {
		canCreateMachine := permission.Check(t, permission.PermMachineCreate,
			permission.Context(permission.CtxIaaS, params["iaas"]))
		if !canCreateMachine {
			return permission.ErrUnauthorized
		}
	}
	response, err := mainDockerProvisioner.addNodeForParams(params, isRegister)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		response["error"] = err.Error()
	}
	return json.NewEncoder(w).Encode(response)
}
开发者ID:reoring,项目名称:tsuru,代码行数:38,代码来源:handlers.go


注:本文中的github.com/tsuru/tsuru/permission.Context函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。