// TeamIDKeys takes a set of DBKeys that must all be tid:-style DBKeys and
// extracts the team id from them. Because teams can be loaded via both FTL and
// the slow team loader, we use a set so we don't return duplicate teamIDs.
492490
func keySetToTeamIDs(dbKeySet libkb.DBKeySet) ([]keybase1.TeamID, error) {
	seen := make(map[keybase1.TeamID]bool)
	teamIDs := make([]keybase1.TeamID, 0, len(dbKeySet))
	for dbKey := range dbKeySet {
		teamID, err := ParseTeamIDDBKey(dbKey.Key)
		if err != nil {
			return nil, err
		}
		_, ok := seen[teamID]
		if !ok {
			teamIDs = append(teamIDs, teamID)
			seen[teamID] = true
		}
	}
	return teamIDs, nil
}
625160
func (c *githubConnector) teamGroupClaims(t team) []string {
	switch c.teamNameField {
	case "both":
		return []string{t.Name, t.Slug}
	case "slug":
		return []string{t.Slug}
	default:
		return []string{t.Name}
	}
}
167438
func (hs *HTTPServer) DeleteTeamByID(c *m.ReqContext) Response {
	orgId := c.OrgId
	teamId := c.ParamsInt64(":teamId")
	user := c.SignedInUser

	if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, user); err != nil {
		return Error(403, "Not allowed to delete team", err)
	}

	if err := hs.Bus.Dispatch(&m.DeleteTeamCommand{OrgId: orgId, Id: teamId}); err != nil {
		if err == m.ErrTeamNotFound {
			return Error(404, "Failed to delete Team. ID not found", nil)
		}
		return Error(500, "Failed to delete Team", err)
	}
	return Success("Team deleted")
}
542106
func (s *Service) TeamMemberDelete(ctx context.Context, teamIdentity string, teamMemberIdentity string) (*TeamMember, error) {
	var teamMember TeamMember
	return &teamMember, s.Delete(ctx, &teamMember, fmt.Sprintf("/teams/%v/members/%v", teamIdentity, teamMemberIdentity))
}
910035
func (c *Client) GetTeam(teamKey string) (*Team, error) {
	content, err := c.GetFantasyContent(
		fmt.Sprintf("%s/team/%s;out=stats,metadata,players,standings,roster",
			YahooBaseURL,
			teamKey))
	if err != nil {
		return nil, err
	}

	if content.Team.TeamID == 0 {
		return nil, fmt.Errorf("no team returned for key='%s'", teamKey)
	}
	return &content.Team, nil
}
307189
func nodeKey(id ID) []byte {
	key := append([]byte(dbNodePrefix), id[:]...)
	key = append(key, ':')
	key = append(key, dbDiscoverRoot...)
	return key
}
572664
func (id ID) GetEpochFromTeamTLF(tid keybase1.TeamID) (
	matches bool, epoch byte, err error) {
	tidBytes := tid.ToBytes()
	if len(tidBytes) != idByteLen {
		return false, 0, errors.Errorf(
			"The length of team ID %s doesn't match that of a TLF ID", tid)
	}

	epochIndex := idByteLen - 2
	if !bytes.Equal(tidBytes[:epochIndex], id.id[:epochIndex]) {
		return false, 0, nil
	}

	return true, id.id[epochIndex], nil
}
380392
func (dl *DaemonLocal) CreateTeamTLF(
	ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) (err error) {
	if err := checkContext(ctx); err != nil {
		return err
	}

	// TODO: add check to make sure the private/public suffix of the
	// team ID matches that of the tlf ID.
	dl.lock.Lock()
	defer dl.lock.Unlock()
	iteamInfo, isImplicit := dl.localImplicitTeams[teamID]
	if isImplicit {
		iteamInfo.TlfID = tlfID
		dl.localImplicitTeams[teamID] = iteamInfo
	}
	_, isRegularTeam := dl.localTeams[teamID]
	if !isImplicit && !isRegularTeam {
		return NoSuchTeamError{teamID.String()}
	}
	dl.localTeamSettings[teamID] = keybase1.KBFSTeamSettings{
		TlfID: keybase1.TLFID(tlfID.String())}
	return nil
}
726571
func (e *EKLib) GetTeamEK(mctx libkb.MetaContext, teamID keybase1.TeamID, generation keybase1.EkGeneration,
	contentCtime *gregor1.Time) (teamEK keybase1.TeamEk, err error) {
	defer mctx.TraceTimed("GetTeamEK", func() error { return err })()

	teamEKBoxStorage := mctx.G().GetTeamEKBoxStorage()
	teamEK, err = teamEKBoxStorage.Get(mctx, teamID, generation, contentCtime)
	if err != nil {
		switch err.(type) {
		case EphemeralKeyError:
			mctx.Debug(err.Error())
			// If we are unable to get the current max generation, try to kick
			// off creation of a new key.
			go func(mctx libkb.MetaContext) {
				maxGeneration, err := teamEKBoxStorage.MaxGeneration(mctx, teamID, true)
				if err != nil {
					mctx.Debug("Unable to get MaxGeneration: %v", err)
					return
				}
				if generation == maxGeneration {
					_, created, cerr := e.GetOrCreateLatestTeamEK(mctx, teamID)
					if cerr != nil {
						mctx.Debug("Unable to GetOrCreateLatestTeamEK: %v", cerr)
					}
					if e.backgroundCreationTestCh != nil {
						e.backgroundCreationTestCh <- created
					}
				}
			}(libkb.NewMetaContextBackground(mctx.G()))
		}
	}
	return teamEK, err
}
1137836
func (k *KBPKIClient) GetTeamRootID(
	ctx context.Context, tid keybase1.TeamID,
	offline keybase1.OfflineAvailability) (keybase1.TeamID, error) {
	if !tid.IsSubTeam() {
		return tid, nil
	}

	teamInfo, err := k.serviceOwner.KeybaseService().LoadTeamPlusKeys(
		ctx, tid, tlf.Unknown, kbfsmd.UnspecifiedKeyGen, keybase1.UserVersion{},
		kbfscrypto.VerifyingKey{}, keybase1.TeamRole_NONE, offline)
	if err != nil {
		return keybase1.TeamID(""), err
	}
	return teamInfo.RootID, nil
}
922045
func (b BlockServerMeasured) GetTeamQuotaInfo(
	ctx context.Context, tid keybase1.TeamID) (
	info *kbfsblock.QuotaInfo, err error) {
	return b.delegate.GetTeamQuotaInfo(ctx, tid)
}
246911
func (t *TeamsClient) List(ctx context.Context, orgID *identity.ID, name string, teamType primitive.TeamType) ([]envelope.Team, error) {
	v := &url.Values{}

	if orgID != nil {
		v.Set("org_id", orgID.String())
	}
	if name != "" {
		v.Set("name", name)
	}
	if teamType != primitive.AnyTeamType {
		v.Set("type", string(teamType))
	}

	var teams []envelope.Team
	err := t.client.RoundTrip(ctx, "GET", "/teams", v, nil, &teams)
	return teams, err
}
545789
func folderFromTeamIDImplicit(ctx context.Context, g *libkb.GlobalContext, teamID keybase1.TeamID) (keybase1.Folder, error) {

	team, err := teams.Load(ctx, g, keybase1.LoadTeamArg{
		ID:     teamID,
		Public: teamID.IsPublic(),
	})
	if err != nil {
		return keybase1.Folder{}, err
	}
	if !team.IsImplicit() {
		return keybase1.Folder{}, fmt.Errorf("Expected an implicit team, but team load said otherwise (%s)", teamID)
	}

	// TODO: This function doesn't currently support conflict info.
	name, err := team.ImplicitTeamDisplayNameString(ctx)
	if err != nil {
		return keybase1.Folder{}, err
	}
	var folderType keybase1.FolderType
	if team.IsPublic() {
		folderType = keybase1.FolderType_PUBLIC
	} else {
		folderType = keybase1.FolderType_PRIVATE
	}
	return keybase1.Folder{
		Name:       name,
		FolderType: folderType,
		Private:    !team.IsPublic(),
	}, nil
}
1355696
func (t *teamSigchainPlayer) assertSubteamName(parent *TeamSigChainState, parentSeqno keybase1.Seqno, subteamNameStr string) (keybase1.TeamName, error) {
	// Ideally, we would assert the team name is a direct child of this team's name.
	// But the middle parts of the names might be out of date.
	// Instead assert:
	// - The root team name is same.
	// - The subteam is 1 level deeper.
	// - The last part of the parent team's name matched
	//   at the parent-seqno that this subteam name was mentioned.
	//   (If the subteam is a.b.c.d then c should match)
	//   The reason this is pegged at seqno instead of simply the latest parent name is
	//   hard to explain, see TestRenameInflateSubteamAfterRenameParent.

	subteamName, err := keybase1.TeamNameFromString(subteamNameStr)
	if err != nil {
		return subteamName, fmt.Errorf("invalid subteam team name '%s': %v", subteamNameStr, err)
	}

	if !parent.inner.RootAncestor.Eq(subteamName.RootAncestorName()) {
		return subteamName, fmt.Errorf("subteam is of a different root team: %v != %v",
			subteamName.RootAncestorName(),
			parent.inner.RootAncestor)
	}

	expectedDepth := parent.inner.NameDepth + 1
	if subteamName.Depth() != expectedDepth {
		return subteamName, fmt.Errorf("subteam name has depth %v but expected %v",
			subteamName.Depth(), expectedDepth)
	}

	// The last part of the parent name at parentSeqno.
	var parentLastPart keybase1.TeamNamePart
	for _, point := range parent.inner.NameLog {
		if point.Seqno > parentSeqno {
			break
		}
		parentLastPart = point.LastPart
	}

	subteamSecondToLastPart := subteamName.Parts[len(subteamName.Parts)-2]
	if !subteamSecondToLastPart.Eq(parentLastPart) {
		return subteamName, fmt.Errorf("subteam name has wrong name for us: %v != %v",
			subteamSecondToLastPart, parentLastPart)
	}

	return subteamName, nil
}
1143431
func GetTeamsByUser(query *m.GetTeamsByUserQuery) error {
	query.Result = make([]*m.TeamDTO, 0)

	var sql bytes.Buffer

	sql.WriteString(getTeamSelectSqlBase())
	sql.WriteString(` INNER JOIN team_member on team.id = team_member.team_id`)
	sql.WriteString(` WHERE team.org_id = ? and team_member.user_id = ?`)

	err := x.SQL(sql.String(), query.OrgId, query.UserId).Find(&query.Result)
	return err
}
363302
func (ks KeyList) IDs() []string {
	keyIDs := make([]string, 0, len(ks))
	for _, k := range ks {
		keyIDs = append(keyIDs, k.ID())
	}
	return keyIDs
}
64746
func getKeyringMembers(ctx context.Context, client *registry.Client,
	orgID *identity.ID) ([]keyringMember, error) {

	teams, err := client.Teams.GetByOrg(ctx, orgID)
	if err != nil {
		return nil, err
	}

	membersTeam, machinesTeam, err := findSystemTeams(teams)
	if err != nil {
		return nil, err
	}

	userMembers, err := client.Memberships.List(ctx, orgID, membersTeam.ID, nil)
	if err != nil {
		return nil, err
	}

	machineMembers, err := client.Memberships.List(ctx, orgID, machinesTeam.ID, nil)
	if err != nil {
		return nil, err
	}

	var members []keyringMember
	for _, membership := range userMembers {
		members = append(members, &userKeyringMember{id: membership.Body.OwnerID})
	}

	for _, membership := range machineMembers {
		machineID := membership.Body.OwnerID
		segment, err := client.Machines.Get(ctx, machineID)
		if err != nil {
			return nil, err
		}

		m := machineKeyringMember{Machine: segment.Machine}
		for _, token := range segment.Tokens {
			if token.Token.Body.State == primitive.MachineTokenActiveState {
				m.tokens = append(m.tokens, *token.Token.ID)
			}
		}
		members = append(members, &m)
	}

	return members, nil
}