// CreateOrganizationAccessRule creates a firewall access rule for the given
// organization identifier.
//
// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-create-access-rule
358954
func (api *API) CreateOrganizationAccessRule(organizationID string, accessRule AccessRule) (*AccessRuleResponse, error) {
	return api.createAccessRule("/accounts/"+organizationID, accessRule)
}
53822
func (o *Enterprise) CreateFirewallRule(child *FirewallRule) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
1046760
func queryOrganization(ctx context.Context, r *http.Request, svc platform.OrganizationService) (o *platform.Organization, err error) {
	filter := platform.OrganizationFilter{}
	if reqID := r.URL.Query().Get(OrgID); reqID != "" {
		filter.ID, err = platform.IDFromString(reqID)
		if err != nil {
			return nil, err
		}
	}

	if name := r.URL.Query().Get(OrgName); name != "" {
		filter.Name = &name
	}

	return svc.FindOrganization(ctx, filter)
}
961290
func (s *Service) OrganizationInvitationCreate(ctx context.Context, organizationIdentity string, o OrganizationInvitationCreateOpts) (*OrganizationInvitation, error) {
	var organizationInvitation OrganizationInvitation
	return &organizationInvitation, s.Put(ctx, &organizationInvitation, fmt.Sprintf("/organizations/%v/invitations", organizationIdentity), o)
}
1268363
func (api OrganizationsAPI) GetOrganizationUsers(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]
	orgMgr := organization.NewManager(r)
	if !orgMgr.Exists(globalID) {
		writeErrorResponse(w, http.StatusNotFound, "organization_not_found")
		return
	}
	authenticatedUser := context.Get(r, "authenticateduser").(string)
	response := organization.GetOrganizationUsersResponseBody{}
	isOwner, err := orgMgr.IsOwner(globalID, authenticatedUser)
	if handleServerError(w, "checking if user is owner of an organization", err) {
		return
	}
	org, err := orgMgr.GetByName(globalID)
	if handleServerError(w, "getting organization by name", err) {
		return
	}
	roleMap := make(map[string]string)
	valMgr := validationdb.NewManager(r)
	allUsernames := append(org.Members, org.Owners...)
	userIdentifierMap, err := organization.MapUsernamesToIdentifiers(allUsernames, valMgr)
	if handleServerError(w, "mapping usernames to identifiers", err) {
		return
	}
	for _, username := range org.Members {
		roleMap[username] = "members"
	}
	for _, username := range org.Owners {
		roleMap[username] = "owners"
	}
	authorizationsMap := make(map[string]user.Authorization)
	// Only owners can see if there are missing permissions
	userMgr := user.NewManager(r)
	if isOwner {
		authorizations, err := userMgr.GetOrganizationAuthorizations(globalID)
		if handleServerError(w, "getting organizaton authorizations", err) {
			return
		}
		for _, authorization := range authorizations {
			authorizationsMap[authorization.Username] = authorization
		}
	}
	users := []organization.OrganizationUser{}
	for username, role := range roleMap {
		orgUser := organization.OrganizationUser{
			Username:      getUserIdentifier(username, userIdentifierMap),
			Role:          role,
			MissingScopes: []string{},
		}
		if isOwner {
			for _, requiredScope := range org.RequiredScopes {
				hasScope := false
				if authorization, hasKey := authorizationsMap[username]; hasKey {
					hasScope = requiredScope.IsAuthorized(authorization)
				} else {
					hasScope = false
				}
				if !hasScope {
					orgUser.MissingScopes = append(orgUser.MissingScopes, requiredScope.Scope)
				}
			}
		}
		users = append(users, orgUser)
	}
	response.HasEditPermissions = isOwner
	response.Users = users
	json.NewEncoder(w).Encode(response)
}
1199233
func (o *Organizations) DefaultOrganization(ctx context.Context) (*chronograf.Organization, error) {
	return nil, fmt.Errorf("unable to get default organizations from the filestore")
}
1278090
func (s *Service) NewOrganization(w http.ResponseWriter, r *http.Request) {
	var req organizationRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		invalidJSON(w, s.Logger)
		return
	}

	if err := req.ValidCreate(); err != nil {
		invalidData(w, err, s.Logger)
		return
	}

	ctx := r.Context()
	org := &chronograf.Organization{
		Name:        req.Name,
		DefaultRole: req.DefaultRole,
	}

	res, err := s.Store.Organizations(ctx).Add(ctx, org)
	if err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}

	// Now that the organization was created, add the user
	// making the request to the organization
	user, ok := hasUserContext(ctx)
	if !ok {
		// Best attempt at cleanup the organization if there were any errors
		_ = s.Store.Organizations(ctx).Delete(ctx, res)
		Error(w, http.StatusInternalServerError, "failed to retrieve user from context", s.Logger)
		return
	}

	user.Roles = []chronograf.Role{
		{
			Organization: res.ID,
			Name:         roles.AdminRoleName,
		},
	}

	orgCtx := context.WithValue(ctx, organizations.ContextKey, res.ID)
	_, err = s.Store.Users(orgCtx).Add(orgCtx, user)
	if err != nil {
		// Best attempt at cleanup the organization if there were any errors adding user to org
		_ = s.Store.Organizations(ctx).Delete(ctx, res)
		s.Logger.Error("failed to add user to organization", err.Error())
		Error(w, http.StatusInternalServerError, "failed to add user to organization", s.Logger)
		return
	}

	co := newOrganizationResponse(res)
	location(w, co.Links.Self)
	encodeJSON(w, http.StatusCreated, co, s.Logger)
}
787763
func (api *API) UserAccessRule(accessRuleID string) (*AccessRuleResponse, error) {
	return api.retrieveAccessRule("/user", accessRuleID)
}
683954
func (s *Service) OrganizationCreate(ctx context.Context, o OrganizationCreateOpts) (*Organization, error) {
	var organization Organization
	return &organization, s.Post(ctx, &organization, fmt.Sprintf("/organizations"), o)
}
552296
func (u *User) GetOrganizationsURL() string {
	if u == nil || u.OrganizationsURL == nil {
		return ""
	}
	return *u.OrganizationsURL
}
647238
func (s *OrgService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) {
	if err := authorizeWriteOrg(ctx, id); err != nil {
		return nil, err
	}

	return s.s.UpdateOrganization(ctx, id, upd)
}
1209324
func (c *Client) CreateOrganization(ctx context.Context, o *platform.Organization) error {
	op := getOp(platform.OpCreateOrganization)
	return c.db.Update(func(tx *bolt.Tx) error {
		unique := c.uniqueOrganizationName(ctx, tx, o)
		if !unique {
			return &platform.Error{
				Code: platform.EConflict,
				Op:   op,
				Msg:  fmt.Sprintf("organization with name %s already exists", o.Name),
			}
		}

		o.ID = c.IDGenerator.ID()
		if err := c.appendOrganizationEventToLog(ctx, tx, o.ID, organizationCreatedEvent); err != nil {
			return &platform.Error{
				Err: err,
				Op:  op,
			}
		}

		if err := c.putOrganization(ctx, tx, o); err != nil {
			return &platform.Error{
				Err: err,
				Op:  op,
			}
		}
		return nil
	})
}
770078
func (s *Service) IdentityProviderCreateByOrganization(ctx context.Context, organizationName string, o IdentityProviderCreateByOrganizationOpts) (*IdentityProvider, error) {
	var identityProvider IdentityProvider
	return &identityProvider, s.Post(ctx, &identityProvider, fmt.Sprintf("/organizations/%v/identity-providers", organizationName), o)
}
1129619
func (c *Client) PutOrganization(ctx context.Context, o *influxdb.Organization) error {
	var err error
	return c.db.Update(func(tx *bolt.Tx) error {
		if pe := c.putOrganization(ctx, tx, o); pe != nil {
			err = pe
		}
		return err
	})
}
400272
func (o *Me) CreateInfrastructureAccessProfile(child *InfrastructureAccessProfile) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
499012
func (api OrganizationsAPI) CreateNewOrganization(w http.ResponseWriter, r *http.Request) {
	var org organization.Organization

	if err := json.NewDecoder(r.Body).Decode(&org); err != nil {
		log.Debug("Error decoding the organization:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	org.Globalid = strings.Trim(org.Globalid, " ")
	if !org.IsValid() {
		log.Debug("Invalid organization")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	api.actualOrganizationCreation(org, w, r)

}
775277
func (m *Manager) GetOrganizationAuthorizations(globalId string) (authorizations []Authorization, err error) {
	qry := bson.M{"grantedto": globalId}
	err = m.getAuthorizationCollection().Find(qry).All(&authorizations)
	if authorizations == nil {
		authorizations = []Authorization{}
	}
	return
}