// GetUserTeams returns all teams that user belongs to in given organization.
777535
func GetUserTeams(orgID, userID int64) ([]*Team, error) {
	return getUserTeams(x, orgID, userID)
}
481108
func GetTeamMembers(c *m.ReqContext) Response {
	query := m.GetTeamMembersQuery{OrgId: c.OrgId, TeamId: c.ParamsInt64(":teamId")}

	if err := bus.Dispatch(&query); err != nil {
		return Error(500, "Failed to get Team Members", err)
	}

	for _, member := range query.Result {
		member.AvatarUrl = dtos.GetGravatarUrl(member.Email)
		member.Labels = []string{}

		if setting.IsEnterprise && setting.LdapEnabled && member.External {
			member.Labels = append(member.Labels, "LDAP")
		}
	}

	return JSON(200, query.Result)
}
202725
func (b *bitbucketConnector) getGroups(ctx context.Context, client *http.Client, groupScope bool, userLogin string) ([]string, error) {
	bitbucketTeams, err := b.userTeams(ctx, client)
	if err != nil {
		return nil, err
	}

	if len(b.teams) > 0 {
		filteredTeams := filterTeams(bitbucketTeams, b.teams)
		if len(filteredTeams) == 0 {
			return nil, fmt.Errorf("bitbucket: user %q is not in any of the required teams", userLogin)
		}
		return filteredTeams, nil
	} else if groupScope {
		return bitbucketTeams, nil
	}

	return nil, nil
}
489532
func (t *TeamService) GetTeams() (*TeamsResponse, error) {
	var teamsRes TeamsResponse
	_, err := t.client.get(TeamURL, url.Values{}, &teamsRes)
	if err != nil {
		return nil, err
	}

	return &teamsRes, nil
}
1186272
func (org *User) GetMembers() error {
	ous, err := GetOrgUsersByOrgID(org.ID)
	if err != nil {
		return err
	}

	org.Members = make([]*User, len(ous))
	for i, ou := range ous {
		org.Members[i], err = GetUserByID(ou.Uid)
		if err != nil {
			return err
		}
	}
	return 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)
}
1363496
func (o *Organization) GetMembers(args Arguments) (members []*Member, err error) {
	path := fmt.Sprintf("organizations/%s/members", o.ID)
	err = o.client.Get(path, args, &members)
	for i := range members {
		members[i].client = o.client
	}
	return
}
434247
func (d *DismissalRestrictionsRequest) GetUsers() []string {
	if d == nil || d.Users == nil {
		return nil
	}
	return *d.Users
}
1022857
func (l *localLoadedTeams) getTeamForMember(ctx context.Context, member keybase1.MemberInfo,
	needAdmin bool) (team *Team, uv keybase1.UserVersion, err error) {
	teamID := member.TeamID
	team = l.teams[teamID]
	if team == nil {
		// Team was not there in local cache - this is the first time
		// localLoadedTeams is asked for this team. Try with no
		// forceRepoll first.
		team, err = Load(ctx, l.G(), keybase1.LoadTeamArg{
			ID:               teamID,
			NeedAdmin:        needAdmin,
			Public:           teamID.IsPublic(),
			ForceRepoll:      false,
			RefreshUIDMapper: true,
		})
		if err != nil {
			return nil, uv, err
		}
		l.teams[teamID] = team
	}

	memberUV, err := verifyMemberRoleInTeam(ctx, member.UserID, member.Role, team)
	if err != nil {
		team, err = Load(ctx, l.G(), keybase1.LoadTeamArg{
			ID:          teamID,
			NeedAdmin:   needAdmin,
			Public:      teamID.IsPublic(),
			ForceRepoll: true,
		})
		if err != nil {
			return nil, uv, err
		}
		l.teams[teamID] = team

		memberUV, err = verifyMemberRoleInTeam(ctx, member.UserID, member.Role, team)
		if err != nil {
			return nil, uv, fmt.Errorf("server was wrong about role in team : %v", err)
		}
	}

	return team, memberUV, nil
}
1156132
func DeleteTeam(t *Team) error {
	if err := t.GetRepositories(); err != nil {
		return err
	}

	// Get organization.
	org, err := GetUserByID(t.OrgID)
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	// Delete all accesses.
	for _, repo := range t.Repos {
		if err = repo.recalculateTeamAccesses(sess, t.ID); err != nil {
			return err
		}
	}

	// Delete team-user.
	if _, err = sess.Where("org_id=?", org.ID).Where("team_id=?", t.ID).Delete(new(TeamUser)); err != nil {
		return err
	}

	// Delete team.
	if _, err = sess.ID(t.ID).Delete(new(Team)); err != nil {
		return err
	}
	// Update organization number of teams.
	if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
		return err
	}

	return sess.Commit()
}
26539
func GetTeamOfOrgByName(orgID int64, name string) (*Team, error) {
	return getTeamOfOrgByName(x, orgID, name)
}
1137200
func (p *provider) getUserTeams(token string) (sets.String, error) {
	userTeams := sets.NewString()
	err := p.page(p.githubUserTeamURL, token,
		func() interface{} {
			return &[]githubTeam{}
		},
		func(obj interface{}) error {
			for _, team := range *(obj.(*[]githubTeam)) {
				if len(team.Slug) > 0 && len(team.Organization.Login) > 0 {
					userTeams.Insert(strings.ToLower(team.Organization.Login + "/" + team.Slug))
				}
			}
			return nil
		},
	)
	return userTeams, err
}
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
}
376826
func (k *KeybaseServiceBase) GetTeamSettings(
	ctx context.Context, teamID keybase1.TeamID,
	offline keybase1.OfflineAvailability) (
	keybase1.KBFSTeamSettings, error) {
	// TODO: get invalidations from the server and cache the settings?
	return k.kbfsClient.GetKBFSTeamSettings(
		ctx, keybase1.GetKBFSTeamSettingsArg{
			TeamID: teamID,
			Oa:     offline,
		})
}
190240
func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response {
	perPage := c.QueryInt("perpage")
	if perPage <= 0 {
		perPage = 1000
	}
	page := c.QueryInt("page")
	if page < 1 {
		page = 1
	}

	var userIdFilter int64
	if hs.Cfg.EditorsCanAdmin && c.OrgRole != m.ROLE_ADMIN {
		userIdFilter = c.SignedInUser.UserId
	}

	query := m.SearchTeamsQuery{
		OrgId:        c.OrgId,
		Query:        c.Query("query"),
		Name:         c.Query("name"),
		UserIdFilter: userIdFilter,
		Page:         page,
		Limit:        perPage,
	}

	if err := bus.Dispatch(&query); err != nil {
		return Error(500, "Failed to search Teams", err)
	}

	for _, team := range query.Result.Teams {
		team.AvatarUrl = dtos.GetGravatarUrlWithDefault(team.Email, team.Name)
	}

	query.Result.Page = page
	query.Result.PerPage = perPage

	return JSON(200, query.Result)
}
501022
func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
	teams, err := org.getUserTeams(x, userID, "team.id")
	if err != nil {
		return nil, fmt.Errorf("getUserTeams [%d]: %v", userID, err)
	}

	teamIDs := make([]int64, len(teams))
	for i := range teams {
		teamIDs[i] = teams[i].ID
	}
	return teamIDs, nil
}
1135064
func (s *Service) AddOnListByTeam(ctx context.Context, teamIdentity string, lr *ListRange) (AddOnListByTeamResult, error) {
	var addOn AddOnListByTeamResult
	return addOn, s.Get(ctx, &addOn, fmt.Sprintf("/teams/%v/addons", teamIdentity), nil, lr)
}