code.gitea.io/gitea@v1.21.7/models/organization/mini_org.go (about)

     1  // Copyright 2022 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package organization
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"strings"
    10  
    11  	"code.gitea.io/gitea/models/db"
    12  	repo_model "code.gitea.io/gitea/models/repo"
    13  	"code.gitea.io/gitea/models/unit"
    14  	user_model "code.gitea.io/gitea/models/user"
    15  
    16  	"xorm.io/builder"
    17  )
    18  
    19  // MinimalOrg represents a simple organization with only the needed columns
    20  type MinimalOrg = Organization
    21  
    22  // GetUserOrgsList returns all organizations the given user has access to
    23  func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg, error) {
    24  	schema, err := db.TableInfo(new(user_model.User))
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	outputCols := []string{
    30  		"id",
    31  		"name",
    32  		"full_name",
    33  		"visibility",
    34  		"avatar",
    35  		"avatar_email",
    36  		"use_custom_avatar",
    37  	}
    38  
    39  	groupByCols := &strings.Builder{}
    40  	for _, col := range outputCols {
    41  		fmt.Fprintf(groupByCols, "`%s`.%s,", schema.Name, col)
    42  	}
    43  	groupByStr := groupByCols.String()
    44  	groupByStr = groupByStr[0 : len(groupByStr)-1]
    45  
    46  	sess := db.GetEngine(ctx)
    47  	sess = sess.Select(groupByStr+", count(distinct repo_id) as org_count").
    48  		Table("user").
    49  		Join("INNER", "team", "`team`.org_id = `user`.id").
    50  		Join("INNER", "team_user", "`team`.id = `team_user`.team_id").
    51  		Join("LEFT", builder.
    52  			Select("id as repo_id, owner_id as repo_owner_id").
    53  			From("repository").
    54  			Where(repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)), "`repository`.repo_owner_id = `team`.org_id").
    55  		Where("`team_user`.uid = ?", user.ID).
    56  		GroupBy(groupByStr)
    57  
    58  	type OrgCount struct {
    59  		Organization `xorm:"extends"`
    60  		OrgCount     int
    61  	}
    62  
    63  	orgCounts := make([]*OrgCount, 0, 10)
    64  
    65  	if err := sess.
    66  		Asc("`user`.name").
    67  		Find(&orgCounts); err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	orgs := make([]*MinimalOrg, len(orgCounts))
    72  	for i, orgCount := range orgCounts {
    73  		orgCount.Organization.NumRepos = orgCount.OrgCount
    74  		orgs[i] = &orgCount.Organization
    75  	}
    76  
    77  	return orgs, nil
    78  }