summaryrefslogtreecommitdiffstats
path: root/models
diff options
context:
space:
mode:
Diffstat (limited to 'models')
-rw-r--r--models/error.go34
-rw-r--r--models/fixtures/repo_transfer.yml7
-rw-r--r--models/issue.go2
-rw-r--r--models/migrations/migrations.go2
-rw-r--r--models/migrations/v174.go23
-rw-r--r--models/models.go1
-rw-r--r--models/notification.go78
-rw-r--r--models/org.go14
-rw-r--r--models/org_test.go18
-rw-r--r--models/repo.go144
-rw-r--r--models/repo_transfer.go335
-rw-r--r--models/repo_transfer_test.go54
12 files changed, 567 insertions, 145 deletions
diff --git a/models/error.go b/models/error.go
index fc161ed806..84b7ebbfa3 100644
--- a/models/error.go
+++ b/models/error.go
@@ -757,6 +757,40 @@ func (err ErrRepoNotExist) Error() string {
err.ID, err.UID, err.OwnerName, err.Name)
}
+// ErrNoPendingRepoTransfer is an error type for repositories without a pending
+// transfer request
+type ErrNoPendingRepoTransfer struct {
+ RepoID int64
+}
+
+func (e ErrNoPendingRepoTransfer) Error() string {
+ return fmt.Sprintf("repository doesn't have a pending transfer [repo_id: %d]", e.RepoID)
+}
+
+// IsErrNoPendingTransfer is an error type when a repository has no pending
+// transfers
+func IsErrNoPendingTransfer(err error) bool {
+ _, ok := err.(ErrNoPendingRepoTransfer)
+ return ok
+}
+
+// ErrRepoTransferInProgress represents the state of a repository that has an
+// ongoing transfer
+type ErrRepoTransferInProgress struct {
+ Uname string
+ Name string
+}
+
+// IsErrRepoTransferInProgress checks if an error is a ErrRepoTransferInProgress.
+func IsErrRepoTransferInProgress(err error) bool {
+ _, ok := err.(ErrRepoTransferInProgress)
+ return ok
+}
+
+func (err ErrRepoTransferInProgress) Error() string {
+ return fmt.Sprintf("repository is already being transferred [uname: %s, name: %s]", err.Uname, err.Name)
+}
+
// ErrRepoAlreadyExist represents a "RepoAlreadyExist" kind of error.
type ErrRepoAlreadyExist struct {
Uname string
diff --git a/models/fixtures/repo_transfer.yml b/models/fixtures/repo_transfer.yml
new file mode 100644
index 0000000000..b841b5e983
--- /dev/null
+++ b/models/fixtures/repo_transfer.yml
@@ -0,0 +1,7 @@
+-
+ id: 1
+ doer_id: 3
+ recipient_id: 1
+ repo_id: 3
+ created_unix: 1553610671
+ updated_unix: 1553610671
diff --git a/models/issue.go b/models/issue.go
index b903e82ad7..c0bafb54e4 100644
--- a/models/issue.go
+++ b/models/issue.go
@@ -563,7 +563,7 @@ func (issue *Issue) ReadBy(userID int64) error {
return err
}
- return setNotificationStatusReadIfUnread(x, userID, issue.ID)
+ return setIssueNotificationStatusReadIfUnread(x, userID, issue.ID)
}
func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go
index 4fc737e1bf..27c159ee4a 100644
--- a/models/migrations/migrations.go
+++ b/models/migrations/migrations.go
@@ -294,6 +294,8 @@ var migrations = []Migration{
NewMigration("Add sessions table for go-chi/session", addSessionTable),
// v173 -> v174
NewMigration("Add time_id column to Comment", addTimeIDCommentColumn),
+ // v174 -> v175
+ NewMigration("create repo transfer table", addRepoTransfer),
}
// GetCurrentDBVersion returns the current db version
diff --git a/models/migrations/v174.go b/models/migrations/v174.go
new file mode 100644
index 0000000000..ce337df2b3
--- /dev/null
+++ b/models/migrations/v174.go
@@ -0,0 +1,23 @@
+// 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 migrations
+
+import (
+ "xorm.io/xorm"
+)
+
+func addRepoTransfer(x *xorm.Engine) error {
+ type RepoTransfer struct {
+ ID int64 `xorm:"pk autoincr"`
+ DoerID int64
+ RecipientID int64
+ RepoID int64
+ TeamIDs []int64
+ CreatedUnix int64 `xorm:"INDEX NOT NULL created"`
+ UpdatedUnix int64 `xorm:"INDEX NOT NULL updated"`
+ }
+
+ return x.Sync(new(RepoTransfer))
+}
diff --git a/models/models.go b/models/models.go
index de50793fe7..ca4d1c4ad1 100644
--- a/models/models.go
+++ b/models/models.go
@@ -133,6 +133,7 @@ func init() {
new(ProjectBoard),
new(ProjectIssue),
new(Session),
+ new(RepoTransfer),
)
gonicNames := []string{"SSL", "UID"}
diff --git a/models/notification.go b/models/notification.go
index 32f3079bf4..a9178b97de 100644
--- a/models/notification.go
+++ b/models/notification.go
@@ -39,6 +39,8 @@ const (
NotificationSourcePullRequest
// NotificationSourceCommit is a notification of a commit
NotificationSourceCommit
+ // NotificationSourceRepository is a notification for a repository
+ NotificationSourceRepository
)
// Notification represents a notification
@@ -119,6 +121,46 @@ func GetNotifications(opts FindNotificationOptions) (NotificationList, error) {
return getNotifications(x, opts)
}
+// CreateRepoTransferNotification creates notification for the user a repository was transferred to
+func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) error {
+ sess := x.NewSession()
+ defer sess.Close()
+ if err := sess.Begin(); err != nil {
+ return err
+ }
+ var notify []*Notification
+
+ if newOwner.IsOrganization() {
+ users, err := getUsersWhoCanCreateOrgRepo(sess, newOwner.ID)
+ if err != nil || len(users) == 0 {
+ return err
+ }
+ for i := range users {
+ notify = append(notify, &Notification{
+ UserID: users[i].ID,
+ RepoID: repo.ID,
+ Status: NotificationStatusUnread,
+ UpdatedBy: doer.ID,
+ Source: NotificationSourceRepository,
+ })
+ }
+ } else {
+ notify = []*Notification{{
+ UserID: newOwner.ID,
+ RepoID: repo.ID,
+ Status: NotificationStatusUnread,
+ UpdatedBy: doer.ID,
+ Source: NotificationSourceRepository,
+ }}
+ }
+
+ if _, err := sess.InsertMulti(notify); err != nil {
+ return err
+ }
+
+ return sess.Commit()
+}
+
// CreateOrUpdateIssueNotifications creates an issue notification
// for each watcher, or updates it if already exists
// receiverID > 0 just send to reciver, else send to all watcher
@@ -363,7 +405,7 @@ func (n *Notification) loadRepo(e Engine) (err error) {
}
func (n *Notification) loadIssue(e Engine) (err error) {
- if n.Issue == nil {
+ if n.Issue == nil && n.IssueID != 0 {
n.Issue, err = getIssueByID(e, n.IssueID)
if err != nil {
return fmt.Errorf("getIssueByID [%d]: %v", n.IssueID, err)
@@ -374,7 +416,7 @@ func (n *Notification) loadIssue(e Engine) (err error) {
}
func (n *Notification) loadComment(e Engine) (err error) {
- if n.Comment == nil && n.CommentID > 0 {
+ if n.Comment == nil && n.CommentID != 0 {
n.Comment, err = getCommentByID(e, n.CommentID)
if err != nil {
return fmt.Errorf("GetCommentByID [%d] for issue ID [%d]: %v", n.CommentID, n.IssueID, err)
@@ -405,10 +447,18 @@ func (n *Notification) GetIssue() (*Issue, error) {
// HTMLURL formats a URL-string to the notification
func (n *Notification) HTMLURL() string {
- if n.Comment != nil {
- return n.Comment.HTMLURL()
+ switch n.Source {
+ case NotificationSourceIssue, NotificationSourcePullRequest:
+ if n.Comment != nil {
+ return n.Comment.HTMLURL()
+ }
+ return n.Issue.HTMLURL()
+ case NotificationSourceCommit:
+ return n.Repository.HTMLURL() + "/commit/" + n.CommitID
+ case NotificationSourceRepository:
+ return n.Repository.HTMLURL()
}
- return n.Issue.HTMLURL()
+ return ""
}
// APIURL formats a URL-string to the notification
@@ -562,8 +612,10 @@ func (nl NotificationList) LoadIssues() ([]int, error) {
if notification.Issue == nil {
notification.Issue = issues[notification.IssueID]
if notification.Issue == nil {
- log.Error("Notification[%d]: IssueID: %d Not Found", notification.ID, notification.IssueID)
- failures = append(failures, i)
+ if notification.IssueID != 0 {
+ log.Error("Notification[%d]: IssueID: %d Not Found", notification.ID, notification.IssueID)
+ failures = append(failures, i)
+ }
continue
}
notification.Issue.Repo = notification.Repository
@@ -683,7 +735,7 @@ func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCoun
return res, x.SQL(sql, since, until, NotificationStatusUnread).Find(&res)
}
-func setNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
+func setIssueNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
notification, err := getIssueNotification(e, userID, issueID)
// ignore if not exists
if err != nil {
@@ -700,6 +752,16 @@ func setNotificationStatusReadIfUnread(e Engine, userID, issueID int64) error {
return err
}
+func setRepoNotificationStatusReadIfUnread(e Engine, userID, repoID int64) error {
+ _, err := e.Where(builder.Eq{
+ "user_id": userID,
+ "status": NotificationStatusUnread,
+ "source": NotificationSourceRepository,
+ "repo_id": repoID,
+ }).Cols("status").Update(&Notification{Status: NotificationStatusRead})
+ return err
+}
+
// SetNotificationStatus change the notification status
func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) error {
notification, err := getNotificationByID(x, notificationID)
diff --git a/models/org.go b/models/org.go
index ee867eec88..437d57d056 100644
--- a/models/org.go
+++ b/models/org.go
@@ -391,6 +391,20 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
Exist(new(Team))
}
+// GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization
+func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) {
+ return getUsersWhoCanCreateOrgRepo(x, orgID)
+}
+
+func getUsersWhoCanCreateOrgRepo(e Engine, orgID int64) ([]*User, error) {
+ users := make([]*User, 0, 10)
+ return users, x.
+ 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": AccessModeOwner})).
+ And("team_user.org_id = ?", orgID).Asc("`user`.name").Find(&users)
+}
+
func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
orgs := make([]*User, 0, 10)
if !showAll {
diff --git a/models/org_test.go b/models/org_test.go
index 79f8b060e7..45268f0f23 100644
--- a/models/org_test.go
+++ b/models/org_test.go
@@ -635,3 +635,21 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) {
assert.Equal(t, test2, false) // user not a part of org
assert.Equal(t, test3, false) // logged out user
}
+
+func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) {
+ assert.NoError(t, PrepareTestDatabase())
+
+ users, err := GetUsersWhoCanCreateOrgRepo(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(7)
+ assert.NoError(t, err)
+ assert.Len(t, users, 1)
+ assert.EqualValues(t, 5, users[0].ID)
+}
diff --git a/models/repo.go b/models/repo.go
index 6cb6f38a48..2c71fc3e1e 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -139,8 +139,9 @@ type RepositoryStatus int
// all kinds of RepositoryStatus
const (
- RepositoryReady RepositoryStatus = iota // a normal repository
- RepositoryBeingMigrated // repository is migrating
+ RepositoryReady RepositoryStatus = iota // a normal repository
+ RepositoryBeingMigrated // repository is migrating
+ RepositoryPendingTransfer // repository pending in ownership transfer state
)
// TrustModelType defines the types of trust model for this repository
@@ -872,6 +873,11 @@ func (repo *Repository) DescriptionHTML() template.HTML {
return template.HTML(markup.Sanitize(string(desc)))
}
+// ReadBy sets repo to be visited by given user.
+func (repo *Repository) ReadBy(userID int64) error {
+ return setRepoNotificationStatusReadIfUnread(x, userID, repo.ID)
+}
+
func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
has, err := e.Get(&Repository{
OwnerID: u.ID,
@@ -1189,140 +1195,6 @@ func IncrementRepoForkNum(ctx DBContext, repoID int64) error {
return err
}
-// TransferOwnership transfers all corresponding setting from old user to new one.
-func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
- newOwner, err := GetUserByName(newOwnerName)
- if err != nil {
- return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
- }
-
- // Check if new owner has repository with same name.
- has, err := IsRepositoryExist(newOwner, repo.Name)
- if err != nil {
- return fmt.Errorf("IsRepositoryExist: %v", err)
- } else if has {
- return ErrRepoAlreadyExist{newOwnerName, repo.Name}
- }
-
- sess := x.NewSession()
- defer sess.Close()
- if err = sess.Begin(); err != nil {
- return fmt.Errorf("sess.Begin: %v", err)
- }
-
- oldOwner := repo.Owner
-
- // Note: we have to set value here to make sure recalculate accesses is based on
- // new owner.
- repo.OwnerID = newOwner.ID
- repo.Owner = newOwner
- repo.OwnerName = newOwner.Name
-
- // Update repository.
- if _, err := sess.ID(repo.ID).Update(repo); err != nil {
- return fmt.Errorf("update owner: %v", err)
- }
-
- // Remove redundant collaborators.
- collaborators, err := repo.getCollaborators(sess, ListOptions{})
- if err != nil {
- return fmt.Errorf("getCollaborators: %v", err)
- }
-
- // Dummy object.
- collaboration := &Collaboration{RepoID: repo.ID}
- for _, c := range collaborators {
- if c.ID != newOwner.ID {
- isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
- if err != nil {
- return fmt.Errorf("IsOrgMember: %v", err)
- } else if !isMember {
- continue
- }
- }
- collaboration.UserID = c.ID
- if _, err = sess.Delete(collaboration); err != nil {
- return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
- }
- }
-
- // Remove old team-repository relations.
- if oldOwner.IsOrganization() {
- if err = oldOwner.removeOrgRepo(sess, repo.ID); err != nil {
- return fmt.Errorf("removeOrgRepo: %v", err)
- }
- }
-
- if newOwner.IsOrganization() {
- if err := newOwner.getTeams(sess); err != nil {
- return fmt.Errorf("GetTeams: %v", err)
- }
- for _, t := range newOwner.Teams {
- if t.IncludesAllRepositories {
- if err := t.addRepository(sess, repo); err != nil {
- return fmt.Errorf("addRepository: %v", err)
- }
- }
- }
- } else if err = repo.recalculateAccesses(sess); err != nil {
- // Organization called this in addRepository method.
- return fmt.Errorf("recalculateAccesses: %v", err)
- }
-
- // Update repository count.
- if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
- return fmt.Errorf("increase new owner repository count: %v", err)
- } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", oldOwner.ID); err != nil {
- return fmt.Errorf("decrease old owner repository count: %v", err)
- }
-
- if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
- return fmt.Errorf("watchRepo: %v", err)
- }
-
- // Remove watch for organization.
- if oldOwner.IsOrganization() {
- if err = watchRepo(sess, oldOwner.ID, repo.ID, false); err != nil {
- return fmt.Errorf("watchRepo [false]: %v", err)
- }
- }
-
- // Rename remote repository to new path and delete local copy.
- dir := UserPath(newOwner.Name)
-
- if err := os.MkdirAll(dir, os.ModePerm); err != nil {
- return fmt.Errorf("Failed to create dir %s: %v", dir, err)
- }
-
- if err = os.Rename(RepoPath(oldOwner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
- return fmt.Errorf("rename repository directory: %v", err)
- }
-
- // Rename remote wiki repository to new path and delete local copy.
- wikiPath := WikiPath(oldOwner.Name, repo.Name)
- isExist, err := util.IsExist(wikiPath)
- if err != nil {
- log.Error("Unable to check if %s exists. Error: %v", wikiPath, err)
- return err
- }
- if isExist {
- if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
- return fmt.Errorf("rename repository wiki: %v", err)
- }
- }
-
- // If there was previously a redirect at this location, remove it.
- if err = deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
- return fmt.Errorf("delete repo redirect: %v", err)
- }
-
- if err := newRepoRedirect(sess, oldOwner.ID, repo.ID, repo.Name, repo.Name); err != nil {
- return fmt.Errorf("newRepoRedirect: %v", err)
- }
-
- return sess.Commit()
-}
-
// ChangeRepositoryName changes all corresponding setting from old repository name to new one.
func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err error) {
oldRepoName := repo.Name
diff --git a/models/repo_transfer.go b/models/repo_transfer.go
new file mode 100644
index 0000000000..cf1e16b9c3
--- /dev/null
+++ b/models/repo_transfer.go
@@ -0,0 +1,335 @@
+// 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 models
+
+import (
+ "fmt"
+ "os"
+
+ "code.gitea.io/gitea/modules/log"
+ "code.gitea.io/gitea/modules/timeutil"
+ "code.gitea.io/gitea/modules/util"
+)
+
+// RepoTransfer is used to manage repository transfers
+type RepoTransfer struct {
+ ID int64 `xorm:"pk autoincr"`
+ DoerID int64
+ Doer *User `xorm:"-"`
+ RecipientID int64
+ Recipient *User `xorm:"-"`
+ RepoID int64
+ TeamIDs []int64
+ Teams []*Team `xorm:"-"`
+
+ CreatedUnix timeutil.TimeStamp `xorm:"INDEX NOT NULL created"`
+ UpdatedUnix timeutil.TimeStamp `xorm:"INDEX NOT NULL updated"`
+}
+
+// LoadAttributes fetches the transfer recipient from the database
+func (r *RepoTransfer) LoadAttributes() error {
+ if r.Recipient == nil {
+ u, err := GetUserByID(r.RecipientID)
+ if err != nil {
+ return err
+ }
+
+ r.Recipient = u
+ }
+
+ if r.Recipient.IsOrganization() && len(r.TeamIDs) != len(r.Teams) {
+
+ for _, v := range r.TeamIDs {
+ team, err := GetTeamByID(v)
+ if err != nil {
+ return err
+ }
+
+ if team.OrgID != r.Recipient.ID {
+ return fmt.Errorf("team %d belongs not to org %d", v, r.Recipient.ID)
+ }
+
+ r.Teams = append(r.Teams, team)
+ }
+ }
+
+ if r.Doer == nil {
+ u, err := GetUserByID(r.DoerID)
+ if err != nil {
+ return err
+ }
+
+ r.Doer = u
+ }
+
+ return nil
+}
+
+// CanUserAcceptTransfer checks if the user has the rights to accept/decline a repo transfer.
+// For user, it checks if it's himself
+// For organizations, it checks if the user is able to create repos
+func (r *RepoTransfer) CanUserAcceptTransfer(u *User) bool {
+ if err := r.LoadAttributes(); err != nil {
+ log.Error("LoadAttributes: %v", err)
+ return false
+ }
+
+ if !r.Recipient.IsOrganization() {
+ return r.RecipientID == u.ID
+ }
+
+ allowed, err := CanCreateOrgRepo(r.RecipientID, u.ID)
+ if err != nil {
+ log.Error("CanCreateOrgRepo: %v", err)
+ return false
+ }
+
+ return allowed
+}
+
+// GetPendingRepositoryTransfer fetches the most recent and ongoing transfer
+// process for the repository
+func GetPendingRepositoryTransfer(repo *Repository) (*RepoTransfer, error) {
+ var transfer = new(RepoTransfer)
+
+ has, err := x.Where("repo_id = ? ", repo.ID).Get(transfer)
+ if err != nil {
+ return nil, err
+ }
+
+ if !has {
+ return nil, ErrNoPendingRepoTransfer{RepoID: repo.ID}
+ }
+
+ return transfer, nil
+}
+
+func deleteRepositoryTransfer(e Engine, repoID int64) error {
+ _, err := e.Where("repo_id = ?", repoID).Delete(&RepoTransfer{})
+ return err
+}
+
+// CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry,
+// thus cancel the transfer process.
+func CancelRepositoryTransfer(repo *Repository) error {
+ sess := x.NewSession()
+ defer sess.Close()
+ if err := sess.Begin(); err != nil {
+ return err
+ }
+
+ repo.Status = RepositoryReady
+ if err := updateRepositoryCols(sess, repo, "status"); err != nil {
+ return err
+ }
+
+ if err := deleteRepositoryTransfer(sess, repo.ID); err != nil {
+ return err
+ }
+
+ return sess.Commit()
+}
+
+// TestRepositoryReadyForTransfer make sure repo is ready to transfer
+func TestRepositoryReadyForTransfer(status RepositoryStatus) error {
+ switch status {
+ case RepositoryBeingMigrated:
+ return fmt.Errorf("repo is not ready, currently migrating")
+ case RepositoryPendingTransfer:
+ return ErrRepoTransferInProgress{}
+ }
+ return nil
+}
+
+// CreatePendingRepositoryTransfer transfer a repo from one owner to a new one.
+// it marks the repository transfer as "pending"
+func CreatePendingRepositoryTransfer(doer, newOwner *User, repoID int64, teams []*Team) error {
+ sess := x.NewSession()
+ defer sess.Close()
+ if err := sess.Begin(); err != nil {
+ return err
+ }
+
+ repo, err := getRepositoryByID(sess, repoID)
+ if err != nil {
+ return err
+ }
+
+ // Make sure repo is ready to transfer
+ if err := TestRepositoryReadyForTransfer(repo.Status); err != nil {
+ return err
+ }
+
+ repo.Status = RepositoryPendingTransfer
+ if err := updateRepositoryCols(sess, repo, "status"); err != nil {
+ return err
+ }
+
+ // Check if new owner has repository with same name.
+ if has, err := isRepositoryExist(sess, newOwner, repo.Name); err != nil {
+ return fmt.Errorf("IsRepositoryExist: %v", err)
+ } else if has {
+ return ErrRepoAlreadyExist{newOwner.LowerName, repo.Name}
+ }
+
+ transfer := &RepoTransfer{
+ RepoID: repo.ID,
+ RecipientID: newOwner.ID,
+ CreatedUnix: timeutil.TimeStampNow(),
+ UpdatedUnix: timeutil.TimeStampNow(),
+ DoerID: doer.ID,
+ TeamIDs: make([]int64, 0, len(teams)),
+ }
+
+ for k := range teams {
+ transfer.TeamIDs = append(transfer.TeamIDs, teams[k].ID)
+ }
+
+ if _, err := sess.Insert(transfer); err != nil {
+ return err
+ }
+
+ return sess.Commit()
+}
+
+// TransferOwnership transfers all corresponding repository items from old user to new one.
+func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
+ sess := x.NewSession()
+ defer sess.Close()
+ if err := sess.Begin(); err != nil {
+ return fmt.Errorf("sess.Begin: %v", err)
+ }
+
+ newOwner, err := getUserByName(sess, newOwnerName)
+ if err != nil {
+ return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
+ }
+
+ // Check if new owner has repository with same name.
+ if has, err := isRepositoryExist(sess, newOwner, repo.Name); err != nil {
+ return fmt.Errorf("IsRepositoryExist: %v", err)
+ } else if has {
+ return ErrRepoAlreadyExist{newOwnerName, repo.Name}
+ }
+
+ oldOwner := repo.Owner
+
+ // Note: we have to set value here to make sure recalculate accesses is based on
+ // new owner.
+ repo.OwnerID = newOwner.ID
+ repo.Owner = newOwner
+ repo.OwnerName = newOwner.Name
+
+ // Update repository.
+ if _, err := sess.ID(repo.ID).Update(repo); err != nil {
+ return fmt.Errorf("update owner: %v", err)
+ }
+
+ // Remove redundant collaborators.
+ collaborators, err := repo.getCollaborators(sess, ListOptions{})
+ if err != nil {
+ return fmt.Errorf("getCollaborators: %v", err)
+ }
+
+ // Dummy object.
+ collaboration := &Collaboration{RepoID: repo.ID}
+ for _, c := range collaborators {
+ if c.ID != newOwner.ID {
+ isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
+ if err != nil {
+ return fmt.Errorf("IsOrgMember: %v", err)
+ } else if !isMember {
+ continue
+ }
+ }
+ collaboration.UserID = c.ID
+ if _, err := sess.Delete(collaboration); err != nil {
+ return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
+ }
+ }
+
+ // Remove old team-repository relations.
+ if oldOwner.IsOrganization() {
+ if err := oldOwner.removeOrgRepo(sess, repo.ID); err != nil {
+ return fmt.Errorf("removeOrgRepo: %v", err)
+ }
+ }
+
+ if newOwner.IsOrganization() {
+ if err := newOwner.getTeams(sess); err != nil {
+ return fmt.Errorf("GetTeams: %v", err)
+ }
+ for _, t := range newOwner.Teams {
+ if t.IncludesAllRepositories {
+ if err := t.addRepository(sess, repo); err != nil {
+ return fmt.Errorf("addRepository: %v", err)
+ }
+ }
+ }
+ } else if err := repo.recalculateAccesses(sess); err != nil {
+ // Organization called this in addRepository method.
+ return fmt.Errorf("recalculateAccesses: %v", err)
+ }
+
+ // Update repository count.
+ if _, err := sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
+ return fmt.Errorf("increase new owner repository count: %v", err)
+ } else if _, err := sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", oldOwner.ID); err != nil {
+ return fmt.Errorf("decrease old owner repository count: %v", err)
+ }
+
+ if err := watchRepo(sess, doer.ID, repo.ID, true); err != nil {
+ return fmt.Errorf("watchRepo: %v", err)
+ }
+
+ // Remove watch for organization.
+ if oldOwner.IsOrganization() {
+ if err := watchRepo(sess, oldOwner.ID, repo.ID, false); err != nil {
+ return fmt.Errorf("watchRepo [false]: %v", err)
+ }
+ }
+
+ // Rename remote repository to new path and delete local copy.
+ dir := UserPath(newOwner.Name)
+
+ if err := os.MkdirAll(dir, os.ModePerm); err != nil {
+ return fmt.Errorf("Failed to create dir %s: %v", dir, err)
+ }
+
+ if err := os.Rename(RepoPath(oldOwner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
+ return fmt.Errorf("rename repository directory: %v", err)
+ }
+
+ // Rename remote wiki repository to new path and delete local copy.
+ wikiPath := WikiPath(oldOwner.Name, repo.Name)
+
+ if isExist, err := util.IsExist(wikiPath); err != nil {
+ log.Error("Unable to check if %s exists. Error: %v", wikiPath, err)
+ return err
+ } else if isExist {
+ if err := os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
+ return fmt.Errorf("rename repository wiki: %v", err)
+ }
+ }
+
+ if err := deleteRepositoryTransfer(sess, repo.ID); err != nil {
+ return fmt.Errorf("deleteRepositoryTransfer: %v", err)
+ }
+ repo.Status = RepositoryReady
+ if err := updateRepositoryCols(sess, repo, "status"); err != nil {
+ return err
+ }
+
+ // If there was previously a redirect at this location, remove it.
+ if err := deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
+ return fmt.Errorf("delete repo redirect: %v", err)
+ }
+
+ if err := newRepoRedirect(sess, oldOwner.ID, repo.ID, repo.Name, repo.Name); err != nil {
+ return fmt.Errorf("newRepoRedirect: %v", err)
+ }
+
+ return sess.Commit()
+}
diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go
new file mode 100644
index 0000000000..55aedac95d
--- /dev/null
+++ b/models/repo_transfer_test.go
@@ -0,0 +1,54 @@
+// 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 models
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRepositoryTransfer(t *testing.T) {
+
+ assert.NoError(t, PrepareTestDatabase())
+
+ doer := AssertExistsAndLoadBean(t, &User{ID: 3}).(*User)
+ repo := AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
+
+ transfer, err := GetPendingRepositoryTransfer(repo)
+ assert.NoError(t, err)
+ assert.NotNil(t, transfer)
+
+ // Cancel transfer
+ assert.NoError(t, CancelRepositoryTransfer(repo))
+
+ transfer, err = GetPendingRepositoryTransfer(repo)
+ assert.Error(t, err)
+ assert.Nil(t, transfer)
+ assert.True(t, IsErrNoPendingTransfer(err))
+
+ user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
+
+ assert.NoError(t, CreatePendingRepositoryTransfer(doer, user2, repo.ID, nil))
+
+ transfer, err = GetPendingRepositoryTransfer(repo)
+ assert.Nil(t, err)
+ assert.NoError(t, transfer.LoadAttributes())
+ assert.Equal(t, "user2", transfer.Recipient.Name)
+
+ user6 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
+
+ // Only transfer can be started at any given time
+ err = CreatePendingRepositoryTransfer(doer, user6, repo.ID, nil)
+ assert.Error(t, err)
+ assert.True(t, IsErrRepoTransferInProgress(err))
+
+ // Unknown user
+ err = CreatePendingRepositoryTransfer(doer, &User{ID: 1000, LowerName: "user1000"}, repo.ID, nil)
+ assert.Error(t, err)
+
+ // Cancel transfer
+ assert.NoError(t, CancelRepositoryTransfer(repo))
+}