Move organization related structs into sub package (#18518)
* Move organization related structs into sub package * Fix test * Fix lint * Move more functions into sub packages * Fix bug * Fix test * Update models/organization/team_repo.go Co-authored-by: KN4CK3R <admin@oldschoolhack.me> * Apply suggestions from code review Co-authored-by: KN4CK3R <admin@oldschoolhack.me> * Fix fmt * Follow suggestion from @Gusted * Fix test * Fix test * Fix bug * Use ctx but db.DefaultContext on routers * Fix bug * Fix bug * fix bug * Update models/organization/team_user.go * Fix bug Co-authored-by: KN4CK3R <admin@oldschoolhack.me> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>tokarchuk/v1.17
parent
d4c789dfc1
commit
b06b9a056c
@ -0,0 +1,24 @@ |
||||
// Copyright 2021 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"path/filepath" |
||||
"testing" |
||||
|
||||
"code.gitea.io/gitea/models/unittest" |
||||
) |
||||
|
||||
func TestMain(m *testing.M) { |
||||
unittest.MainTest(m, filepath.Join("..", ".."), |
||||
"user.yml", |
||||
"org_user.yml", |
||||
"team.yml", |
||||
"team_repo.yml", |
||||
"team_unit.yml", |
||||
"team_user.yml", |
||||
"repository.yml", |
||||
) |
||||
} |
@ -0,0 +1,859 @@ |
||||
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
"fmt" |
||||
"strings" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/perm" |
||||
repo_model "code.gitea.io/gitea/models/repo" |
||||
"code.gitea.io/gitea/models/unit" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
"code.gitea.io/gitea/modules/log" |
||||
"code.gitea.io/gitea/modules/setting" |
||||
"code.gitea.io/gitea/modules/structs" |
||||
|
||||
"xorm.io/builder" |
||||
) |
||||
|
||||
// ________ .__ __ .__
|
||||
// \_____ \_______ _________ ____ |__|____________ _/ |_|__| ____ ____
|
||||
// / | \_ __ \/ ___\__ \ / \| \___ /\__ \\ __\ |/ _ \ / \
|
||||
// / | \ | \/ /_/ > __ \| | \ |/ / / __ \| | | ( <_> ) | \
|
||||
// \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| /
|
||||
// \/ /_____/ \/ \/ \/ \/ \/
|
||||
|
||||
// ErrOrgNotExist represents a "OrgNotExist" kind of error.
|
||||
type ErrOrgNotExist struct { |
||||
ID int64 |
||||
Name string |
||||
} |
||||
|
||||
// IsErrOrgNotExist checks if an error is a ErrOrgNotExist.
|
||||
func IsErrOrgNotExist(err error) bool { |
||||
_, ok := err.(ErrOrgNotExist) |
||||
return ok |
||||
} |
||||
|
||||
func (err ErrOrgNotExist) Error() string { |
||||
return fmt.Sprintf("org does not exist [id: %d, name: %s]", err.ID, err.Name) |
||||
} |
||||
|
||||
// ErrLastOrgOwner represents a "LastOrgOwner" kind of error.
|
||||
type ErrLastOrgOwner struct { |
||||
UID int64 |
||||
} |
||||
|
||||
// IsErrLastOrgOwner checks if an error is a ErrLastOrgOwner.
|
||||
func IsErrLastOrgOwner(err error) bool { |
||||
_, ok := err.(ErrLastOrgOwner) |
||||
return ok |
||||
} |
||||
|
||||
func (err ErrLastOrgOwner) Error() string { |
||||
return fmt.Sprintf("user is the last member of owner team [uid: %d]", err.UID) |
||||
} |
||||
|
||||
// ErrUserNotAllowedCreateOrg represents a "UserNotAllowedCreateOrg" kind of error.
|
||||
type ErrUserNotAllowedCreateOrg struct{} |
||||
|
||||
// IsErrUserNotAllowedCreateOrg checks if an error is an ErrUserNotAllowedCreateOrg.
|
||||
func IsErrUserNotAllowedCreateOrg(err error) bool { |
||||
_, ok := err.(ErrUserNotAllowedCreateOrg) |
||||
return ok |
||||
} |
||||
|
||||
func (err ErrUserNotAllowedCreateOrg) Error() string { |
||||
return "user is not allowed to create organizations" |
||||
} |
||||
|
||||
// Organization represents an organization
|
||||
type Organization user_model.User |
||||
|
||||
// OrgFromUser converts user to organization
|
||||
func OrgFromUser(user *user_model.User) *Organization { |
||||
return (*Organization)(user) |
||||
} |
||||
|
||||
// TableName represents the real table name of Organization
|
||||
func (Organization) TableName() string { |
||||
return "user" |
||||
} |
||||
|
||||
// IsOwnedBy returns true if given user is in the owner team.
|
||||
func (org *Organization) IsOwnedBy(uid int64) (bool, error) { |
||||
return IsOrganizationOwner(db.DefaultContext, org.ID, uid) |
||||
} |
||||
|
||||
// IsOrgMember returns true if given user is member of organization.
|
||||
func (org *Organization) IsOrgMember(uid int64) (bool, error) { |
||||
return IsOrganizationMember(db.DefaultContext, org.ID, uid) |
||||
} |
||||
|
||||
// CanCreateOrgRepo returns true if given user can create repo in organization
|
||||
func (org *Organization) CanCreateOrgRepo(uid int64) (bool, error) { |
||||
return CanCreateOrgRepo(org.ID, uid) |
||||
} |
||||
|
||||
func (org *Organization) getTeam(ctx context.Context, name string) (*Team, error) { |
||||
return getTeam(ctx, org.ID, name) |
||||
} |
||||
|
||||
// GetTeam returns named team of organization.
|
||||
func (org *Organization) GetTeam(name string) (*Team, error) { |
||||
return org.getTeam(db.DefaultContext, name) |
||||
} |
||||
|
||||
func (org *Organization) getOwnerTeam(ctx context.Context) (*Team, error) { |
||||
return org.getTeam(ctx, OwnerTeamName) |
||||
} |
||||
|
||||
// GetOwnerTeam returns owner team of organization.
|
||||
func (org *Organization) GetOwnerTeam() (*Team, error) { |
||||
return org.getOwnerTeam(db.DefaultContext) |
||||
} |
||||
|
||||
// FindOrgTeams returns all teams of a given organization
|
||||
func FindOrgTeams(ctx context.Context, orgID int64) ([]*Team, error) { |
||||
var teams []*Team |
||||
return teams, db.GetEngine(ctx). |
||||
Where("org_id=?", orgID). |
||||
OrderBy("CASE WHEN name LIKE '" + OwnerTeamName + "' THEN '' ELSE name END"). |
||||
Find(&teams) |
||||
} |
||||
|
||||
// LoadTeams load teams if not loaded.
|
||||
func (org *Organization) LoadTeams() ([]*Team, error) { |
||||
return FindOrgTeams(db.DefaultContext, org.ID) |
||||
} |
||||
|
||||
// GetMembers returns all members of organization.
|
||||
func (org *Organization) GetMembers() (user_model.UserList, map[int64]bool, error) { |
||||
return FindOrgMembers(&FindOrgMembersOpts{ |
||||
OrgID: org.ID, |
||||
}) |
||||
} |
||||
|
||||
// HasMemberWithUserID returns true if user with userID is part of the u organisation.
|
||||
func (org *Organization) HasMemberWithUserID(userID int64) bool { |
||||
return org.hasMemberWithUserID(db.DefaultContext, userID) |
||||
} |
||||
|
||||
func (org *Organization) hasMemberWithUserID(ctx context.Context, userID int64) bool { |
||||
isMember, err := IsOrganizationMember(ctx, org.ID, userID) |
||||
if err != nil { |
||||
log.Error("IsOrganizationMember: %v", err) |
||||
return false |
||||
} |
||||
return isMember |
||||
} |
||||
|
||||
// AvatarLink returns the full avatar link with http host
|
||||
func (org *Organization) AvatarLink() string { |
||||
return org.AsUser().AvatarLink() |
||||
} |
||||
|
||||
// HTMLURL returns the organization's full link.
|
||||
func (org *Organization) HTMLURL() string { |
||||
return org.AsUser().HTMLURL() |
||||
} |
||||
|
||||
// OrganisationLink returns the organization sub page link.
|
||||
func (org *Organization) OrganisationLink() string { |
||||
return org.AsUser().OrganisationLink() |
||||
} |
||||
|
||||
// ShortName ellipses username to length
|
||||
func (org *Organization) ShortName(length int) string { |
||||
return org.AsUser().ShortName(length) |
||||
} |
||||
|
||||
// HomeLink returns the user or organization home page link.
|
||||
func (org *Organization) HomeLink() string { |
||||
return org.AsUser().HomeLink() |
||||
} |
||||
|
||||
// CanCreateRepo returns if user login can create a repository
|
||||
// NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
|
||||
func (org *Organization) CanCreateRepo() bool { |
||||
return org.AsUser().CanCreateRepo() |
||||
} |
||||
|
||||
// FindOrgMembersOpts represensts find org members conditions
|
||||
type FindOrgMembersOpts struct { |
||||
db.ListOptions |
||||
OrgID int64 |
||||
PublicOnly bool |
||||
} |
||||
|
||||
// CountOrgMembers counts the organization's members
|
||||
func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) { |
||||
sess := db.GetEngine(db.DefaultContext).Where("org_id=?", opts.OrgID) |
||||
if opts.PublicOnly { |
||||
sess.And("is_public = ?", true) |
||||
} |
||||
return sess.Count(new(OrgUser)) |
||||
} |
||||
|
||||
// FindOrgMembers loads organization members according conditions
|
||||
func FindOrgMembers(opts *FindOrgMembersOpts) (user_model.UserList, map[int64]bool, error) { |
||||
ous, err := GetOrgUsersByOrgID(opts) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
|
||||
ids := make([]int64, len(ous)) |
||||
idsIsPublic := make(map[int64]bool, len(ous)) |
||||
for i, ou := range ous { |
||||
ids[i] = ou.UID |
||||
idsIsPublic[ou.UID] = ou.IsPublic |
||||
} |
||||
|
||||
users, err := user_model.GetUsersByIDs(ids) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
return users, idsIsPublic, nil |
||||
} |
||||
|
||||
// AsUser returns the org as user object
|
||||
func (org *Organization) AsUser() *user_model.User { |
||||
return (*user_model.User)(org) |
||||
} |
||||
|
||||
// DisplayName returns full name if it's not empty,
|
||||
// returns username otherwise.
|
||||
func (org *Organization) DisplayName() string { |
||||
return org.AsUser().DisplayName() |
||||
} |
||||
|
||||
// CustomAvatarRelativePath returns user custom avatar relative path.
|
||||
func (org *Organization) CustomAvatarRelativePath() string { |
||||
return org.Avatar |
||||
} |
||||
|
||||
// CreateOrganization creates record of a new organization.
|
||||
func CreateOrganization(org *Organization, owner *user_model.User) (err error) { |
||||
if !owner.CanCreateOrganization() { |
||||
return ErrUserNotAllowedCreateOrg{} |
||||
} |
||||
|
||||
if err = user_model.IsUsableUsername(org.Name); err != nil { |
||||
return err |
||||
} |
||||
|
||||
isExist, err := user_model.IsUserExist(0, org.Name) |
||||
if err != nil { |
||||
return err |
||||
} else if isExist { |
||||
return user_model.ErrUserAlreadyExist{Name: org.Name} |
||||
} |
||||
|
||||
org.LowerName = strings.ToLower(org.Name) |
||||
if org.Rands, err = user_model.GetUserSalt(); err != nil { |
||||
return err |
||||
} |
||||
if org.Salt, err = user_model.GetUserSalt(); err != nil { |
||||
return err |
||||
} |
||||
org.UseCustomAvatar = true |
||||
org.MaxRepoCreation = -1 |
||||
org.NumTeams = 1 |
||||
org.NumMembers = 1 |
||||
org.Type = user_model.UserTypeOrganization |
||||
|
||||
ctx, committer, err := db.TxContext() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer committer.Close() |
||||
|
||||
if err = user_model.DeleteUserRedirect(ctx, org.Name); err != nil { |
||||
return err |
||||
} |
||||
|
||||
if err = db.Insert(ctx, org); err != nil { |
||||
return fmt.Errorf("insert organization: %v", err) |
||||
} |
||||
if err = user_model.GenerateRandomAvatarCtx(ctx, org.AsUser()); err != nil { |
||||
return fmt.Errorf("generate random avatar: %v", err) |
||||
} |
||||
|
||||
// Add initial creator to organization and owner team.
|
||||
if err = db.Insert(ctx, &OrgUser{ |
||||
UID: owner.ID, |
||||
OrgID: org.ID, |
||||
}); err != nil { |
||||
return fmt.Errorf("insert org-user relation: %v", err) |
||||
} |
||||
|
||||
// Create default owner team.
|
||||
t := &Team{ |
||||
OrgID: org.ID, |
||||
LowerName: strings.ToLower(OwnerTeamName), |
||||
Name: OwnerTeamName, |
||||
AccessMode: perm.AccessModeOwner, |
||||
NumMembers: 1, |
||||
IncludesAllRepositories: true, |
||||
CanCreateOrgRepo: true, |
||||
} |
||||
if err = db.Insert(ctx, t); err != nil { |
||||
return fmt.Errorf("insert owner team: %v", err) |
||||
} |
||||
|
||||
// insert units for team
|
||||
units := make([]TeamUnit, 0, len(unit.AllRepoUnitTypes)) |
||||
for _, tp := range unit.AllRepoUnitTypes { |
||||
units = append(units, TeamUnit{ |
||||
OrgID: org.ID, |
||||
TeamID: t.ID, |
||||
Type: tp, |
||||
}) |
||||
} |
||||
|
||||
if err = db.Insert(ctx, &units); err != nil { |
||||
return err |
||||
} |
||||
|
||||
if err = db.Insert(ctx, &TeamUser{ |
||||
UID: owner.ID, |
||||
OrgID: org.ID, |
||||
TeamID: t.ID, |
||||
}); err != nil { |
||||
return fmt.Errorf("insert team-user relation: %v", err) |
||||
} |
||||
|
||||
return committer.Commit() |
||||
} |
||||
|
||||
// GetOrgByName returns organization by given name.
|
||||
func GetOrgByName(name string) (*Organization, error) { |
||||
if len(name) == 0 { |
||||
return nil, ErrOrgNotExist{0, name} |
||||
} |
||||
u := &Organization{ |
||||
LowerName: strings.ToLower(name), |
||||
Type: user_model.UserTypeOrganization, |
||||
} |
||||
has, err := db.GetEngine(db.DefaultContext).Get(u) |
||||
if err != nil { |
||||
return nil, err |
||||
} else if !has { |
||||
return nil, ErrOrgNotExist{0, name} |
||||
} |
||||
return u, nil |
||||
} |
||||
|
||||
// CountOrganizations returns number of organizations.
|
||||
func CountOrganizations() int64 { |
||||
count, _ := db.GetEngine(db.DefaultContext). |
||||
Where("type=1"). |
||||
Count(new(Organization)) |
||||
return count |
||||
} |
||||
|
||||
// DeleteOrganization deletes models associated to an organization.
|
||||
func DeleteOrganization(ctx context.Context, org *Organization) error { |
||||
if org.Type != user_model.UserTypeOrganization { |
||||
return fmt.Errorf("%s is a user not an organization", org.Name) |
||||
} |
||||
|
||||
if err := db.DeleteBeans(ctx, |
||||
&Team{OrgID: org.ID}, |
||||
&OrgUser{OrgID: org.ID}, |
||||
&TeamUser{OrgID: org.ID}, |
||||
&TeamUnit{OrgID: org.ID}, |
||||
); err != nil { |
||||
return fmt.Errorf("deleteBeans: %v", err) |
||||
} |
||||
|
||||
if _, err := db.GetEngine(ctx).ID(org.ID).Delete(new(user_model.User)); err != nil { |
||||
return fmt.Errorf("Delete: %v", err) |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// GetOrgUserMaxAuthorizeLevel returns highest authorize level of user in an organization
|
||||
func (org *Organization) GetOrgUserMaxAuthorizeLevel(uid int64) (perm.AccessMode, error) { |
||||
var authorize perm.AccessMode |
||||
_, err := db.GetEngine(db.DefaultContext). |
||||
Select("max(team.authorize)"). |
||||
Table("team"). |
||||
Join("INNER", "team_user", "team_user.team_id = team.id"). |
||||
Where("team_user.uid = ?", uid). |
||||
And("team_user.org_id = ?", org.ID). |
||||
Get(&authorize) |
||||
return authorize, err |
||||
} |
||||
|
||||
// GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization
|
||||
func GetUsersWhoCanCreateOrgRepo(ctx context.Context, orgID int64) ([]*user_model.User, error) { |
||||
users := make([]*user_model.User, 0, 10) |
||||
return users, db.GetEngine(ctx). |
||||
Join("INNER", "`team_user`", "`team_user`.uid=`user`.id"). |
||||
Join("INNER", "`team`", "`team`.id=`team_user`.team_id"). |
||||
Where(builder.Eq{"team.can_create_org_repo": true}.Or(builder.Eq{"team.authorize": perm.AccessModeOwner})). |
||||
And("team_user.org_id = ?", orgID).Asc("`user`.name").Find(&users) |
||||
} |
||||
|
||||
// SearchOrganizationsOptions options to filter organizations
|
||||
type SearchOrganizationsOptions struct { |
||||
db.ListOptions |
||||
All bool |
||||
} |
||||
|
||||
// FindOrgOptions finds orgs options
|
||||
type FindOrgOptions struct { |
||||
db.ListOptions |
||||
UserID int64 |
||||
IncludePrivate bool |
||||
} |
||||
|
||||
func queryUserOrgIDs(userID int64, includePrivate bool) *builder.Builder { |
||||
cond := builder.Eq{"uid": userID} |
||||
if !includePrivate { |
||||
cond["is_public"] = true |
||||
} |
||||
return builder.Select("org_id").From("org_user").Where(cond) |
||||
} |
||||
|
||||
func (opts FindOrgOptions) toConds() builder.Cond { |
||||
cond := builder.NewCond() |
||||
if opts.UserID > 0 { |
||||
cond = cond.And(builder.In("`user`.`id`", queryUserOrgIDs(opts.UserID, opts.IncludePrivate))) |
||||
} |
||||
if !opts.IncludePrivate { |
||||
cond = cond.And(builder.Eq{"`user`.visibility": structs.VisibleTypePublic}) |
||||
} |
||||
return cond |
||||
} |
||||
|
||||
// FindOrgs returns a list of organizations according given conditions
|
||||
func FindOrgs(opts FindOrgOptions) ([]*Organization, error) { |
||||
orgs := make([]*Organization, 0, 10) |
||||
sess := db.GetEngine(db.DefaultContext). |
||||
Where(opts.toConds()). |
||||
Asc("`user`.name") |
||||
if opts.Page > 0 && opts.PageSize > 0 { |
||||
sess.Limit(opts.PageSize, opts.PageSize*(opts.Page-1)) |
||||
} |
||||
return orgs, sess.Find(&orgs) |
||||
} |
||||
|
||||
// CountOrgs returns total count organizations according options
|
||||
func CountOrgs(opts FindOrgOptions) (int64, error) { |
||||
return db.GetEngine(db.DefaultContext). |
||||
Where(opts.toConds()). |
||||
Count(new(user_model.User)) |
||||
} |
||||
|
||||
func getOwnedOrgsByUserID(sess db.Engine, userID int64) ([]*Organization, error) { |
||||
orgs := make([]*Organization, 0, 10) |
||||
return orgs, sess. |
||||
Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id"). |
||||
Join("INNER", "`team`", "`team`.id=`team_user`.team_id"). |
||||
Where("`team_user`.uid=?", userID). |
||||
And("`team`.authorize=?", perm.AccessModeOwner). |
||||
Asc("`user`.name"). |
||||
Find(&orgs) |
||||
} |
||||
|
||||
// HasOrgOrUserVisible tells if the given user can see the given org or user
|
||||
func HasOrgOrUserVisible(ctx context.Context, orgOrUser, user *user_model.User) bool { |
||||
// Not SignedUser
|
||||
if user == nil { |
||||
return orgOrUser.Visibility == structs.VisibleTypePublic |
||||
} |
||||
|
||||
if user.IsAdmin || orgOrUser.ID == user.ID { |
||||
return true |
||||
} |
||||
|
||||
if (orgOrUser.Visibility == structs.VisibleTypePrivate || user.IsRestricted) && !OrgFromUser(orgOrUser).hasMemberWithUserID(ctx, user.ID) { |
||||
return false |
||||
} |
||||
return true |
||||
} |
||||
|
||||
// HasOrgsVisible tells if the given user can see at least one of the orgs provided
|
||||
func HasOrgsVisible(orgs []*Organization, user *user_model.User) bool { |
||||
if len(orgs) == 0 { |
||||
return false |
||||
} |
||||
|
||||
for _, org := range orgs { |
||||
if HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user) { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
|
||||
// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
|
||||
func GetOwnedOrgsByUserID(userID int64) ([]*Organization, error) { |
||||
return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext), userID) |
||||
} |
||||
|
||||
// GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
|
||||
// given user ID, ordered descending by the given condition.
|
||||
func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*Organization, error) { |
||||
return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext).Desc(desc), userID) |
||||
} |
||||
|
||||
// GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
|
||||
// are allowed to create repos.
|
||||
func GetOrgsCanCreateRepoByUserID(userID int64) ([]*Organization, error) { |
||||
orgs := make([]*Organization, 0, 10) |
||||
|
||||
return orgs, db.GetEngine(db.DefaultContext).Where(builder.In("id", builder.Select("`user`.id").From("`user`"). |
||||
Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id"). |
||||
Join("INNER", "`team`", "`team`.id = `team_user`.team_id"). |
||||
Where(builder.Eq{"`team_user`.uid": userID}). |
||||
And(builder.Eq{"`team`.authorize": perm.AccessModeOwner}.Or(builder.Eq{"`team`.can_create_org_repo": true})))). |
||||
Asc("`user`.name"). |
||||
Find(&orgs) |
||||
} |
||||
|
||||
// GetOrgUsersByUserID returns all organization-user relations by user ID.
|
||||
func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUser, error) { |
||||
ous := make([]*OrgUser, 0, 10) |
||||
sess := db.GetEngine(db.DefaultContext). |
||||
Join("LEFT", "`user`", "`org_user`.org_id=`user`.id"). |
||||
Where("`org_user`.uid=?", uid) |
||||
if !opts.All { |
||||
// Only show public organizations
|
||||
sess.And("is_public=?", true) |
||||
} |
||||
|
||||
if opts.PageSize != 0 { |
||||
sess = db.SetSessionPagination(sess, opts) |
||||
} |
||||
|
||||
err := sess. |
||||
Asc("`user`.name"). |
||||
Find(&ous) |
||||
return ous, err |
||||
} |
||||
|
||||
// GetOrgUsersByOrgID returns all organization-user relations by organization ID.
|
||||
func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) { |
||||
return getOrgUsersByOrgID(db.GetEngine(db.DefaultContext), opts) |
||||
} |
||||
|
||||
func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) { |
||||
sess := e.Where("org_id=?", opts.OrgID) |
||||
if opts.PublicOnly { |
||||
sess.And("is_public = ?", true) |
||||
} |
||||
if opts.ListOptions.PageSize > 0 { |
||||
sess = db.SetSessionPagination(sess, opts) |
||||
|
||||
ous := make([]*OrgUser, 0, opts.PageSize) |
||||
return ous, sess.Find(&ous) |
||||
} |
||||
|
||||
var ous []*OrgUser |
||||
return ous, sess.Find(&ous) |
||||
} |
||||
|
||||
// ChangeOrgUserStatus changes public or private membership status.
|
||||
func ChangeOrgUserStatus(orgID, uid int64, public bool) error { |
||||
ou := new(OrgUser) |
||||
has, err := db.GetEngine(db.DefaultContext). |
||||
Where("uid=?", uid). |
||||
And("org_id=?", orgID). |
||||
Get(ou) |
||||
if err != nil { |
||||
return err |
||||
} else if !has { |
||||
return nil |
||||
} |
||||
|
||||
ou.IsPublic = public |
||||
_, err = db.GetEngine(db.DefaultContext).ID(ou.ID).Cols("is_public").Update(ou) |
||||
return err |
||||
} |
||||
|
||||
// AddOrgUser adds new user to given organization.
|
||||
func AddOrgUser(orgID, uid int64) error { |
||||
isAlreadyMember, err := IsOrganizationMember(db.DefaultContext, orgID, uid) |
||||
if err != nil || isAlreadyMember { |
||||
return err |
||||
} |
||||
|
||||
ctx, committer, err := db.TxContext() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer committer.Close() |
||||
|
||||
ou := &OrgUser{ |
||||
UID: uid, |
||||
OrgID: orgID, |
||||
IsPublic: setting.Service.DefaultOrgMemberVisible, |
||||
} |
||||
|
||||
if err := db.Insert(ctx, ou); err != nil { |
||||
return err |
||||
} else if _, err = db.Exec(ctx, "UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil { |
||||
return err |
||||
} |
||||
|
||||
return committer.Commit() |
||||
} |
||||
|
||||
// GetOrgByIDCtx returns the user object by given ID if exists.
|
||||
func GetOrgByIDCtx(ctx context.Context, id int64) (*Organization, error) { |
||||
u := new(Organization) |
||||
has, err := db.GetEngine(ctx).ID(id).Get(u) |
||||
if err != nil { |
||||
return nil, err |
||||
} else if !has { |
||||
return nil, user_model.ErrUserNotExist{ |
||||
UID: id, |
||||
Name: "", |
||||
KeyID: 0, |
||||
} |
||||
} |
||||
return u, nil |
||||
} |
||||
|
||||
// GetOrgByID returns the user object by given ID if exists.
|
||||
func GetOrgByID(id int64) (*Organization, error) { |
||||
return GetOrgByIDCtx(db.DefaultContext, id) |
||||
} |
||||
|
||||
// RemoveOrgRepo removes all team-repository relations of organization.
|
||||
func RemoveOrgRepo(ctx context.Context, orgID, repoID int64) error { |
||||
teamRepos := make([]*TeamRepo, 0, 10) |
||||
e := db.GetEngine(ctx) |
||||
if err := e.Find(&teamRepos, &TeamRepo{OrgID: orgID, RepoID: repoID}); err != nil { |
||||
return err |
||||
} |
||||
|
||||
if len(teamRepos) == 0 { |
||||
return nil |
||||
} |
||||
|
||||
if _, err := e.Delete(&TeamRepo{ |
||||
OrgID: orgID, |
||||
RepoID: repoID, |
||||
}); err != nil { |
||||
return err |
||||
} |
||||
|
||||
teamIDs := make([]int64, len(teamRepos)) |
||||
for i, teamRepo := range teamRepos { |
||||
teamIDs[i] = teamRepo.TeamID |
||||
} |
||||
|
||||
_, err := e.Decr("num_repos").In("id", teamIDs).Update(new(Team)) |
||||
return err |
||||
} |
||||
|
||||
func (org *Organization) getUserTeams(e db.Engine, userID int64, cols ...string) ([]*Team, error) { |
||||
teams := make([]*Team, 0, org.NumTeams) |
||||
return teams, e. |
||||
Where("`team_user`.org_id = ?", org.ID). |
||||
Join("INNER", "team_user", "`team_user`.team_id = team.id"). |
||||
Join("INNER", "`user`", "`user`.id=team_user.uid"). |
||||
And("`team_user`.uid = ?", userID). |
||||
Asc("`user`.name"). |
||||
Cols(cols...). |
||||
Find(&teams) |
||||
} |
||||
|
||||
func (org *Organization) getUserTeamIDs(ctx context.Context, userID int64) ([]int64, error) { |
||||
teamIDs := make([]int64, 0, org.NumTeams) |
||||
return teamIDs, db.GetEngine(ctx). |
||||
Table("team"). |
||||
Cols("team.id"). |
||||
Where("`team_user`.org_id = ?", org.ID). |
||||
Join("INNER", "team_user", "`team_user`.team_id = team.id"). |
||||
And("`team_user`.uid = ?", userID). |
||||
Find(&teamIDs) |
||||
} |
||||
|
||||
// TeamsWithAccessToRepo returns all teams that have given access level to the repository.
|
||||
func (org *Organization) TeamsWithAccessToRepo(repoID int64, mode perm.AccessMode) ([]*Team, error) { |
||||
return GetTeamsWithAccessToRepo(org.ID, repoID, mode) |
||||
} |
||||
|
||||
// GetUserTeamIDs returns of all team IDs of the organization that user is member of.
|
||||
func (org *Organization) GetUserTeamIDs(userID int64) ([]int64, error) { |
||||
return org.getUserTeamIDs(db.DefaultContext, userID) |
||||
} |
||||
|
||||
// GetUserTeams returns all teams that belong to user,
|
||||
// and that the user has joined.
|
||||
func (org *Organization) GetUserTeams(userID int64) ([]*Team, error) { |
||||
return org.getUserTeams(db.GetEngine(db.DefaultContext), userID) |
||||
} |
||||
|
||||
// AccessibleReposEnvironment operations involving the repositories that are
|
||||
// accessible to a particular user
|
||||
type AccessibleReposEnvironment interface { |
||||
CountRepos() (int64, error) |
||||
RepoIDs(page, pageSize int) ([]int64, error) |
||||
Repos(page, pageSize int) ([]*repo_model.Repository, error) |
||||
MirrorRepos() ([]*repo_model.Repository, error) |
||||
AddKeyword(keyword string) |
||||
SetSort(db.SearchOrderBy) |
||||
} |
||||
|
||||
type accessibleReposEnv struct { |
||||
org *Organization |
||||
user *user_model.User |
||||
team *Team |
||||
teamIDs []int64 |
||||
e db.Engine |
||||
keyword string |
||||
orderBy db.SearchOrderBy |
||||
} |
||||
|
||||
// AccessibleReposEnv builds an AccessibleReposEnvironment for the repositories in `org`
|
||||
// that are accessible to the specified user.
|
||||
func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (AccessibleReposEnvironment, error) { |
||||
var user *user_model.User |
||||
|
||||
if userID > 0 { |
||||
u, err := user_model.GetUserByIDCtx(ctx, userID) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
user = u |
||||
} |
||||
|
||||
teamIDs, err := org.getUserTeamIDs(ctx, userID) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return &accessibleReposEnv{ |
||||
org: org, |
||||
user: user, |
||||
teamIDs: teamIDs, |
||||
e: db.GetEngine(ctx), |
||||
orderBy: db.SearchOrderByRecentUpdated, |
||||
}, nil |
||||
} |
||||
|
||||
// AccessibleTeamReposEnv an AccessibleReposEnvironment for the repositories in `org`
|
||||
// that are accessible to the specified team.
|
||||
func (org *Organization) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvironment { |
||||
return &accessibleReposEnv{ |
||||
org: org, |
||||
team: team, |
||||
e: db.GetEngine(db.DefaultContext), |
||||
orderBy: db.SearchOrderByRecentUpdated, |
||||
} |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) cond() builder.Cond { |
||||
cond := builder.NewCond() |
||||
if env.team != nil { |
||||
cond = cond.And(builder.Eq{"team_repo.team_id": env.team.ID}) |
||||
} else { |
||||
if env.user == nil || !env.user.IsRestricted { |
||||
cond = cond.Or(builder.Eq{ |
||||
"`repository`.owner_id": env.org.ID, |
||||
"`repository`.is_private": false, |
||||
}) |
||||
} |
||||
if len(env.teamIDs) > 0 { |
||||
cond = cond.Or(builder.In("team_repo.team_id", env.teamIDs)) |
||||
} |
||||
} |
||||
if env.keyword != "" { |
||||
cond = cond.And(builder.Like{"`repository`.lower_name", strings.ToLower(env.keyword)}) |
||||
} |
||||
return cond |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) CountRepos() (int64, error) { |
||||
repoCount, err := env.e. |
||||
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id"). |
||||
Where(env.cond()). |
||||
Distinct("`repository`.id"). |
||||
Count(&repo_model.Repository{}) |
||||
if err != nil { |
||||
return 0, fmt.Errorf("count user repositories in organization: %v", err) |
||||
} |
||||
return repoCount, nil |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) { |
||||
if page <= 0 { |
||||
page = 1 |
||||
} |
||||
|
||||
repoIDs := make([]int64, 0, pageSize) |
||||
return repoIDs, env.e. |
||||
Table("repository"). |
||||
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id"). |
||||
Where(env.cond()). |
||||
GroupBy("`repository`.id,`repository`."+strings.Fields(string(env.orderBy))[0]). |
||||
OrderBy(string(env.orderBy)). |
||||
Limit(pageSize, (page-1)*pageSize). |
||||
Cols("`repository`.id"). |
||||
Find(&repoIDs) |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*repo_model.Repository, error) { |
||||
repoIDs, err := env.RepoIDs(page, pageSize) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err) |
||||
} |
||||
|
||||
repos := make([]*repo_model.Repository, 0, len(repoIDs)) |
||||
if len(repoIDs) == 0 { |
||||
return repos, nil |
||||
} |
||||
|
||||
return repos, env.e. |
||||
In("`repository`.id", repoIDs). |
||||
OrderBy(string(env.orderBy)). |
||||
Find(&repos) |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) { |
||||
repoIDs := make([]int64, 0, 10) |
||||
return repoIDs, env.e. |
||||
Table("repository"). |
||||
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true). |
||||
Where(env.cond()). |
||||
GroupBy("`repository`.id, `repository`.updated_unix"). |
||||
OrderBy(string(env.orderBy)). |
||||
Cols("`repository`.id"). |
||||
Find(&repoIDs) |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) MirrorRepos() ([]*repo_model.Repository, error) { |
||||
repoIDs, err := env.MirrorRepoIDs() |
||||
if err != nil { |
||||
return nil, fmt.Errorf("MirrorRepoIDs: %v", err) |
||||
} |
||||
|
||||
repos := make([]*repo_model.Repository, 0, len(repoIDs)) |
||||
if len(repoIDs) == 0 { |
||||
return repos, nil |
||||
} |
||||
|
||||
return repos, env.e. |
||||
In("`repository`.id", repoIDs). |
||||
Find(&repos) |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) AddKeyword(keyword string) { |
||||
env.keyword = keyword |
||||
} |
||||
|
||||
func (env *accessibleReposEnv) SetSort(orderBy db.SearchOrderBy) { |
||||
env.orderBy = orderBy |
||||
} |
@ -0,0 +1,478 @@ |
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"testing" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
repo_model "code.gitea.io/gitea/models/repo" |
||||
"code.gitea.io/gitea/models/unittest" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
"code.gitea.io/gitea/modules/structs" |
||||
|
||||
"github.com/stretchr/testify/assert" |
||||
) |
||||
|
||||
func TestUser_IsOwnedBy(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
for _, testCase := range []struct { |
||||
OrgID int64 |
||||
UserID int64 |
||||
ExpectedOwner bool |
||||
}{ |
||||
{3, 2, true}, |
||||
{3, 1, false}, |
||||
{3, 3, false}, |
||||
{3, 4, false}, |
||||
{2, 2, false}, // user2 is not an organization
|
||||
{2, 3, false}, |
||||
} { |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: testCase.OrgID}).(*Organization) |
||||
isOwner, err := org.IsOwnedBy(testCase.UserID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, testCase.ExpectedOwner, isOwner) |
||||
} |
||||
} |
||||
|
||||
func TestUser_IsOrgMember(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
for _, testCase := range []struct { |
||||
OrgID int64 |
||||
UserID int64 |
||||
ExpectedMember bool |
||||
}{ |
||||
{3, 2, true}, |
||||
{3, 4, true}, |
||||
{3, 1, false}, |
||||
{3, 3, false}, |
||||
{2, 2, false}, // user2 is not an organization
|
||||
{2, 3, false}, |
||||
} { |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: testCase.OrgID}).(*Organization) |
||||
isMember, err := org.IsOrgMember(testCase.UserID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, testCase.ExpectedMember, isMember) |
||||
} |
||||
} |
||||
|
||||
func TestUser_GetTeam(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
team, err := org.GetTeam("team1") |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, org.ID, team.OrgID) |
||||
assert.Equal(t, "team1", team.LowerName) |
||||
|
||||
_, err = org.GetTeam("does not exist") |
||||
assert.True(t, IsErrTeamNotExist(err)) |
||||
|
||||
nonOrg := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 2}).(*Organization) |
||||
_, err = nonOrg.GetTeam("team") |
||||
assert.True(t, IsErrTeamNotExist(err)) |
||||
} |
||||
|
||||
func TestUser_GetOwnerTeam(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
team, err := org.GetOwnerTeam() |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, org.ID, team.OrgID) |
||||
|
||||
nonOrg := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 2}).(*Organization) |
||||
_, err = nonOrg.GetOwnerTeam() |
||||
assert.True(t, IsErrTeamNotExist(err)) |
||||
} |
||||
|
||||
func TestUser_GetTeams(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
teams, err := org.LoadTeams() |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, teams, 4) { |
||||
assert.Equal(t, int64(1), teams[0].ID) |
||||
assert.Equal(t, int64(2), teams[1].ID) |
||||
assert.Equal(t, int64(12), teams[2].ID) |
||||
assert.Equal(t, int64(7), teams[3].ID) |
||||
} |
||||
} |
||||
|
||||
func TestUser_GetMembers(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
members, _, err := org.GetMembers() |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, members, 3) { |
||||
assert.Equal(t, int64(2), members[0].ID) |
||||
assert.Equal(t, int64(28), members[1].ID) |
||||
assert.Equal(t, int64(4), members[2].ID) |
||||
} |
||||
} |
||||
|
||||
func TestGetOrgByName(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
org, err := GetOrgByName("user3") |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, 3, org.ID) |
||||
assert.Equal(t, "user3", org.Name) |
||||
|
||||
_, err = GetOrgByName("user2") // user2 is an individual
|
||||
assert.True(t, IsErrOrgNotExist(err)) |
||||
|
||||
_, err = GetOrgByName("") // corner case
|
||||
assert.True(t, IsErrOrgNotExist(err)) |
||||
} |
||||
|
||||
func TestCountOrganizations(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&user_model.User{}) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, CountOrganizations()) |
||||
} |
||||
|
||||
func TestIsOrganizationOwner(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(orgID, userID int64, expected bool) { |
||||
isOwner, err := IsOrganizationOwner(db.DefaultContext, orgID, userID) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, expected, isOwner) |
||||
} |
||||
test(3, 2, true) |
||||
test(3, 3, false) |
||||
test(6, 5, true) |
||||
test(6, 4, false) |
||||
test(unittest.NonexistentID, unittest.NonexistentID, false) |
||||
} |
||||
|
||||
func TestIsOrganizationMember(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(orgID, userID int64, expected bool) { |
||||
isMember, err := IsOrganizationMember(db.DefaultContext, orgID, userID) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, expected, isMember) |
||||
} |
||||
test(3, 2, true) |
||||
test(3, 3, false) |
||||
test(3, 4, true) |
||||
test(6, 5, true) |
||||
test(6, 4, false) |
||||
test(unittest.NonexistentID, unittest.NonexistentID, false) |
||||
} |
||||
|
||||
func TestIsPublicMembership(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(orgID, userID int64, expected bool) { |
||||
isMember, err := IsPublicMembership(orgID, userID) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, expected, isMember) |
||||
} |
||||
test(3, 2, true) |
||||
test(3, 3, false) |
||||
test(3, 4, false) |
||||
test(6, 5, true) |
||||
test(6, 4, false) |
||||
test(unittest.NonexistentID, unittest.NonexistentID, false) |
||||
} |
||||
|
||||
func TestFindOrgs(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
orgs, err := FindOrgs(FindOrgOptions{ |
||||
UserID: 4, |
||||
IncludePrivate: true, |
||||
}) |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, orgs, 1) { |
||||
assert.EqualValues(t, 3, orgs[0].ID) |
||||
} |
||||
|
||||
orgs, err = FindOrgs(FindOrgOptions{ |
||||
UserID: 4, |
||||
IncludePrivate: false, |
||||
}) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, orgs, 0) |
||||
|
||||
total, err := CountOrgs(FindOrgOptions{ |
||||
UserID: 4, |
||||
IncludePrivate: true, |
||||
}) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, 1, total) |
||||
} |
||||
|
||||
func TestGetOwnedOrgsByUserID(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
orgs, err := GetOwnedOrgsByUserID(2) |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, orgs, 1) { |
||||
assert.EqualValues(t, 3, orgs[0].ID) |
||||
} |
||||
|
||||
orgs, err = GetOwnedOrgsByUserID(4) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, orgs, 0) |
||||
} |
||||
|
||||
func TestGetOwnedOrgsByUserIDDesc(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
orgs, err := GetOwnedOrgsByUserIDDesc(5, "id") |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, orgs, 2) { |
||||
assert.EqualValues(t, 7, orgs[0].ID) |
||||
assert.EqualValues(t, 6, orgs[1].ID) |
||||
} |
||||
|
||||
orgs, err = GetOwnedOrgsByUserIDDesc(4, "id") |
||||
assert.NoError(t, err) |
||||
assert.Len(t, orgs, 0) |
||||
} |
||||
|
||||
func TestGetOrgUsersByUserID(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
orgUsers, err := GetOrgUsersByUserID(5, &SearchOrganizationsOptions{All: true}) |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, orgUsers, 2) { |
||||
assert.Equal(t, OrgUser{ |
||||
ID: orgUsers[0].ID, |
||||
OrgID: 6, |
||||
UID: 5, |
||||
IsPublic: true, |
||||
}, *orgUsers[0]) |
||||
assert.Equal(t, OrgUser{ |
||||
ID: orgUsers[1].ID, |
||||
OrgID: 7, |
||||
UID: 5, |
||||
IsPublic: false, |
||||
}, *orgUsers[1]) |
||||
} |
||||
|
||||
publicOrgUsers, err := GetOrgUsersByUserID(5, &SearchOrganizationsOptions{All: false}) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, publicOrgUsers, 1) |
||||
assert.Equal(t, *orgUsers[0], *publicOrgUsers[0]) |
||||
|
||||
orgUsers, err = GetOrgUsersByUserID(1, &SearchOrganizationsOptions{All: true}) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, orgUsers, 0) |
||||
} |
||||
|
||||
func TestGetOrgUsersByOrgID(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
orgUsers, err := GetOrgUsersByOrgID(&FindOrgMembersOpts{ |
||||
ListOptions: db.ListOptions{}, |
||||
OrgID: 3, |
||||
PublicOnly: false, |
||||
}) |
||||
assert.NoError(t, err) |
||||
if assert.Len(t, orgUsers, 3) { |
||||
assert.Equal(t, OrgUser{ |
||||
ID: orgUsers[0].ID, |
||||
OrgID: 3, |
||||
UID: 2, |
||||
IsPublic: true, |
||||
}, *orgUsers[0]) |
||||
assert.Equal(t, OrgUser{ |
||||
ID: orgUsers[1].ID, |
||||
OrgID: 3, |
||||
UID: 4, |
||||
IsPublic: false, |
||||
}, *orgUsers[1]) |
||||
} |
||||
|
||||
orgUsers, err = GetOrgUsersByOrgID(&FindOrgMembersOpts{ |
||||
ListOptions: db.ListOptions{}, |
||||
OrgID: unittest.NonexistentID, |
||||
PublicOnly: false, |
||||
}) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, orgUsers, 0) |
||||
} |
||||
|
||||
func TestChangeOrgUserStatus(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
testSuccess := func(orgID, userID int64, public bool) { |
||||
assert.NoError(t, ChangeOrgUserStatus(orgID, userID, public)) |
||||
orgUser := unittest.AssertExistsAndLoadBean(t, &OrgUser{OrgID: orgID, UID: userID}).(*OrgUser) |
||||
assert.Equal(t, public, orgUser.IsPublic) |
||||
} |
||||
|
||||
testSuccess(3, 2, false) |
||||
testSuccess(3, 2, false) |
||||
testSuccess(3, 4, true) |
||||
assert.NoError(t, ChangeOrgUserStatus(unittest.NonexistentID, unittest.NonexistentID, true)) |
||||
} |
||||
|
||||
func TestUser_GetUserTeamIDs(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
testSuccess := func(userID int64, expected []int64) { |
||||
teamIDs, err := org.GetUserTeamIDs(userID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, teamIDs) |
||||
} |
||||
testSuccess(2, []int64{1, 2}) |
||||
testSuccess(4, []int64{2}) |
||||
testSuccess(unittest.NonexistentID, []int64{}) |
||||
} |
||||
|
||||
func TestAccessibleReposEnv_CountRepos(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
testSuccess := func(userID, expectedCount int64) { |
||||
env, err := AccessibleReposEnv(db.DefaultContext, org, userID) |
||||
assert.NoError(t, err) |
||||
count, err := env.CountRepos() |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, expectedCount, count) |
||||
} |
||||
testSuccess(2, 3) |
||||
testSuccess(4, 2) |
||||
} |
||||
|
||||
func TestAccessibleReposEnv_RepoIDs(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
testSuccess := func(userID, _, pageSize int64, expectedRepoIDs []int64) { |
||||
env, err := AccessibleReposEnv(db.DefaultContext, org, userID) |
||||
assert.NoError(t, err) |
||||
repoIDs, err := env.RepoIDs(1, 100) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expectedRepoIDs, repoIDs) |
||||
} |
||||
testSuccess(2, 1, 100, []int64{3, 5, 32}) |
||||
testSuccess(4, 0, 100, []int64{3, 32}) |
||||
} |
||||
|
||||
func TestAccessibleReposEnv_Repos(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
testSuccess := func(userID int64, expectedRepoIDs []int64) { |
||||
env, err := AccessibleReposEnv(db.DefaultContext, org, userID) |
||||
assert.NoError(t, err) |
||||
repos, err := env.Repos(1, 100) |
||||
assert.NoError(t, err) |
||||
expectedRepos := make([]*repo_model.Repository, len(expectedRepoIDs)) |
||||
for i, repoID := range expectedRepoIDs { |
||||
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, |
||||
&repo_model.Repository{ID: repoID}).(*repo_model.Repository) |
||||
} |
||||
assert.Equal(t, expectedRepos, repos) |
||||
} |
||||
testSuccess(2, []int64{3, 5, 32}) |
||||
testSuccess(4, []int64{3, 32}) |
||||
} |
||||
|
||||
func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
org := unittest.AssertExistsAndLoadBean(t, &Organization{ID: 3}).(*Organization) |
||||
testSuccess := func(userID int64, expectedRepoIDs []int64) { |
||||
env, err := AccessibleReposEnv(db.DefaultContext, org, userID) |
||||
assert.NoError(t, err) |
||||
repos, err := env.MirrorRepos() |
||||
assert.NoError(t, err) |
||||
expectedRepos := make([]*repo_model.Repository, len(expectedRepoIDs)) |
||||
for i, repoID := range expectedRepoIDs { |
||||
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, |
||||
&repo_model.Repository{ID: repoID}).(*repo_model.Repository) |
||||
} |
||||
assert.Equal(t, expectedRepos, repos) |
||||
} |
||||
testSuccess(2, []int64{5}) |
||||
testSuccess(4, []int64{}) |
||||
} |
||||
|
||||
func TestHasOrgVisibleTypePublic(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) |
||||
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) |
||||
|
||||
const newOrgName = "test-org-public" |
||||
org := &Organization{ |
||||
Name: newOrgName, |
||||
Visibility: structs.VisibleTypePublic, |
||||
} |
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) |
||||
assert.NoError(t, CreateOrganization(org, owner)) |
||||
org = unittest.AssertExistsAndLoadBean(t, |
||||
&Organization{Name: org.Name, Type: user_model.UserTypeOrganization}).(*Organization) |
||||
test1 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) |
||||
test2 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) |
||||
test3 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) |
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.True(t, test3) // logged out user
|
||||
} |
||||
|
||||
func TestHasOrgVisibleTypeLimited(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) |
||||
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) |
||||
|
||||
const newOrgName = "test-org-limited" |
||||
org := &Organization{ |
||||
Name: newOrgName, |
||||
Visibility: structs.VisibleTypeLimited, |
||||
} |
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) |
||||
assert.NoError(t, CreateOrganization(org, owner)) |
||||
org = unittest.AssertExistsAndLoadBean(t, |
||||
&Organization{Name: org.Name, Type: user_model.UserTypeOrganization}).(*Organization) |
||||
test1 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) |
||||
test2 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) |
||||
test3 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) |
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
} |
||||
|
||||
func TestHasOrgVisibleTypePrivate(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) |
||||
user3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}).(*user_model.User) |
||||
|
||||
const newOrgName = "test-org-private" |
||||
org := &Organization{ |
||||
Name: newOrgName, |
||||
Visibility: structs.VisibleTypePrivate, |
||||
} |
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) |
||||
assert.NoError(t, CreateOrganization(org, owner)) |
||||
org = unittest.AssertExistsAndLoadBean(t, |
||||
&Organization{Name: org.Name, Type: user_model.UserTypeOrganization}).(*Organization) |
||||
test1 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) |
||||
test2 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), user3) |
||||
test3 := HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil) |
||||
assert.True(t, test1) // owner of org
|
||||
assert.False(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
} |
||||
|
||||
func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
users, err := GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 3) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, users, 2) |
||||
var ids []int64 |
||||
for i := range users { |
||||
ids = append(ids, users[i].ID) |
||||
} |
||||
assert.ElementsMatch(t, ids, []int64{2, 28}) |
||||
|
||||
users, err = GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 7) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, users, 1) |
||||
assert.EqualValues(t, 5, users[0].ID) |
||||
} |
@ -0,0 +1,83 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
"code.gitea.io/gitea/modules/log" |
||||
|
||||
"xorm.io/builder" |
||||
) |
||||
|
||||
// ________ ____ ___
|
||||
// \_____ \_______ ____ | | \______ ___________
|
||||
// / | \_ __ \/ ___\| | / ___// __ \_ __ \
|
||||
// / | \ | \/ /_/ > | /\___ \\ ___/| | \/
|
||||
// \_______ /__| \___ /|______//____ >\___ >__|
|
||||
// \/ /_____/ \/ \/
|
||||
|
||||
// OrgUser represents an organization-user relation.
|
||||
type OrgUser struct { |
||||
ID int64 `xorm:"pk autoincr"` |
||||
UID int64 `xorm:"INDEX UNIQUE(s)"` |
||||
OrgID int64 `xorm:"INDEX UNIQUE(s)"` |
||||
IsPublic bool `xorm:"INDEX"` |
||||
} |
||||
|
||||
func init() { |
||||
db.RegisterModel(new(OrgUser)) |
||||
} |
||||
|
||||
// GetOrganizationCount returns count of membership of organization of the user.
|
||||
func GetOrganizationCount(ctx context.Context, u *user_model.User) (int64, error) { |
||||
return db.GetEngine(ctx). |
||||
Where("uid=?", u.ID). |
||||
Count(new(OrgUser)) |
||||
} |
||||
|
||||
// IsOrganizationOwner returns true if given user is in the owner team.
|
||||
func IsOrganizationOwner(ctx context.Context, orgID, uid int64) (bool, error) { |
||||
ownerTeam, err := GetOwnerTeam(ctx, orgID) |
||||
if err != nil { |
||||
if IsErrTeamNotExist(err) { |
||||
log.Error("Organization does not have owner team: %d", orgID) |
||||
return false, nil |
||||
} |
||||
return false, err |
||||
} |
||||
return IsTeamMember(ctx, orgID, ownerTeam.ID, uid) |
||||
} |
||||
|
||||
// IsOrganizationMember returns true if given user is member of organization.
|
||||
func IsOrganizationMember(ctx context.Context, orgID, uid int64) (bool, error) { |
||||
return db.GetEngine(ctx). |
||||
Where("uid=?", uid). |
||||
And("org_id=?", orgID). |
||||
Table("org_user"). |
||||
Exist() |
||||
} |
||||
|
||||
// IsPublicMembership returns true if the given user's membership of given org is public.
|
||||
func IsPublicMembership(orgID, uid int64) (bool, error) { |
||||
return db.GetEngine(db.DefaultContext). |
||||
Where("uid=?", uid). |
||||
And("org_id=?", orgID). |
||||
And("is_public=?", true). |
||||
Table("org_user"). |
||||
Exist() |
||||
} |
||||
|
||||
// CanCreateOrgRepo returns true if user can create repo in organization
|
||||
func CanCreateOrgRepo(orgID, uid int64) (bool, error) { |
||||
return db.GetEngine(db.DefaultContext). |
||||
Where(builder.Eq{"team.can_create_org_repo": true}). |
||||
Join("INNER", "team_user", "team_user.team_id = team.id"). |
||||
And("team_user.uid = ?", uid). |
||||
And("team_user.org_id = ?", orgID). |
||||
Exist(new(Team)) |
||||
} |
@ -0,0 +1,72 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"fmt" |
||||
"testing" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/unittest" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
|
||||
"github.com/stretchr/testify/assert" |
||||
) |
||||
|
||||
func TestUserIsPublicMember(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
tt := []struct { |
||||
uid int64 |
||||
orgid int64 |
||||
expected bool |
||||
}{ |
||||
{2, 3, true}, |
||||
{4, 3, false}, |
||||
{5, 6, true}, |
||||
{5, 7, false}, |
||||
} |
||||
for _, v := range tt { |
||||
t.Run(fmt.Sprintf("UserId%dIsPublicMemberOf%d", v.uid, v.orgid), func(t *testing.T) { |
||||
testUserIsPublicMember(t, v.uid, v.orgid, v.expected) |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { |
||||
user, err := user_model.GetUserByID(uid) |
||||
assert.NoError(t, err) |
||||
is, err := IsPublicMembership(orgID, user.ID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, is) |
||||
} |
||||
|
||||
func TestIsUserOrgOwner(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
tt := []struct { |
||||
uid int64 |
||||
orgid int64 |
||||
expected bool |
||||
}{ |
||||
{2, 3, true}, |
||||
{4, 3, false}, |
||||
{5, 6, true}, |
||||
{5, 7, true}, |
||||
} |
||||
for _, v := range tt { |
||||
t.Run(fmt.Sprintf("UserId%dIsOrgOwnerOf%d", v.uid, v.orgid), func(t *testing.T) { |
||||
testIsUserOrgOwner(t, v.uid, v.orgid, v.expected) |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { |
||||
user, err := user_model.GetUserByID(uid) |
||||
assert.NoError(t, err) |
||||
is, err := IsOrganizationOwner(db.DefaultContext, orgID, user.ID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, is) |
||||
} |
@ -0,0 +1,359 @@ |
||||
// Copyright 2018 The Gitea Authors. All rights reserved.
|
||||
// Copyright 2016 The Gogs Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
"fmt" |
||||
"strings" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/perm" |
||||
repo_model "code.gitea.io/gitea/models/repo" |
||||
"code.gitea.io/gitea/models/unit" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
"code.gitea.io/gitea/modules/log" |
||||
|
||||
"xorm.io/builder" |
||||
) |
||||
|
||||
// ___________
|
||||
// \__ ___/___ _____ _____
|
||||
// | |_/ __ \\__ \ / \
|
||||
// | |\ ___/ / __ \| Y Y \
|
||||
// |____| \___ >____ /__|_| /
|
||||
// \/ \/ \/
|
||||
|
||||
// ErrTeamAlreadyExist represents a "TeamAlreadyExist" kind of error.
|
||||
type ErrTeamAlreadyExist struct { |
||||
OrgID int64 |
||||
Name string |
||||
} |
||||
|
||||
// IsErrTeamAlreadyExist checks if an error is a ErrTeamAlreadyExist.
|
||||
func IsErrTeamAlreadyExist(err error) bool { |
||||
_, ok := err.(ErrTeamAlreadyExist) |
||||
return ok |
||||
} |
||||
|
||||
func (err ErrTeamAlreadyExist) Error() string { |
||||
return fmt.Sprintf("team already exists [org_id: %d, name: %s]", err.OrgID, err.Name) |
||||
} |
||||
|
||||
// ErrTeamNotExist represents a "TeamNotExist" error
|
||||
type ErrTeamNotExist struct { |
||||
OrgID int64 |
||||
TeamID int64 |
||||
Name string |
||||
} |
||||
|
||||
// IsErrTeamNotExist checks if an error is a ErrTeamNotExist.
|
||||
func IsErrTeamNotExist(err error) bool { |
||||
_, ok := err.(ErrTeamNotExist) |
||||
return ok |
||||
} |
||||
|
||||
func (err ErrTeamNotExist) Error() string { |
||||
return fmt.Sprintf("team does not exist [org_id %d, team_id %d, name: %s]", err.OrgID, err.TeamID, err.Name) |
||||
} |
||||
|
||||
// OwnerTeamName return the owner team name
|
||||
const OwnerTeamName = "Owners" |
||||
|
||||
// Team represents a organization team.
|
||||
type Team struct { |
||||
ID int64 `xorm:"pk autoincr"` |
||||
OrgID int64 `xorm:"INDEX"` |
||||
LowerName string |
||||
Name string |
||||
Description string |
||||
AccessMode perm.AccessMode `xorm:"'authorize'"` |
||||
Repos []*repo_model.Repository `xorm:"-"` |
||||
Members []*user_model.User `xorm:"-"` |
||||
NumRepos int |
||||
NumMembers int |
||||
Units []*TeamUnit `xorm:"-"` |
||||
IncludesAllRepositories bool `xorm:"NOT NULL DEFAULT false"` |
||||
CanCreateOrgRepo bool `xorm:"NOT NULL DEFAULT false"` |
||||
} |
||||
|
||||
func init() { |
||||
db.RegisterModel(new(Team)) |
||||
db.RegisterModel(new(TeamUser)) |
||||
db.RegisterModel(new(TeamRepo)) |
||||
db.RegisterModel(new(TeamUnit)) |
||||
} |
||||
|
||||
// SearchTeamOptions holds the search options
|
||||
type SearchTeamOptions struct { |
||||
db.ListOptions |
||||
UserID int64 |
||||
Keyword string |
||||
OrgID int64 |
||||
IncludeDesc bool |
||||
} |
||||
|
||||
// SearchTeam search for teams. Caller is responsible to check permissions.
|
||||
func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) { |
||||
if opts.Page <= 0 { |
||||
opts.Page = 1 |
||||
} |
||||
if opts.PageSize == 0 { |
||||
// Default limit
|
||||
opts.PageSize = 10 |
||||
} |
||||
|
||||
cond := builder.NewCond() |
||||
|
||||
if len(opts.Keyword) > 0 { |
||||
lowerKeyword := strings.ToLower(opts.Keyword) |
||||
var keywordCond builder.Cond = builder.Like{"lower_name", lowerKeyword} |
||||
if opts.IncludeDesc { |
||||
keywordCond = keywordCond.Or(builder.Like{"LOWER(description)", lowerKeyword}) |
||||
} |
||||
cond = cond.And(keywordCond) |
||||
} |
||||
|
||||
cond = cond.And(builder.Eq{"org_id": opts.OrgID}) |
||||
|
||||
sess := db.GetEngine(db.DefaultContext) |
||||
|
||||
count, err := sess. |
||||
Where(cond). |
||||
Count(new(Team)) |
||||
if err != nil { |
||||
return nil, 0, err |
||||
} |
||||
|
||||
sess = sess.Where(cond) |
||||
if opts.PageSize == -1 { |
||||
opts.PageSize = int(count) |
||||
} else { |
||||
sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize) |
||||
} |
||||
|
||||
teams := make([]*Team, 0, opts.PageSize) |
||||
if err = sess. |
||||
OrderBy("lower_name"). |
||||
Find(&teams); err != nil { |
||||
return nil, 0, err |
||||
} |
||||
|
||||
return teams, count, nil |
||||
} |
||||
|
||||
// ColorFormat provides a basic color format for a Team
|
||||
func (t *Team) ColorFormat(s fmt.State) { |
||||
if t == nil { |
||||
log.ColorFprintf(s, "%d:%s (OrgID: %d) %-v", |
||||
log.NewColoredIDValue(0), |
||||
"<nil>", |
||||
log.NewColoredIDValue(0), |
||||
0) |
||||
return |
||||
} |
||||
log.ColorFprintf(s, "%d:%s (OrgID: %d) %-v", |
||||
log.NewColoredIDValue(t.ID), |
||||
t.Name, |
||||
log.NewColoredIDValue(t.OrgID), |
||||
t.AccessMode) |
||||
} |
||||
|
||||
// GetUnits return a list of available units for a team
|
||||
func (t *Team) GetUnits() error { |
||||
return t.getUnits(db.DefaultContext) |
||||
} |
||||
|
||||
func (t *Team) getUnits(ctx context.Context) (err error) { |
||||
if t.Units != nil { |
||||
return nil |
||||
} |
||||
|
||||
t.Units, err = getUnitsByTeamID(ctx, t.ID) |
||||
return err |
||||
} |
||||
|
||||
// GetUnitNames returns the team units names
|
||||
func (t *Team) GetUnitNames() (res []string) { |
||||
if t.AccessMode >= perm.AccessModeAdmin { |
||||
return unit.AllUnitKeyNames() |
||||
} |
||||
|
||||
for _, u := range t.Units { |
||||
res = append(res, unit.Units[u.Type].NameKey) |
||||
} |
||||
return |
||||
} |
||||
|
||||
// GetUnitsMap returns the team units permissions
|
||||
func (t *Team) GetUnitsMap() map[string]string { |
||||
m := make(map[string]string) |
||||
if t.AccessMode >= perm.AccessModeAdmin { |
||||
for _, u := range unit.Units { |
||||
m[u.NameKey] = t.AccessMode.String() |
||||
} |
||||
} else { |
||||
for _, u := range t.Units { |
||||
m[u.Unit().NameKey] = u.AccessMode.String() |
||||
} |
||||
} |
||||
return m |
||||
} |
||||
|
||||
// IsOwnerTeam returns true if team is owner team.
|
||||
func (t *Team) IsOwnerTeam() bool { |
||||
return t.Name == OwnerTeamName |
||||
} |
||||
|
||||
// IsMember returns true if given user is a member of team.
|
||||
func (t *Team) IsMember(userID int64) bool { |
||||
isMember, err := IsTeamMember(db.DefaultContext, t.OrgID, t.ID, userID) |
||||
if err != nil { |
||||
log.Error("IsMember: %v", err) |
||||
return false |
||||
} |
||||
return isMember |
||||
} |
||||
|
||||
// GetRepositoriesCtx returns paginated repositories in team of organization.
|
||||
func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { |
||||
if t.Repos != nil { |
||||
return nil |
||||
} |
||||
t.Repos, err = GetTeamRepositories(ctx, &SearchTeamRepoOptions{ |
||||
TeamID: t.ID, |
||||
}) |
||||
return |
||||
} |
||||
|
||||
// GetMembersCtx returns paginated members in team of organization.
|
||||
func (t *Team) GetMembersCtx(ctx context.Context) (err error) { |
||||
t.Members, err = GetTeamMembers(ctx, &SearchMembersOptions{ |
||||
TeamID: t.ID, |
||||
}) |
||||
return err |
||||
} |
||||
|
||||
// UnitEnabled returns if the team has the given unit type enabled
|
||||
func (t *Team) UnitEnabled(tp unit.Type) bool { |
||||
return t.unitEnabled(db.DefaultContext, tp) |
||||
} |
||||
|
||||
func (t *Team) unitEnabled(ctx context.Context, tp unit.Type) bool { |
||||
return t.UnitAccessMode(ctx, tp) > perm.AccessModeNone |
||||
} |
||||
|
||||
// UnitAccessMode returns if the team has the given unit type enabled
|
||||
func (t *Team) UnitAccessMode(ctx context.Context, tp unit.Type) perm.AccessMode { |
||||
if err := t.getUnits(ctx); err != nil { |
||||
log.Warn("Error loading team (ID: %d) units: %s", t.ID, err.Error()) |
||||
} |
||||
|
||||
for _, unit := range t.Units { |
||||
if unit.Type == tp { |
||||
return unit.AccessMode |
||||
} |
||||
} |
||||
return perm.AccessModeNone |
||||
} |
||||
|
||||
// IsUsableTeamName tests if a name could be as team name
|
||||
func IsUsableTeamName(name string) error { |
||||
switch name { |
||||
case "new": |
||||
return db.ErrNameReserved{Name: name} |
||||
default: |
||||
return nil |
||||
} |
||||
} |
||||
|
||||
func getTeam(ctx context.Context, orgID int64, name string) (*Team, error) { |
||||
t := &Team{ |
||||
OrgID: orgID, |
||||
LowerName: strings.ToLower(name), |
||||
} |
||||
has, err := db.GetByBean(ctx, t) |
||||
if err != nil { |
||||
return nil, err |
||||
} else if !has { |
||||
return nil, ErrTeamNotExist{orgID, 0, name} |
||||
} |
||||
return t, nil |
||||
} |
||||
|
||||
// GetTeam returns team by given team name and organization.
|
||||
func GetTeam(orgID int64, name string) (*Team, error) { |
||||
return getTeam(db.DefaultContext, orgID, name) |
||||
} |
||||
|
||||
// GetTeamIDsByNames returns a slice of team ids corresponds to names.
|
||||
func GetTeamIDsByNames(orgID int64, names []string, ignoreNonExistent bool) ([]int64, error) { |
||||
ids := make([]int64, 0, len(names)) |
||||
for _, name := range names { |
||||
u, err := GetTeam(orgID, name) |
||||
if err != nil { |
||||
if ignoreNonExistent { |
||||
continue |
||||
} else { |
||||
return nil, err |
||||
} |
||||
} |
||||
ids = append(ids, u.ID) |
||||
} |
||||
return ids, nil |
||||
} |
||||
|
||||
// GetOwnerTeam returns team by given team name and organization.
|
||||
func GetOwnerTeam(ctx context.Context, orgID int64) (*Team, error) { |
||||
return getTeam(ctx, orgID, OwnerTeamName) |
||||
} |
||||
|
||||
// GetTeamByIDCtx returns team by given ID.
|
||||
func GetTeamByIDCtx(ctx context.Context, teamID int64) (*Team, error) { |
||||
t := new(Team) |
||||
has, err := db.GetEngine(ctx).ID(teamID).Get(t) |
||||
if err != nil { |
||||
return nil, err |
||||
} else if !has { |
||||
return nil, ErrTeamNotExist{0, teamID, ""} |
||||
} |
||||
return t, nil |
||||
} |
||||
|
||||
// GetTeamByID returns team by given ID.
|
||||
func GetTeamByID(teamID int64) (*Team, error) { |
||||
return GetTeamByIDCtx(db.DefaultContext, teamID) |
||||
} |
||||
|
||||
// GetTeamNamesByID returns team's lower name from a list of team ids.
|
||||
func GetTeamNamesByID(teamIDs []int64) ([]string, error) { |
||||
if len(teamIDs) == 0 { |
||||
return []string{}, nil |
||||
} |
||||
|
||||
var teamNames []string |
||||
err := db.GetEngine(db.DefaultContext).Table("team"). |
||||
Select("lower_name"). |
||||
In("id", teamIDs). |
||||
Asc("name"). |
||||
Find(&teamNames) |
||||
|
||||
return teamNames, err |
||||
} |
||||
|
||||
func getRepoTeams(e db.Engine, repo *repo_model.Repository) (teams []*Team, err error) { |
||||
return teams, e. |
||||
Join("INNER", "team_repo", "team_repo.team_id = team.id"). |
||||
Where("team.org_id = ?", repo.OwnerID). |
||||
And("team_repo.repo_id=?", repo.ID). |
||||
OrderBy("CASE WHEN name LIKE '" + OwnerTeamName + "' THEN '' ELSE name END"). |
||||
Find(&teams) |
||||
} |
||||
|
||||
// GetRepoTeams gets the list of teams that has access to the repository
|
||||
func GetRepoTeams(repo *repo_model.Repository) ([]*Team, error) { |
||||
return getRepoTeams(db.GetEngine(db.DefaultContext), repo) |
||||
} |
@ -0,0 +1,84 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/perm" |
||||
repo_model "code.gitea.io/gitea/models/repo" |
||||
"xorm.io/builder" |
||||
) |
||||
|
||||
// TeamRepo represents an team-repository relation.
|
||||
type TeamRepo struct { |
||||
ID int64 `xorm:"pk autoincr"` |
||||
OrgID int64 `xorm:"INDEX"` |
||||
TeamID int64 `xorm:"UNIQUE(s)"` |
||||
RepoID int64 `xorm:"UNIQUE(s)"` |
||||
} |
||||
|
||||
// HasTeamRepo returns true if given repository belongs to team.
|
||||
func HasTeamRepo(ctx context.Context, orgID, teamID, repoID int64) bool { |
||||
has, _ := db.GetEngine(ctx). |
||||
Where("org_id=?", orgID). |
||||
And("team_id=?", teamID). |
||||
And("repo_id=?", repoID). |
||||
Get(new(TeamRepo)) |
||||
return has |
||||
} |
||||
|
||||
type SearchTeamRepoOptions struct { |
||||
db.ListOptions |
||||
TeamID int64 |
||||
} |
||||
|
||||
// GetRepositories returns paginated repositories in team of organization.
|
||||
func GetTeamRepositories(ctx context.Context, opts *SearchTeamRepoOptions) ([]*repo_model.Repository, error) { |
||||
sess := db.GetEngine(ctx) |
||||
if opts.TeamID > 0 { |
||||
sess = sess.In("id", |
||||
builder.Select("repo_id"). |
||||
From("team_repo"). |
||||
Where(builder.Eq{"team_id": opts.TeamID}), |
||||
) |
||||
} |
||||
if opts.PageSize > 0 { |
||||
sess.Limit(opts.PageSize, opts.Page*opts.PageSize) |
||||
} |
||||
var repos []*repo_model.Repository |
||||
return repos, sess.OrderBy("repository.name"). |
||||
Find(&repos) |
||||
} |
||||
|
||||
// AddTeamRepo addes a repo for an organization's team
|
||||
func AddTeamRepo(ctx context.Context, orgID, teamID, repoID int64) error { |
||||
_, err := db.GetEngine(ctx).Insert(&TeamRepo{ |
||||
OrgID: orgID, |
||||
TeamID: teamID, |
||||
RepoID: repoID, |
||||
}) |
||||
return err |
||||
} |
||||
|
||||
// RemoveTeamRepo remove repository from team
|
||||
func RemoveTeamRepo(ctx context.Context, teamID, repoID int64) error { |
||||
_, err := db.DeleteByBean(ctx, &TeamRepo{ |
||||
TeamID: teamID, |
||||
RepoID: repoID, |
||||
}) |
||||
return err |
||||
} |
||||
|
||||
// GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
|
||||
func GetTeamsWithAccessToRepo(orgID, repoID int64, mode perm.AccessMode) ([]*Team, error) { |
||||
teams := make([]*Team, 0, 5) |
||||
return teams, db.GetEngine(db.DefaultContext).Where("team.authorize >= ?", mode). |
||||
Join("INNER", "team_repo", "team_repo.team_id = team.id"). |
||||
And("team_repo.org_id = ?", orgID). |
||||
And("team_repo.repo_id = ?", repoID). |
||||
Find(&teams) |
||||
} |
@ -0,0 +1,199 @@ |
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"testing" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/unittest" |
||||
|
||||
"github.com/stretchr/testify/assert" |
||||
) |
||||
|
||||
func TestTeam_IsOwnerTeam(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) |
||||
assert.True(t, team.IsOwnerTeam()) |
||||
|
||||
team = unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) |
||||
assert.False(t, team.IsOwnerTeam()) |
||||
} |
||||
|
||||
func TestTeam_IsMember(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) |
||||
assert.True(t, team.IsMember(2)) |
||||
assert.False(t, team.IsMember(4)) |
||||
assert.False(t, team.IsMember(unittest.NonexistentID)) |
||||
|
||||
team = unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) |
||||
assert.True(t, team.IsMember(2)) |
||||
assert.True(t, team.IsMember(4)) |
||||
assert.False(t, team.IsMember(unittest.NonexistentID)) |
||||
} |
||||
|
||||
func TestTeam_GetRepositories(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
test := func(teamID int64) { |
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) |
||||
assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext)) |
||||
assert.Len(t, team.Repos, team.NumRepos) |
||||
for _, repo := range team.Repos { |
||||
unittest.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repo.ID}) |
||||
} |
||||
} |
||||
test(1) |
||||
test(3) |
||||
} |
||||
|
||||
func TestTeam_GetMembers(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
test := func(teamID int64) { |
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) |
||||
assert.NoError(t, team.GetMembersCtx(db.DefaultContext)) |
||||
assert.Len(t, team.Members, team.NumMembers) |
||||
for _, member := range team.Members { |
||||
unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) |
||||
} |
||||
} |
||||
test(1) |
||||
test(3) |
||||
} |
||||
|
||||
func TestGetTeam(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
testSuccess := func(orgID int64, name string) { |
||||
team, err := GetTeam(orgID, name) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, orgID, team.OrgID) |
||||
assert.Equal(t, name, team.Name) |
||||
} |
||||
testSuccess(3, "Owners") |
||||
testSuccess(3, "team1") |
||||
|
||||
_, err := GetTeam(3, "nonexistent") |
||||
assert.Error(t, err) |
||||
_, err = GetTeam(unittest.NonexistentID, "Owners") |
||||
assert.Error(t, err) |
||||
} |
||||
|
||||
func TestGetTeamByID(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
testSuccess := func(teamID int64) { |
||||
team, err := GetTeamByID(teamID) |
||||
assert.NoError(t, err) |
||||
assert.EqualValues(t, teamID, team.ID) |
||||
} |
||||
testSuccess(1) |
||||
testSuccess(2) |
||||
testSuccess(3) |
||||
testSuccess(4) |
||||
|
||||
_, err := GetTeamByID(unittest.NonexistentID) |
||||
assert.Error(t, err) |
||||
} |
||||
|
||||
func TestIsTeamMember(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(orgID, teamID, userID int64, expected bool) { |
||||
isMember, err := IsTeamMember(db.DefaultContext, orgID, teamID, userID) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, isMember) |
||||
} |
||||
|
||||
test(3, 1, 2, true) |
||||
test(3, 1, 4, false) |
||||
test(3, 1, unittest.NonexistentID, false) |
||||
|
||||
test(3, 2, 2, true) |
||||
test(3, 2, 4, true) |
||||
|
||||
test(3, unittest.NonexistentID, unittest.NonexistentID, false) |
||||
test(unittest.NonexistentID, unittest.NonexistentID, unittest.NonexistentID, false) |
||||
} |
||||
|
||||
func TestGetTeamMembers(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
test := func(teamID int64) { |
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) |
||||
members, err := GetTeamMembers(db.DefaultContext, &SearchMembersOptions{ |
||||
TeamID: teamID, |
||||
}) |
||||
assert.NoError(t, err) |
||||
assert.Len(t, members, team.NumMembers) |
||||
for _, member := range members { |
||||
unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) |
||||
} |
||||
} |
||||
test(1) |
||||
test(3) |
||||
} |
||||
|
||||
func TestGetUserTeams(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(userID int64) { |
||||
teams, _, err := SearchTeam(&SearchTeamOptions{UserID: userID}) |
||||
assert.NoError(t, err) |
||||
for _, team := range teams { |
||||
unittest.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) |
||||
} |
||||
} |
||||
test(2) |
||||
test(5) |
||||
test(unittest.NonexistentID) |
||||
} |
||||
|
||||
func TestGetUserOrgTeams(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
test := func(orgID, userID int64) { |
||||
teams, err := GetUserOrgTeams(db.DefaultContext, orgID, userID) |
||||
assert.NoError(t, err) |
||||
for _, team := range teams { |
||||
assert.EqualValues(t, orgID, team.OrgID) |
||||
unittest.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) |
||||
} |
||||
} |
||||
test(3, 2) |
||||
test(3, 4) |
||||
test(3, unittest.NonexistentID) |
||||
} |
||||
|
||||
func TestHasTeamRepo(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
test := func(teamID, repoID int64, expected bool) { |
||||
team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) |
||||
assert.Equal(t, expected, HasTeamRepo(db.DefaultContext, team.OrgID, teamID, repoID)) |
||||
} |
||||
test(1, 1, false) |
||||
test(1, 3, true) |
||||
test(1, 5, true) |
||||
test(1, unittest.NonexistentID, false) |
||||
|
||||
test(2, 3, true) |
||||
test(2, 5, false) |
||||
} |
||||
|
||||
func TestUsersInTeamsCount(t *testing.T) { |
||||
assert.NoError(t, unittest.PrepareTestDatabase()) |
||||
|
||||
test := func(teamIDs, userIDs []int64, expected int64) { |
||||
count, err := UsersInTeamsCount(teamIDs, userIDs) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, expected, count) |
||||
} |
||||
|
||||
test([]int64{2}, []int64{1, 2, 3, 4}, 1) // only userid 2
|
||||
test([]int64{1, 2, 3, 4, 5}, []int64{2, 5}, 2) // userid 2,4
|
||||
test([]int64{1, 2, 3, 4, 5}, []int64{2, 3, 5}, 3) // userid 2,4,5
|
||||
} |
@ -0,0 +1,52 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
"code.gitea.io/gitea/models/perm" |
||||
"code.gitea.io/gitea/models/unit" |
||||
) |
||||
|
||||
// TeamUnit describes all units of a repository
|
||||
type TeamUnit struct { |
||||
ID int64 `xorm:"pk autoincr"` |
||||
OrgID int64 `xorm:"INDEX"` |
||||
TeamID int64 `xorm:"UNIQUE(s)"` |
||||
Type unit.Type `xorm:"UNIQUE(s)"` |
||||
AccessMode perm.AccessMode |
||||
} |
||||
|
||||
// Unit returns Unit
|
||||
func (t *TeamUnit) Unit() unit.Unit { |
||||
return unit.Units[t.Type] |
||||
} |
||||
|
||||
func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err error) { |
||||
return units, db.GetEngine(ctx).Where("team_id = ?", teamID).Find(&units) |
||||
} |
||||
|
||||
// UpdateTeamUnits updates a teams's units
|
||||
func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { |
||||
ctx, committer, err := db.TxContext() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer committer.Close() |
||||
|
||||
if _, err = db.GetEngine(ctx).Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil { |
||||
return err |
||||
} |
||||
|
||||
if len(units) > 0 { |
||||
if err = db.Insert(ctx, units); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
|
||||
return committer.Commit() |
||||
} |
@ -0,0 +1,109 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package organization |
||||
|
||||
import ( |
||||
"context" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
"xorm.io/builder" |
||||
) |
||||
|
||||
// TeamUser represents an team-user relation.
|
||||
type TeamUser struct { |
||||
ID int64 `xorm:"pk autoincr"` |
||||
OrgID int64 `xorm:"INDEX"` |
||||
TeamID int64 `xorm:"UNIQUE(s)"` |
||||
UID int64 `xorm:"UNIQUE(s)"` |
||||
} |
||||
|
||||
// IsTeamMember returns true if given user is a member of team.
|
||||
func IsTeamMember(ctx context.Context, orgID, teamID, userID int64) (bool, error) { |
||||
return db.GetEngine(ctx). |
||||
Where("org_id=?", orgID). |
||||
And("team_id=?", teamID). |
||||
And("uid=?", userID). |
||||
Table("team_user"). |
||||
Exist() |
||||
} |
||||
|
||||
// GetTeamUsersByTeamID returns team users for a team
|
||||
func GetTeamUsersByTeamID(ctx context.Context, teamID int64) ([]*TeamUser, error) { |
||||
teamUsers := make([]*TeamUser, 0, 10) |
||||
return teamUsers, db.GetEngine(ctx). |
||||
Where("team_id=?", teamID). |
||||
Find(&teamUsers) |
||||
} |
||||
|
||||
// SearchMembersOptions holds the search options
|
||||
type SearchMembersOptions struct { |
||||
db.ListOptions |
||||
TeamID int64 |
||||
} |
||||
|
||||
func (opts SearchMembersOptions) ToConds() builder.Cond { |
||||
cond := builder.NewCond() |
||||
if opts.TeamID > 0 { |
||||
cond = cond.And(builder.Eq{"": opts.TeamID}) |
||||
} |
||||
return cond |
||||
} |
||||
|
||||
// GetTeamMembers returns all members in given team of organization.
|
||||
func GetTeamMembers(ctx context.Context, opts *SearchMembersOptions) ([]*user_model.User, error) { |
||||
var members []*user_model.User |
||||
sess := db.GetEngine(ctx) |
||||
if opts.TeamID > 0 { |
||||
sess = sess.In("id", |
||||
builder.Select("uid"). |
||||
From("team_user"). |
||||
Where(builder.Eq{"team_id": opts.TeamID}), |
||||
) |
||||
} |
||||
if opts.PageSize > 0 && opts.Page > -1 { |
||||
sess = sess.Limit(opts.PageSize, opts.Page*opts.PageSize) |
||||
} |
||||
if err := sess.OrderBy("full_name, name").Find(&members); err != nil { |
||||
return nil, err |
||||
} |
||||
return members, nil |
||||
} |
||||
|
||||
// GetUserOrgTeams returns all teams that user belongs to in given organization.
|
||||
func GetUserOrgTeams(ctx context.Context, orgID, userID int64) (teams []*Team, err error) { |
||||
return teams, db.GetEngine(ctx). |
||||
Join("INNER", "team_user", "team_user.team_id = team.id"). |
||||
Where("team.org_id = ?", orgID). |
||||
And("team_user.uid=?", userID). |
||||
Find(&teams) |
||||
} |
||||
|
||||
// GetUserRepoTeams returns user repo's teams
|
||||
func GetUserRepoTeams(ctx context.Context, orgID, userID, repoID int64) (teams []*Team, err error) { |
||||
return teams, db.GetEngine(ctx). |
||||
Join("INNER", "team_user", "team_user.team_id = team.id"). |
||||
Join("INNER", "team_repo", "team_repo.team_id = team.id"). |
||||
Where("team.org_id = ?", orgID). |
||||
And("team_user.uid=?", userID). |
||||
And("team_repo.repo_id=?", repoID). |
||||
Find(&teams) |
||||
} |
||||
|
||||
// IsUserInTeams returns if a user in some teams
|
||||
func IsUserInTeams(ctx context.Context, userID int64, teamIDs []int64) (bool, error) { |
||||
return db.GetEngine(ctx).Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser)) |
||||
} |
||||
|
||||
// UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
|
||||
func UsersInTeamsCount(userIDs, teamIDs []int64) (int64, error) { |
||||
var ids []int64 |
||||
if err := db.GetEngine(db.DefaultContext).In("uid", userIDs).In("team_id", teamIDs). |
||||
Table("team_user"). |
||||
Cols("uid").GroupBy("uid").Find(&ids); err != nil { |
||||
return 0, err |
||||
} |
||||
return int64(len(ids)), nil |
||||
} |
@ -0,0 +1,87 @@ |
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package repo |
||||
|
||||
import ( |
||||
"context" |
||||
|
||||
"code.gitea.io/gitea/models/db" |
||||
user_model "code.gitea.io/gitea/models/user" |
||||
) |
||||
|
||||
// GetStarredRepos returns the repos starred by a particular user
|
||||
func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { |
||||
sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). |
||||
Join("LEFT", "star", "`repository`.id=`star`.repo_id") |
||||
if !private { |
||||
sess = sess.And("is_private=?", false) |
||||
} |
||||
|
||||
if listOptions.Page != 0 { |
||||
sess = db.SetSessionPagination(sess, &listOptions) |
||||
|
||||
repos := make([]*Repository, 0, listOptions.PageSize) |
||||
return repos, sess.Find(&repos) |
||||
} |
||||
|
||||
repos := make([]*Repository, 0, 10) |
||||
return repos, sess.Find(&repos) |
||||
} |
||||
|
||||
// GetWatchedRepos returns the repos watched by a particular user
|
||||
func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { |
||||
sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). |
||||
And("`watch`.mode<>?", WatchModeDont). |
||||
Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") |
||||
if !private { |
||||
sess = sess.And("is_private=?", false) |
||||
} |
||||
|
||||
if listOptions.Page != 0 { |
||||
sess = db.SetSessionPagination(sess, &listOptions) |
||||
|
||||
repos := make([]*Repository, 0, listOptions.PageSize) |
||||
total, err := sess.FindAndCount(&repos) |
||||
return repos, total, err |
||||
} |
||||
|
||||
repos := make([]*Repository, 0, 10) |
||||
total, err := sess.FindAndCount(&repos) |
||||
return repos, total, err |
||||
} |
||||
|
||||
// CountUserRepositories returns number of repositories user owns.
|
||||
// Argument private only takes effect when it is false,
|
||||
// set it true to count all repositories.
|
||||
func CountUserRepositories(userID int64, private bool) int64 { |
||||
return countRepositories(userID, private) |
||||
} |
||||
|
||||
func getRepositoryCount(e db.Engine, ownerID int64) (int64, error) { |
||||
return e.Count(&Repository{OwnerID: ownerID}) |
||||
} |
||||
|
||||
func getPublicRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { |
||||
return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID}) |
||||
} |
||||
|
||||
func getPrivateRepositoryCount(e db.Engine, u *user_model.User) (int64, error) { |
||||
return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID}) |
||||
} |
||||
|
||||
// GetRepositoryCount returns the total number of repositories of user.
|
||||
func GetRepositoryCount(ctx context.Context, ownerID int64) (int64, error) { |
||||
return getRepositoryCount(db.GetEngine(ctx), ownerID) |
||||
} |
||||
|
||||
// GetPublicRepositoryCount returns the total number of public repositories of user.
|
||||
func GetPublicRepositoryCount(u *user_model.User) (int64, error) { |
||||
return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u) |
||||
} |
||||
|
||||
// GetPrivateRepositoryCount returns the total number of private repositories of user.
|
||||
func GetPrivateRepositoryCount(u *user_model.User) (int64, error) { |
||||
return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u) |
||||
} |
Loading…
Reference in new issue