Remove unnecessary attributes of User struct (#17745)
* Remove unnecessary functions of User struct * Move more database methods out of user struct * Move more database methods out of user struct * Fix template failure * Fix bug * Remove finished FIXME * remove unnecessary code
This commit is contained in:
parent
c2ab19888f
commit
baed01f247
42 changed files with 279 additions and 451 deletions
|
@ -105,66 +105,6 @@ func accessLevel(e db.Engine, user *User, repo *Repository) (AccessMode, error)
|
|||
return a.Mode, nil
|
||||
}
|
||||
|
||||
type repoAccess struct {
|
||||
Access `xorm:"extends"`
|
||||
Repository `xorm:"extends"`
|
||||
}
|
||||
|
||||
func (repoAccess) TableName() string {
|
||||
return "access"
|
||||
}
|
||||
|
||||
// GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
|
||||
func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
|
||||
rows, err := db.GetEngine(db.DefaultContext).
|
||||
Join("INNER", "repository", "repository.id = access.repo_id").
|
||||
Where("access.user_id = ?", user.ID).
|
||||
And("repository.owner_id <> ?", user.ID).
|
||||
Rows(new(repoAccess))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
repos := make(map[*Repository]AccessMode, 10)
|
||||
ownerCache := make(map[int64]*User, 10)
|
||||
for rows.Next() {
|
||||
var repo repoAccess
|
||||
err = rows.Scan(&repo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ok bool
|
||||
if repo.Owner, ok = ownerCache[repo.OwnerID]; !ok {
|
||||
if err = repo.GetOwner(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ownerCache[repo.OwnerID] = repo.Owner
|
||||
}
|
||||
|
||||
repos[&repo.Repository] = repo.Access.Mode
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
// GetAccessibleRepositories finds repositories which the user has access but does not own.
|
||||
// If limit is smaller than 1 means returns all found results.
|
||||
func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
|
||||
sess := db.GetEngine(db.DefaultContext).
|
||||
Where("owner_id !=? ", user.ID).
|
||||
Desc("updated_unix")
|
||||
if limit > 0 {
|
||||
sess.Limit(limit)
|
||||
repos = make([]*Repository, 0, limit)
|
||||
} else {
|
||||
repos = make([]*Repository, 0, 10)
|
||||
}
|
||||
return repos, sess.
|
||||
Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).
|
||||
Find(&repos)
|
||||
}
|
||||
|
||||
func maxAccessMode(modes ...AccessMode) AccessMode {
|
||||
max := AccessModeNone
|
||||
for _, mode := range modes {
|
||||
|
|
|
@ -90,39 +90,6 @@ func TestHasAccess(t *testing.T) {
|
|||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestUser_GetRepositoryAccesses(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
|
||||
accesses, err := user1.GetRepositoryAccesses()
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, accesses, 0)
|
||||
|
||||
user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
|
||||
accesses, err = user29.GetRepositoryAccesses()
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, accesses, 2)
|
||||
}
|
||||
|
||||
func TestUser_GetAccessibleRepositories(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
|
||||
repos, err := user1.GetAccessibleRepositories(0)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, repos, 0)
|
||||
|
||||
user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
|
||||
repos, err = user2.GetAccessibleRepositories(0)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, repos, 4)
|
||||
|
||||
user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
|
||||
repos, err = user29.GetAccessibleRepositories(0)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, repos, 2)
|
||||
}
|
||||
|
||||
func TestRepository_RecalculateAccesses(t *testing.T) {
|
||||
// test with organization repo
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
|
|
@ -125,6 +125,12 @@ 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
|
||||
|
@ -240,7 +246,7 @@ func CreateOrganization(org *Organization, owner *User) (err error) {
|
|||
if err = db.Insert(ctx, org); err != nil {
|
||||
return fmt.Errorf("insert organization: %v", err)
|
||||
}
|
||||
if err = org.AsUser().generateRandomAvatar(db.GetEngine(ctx)); err != nil {
|
||||
if err = generateRandomAvatar(db.GetEngine(ctx), org.AsUser()); err != nil {
|
||||
return fmt.Errorf("generate random avatar: %v", err)
|
||||
}
|
||||
|
||||
|
@ -546,8 +552,8 @@ func CountOrgs(opts FindOrgOptions) (int64, error) {
|
|||
Count(new(User))
|
||||
}
|
||||
|
||||
func getOwnedOrgsByUserID(sess db.Engine, userID int64) ([]*User, error) {
|
||||
orgs := make([]*User, 0, 10)
|
||||
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").
|
||||
|
@ -593,20 +599,20 @@ func HasOrgsVisible(orgs []*Organization, user *User) bool {
|
|||
}
|
||||
|
||||
// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
|
||||
func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
|
||||
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) ([]*User, error) {
|
||||
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) ([]*User, error) {
|
||||
orgs := make([]*User, 0, 10)
|
||||
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").
|
||||
|
|
|
@ -754,19 +754,20 @@ func (repo *Repository) UpdateSize(ctx context.Context) error {
|
|||
return repo.updateSize(db.GetEngine(ctx))
|
||||
}
|
||||
|
||||
// CanUserFork returns true if specified user can fork repository.
|
||||
func (repo *Repository) CanUserFork(user *User) (bool, error) {
|
||||
// CanUserForkRepo returns true if specified user can fork repository.
|
||||
func CanUserForkRepo(user *User, repo *Repository) (bool, error) {
|
||||
if user == nil {
|
||||
return false, nil
|
||||
}
|
||||
if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
|
||||
if repo.OwnerID != user.ID && !HasForkedRepo(user.ID, repo.ID) {
|
||||
return true, nil
|
||||
}
|
||||
if err := user.GetOwnedOrganizations(); err != nil {
|
||||
ownedOrgs, err := GetOwnedOrgsByUserID(user.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, org := range user.OwnedOrgs {
|
||||
if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
|
||||
for _, org := range ownedOrgs {
|
||||
if repo.OwnerID != org.ID && !HasForkedRepo(org.ID, repo.ID) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
@ -2036,13 +2037,25 @@ func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
|
|||
// \___ / \____/|__| |__|_ \
|
||||
// \/ \/
|
||||
|
||||
// HasForkedRepo checks if given user has already forked a repository with given ID.
|
||||
func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
|
||||
// GetForkedRepo checks if given user has already forked a repository with given ID.
|
||||
func GetForkedRepo(ownerID, repoID int64) *Repository {
|
||||
repo := new(Repository)
|
||||
has, _ := db.GetEngine(db.DefaultContext).
|
||||
Where("owner_id=? AND fork_id=?", ownerID, repoID).
|
||||
Get(repo)
|
||||
return repo, has
|
||||
if has {
|
||||
return repo
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HasForkedRepo checks if given user has already forked a repository with given ID.
|
||||
func HasForkedRepo(ownerID, repoID int64) bool {
|
||||
has, _ := db.GetEngine(db.DefaultContext).
|
||||
Table("repository").
|
||||
Where("owner_id=? AND fork_id=?", ownerID, repoID).
|
||||
Exist()
|
||||
return has
|
||||
}
|
||||
|
||||
// CopyLFS copies LFS data from one repo to another
|
||||
|
|
|
@ -74,7 +74,7 @@ func isStaring(e db.Engine, userID, repoID int64) bool {
|
|||
}
|
||||
|
||||
// GetStargazers returns the users that starred the repo.
|
||||
func (repo *Repository) GetStargazers(opts db.ListOptions) ([]*User, error) {
|
||||
func GetStargazers(repo *Repository, opts db.ListOptions) ([]*User, error) {
|
||||
sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID).
|
||||
Join("LEFT", "star", "`user`.id = star.uid")
|
||||
if opts.Page > 0 {
|
||||
|
@ -87,48 +87,3 @@ func (repo *Repository) GetStargazers(opts db.ListOptions) ([]*User, error) {
|
|||
users := make([]*User, 0, 8)
|
||||
return users, sess.Find(&users)
|
||||
}
|
||||
|
||||
// GetStarredRepos returns the repos the user starred.
|
||||
func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string) (repos RepositoryList, err error) {
|
||||
if len(orderBy) == 0 {
|
||||
orderBy = "updated_unix DESC"
|
||||
}
|
||||
sess := db.GetEngine(db.DefaultContext).
|
||||
Join("INNER", "star", "star.repo_id = repository.id").
|
||||
Where("star.uid = ?", u.ID).
|
||||
OrderBy(orderBy)
|
||||
|
||||
if !private {
|
||||
sess = sess.And("is_private = ?", false)
|
||||
}
|
||||
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
sess.Limit(pageSize, (page-1)*pageSize)
|
||||
|
||||
repos = make([]*Repository, 0, pageSize)
|
||||
|
||||
if err = sess.Find(&repos); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = repos.loadAttributes(db.GetEngine(db.DefaultContext)); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetStarredRepoCount returns the numbers of repo the user starred.
|
||||
func (u *User) GetStarredRepoCount(private bool) (int64, error) {
|
||||
sess := db.GetEngine(db.DefaultContext).
|
||||
Join("INNER", "star", "star.repo_id = repository.id").
|
||||
Where("star.uid = ?", u.ID)
|
||||
|
||||
if !private {
|
||||
sess = sess.And("is_private = ?", false)
|
||||
}
|
||||
|
||||
return sess.Count(&Repository{})
|
||||
}
|
||||
|
|
|
@ -36,7 +36,7 @@ func TestRepository_GetStargazers(t *testing.T) {
|
|||
// repo with stargazers
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
|
||||
gazers, err := repo.GetStargazers(db.ListOptions{Page: 0})
|
||||
gazers, err := GetStargazers(repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, gazers, 1) {
|
||||
assert.Equal(t, int64(2), gazers[0].ID)
|
||||
|
@ -47,53 +47,7 @@ func TestRepository_GetStargazers2(t *testing.T) {
|
|||
// repo with stargazers
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
|
||||
gazers, err := repo.GetStargazers(db.ListOptions{Page: 0})
|
||||
gazers, err := GetStargazers(repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, gazers, 0)
|
||||
}
|
||||
|
||||
func TestUser_GetStarredRepos(t *testing.T) {
|
||||
// user who has starred repos
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
|
||||
starred, err := user.GetStarredRepos(false, 1, 10, "")
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, starred, 1) {
|
||||
assert.Equal(t, int64(4), starred[0].ID)
|
||||
}
|
||||
|
||||
starred, err = user.GetStarredRepos(true, 1, 10, "")
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, starred, 2) {
|
||||
assert.Equal(t, int64(2), starred[0].ID)
|
||||
assert.Equal(t, int64(4), starred[1].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUser_GetStarredRepos2(t *testing.T) {
|
||||
// user who has no starred repos
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
|
||||
starred, err := user.GetStarredRepos(false, 1, 10, "")
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, starred, 0)
|
||||
|
||||
starred, err = user.GetStarredRepos(true, 1, 10, "")
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, starred, 0)
|
||||
}
|
||||
|
||||
func TestUserGetStarredRepoCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
|
||||
counts, err := user.GetStarredRepoCount(false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), counts)
|
||||
|
||||
counts, err = user.GetStarredRepoCount(true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), counts)
|
||||
}
|
||||
|
|
118
models/user.go
118
models/user.go
|
@ -113,8 +113,6 @@ type User struct {
|
|||
LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
LoginName string
|
||||
Type UserType
|
||||
OwnedOrgs []*User `xorm:"-"`
|
||||
Repos []*Repository `xorm:"-"`
|
||||
Location string
|
||||
Website string
|
||||
Rands string `xorm:"VARCHAR(10)"`
|
||||
|
@ -219,16 +217,16 @@ func (u *User) SetLastLogin() {
|
|||
u.LastLoginUnix = timeutil.TimeStampNow()
|
||||
}
|
||||
|
||||
// UpdateDiffViewStyle updates the users diff view style
|
||||
func (u *User) UpdateDiffViewStyle(style string) error {
|
||||
// UpdateUserDiffViewStyle updates the users diff view style
|
||||
func UpdateUserDiffViewStyle(u *User, style string) error {
|
||||
u.DiffViewStyle = style
|
||||
return UpdateUserCols(u, "diff_view_style")
|
||||
return UpdateUserCols(db.DefaultContext, u, "diff_view_style")
|
||||
}
|
||||
|
||||
// UpdateTheme updates a users' theme irrespective of the site wide theme
|
||||
func (u *User) UpdateTheme(themeName string) error {
|
||||
// UpdateUserTheme updates a users' theme irrespective of the site wide theme
|
||||
func UpdateUserTheme(u *User, themeName string) error {
|
||||
u.Theme = themeName
|
||||
return UpdateUserCols(u, "theme")
|
||||
return UpdateUserCols(db.DefaultContext, u, "theme")
|
||||
}
|
||||
|
||||
// GetEmail returns an noreply email, if the user has set to keep his
|
||||
|
@ -256,12 +254,6 @@ func (u *User) IsOAuth2() bool {
|
|||
return u.LoginType == login.OAuth2
|
||||
}
|
||||
|
||||
// HasForkedRepo checks if user has already forked a repository with given ID.
|
||||
func (u *User) HasForkedRepo(repoID int64) bool {
|
||||
_, has := HasForkedRepo(u.ID, repoID)
|
||||
return has
|
||||
}
|
||||
|
||||
// MaxCreationLimit returns the number of repositories a user is allowed to create
|
||||
func (u *User) MaxCreationLimit() int {
|
||||
if u.MaxRepoCreation <= -1 {
|
||||
|
@ -337,8 +329,8 @@ func (u *User) GenerateEmailActivateCode(email string) string {
|
|||
return code
|
||||
}
|
||||
|
||||
// GetFollowers returns range of user's followers.
|
||||
func (u *User) GetFollowers(listOptions db.ListOptions) ([]*User, error) {
|
||||
// GetUserFollowers returns range of user's followers.
|
||||
func GetUserFollowers(u *User, listOptions db.ListOptions) ([]*User, error) {
|
||||
sess := db.GetEngine(db.DefaultContext).
|
||||
Where("follow.follow_id=?", u.ID).
|
||||
Join("LEFT", "follow", "`user`.id=follow.user_id")
|
||||
|
@ -354,13 +346,8 @@ func (u *User) GetFollowers(listOptions db.ListOptions) ([]*User, error) {
|
|||
return users, sess.Find(&users)
|
||||
}
|
||||
|
||||
// IsFollowing returns true if user is following followID.
|
||||
func (u *User) IsFollowing(followID int64) bool {
|
||||
return user_model.IsFollowing(u.ID, followID)
|
||||
}
|
||||
|
||||
// GetFollowing returns range of user's following.
|
||||
func (u *User) GetFollowing(listOptions db.ListOptions) ([]*User, error) {
|
||||
// GetUserFollowing returns range of user's following.
|
||||
func GetUserFollowing(u *User, listOptions db.ListOptions) ([]*User, error) {
|
||||
sess := db.GetEngine(db.DefaultContext).
|
||||
Where("follow.user_id=?", u.ID).
|
||||
Join("LEFT", "follow", "`user`.id=follow.follow_id")
|
||||
|
@ -442,12 +429,12 @@ func (u *User) IsPasswordSet() bool {
|
|||
return len(u.Passwd) != 0
|
||||
}
|
||||
|
||||
// IsVisibleToUser check if viewer is able to see user profile
|
||||
func (u *User) IsVisibleToUser(viewer *User) bool {
|
||||
return u.isVisibleToUser(db.GetEngine(db.DefaultContext), viewer)
|
||||
// IsUserVisibleToViewer check if viewer is able to see user profile
|
||||
func IsUserVisibleToViewer(u *User, viewer *User) bool {
|
||||
return isUserVisibleToViewer(db.GetEngine(db.DefaultContext), u, viewer)
|
||||
}
|
||||
|
||||
func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool {
|
||||
func isUserVisibleToViewer(e db.Engine, u *User, viewer *User) bool {
|
||||
if viewer != nil && viewer.IsAdmin {
|
||||
return true
|
||||
}
|
||||
|
@ -503,26 +490,6 @@ func (u *User) IsOrganization() bool {
|
|||
return u.Type == UserTypeOrganization
|
||||
}
|
||||
|
||||
// IsUserOrgOwner returns true if user is in the owner team of given organization.
|
||||
func (u *User) IsUserOrgOwner(orgID int64) bool {
|
||||
isOwner, err := IsOrganizationOwner(orgID, u.ID)
|
||||
if err != nil {
|
||||
log.Error("IsOrganizationOwner: %v", err)
|
||||
return false
|
||||
}
|
||||
return isOwner
|
||||
}
|
||||
|
||||
// IsPublicMember returns true if user public his/her membership in given organization.
|
||||
func (u *User) IsPublicMember(orgID int64) bool {
|
||||
isMember, err := IsPublicMembership(orgID, u.ID)
|
||||
if err != nil {
|
||||
log.Error("IsPublicMembership: %v", err)
|
||||
return false
|
||||
}
|
||||
return isMember
|
||||
}
|
||||
|
||||
// GetOrganizationCount returns count of membership of organization of the user.
|
||||
func GetOrganizationCount(ctx context.Context, u *User) (int64, error) {
|
||||
return db.GetEngine(ctx).
|
||||
|
@ -530,17 +497,6 @@ func GetOrganizationCount(ctx context.Context, u *User) (int64, error) {
|
|||
Count(new(OrgUser))
|
||||
}
|
||||
|
||||
// GetOrganizationCount returns count of membership of organization of user.
|
||||
func (u *User) GetOrganizationCount() (int64, error) {
|
||||
return GetOrganizationCount(db.DefaultContext, u)
|
||||
}
|
||||
|
||||
// GetRepositories returns repositories that user owns, including private repositories.
|
||||
func (u *User) GetRepositories(listOpts db.ListOptions, names ...string) (err error) {
|
||||
u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts, LowerNames: names})
|
||||
return err
|
||||
}
|
||||
|
||||
// GetRepositoryIDs returns repositories IDs where user owned and has unittypes
|
||||
// Caller shall check that units is not globally disabled
|
||||
func (u *User) GetRepositoryIDs(units ...unit.Type) ([]int64, error) {
|
||||
|
@ -644,17 +600,6 @@ func (u *User) GetActiveAccessRepoIDs(units ...unit.Type) ([]int64, error) {
|
|||
return append(ids, ids2...), nil
|
||||
}
|
||||
|
||||
// GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
|
||||
func (u *User) GetMirrorRepositories() ([]*Repository, error) {
|
||||
return GetUserMirrorRepositories(u.ID)
|
||||
}
|
||||
|
||||
// GetOwnedOrganizations returns all organizations that user owns.
|
||||
func (u *User) GetOwnedOrganizations() (err error) {
|
||||
u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// DisplayName returns full name if it's not empty,
|
||||
// returns username otherwise.
|
||||
func (u *User) DisplayName() string {
|
||||
|
@ -714,9 +659,9 @@ func (u *User) EmailNotifications() string {
|
|||
}
|
||||
|
||||
// SetEmailNotifications sets the user's email notification preference
|
||||
func (u *User) SetEmailNotifications(set string) error {
|
||||
func SetEmailNotifications(u *User, set string) error {
|
||||
u.EmailNotificationsPreference = set
|
||||
if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
|
||||
if err := UpdateUserCols(db.DefaultContext, u, "email_notifications_preference"); err != nil {
|
||||
log.Error("SetEmailNotifications: %v", err)
|
||||
return err
|
||||
}
|
||||
|
@ -983,25 +928,6 @@ func VerifyUserActiveCode(code string) (user *User) {
|
|||
return nil
|
||||
}
|
||||
|
||||
// VerifyActiveEmailCode verifies active email code when active account
|
||||
func VerifyActiveEmailCode(code, email string) *user_model.EmailAddress {
|
||||
minutes := setting.Service.ActiveCodeLives
|
||||
|
||||
if user := getVerifyUser(code); user != nil {
|
||||
// time limit code
|
||||
prefix := code[:base.TimeLimitCodeLength]
|
||||
data := fmt.Sprintf("%d%s%s%s%s", user.ID, email, user.LowerName, user.Passwd, user.Rands)
|
||||
|
||||
if base.VerifyTimeLimitCode(data, minutes, prefix) {
|
||||
emailAddress := &user_model.EmailAddress{UID: user.ID, Email: email}
|
||||
if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has {
|
||||
return emailAddress
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChangeUserName changes all corresponding setting from old user name to new one.
|
||||
func ChangeUserName(u *User, newUserName string) (err error) {
|
||||
oldUserName := u.Name
|
||||
|
@ -1090,8 +1016,8 @@ func UpdateUser(u *User) error {
|
|||
}
|
||||
|
||||
// UpdateUserCols update user according special columns
|
||||
func UpdateUserCols(u *User, cols ...string) error {
|
||||
return updateUserCols(db.GetEngine(db.DefaultContext), u, cols...)
|
||||
func UpdateUserCols(ctx context.Context, u *User, cols ...string) error {
|
||||
return updateUserCols(db.GetEngine(ctx), u, cols...)
|
||||
}
|
||||
|
||||
func updateUserCols(e db.Engine, u *User, cols ...string) error {
|
||||
|
@ -1228,14 +1154,6 @@ func DeleteUser(ctx context.Context, u *User) (err error) {
|
|||
if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
|
||||
return fmt.Errorf("deletePublicKeys: %v", err)
|
||||
}
|
||||
err = rewriteAllPublicKeys(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = rewriteAllPrincipalKeys(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ***** END: PublicKey *****
|
||||
|
||||
// ***** START: GPGPublicKey *****
|
||||
|
|
|
@ -25,11 +25,11 @@ func (u *User) CustomAvatarRelativePath() string {
|
|||
}
|
||||
|
||||
// GenerateRandomAvatar generates a random avatar for user.
|
||||
func (u *User) GenerateRandomAvatar() error {
|
||||
return u.generateRandomAvatar(db.GetEngine(db.DefaultContext))
|
||||
func GenerateRandomAvatar(u *User) error {
|
||||
return generateRandomAvatar(db.GetEngine(db.DefaultContext), u)
|
||||
}
|
||||
|
||||
func (u *User) generateRandomAvatar(e db.Engine) error {
|
||||
func generateRandomAvatar(e db.Engine, u *User) error {
|
||||
seed := u.Email
|
||||
if len(seed) == 0 {
|
||||
seed = u.Name
|
||||
|
@ -80,7 +80,7 @@ func (u *User) AvatarLinkWithSize(size int) string {
|
|||
|
||||
if useLocalAvatar {
|
||||
if u.Avatar == "" && autoGenerateAvatar {
|
||||
if err := u.GenerateRandomAvatar(); err != nil {
|
||||
if err := GenerateRandomAvatar(u); err != nil {
|
||||
log.Error("GenerateRandomAvatar: %v", err)
|
||||
}
|
||||
}
|
||||
|
@ -101,42 +101,6 @@ func (u *User) AvatarLink() string {
|
|||
return link
|
||||
}
|
||||
|
||||
// UploadAvatar saves custom avatar for user.
|
||||
// FIXME: split uploads to different subdirs in case we have massive users.
|
||||
func (u *User) UploadAvatar(data []byte) error {
|
||||
m, err := avatar.Prepare(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, committer, err := db.TxContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
u.UseCustomAvatar = true
|
||||
// Different users can upload same image as avatar
|
||||
// If we prefix it with u.ID, it will be separated
|
||||
// Otherwise, if any of the users delete his avatar
|
||||
// Other users will lose their avatars too.
|
||||
u.Avatar = fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data)))))
|
||||
if err = updateUserCols(db.GetEngine(ctx), u, "use_custom_avatar", "avatar"); err != nil {
|
||||
return fmt.Errorf("updateUser: %v", err)
|
||||
}
|
||||
|
||||
if err := storage.SaveFrom(storage.Avatars, u.CustomAvatarRelativePath(), func(w io.Writer) error {
|
||||
if err := png.Encode(w, *m); err != nil {
|
||||
log.Error("Encode: %v", err)
|
||||
}
|
||||
return err
|
||||
}); err != nil {
|
||||
return fmt.Errorf("Failed to create dir %s: %v", u.CustomAvatarRelativePath(), err)
|
||||
}
|
||||
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// IsUploadAvatarChanged returns true if the current user's avatar would be changed with the provided data
|
||||
func (u *User) IsUploadAvatarChanged(data []byte) bool {
|
||||
if !u.UseCustomAvatar || len(u.Avatar) == 0 {
|
||||
|
@ -145,21 +109,3 @@ func (u *User) IsUploadAvatarChanged(data []byte) bool {
|
|||
avatarID := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data)))))
|
||||
return u.Avatar != avatarID
|
||||
}
|
||||
|
||||
// DeleteAvatar deletes the user's custom avatar.
|
||||
func (u *User) DeleteAvatar() error {
|
||||
aPath := u.CustomAvatarRelativePath()
|
||||
log.Trace("DeleteAvatar[%d]: %s", u.ID, aPath)
|
||||
if len(u.Avatar) > 0 {
|
||||
if err := storage.Avatars.Delete(aPath); err != nil {
|
||||
return fmt.Errorf("Failed to remove %s: %v", aPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
u.UseCustomAvatar = false
|
||||
u.Avatar = ""
|
||||
if _, err := db.GetEngine(db.DefaultContext).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
|
||||
return fmt.Errorf("UpdateUser: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -10,6 +10,8 @@ import (
|
|||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
|
@ -93,6 +95,25 @@ func MakeEmailPrimary(email *user_model.EmailAddress) error {
|
|||
return committer.Commit()
|
||||
}
|
||||
|
||||
// VerifyActiveEmailCode verifies active email code when active account
|
||||
func VerifyActiveEmailCode(code, email string) *user_model.EmailAddress {
|
||||
minutes := setting.Service.ActiveCodeLives
|
||||
|
||||
if user := getVerifyUser(code); user != nil {
|
||||
// time limit code
|
||||
prefix := code[:base.TimeLimitCodeLength]
|
||||
data := fmt.Sprintf("%d%s%s%s%s", user.ID, email, user.LowerName, user.Passwd, user.Rands)
|
||||
|
||||
if base.VerifyTimeLimitCode(data, minutes, prefix) {
|
||||
emailAddress := &user_model.EmailAddress{UID: user.ID, Email: email}
|
||||
if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has {
|
||||
return emailAddress
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SearchEmailOrderBy is used to sort the results from SearchEmails()
|
||||
type SearchEmailOrderBy string
|
||||
|
||||
|
|
|
@ -52,7 +52,9 @@ func TestUserIsPublicMember(t *testing.T) {
|
|||
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) {
|
||||
user, err := GetUserByID(uid)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, user.IsPublicMember(orgID))
|
||||
is, err := IsPublicMembership(orgID, user.ID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, is)
|
||||
}
|
||||
|
||||
func TestIsUserOrgOwner(t *testing.T) {
|
||||
|
@ -78,7 +80,9 @@ func TestIsUserOrgOwner(t *testing.T) {
|
|||
func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) {
|
||||
user, err := GetUserByID(uid)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, user.IsUserOrgOwner(orgID))
|
||||
is, err := IsOrganizationOwner(orgID, user.ID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, is)
|
||||
}
|
||||
|
||||
func TestGetUserEmailsByNames(t *testing.T) {
|
||||
|
@ -198,13 +202,13 @@ func TestEmailNotificationPreferences(t *testing.T) {
|
|||
assert.Equal(t, test.expected, user.EmailNotifications())
|
||||
|
||||
// Try all possible settings
|
||||
assert.NoError(t, user.SetEmailNotifications(EmailNotificationsEnabled))
|
||||
assert.NoError(t, SetEmailNotifications(user, EmailNotificationsEnabled))
|
||||
assert.Equal(t, EmailNotificationsEnabled, user.EmailNotifications())
|
||||
|
||||
assert.NoError(t, user.SetEmailNotifications(EmailNotificationsOnMention))
|
||||
assert.NoError(t, SetEmailNotifications(user, EmailNotificationsOnMention))
|
||||
assert.Equal(t, EmailNotificationsOnMention, user.EmailNotifications())
|
||||
|
||||
assert.NoError(t, user.SetEmailNotifications(EmailNotificationsDisabled))
|
||||
assert.NoError(t, SetEmailNotifications(user, EmailNotificationsDisabled))
|
||||
assert.Equal(t, EmailNotificationsDisabled, user.EmailNotifications())
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue