// Get the list organizations a user is owner or member of
// It is handler for GET /users/{username}/organizations
548187
func (api UsersusernameorganizationsAPI) Get(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]

	orgMgr := organizationdb.NewManager(r)

	orgs, err := orgMgr.AllByUserChain(username)
	if err != nil {
		log.Error("Failed to load all organizations the user belongs to: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	type UserOrganizations struct {
		Member []string `json:"member"`
		Owner  []string `json:"owner"`
	}
	userOrgs := UserOrganizations{
		Member: []string{},
		Owner:  []string{},
	}

	availableScopes, _ := context.Get(r, "availablescopes").(string)
	scopes := oauth2.SplitScopeString(availableScopes)
	isAdmin := oauth2.CheckScopes([]string{"user:admin"}, scopes)

	// if not isAdmin filter out orgs our scopes have access to
	if !isAdmin {
		userOrgs.Member = filterOrgs(orgs, scopes)
	} else {
		userOrgs.Member = orgs
	}

	userOrgs.Owner, userOrgs.Member, err = orgMgr.SplitOwnedOrgs(userOrgs.Member, username)
	if err != nil {
		log.Error("Failed to sort organizations to owner and member: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
	}
	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(&userOrgs)
}
1342981
func (org *Organization) Organizations() ([]*Organization, error) {
	var os []orgResource
	err := org.PPE.get(fmt.Sprintf("/orgs/%s/orgs", org.PrimaryDomain), &os)
	if err != nil {
		return []*Organization{}, err
	}
	orgs := make([]*Organization, len(os))
	for i, o := range os {
		orgs[i] = orgFromOrgResource(org.PPE, o)
	}
	return orgs, nil
}
404665
func (c *Client) GetUsers() ([]services.User, error) {
	out, err := c.Get(c.Endpoint("users"), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var items []json.RawMessage
	if err := json.Unmarshal(out.Bytes(), &items); err != nil {
		return nil, trace.Wrap(err)
	}
	users := make([]services.User, len(items))
	for i, userBytes := range items {
		user, err := services.GetUserMarshaler().UnmarshalUser(userBytes, services.SkipValidation())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		users[i] = user
	}
	return users, nil
}
721799
func (c *Client) ListUsers() (rec []UserInfo, err error) {
	req, err := newGETRequest(c, "users/")
	if err != nil {
		return []UserInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []UserInfo{}, err
	}

	return rec, nil
}
846885
func (s *Service) IdentityProviderListByOrganization(ctx context.Context, organizationName string, lr *ListRange) (IdentityProviderListByOrganizationResult, error) {
	var identityProvider IdentityProviderListByOrganizationResult
	return identityProvider, s.Get(ctx, &identityProvider, fmt.Sprintf("/organizations/%v/identity-providers", organizationName), nil, lr)
}
896983
func (c *githubConnector) getGroups(ctx context.Context, client *http.Client, groupScope bool, userLogin string) ([]string, error) {
	if len(c.orgs) > 0 {
		return c.groupsForOrgs(ctx, client, userLogin)
	} else if c.org != "" {
		return c.teamsForOrg(ctx, client, c.org)
	} else if groupScope && c.loadAllGroups {
		return c.userGroups(ctx, client)
	}
	return nil, nil
}
1136598
func (api OrganizationsAPI) GetOrganization(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]
	orgMgr := organization.NewManager(r)

	org, 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
	}

	// replace owners and members usernames
	orgView, err := org.ConvertToView(user.NewManager(r), validationdb.NewManager(r))
	if handleServerError(w, "converting organization to organization view", err) {
		return
	}
	json.NewEncoder(w).Encode(orgView)
}
892076
func (c *Client) OrganizationAppListForOrganization(organizationIdentity string, lr *ListRange) ([]OrganizationApp, error) {
	req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/apps", nil, nil)
	if err != nil {
		return nil, err
	}

	if lr != nil {
		lr.SetHeader(req)
	}

	var organizationAppsRes []OrganizationApp
	return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
845182
func (t *TeamsService) GetMembers(uri *Hyperlink, uriParams M) (
	members []User, result *Result) {
	url, err := ExpandWithDefault(uri, &TeamMembersURL, uriParams)
	if err != nil {
		return []User(nil), &Result{Err: err}
	}
	return t.client.Users(url).All()
}
883136
func GetOrgIDsByUserID(userID int64, showPrivate bool) ([]int64, error) {
	orgIDs := make([]int64, 0, 5)
	sess := x.Table("org_user").Where("uid = ?", userID)
	if !showPrivate {
		sess.And("is_public = ?", true)
	}
	return orgIDs, sess.Distinct("org_id").Find(&orgIDs)
}
86425
func (c *Client) OrganizationAppList(lr *ListRange) ([]OrganizationApp, error) {
	req, err := c.NewRequest("GET", "/organizations/apps", nil, nil)
	if err != nil {
		return nil, err
	}

	if lr != nil {
		lr.SetHeader(req)
	}

	var organizationAppsRes []OrganizationApp
	return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
977554
func (api *API) OrganizationInvites(organizationID string) ([]OrganizationInvite, ResultInfo, error) {
	var r organizationInvitesResponse
	uri := "/organizations/" + organizationID + "/invites"
	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return []OrganizationInvite{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError)
	}

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

	return r.Result, r.ResultInfo, nil
}
230916
func (client *Client) GetOrganizations(filters ...Filter) ([]Organization, Warnings, error) {
	allQueries := ConvertFilterParameters(filters)
	allQueries.Add("order-by", "name")
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetOrganizationsRequest,
		Query:       allQueries,
	})

	if err != nil {
		return nil, nil, err
	}

	var fullOrgsList []Organization
	warnings, err := client.paginate(request, Organization{}, func(item interface{}) error {
		if org, ok := item.(Organization); ok {
			fullOrgsList = append(fullOrgsList, org)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   Organization{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullOrgsList, warnings, err
}
625846
func (cs *UserService) List() ([]UsersResponse, error) {

	req, err := cs.client.NewRequest("GET", "/users", nil)
	if err != nil {
		return nil, err
	}

	resp, err := cs.client.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if err := validateResponse(resp); err != nil {
		return nil, err
	}

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	bodyString := string(bodyBytes)

	u := &listUsersJSONResponse{}
	err = json.Unmarshal([]byte(bodyString), &u)

	return u.Users, err
}
434247
func (d *DismissalRestrictionsRequest) GetUsers() []string {
	if d == nil || d.Users == nil {
		return nil
	}
	return *d.Users
}
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
}
504288
func GetUsers() []User {
	var userPagesResponse struct {
		NextURL   *string `json:"next_url"`
		Resources []struct {
			Metadata struct {
				GUID      string    `json:"guid"`
				CreatedAt time.Time `json:"created_at"`
			} `json:"metadata"`
			Entity struct {
				Username string `json:"username"`
			} `json:"entity"`
		} `json:"resources"`
	}

	var allUsers []User
	nextURL := "/v2/users?results-per-page=50"

	for {
		session := CF("curl", nextURL)
		Eventually(session).Should(Exit(0))

		err := json.Unmarshal(session.Out.Contents(), &userPagesResponse)
		Expect(err).NotTo(HaveOccurred())
		for _, resource := range userPagesResponse.Resources {
			allUsers = append(allUsers, User{
				GUID:      resource.Metadata.GUID,
				CreatedAt: resource.Metadata.CreatedAt,
				Username:  resource.Entity.Username,
			})
		}

		if userPagesResponse.NextURL == nil {
			break
		}
		nextURL = *userPagesResponse.NextURL
	}

	return allUsers
}