// UpdateAuthorization is the handler for PUT /users/{username}/authorizations/{grantedTo}
// Modify which information an organization is able to see.
4537
func (api UsersAPI) UpdateAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	authorization := &user.Authorization{}

	if err := json.NewDecoder(r.Body).Decode(authorization); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	userMgr := user.NewManager(r)
	userobj, err := userMgr.GetByName(username)
	if handleServerError(w, "getting user by name", err) {
		return
	}
	verifiedEmails := []user.EmailAddress{}
	if len(authorization.OwnerOf.EmailAddresses) != 0 || len(authorization.ValidatedEmailAddresses) > 0 {
		verifiedEmails, err = api.getValidatedEmails(r, *userobj)
		if handleServerError(w, "getting verified emails", err) {
			return
		}
	}

	verifiedPhones := []user.Phonenumber{}
	if len(authorization.ValidatedPhonenumbers) > 0 {
		verifiedPhones, err = api.getValidatedPhones(r, *userobj)
		if handleServerError(w, "getting verified phone numbers", err) {
			return
		}
	}

	authorization.Username = username
	authorization.GrantedTo = grantedTo
	authorization.Addresses = FilterAuthorizationMaps(authorization.Addresses)
	authorization.EmailAddresses = FilterAuthorizationMaps(authorization.EmailAddresses)
	authorization.ValidatedEmailAddresses = FilterValidatedEmails(FilterAuthorizationMaps(authorization.ValidatedEmailAddresses), verifiedEmails)
	authorization.Phonenumbers = FilterAuthorizationMaps(authorization.Phonenumbers)
	authorization.ValidatedPhonenumbers = FilterValidatedPhones(FilterAuthorizationMaps(authorization.ValidatedPhonenumbers), verifiedPhones)
	authorization.BankAccounts = FilterAuthorizationMaps(authorization.BankAccounts)
	authorization.PublicKeys = FilterAuthorizationMaps(authorization.PublicKeys)
	authorization.DigitalWallet = FilterDigitalWallet(authorization.DigitalWallet)
	authorization.OwnerOf = FilterOwnerOf(authorization.OwnerOf, verifiedEmails)
	authorization.Avatars = FilterAuthorizationMaps(authorization.Avatars)

	existingAuth, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "getting existing authorization", err) {
		return
	}
	if existingAuth != nil {
		// Merge authorizations
		authorization.Merge(existingAuth)
	}

	err = userMgr.UpdateAuthorization(authorization)
	if handleServerError(w, "updating authorization", err) {
		return
	}
	w.Header().Set("Content-type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(authorization)
}
188069
func (api *API) UpdateOrganizationAccessRule(organizationID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) {
	return api.updateAccessRule("/accounts/"+organizationID, accessRuleID, accessRule)
}
1110323
func (r *rest) AppAuthorize(c *gin.Context) {
	resp := r.server.NewResponse()
	defer resp.Close()
	if ar := r.server.HandleAuthorizeRequest(resp, c.Request); ar != nil {
		userId, ok := handleLoginPage(r, ar, c)
		if !ok {
			return
		}
		ar.UserData = userId
		ar.Authorized = true
		r.server.FinishAuthorizeRequest(resp, c.Request, ar)
	}
	if resp.IsError && resp.InternalError != nil {
		log.Printf("ERROR: %s\n", resp.InternalError)
	}
	if !resp.IsError {
		//resp.Output["custom_parameter"] = 42
	}
	osin.OutputJSON(resp, c.Writer, c.Request)
}
1004914
func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (a *platform.Authorization, err error) {
	defer func(start time.Time) {
		labels := prometheus.Labels{
			"method": "setAuthorizationStatus",
			"error":  fmt.Sprint(err != nil),
		}
		s.requestCount.With(labels).Add(1)
		s.requestDuration.With(labels).Observe(time.Since(start).Seconds())
	}(time.Now())

	return s.AuthorizationService.UpdateAuthorization(ctx, id, upd)
}
19880
func (r *contextAuthorizer) Authorize(ctx context.Context) (*AuthContext, error) {
	return &r.authContext, nil
}
558053
func NewAuthorizationHandler(userService platform.UserService) *AuthorizationHandler {
	h := &AuthorizationHandler{
		Router:      NewRouter(),
		Logger:      zap.NewNop(),
		UserService: userService,
	}

	h.HandlerFunc("POST", "/api/v2/authorizations", h.handlePostAuthorization)
	h.HandlerFunc("GET", "/api/v2/authorizations", h.handleGetAuthorizations)
	h.HandlerFunc("GET", "/api/v2/authorizations/:id", h.handleGetAuthorization)
	h.HandlerFunc("PATCH", "/api/v2/authorizations/:id", h.handleSetAuthorizationStatus)
	h.HandlerFunc("DELETE", "/api/v2/authorizations/:id", h.handleDeleteAuthorization)
	return h
}
184756
func NoAuthorization() func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
	return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
		blob, err := RequestTeamInfo(tc, TeamAPI)
		var data []TeamInfo
		err = json.Unmarshal(blob, &data)
		if err != nil {
			glog.Errorf("[Gin-OAuth] JSON.Unmarshal failed, caused by: %s", err)
		}
		for _, teamInfo := range data {
			if teamInfo.Type == "official" {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id)
				return true
			}
		}
		return true
	}
}
981396
func (s *UpdateRouteInput) SetAuthorizationType(v string) *UpdateRouteInput {
	s.AuthorizationType = &v
	return s
}
677115
func (c *Client) SetAuthorizationStatus(ctx context.Context, id platform.ID, status platform.Status) error {
	return c.db.Update(func(tx *bolt.Tx) error {
		if pe := c.updateAuthorization(ctx, tx, id, status); pe != nil {
			return &platform.Error{
				Err: pe,
				Op:  platform.OpSetAuthorizationStatus,
			}
		}
		return nil
	})
}
1204931
func (controllerAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
	if authInfo.Controller {
		return nil
	}
	return errors.Errorf("%s is not a controller", names.ReadableString(authInfo.Entity.Tag()))
}
1039761
func (c *Client) VoidAuthorization(authID string) (*Authorization, error) {
	buf := bytes.NewBuffer([]byte(""))
	req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v2/payments/authorization/"+authID+"/void"), buf)
	if err != nil {
		return &Authorization{}, err
	}

	auth := &Authorization{}
	err = c.SendWithAuth(req, auth)
	return auth, err
}
770592
func WithAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler {
	if a == nil {
		klog.Warningf("Authorization is disabled")
		return handler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		ae := request.AuditEventFrom(ctx)

		attributes, err := GetAuthorizerAttributes(ctx)
		if err != nil {
			responsewriters.InternalError(w, req, err)
			return
		}
		authorized, reason, err := a.Authorize(attributes)
		// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.
		if authorized == authorizer.DecisionAllow {
			audit.LogAnnotation(ae, decisionAnnotationKey, decisionAllow)
			audit.LogAnnotation(ae, reasonAnnotationKey, reason)
			handler.ServeHTTP(w, req)
			return
		}
		if err != nil {
			audit.LogAnnotation(ae, reasonAnnotationKey, reasonError)
			responsewriters.InternalError(w, req, err)
			return
		}

		klog.V(4).Infof("Forbidden: %#v, Reason: %q", req.RequestURI, reason)
		audit.LogAnnotation(ae, decisionAnnotationKey, decisionForbid)
		audit.LogAnnotation(ae, reasonAnnotationKey, reason)
		responsewriters.Forbidden(ctx, attributes, w, req, reason, s)
	})
}
804474
func (vi *ValidatorImpl) authorizeUpdate(configUpdateEnv *cb.ConfigUpdateEnvelope) (map[string]comparable, error) {
	if configUpdateEnv == nil {
		return nil, errors.Errorf("cannot process nil ConfigUpdateEnvelope")
	}

	configUpdate, err := UnmarshalConfigUpdate(configUpdateEnv.ConfigUpdate)
	if err != nil {
		return nil, err
	}

	if configUpdate.ChannelId != vi.channelID {
		return nil, errors.Errorf("ConfigUpdate for channel '%s' but envelope for channel '%s'", configUpdate.ChannelId, vi.channelID)
	}

	readSet, err := mapConfig(configUpdate.ReadSet, vi.namespace)
	if err != nil {
		return nil, errors.Wrapf(err, "error mapping ReadSet")
	}
	err = vi.verifyReadSet(readSet)
	if err != nil {
		return nil, errors.Wrapf(err, "error validating ReadSet")
	}

	writeSet, err := mapConfig(configUpdate.WriteSet, vi.namespace)
	if err != nil {
		return nil, errors.Wrapf(err, "error mapping WriteSet")
	}

	deltaSet := computeDeltaSet(readSet, writeSet)
	signedData, err := configUpdateEnv.AsSignedData()
	if err != nil {
		return nil, err
	}

	if err = vi.verifyDeltaSet(deltaSet, signedData); err != nil {
		return nil, errors.Wrapf(err, "error validating DeltaSet")
	}

	fullProposedConfig := vi.computeUpdateResult(deltaSet)
	if err := verifyFullProposedConfig(writeSet, fullProposedConfig); err != nil {
		return nil, errors.Wrapf(err, "full config did not verify")
	}

	return fullProposedConfig, nil
}
37966
func (s *HttpDataSourceConfig) SetAuthorizationConfig(v *AuthorizationConfig) *HttpDataSourceConfig {
	s.AuthorizationConfig = v
	return s
}
292306
func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) {
	var a *influxdb.Authorization
	var err error
	err = s.kv.Update(ctx, func(tx Tx) error {
		a, err = s.updateAuthorization(ctx, tx, id, upd)
		return err
	})
	return a, err
}
478426
func (s *PutMethodInput) SetAuthorizerId(v string) *PutMethodInput {
	s.AuthorizerId = &v
	return s
}
758876
func NewAuthorizationBackend(b *APIBackend) *AuthorizationBackend {
	return &AuthorizationBackend{
		Logger: b.Logger.With(zap.String("handler", "authorization")),

		AuthorizationService: b.AuthorizationService,
		OrganizationService:  b.OrganizationService,
		UserService:          b.UserService,
		LookupService:        b.LookupService,
	}
}