// GetOrganizationLogo is the handler for GET /organizations/globalid/logo
// Get the Logo from an organization
325541
func (api OrganizationsAPI) GetOrganizationLogo(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]
	logoMgr := organization.NewLogoManager(r)

	logo, err := logoMgr.GetLogo(globalid)

	if err != nil && err != mgo.ErrNotFound {
		log.Error("Error getting logo", err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	response := struct {
		Logo string `json:"logo"`
	}{
		Logo: logo,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}
1266970
func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) {
	ccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(ccv2.Filter{
		Type:     constant.OrganizationGUIDFilter,
		Operator: constant.EqualOperator,
		Values:   []string{orgGUID},
	})
	if err != nil {
		return []Space{}, Warnings(warnings), err
	}

	spaces := make([]Space, len(ccv2Spaces))
	for i, ccv2Space := range ccv2Spaces {
		spaces[i] = Space(ccv2Space)
	}

	return spaces, Warnings(warnings), nil
}
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)
}
1117178
func (actor Actor) GetOrganizationByName(name string) (Organization, Warnings, error) {
	orgs, warnings, err := actor.CloudControllerClient.GetOrganizations(
		ccv3.Query{Key: ccv3.NameFilter, Values: []string{name}},
	)
	if err != nil {
		return Organization{}, Warnings(warnings), err
	}

	if len(orgs) == 0 {
		return Organization{}, Warnings(warnings), actionerror.OrganizationNotFoundError{Name: name}
	}

	return Organization(orgs[0]), Warnings(warnings), nil
}
358341
func getOrganizations(client *github.Client, log chronograf.Logger) ([]*github.Organization, error) {
	// Get all pages of results
	var allOrgs []*github.Organization
	for {
		opt := &github.ListOptions{
			PerPage: 10,
		}
		// Get the organizations for the current authenticated user.
		orgs, resp, err := client.Organizations.List(context.TODO(), "", opt)
		if err != nil {
			logResponseError(log, resp, err)
			return nil, err
		}
		allOrgs = append(allOrgs, orgs...)
		if resp.NextPage == 0 {
			break
		}
		opt.Page = resp.NextPage
	}
	return allOrgs, nil
}
1316972
func (s *Service) FindOrganizationByName(ctx context.Context, n string) (*influxdb.Organization, error) {
	span, ctx := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	var o *influxdb.Organization

	err := s.kv.View(ctx, func(tx Tx) error {
		org, err := s.findOrganizationByName(ctx, tx, n)
		if err != nil {
			return err
		}
		o = org
		return nil
	})

	return o, err
}
271552
func (h *OrgHandler) handleGetOrgLog(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeGetOrganizationLogRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	log, _, err := h.OrganizationOperationLogService.GetOrganizationOperationLog(ctx, req.OrganizationID, req.opts)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newOrganizationLogResponse(req.OrganizationID, log)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
1022765
func (multi *OrganizationsStore) DefaultOrganization(ctx context.Context) (*chronograf.Organization, error) {
	errors := []string{}
	for _, store := range multi.Stores {
		org, err := store.DefaultOrganization(ctx)
		if err == nil {
			return org, nil
		}
		errors = append(errors, err.Error())
	}
	return nil, fmt.Errorf("unknown error while getting default organization: %s", strings.Join(errors, " "))

}
1056274
func (u *User) GetOrganizations(showPrivate bool) error {
	orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
	if err != nil {
		return fmt.Errorf("GetOrgIDsByUserID: %v", err)
	}
	if len(orgIDs) == 0 {
		return nil
	}

	u.Orgs = make([]*User, 0, len(orgIDs))
	if err = x.Where("type = ?", USER_TYPE_ORGANIZATION).In("id", orgIDs).Find(&u.Orgs); err != nil {
		return err
	}
	return nil
}
201426
func (c *Client) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) {
	var o *influxdb.Organization
	err := c.db.View(func(tx *bolt.Tx) error {
		org, pe := c.findOrganizationByID(ctx, tx, id)
		if pe != nil {
			return &influxdb.Error{
				Op:  getOp(influxdb.OpFindOrganizationByID),
				Err: pe,
			}
		}
		o = org
		return nil
	})

	if err != nil {
		return nil, err
	}

	return o, nil
}
50762
func (client *Client) GetOrganization(guid string) (Organization, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetOrganizationRequest,
		URIParams:   Params{"organization_guid": guid},
	})
	if err != nil {
		return Organization{}, nil, err
	}

	var org Organization
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &org,
	}

	err = client.connection.Make(request, &response)
	return org, response.Warnings, err
}
545655
func (api OrganizationsAPI) CreateOrganizationDns(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]

	dns := DnsAddress{}

	if err := json.NewDecoder(r.Body).Decode(&dns); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !dns.Validate() {
		log.Debug("Invalid DNS name: ", dns.Name)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	orgMgr := organization.NewManager(r)
	organisation, err := orgMgr.GetByName(globalID)
	if err != nil {
		if err == mgo.ErrNotFound {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		} else {
			handleServerError(w, "getting organization", err)
		}
		return
	}
	for _, d := range organisation.DNS {
		if dns.Name == d {
			http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
			return
		}
	}
	err = orgMgr.AddDNS(organisation, dns.Name)

	if handleServerError(w, "adding DNS name", err) {
		return
	}

	w.Header().Set("Content-Type", "application/json")

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(dns)
}
546274
func (api *API) ListOrganizations() ([]Organization, ResultInfo, error) {
	var r organizationResponse
	res, err := api.makeRequest("GET", "/user/organizations", nil)
	if err != nil {
		return []Organization{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError)
	}

	err = json.Unmarshal(res, &r)
	if err != nil {
		return []Organization{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError)
	}

	return r.Result, r.ResultInfo, nil
}
861059
func (s *OrganizationService) FindOrganization(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) {
	return s.FindOrganizationF(ctx, filter)
}
1106729
func (s *OrganizationOperationLogService) GetOrganizationOperationLog(ctx context.Context, id platform.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) {
	return s.GetOrganizationOperationLogFn(ctx, id, opts)
}
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)
}
329482
func (s *OrganizationService) FindOrganizationByID(ctx context.Context, id platform.ID) (*platform.Organization, error) {
	return s.FindOrganizationByIDF(ctx, id)
}