summaryrefslogtreecommitdiffstats
path: root/services
diff options
context:
space:
mode:
authorKN4CK3R <admin@oldschoolhack.me>2021-11-18 18:42:27 +0100
committerGitHub <noreply@github.com>2021-11-19 01:42:27 +0800
commitf34151bdb22c8160b0a6eafef20725ebae1768da (patch)
tree2abcc5845e4a9cf3769deb27ba5a3ecccd2ad8c9 /services
parent55be5fe3399d18b7d2477519707aecf5f99f1de5 (diff)
downloadgitea-f34151bdb22c8160b0a6eafef20725ebae1768da.tar.gz
gitea-f34151bdb22c8160b0a6eafef20725ebae1768da.zip
Move user/org deletion to services (#17673)
Diffstat (limited to 'services')
-rw-r--r--services/cron/tasks.go6
-rw-r--r--services/cron/tasks_extended.go3
-rw-r--r--services/org/org.go61
-rw-r--r--services/org/org_test.go37
-rw-r--r--services/user/user.go106
-rw-r--r--services/user/user_test.go101
-rw-r--r--services/wiki/wiki.go3
7 files changed, 312 insertions, 5 deletions
diff --git a/services/cron/tasks.go b/services/cron/tasks.go
index d29bf6d6bd..732eead930 100644
--- a/services/cron/tasks.go
+++ b/services/cron/tasks.go
@@ -90,18 +90,18 @@ func (t *Task) RunWithUser(doer *models.User, config Config) {
if err := t.fun(ctx, doer, config); err != nil {
if db.IsErrCancelled(err) {
message := err.(db.ErrCancelled).Message
- if err := admin_model.CreateNotice(admin_model.NoticeTask, config.FormatMessage(t.Name, "aborted", doer, message)); err != nil {
+ if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage(t.Name, "aborted", doer, message)); err != nil {
log.Error("CreateNotice: %v", err)
}
return
}
- if err := admin_model.CreateNotice(admin_model.NoticeTask, config.FormatMessage(t.Name, "error", doer, err)); err != nil {
+ if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage(t.Name, "error", doer, err)); err != nil {
log.Error("CreateNotice: %v", err)
}
return
}
if config.DoNoticeOnSuccess() {
- if err := admin_model.CreateNotice(admin_model.NoticeTask, config.FormatMessage(t.Name, "finished", doer)); err != nil {
+ if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage(t.Name, "finished", doer)); err != nil {
log.Error("CreateNotice: %v", err)
}
}
diff --git a/services/cron/tasks_extended.go b/services/cron/tasks_extended.go
index 1f115de43a..b0cb5ee921 100644
--- a/services/cron/tasks_extended.go
+++ b/services/cron/tasks_extended.go
@@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/updatechecker"
repo_service "code.gitea.io/gitea/services/repository"
+ user_service "code.gitea.io/gitea/services/user"
)
func registerDeleteInactiveUsers() {
@@ -25,7 +26,7 @@ func registerDeleteInactiveUsers() {
OlderThan: 0 * time.Second,
}, func(ctx context.Context, _ *models.User, config Config) error {
olderThanConfig := config.(*OlderThanConfig)
- return models.DeleteInactiveUsers(ctx, olderThanConfig.OlderThan)
+ return user_service.DeleteInactiveUsers(ctx, olderThanConfig.OlderThan)
})
}
diff --git a/services/org/org.go b/services/org/org.go
new file mode 100644
index 0000000000..cb1f1eca03
--- /dev/null
+++ b/services/org/org.go
@@ -0,0 +1,61 @@
+// 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 org
+
+import (
+ "fmt"
+
+ "code.gitea.io/gitea/models"
+ "code.gitea.io/gitea/models/db"
+ "code.gitea.io/gitea/modules/storage"
+ "code.gitea.io/gitea/modules/util"
+)
+
+// DeleteOrganization completely and permanently deletes everything of organization.
+func DeleteOrganization(org *models.User) error {
+ if !org.IsOrganization() {
+ return fmt.Errorf("%s is a user not an organization", org.Name)
+ }
+
+ ctx, commiter, err := db.TxContext()
+ if err != nil {
+ return err
+ }
+ defer commiter.Close()
+
+ // Check ownership of repository.
+ count, err := models.GetRepositoryCount(ctx, org)
+ if err != nil {
+ return fmt.Errorf("GetRepositoryCount: %v", err)
+ } else if count > 0 {
+ return models.ErrUserOwnRepos{UID: org.ID}
+ }
+
+ if err := models.DeleteOrganization(ctx, org); err != nil {
+ return fmt.Errorf("DeleteOrganization: %v", err)
+ }
+
+ if err := commiter.Commit(); err != nil {
+ return err
+ }
+
+ // FIXME: system notice
+ // Note: There are something just cannot be roll back,
+ // so just keep error logs of those operations.
+ path := models.UserPath(org.Name)
+
+ if err := util.RemoveAll(path); err != nil {
+ return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
+ }
+
+ if len(org.Avatar) > 0 {
+ avatarPath := org.CustomAvatarRelativePath()
+ if err := storage.Avatars.Delete(avatarPath); err != nil {
+ return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
+ }
+ }
+
+ return nil
+}
diff --git a/services/org/org_test.go b/services/org/org_test.go
new file mode 100644
index 0000000000..5fec086d10
--- /dev/null
+++ b/services/org/org_test.go
@@ -0,0 +1,37 @@
+// 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 org
+
+import (
+ "path/filepath"
+ "testing"
+
+ "code.gitea.io/gitea/models"
+ "code.gitea.io/gitea/models/unittest"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestMain(m *testing.M) {
+ unittest.MainTest(m, filepath.Join("..", ".."))
+}
+
+func TestDeleteOrganization(t *testing.T) {
+ assert.NoError(t, unittest.PrepareTestDatabase())
+ org := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 6}).(*models.User)
+ assert.NoError(t, DeleteOrganization(org))
+ unittest.AssertNotExistsBean(t, &models.User{ID: 6})
+ unittest.AssertNotExistsBean(t, &models.OrgUser{OrgID: 6})
+ unittest.AssertNotExistsBean(t, &models.Team{OrgID: 6})
+
+ org = unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
+ err := DeleteOrganization(org)
+ assert.Error(t, err)
+ assert.True(t, models.IsErrUserOwnRepos(err))
+
+ user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
+ assert.Error(t, DeleteOrganization(user))
+ unittest.CheckConsistencyFor(t, &models.User{}, &models.Team{})
+}
diff --git a/services/user/user.go b/services/user/user.go
new file mode 100644
index 0000000000..a08e40f86e
--- /dev/null
+++ b/services/user/user.go
@@ -0,0 +1,106 @@
+// 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 user
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "code.gitea.io/gitea/models"
+ admin_model "code.gitea.io/gitea/models/admin"
+ "code.gitea.io/gitea/models/db"
+ user_model "code.gitea.io/gitea/models/user"
+ "code.gitea.io/gitea/modules/storage"
+ "code.gitea.io/gitea/modules/util"
+)
+
+// DeleteUser completely and permanently deletes everything of a user,
+// but issues/comments/pulls will be kept and shown as someone has been deleted,
+// unless the user is younger than USER_DELETE_WITH_COMMENTS_MAX_DAYS.
+func DeleteUser(u *models.User) error {
+ if u.IsOrganization() {
+ return fmt.Errorf("%s is an organization not a user", u.Name)
+ }
+
+ ctx, commiter, err := db.TxContext()
+ if err != nil {
+ return err
+ }
+ defer commiter.Close()
+
+ // Note: A user owns any repository or belongs to any organization
+ // cannot perform delete operation.
+
+ // Check ownership of repository.
+ count, err := models.GetRepositoryCount(ctx, u)
+ if err != nil {
+ return fmt.Errorf("GetRepositoryCount: %v", err)
+ } else if count > 0 {
+ return models.ErrUserOwnRepos{UID: u.ID}
+ }
+
+ // Check membership of organization.
+ count, err = models.GetOrganizationCount(ctx, u)
+ if err != nil {
+ return fmt.Errorf("GetOrganizationCount: %v", err)
+ } else if count > 0 {
+ return models.ErrUserHasOrgs{UID: u.ID}
+ }
+
+ if err := models.DeleteUser(ctx, u); err != nil {
+ return fmt.Errorf("DeleteUser: %v", err)
+ }
+
+ if err := commiter.Commit(); err != nil {
+ return err
+ }
+
+ // Note: There are something just cannot be roll back,
+ // so just keep error logs of those operations.
+ path := models.UserPath(u.Name)
+ if err := util.RemoveAll(path); err != nil {
+ err = fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
+ _ = admin_model.CreateNotice(db.DefaultContext, admin_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err))
+ return err
+ }
+
+ if u.Avatar != "" {
+ avatarPath := u.CustomAvatarRelativePath()
+ if err := storage.Avatars.Delete(avatarPath); err != nil {
+ err = fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
+ _ = admin_model.CreateNotice(db.DefaultContext, admin_model.NoticeTask, fmt.Sprintf("delete user '%s': %v", u.Name, err))
+ return err
+ }
+ }
+
+ return nil
+}
+
+// DeleteInactiveUsers deletes all inactive users and email addresses.
+func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) error {
+ users, err := models.GetInactiveUsers(ctx, olderThan)
+ if err != nil {
+ return err
+ }
+
+ // FIXME: should only update authorized_keys file once after all deletions.
+ for _, u := range users {
+ select {
+ case <-ctx.Done():
+ return db.ErrCancelledf("Before delete inactive user %s", u.Name)
+ default:
+ }
+ if err := DeleteUser(u); err != nil {
+ // Ignore users that were set inactive by admin.
+ if models.IsErrUserOwnRepos(err) || models.IsErrUserHasOrgs(err) {
+ continue
+ }
+ return err
+ }
+ }
+
+ return user_model.DeleteInactiveEmailAddresses(ctx)
+}
diff --git a/services/user/user_test.go b/services/user/user_test.go
new file mode 100644
index 0000000000..9162273fae
--- /dev/null
+++ b/services/user/user_test.go
@@ -0,0 +1,101 @@
+// 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 user
+
+import (
+ "path/filepath"
+ "testing"
+
+ "code.gitea.io/gitea/models"
+ "code.gitea.io/gitea/models/db"
+ "code.gitea.io/gitea/models/unittest"
+ "code.gitea.io/gitea/modules/setting"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestMain(m *testing.M) {
+ unittest.MainTest(m, filepath.Join("..", ".."))
+}
+
+func TestDeleteUser(t *testing.T) {
+ test := func(userID int64) {
+ assert.NoError(t, unittest.PrepareTestDatabase())
+ user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: userID}).(*models.User)
+
+ ownedRepos := make([]*models.Repository, 0, 10)
+ assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &models.Repository{OwnerID: userID}))
+ if len(ownedRepos) > 0 {
+ err := DeleteUser(user)
+ assert.Error(t, err)
+ assert.True(t, models.IsErrUserOwnRepos(err))
+ return
+ }
+
+ orgUsers := make([]*models.OrgUser, 0, 10)
+ assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &models.OrgUser{UID: userID}))
+ for _, orgUser := range orgUsers {
+ if err := models.RemoveOrgUser(orgUser.OrgID, orgUser.UID); err != nil {
+ assert.True(t, models.IsErrLastOrgOwner(err))
+ return
+ }
+ }
+ assert.NoError(t, DeleteUser(user))
+ unittest.AssertNotExistsBean(t, &models.User{ID: userID})
+ unittest.CheckConsistencyFor(t, &models.User{}, &models.Repository{})
+ }
+ test(2)
+ test(4)
+ test(8)
+ test(11)
+
+ org := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
+ assert.Error(t, DeleteUser(org))
+}
+
+func TestCreateUser(t *testing.T) {
+ user := &models.User{
+ Name: "GiteaBot",
+ Email: "GiteaBot@gitea.io",
+ Passwd: ";p['////..-++']",
+ IsAdmin: false,
+ Theme: setting.UI.DefaultTheme,
+ MustChangePassword: false,
+ }
+
+ assert.NoError(t, models.CreateUser(user))
+
+ assert.NoError(t, DeleteUser(user))
+}
+
+func TestCreateUser_Issue5882(t *testing.T) {
+ // Init settings
+ _ = setting.Admin
+
+ passwd := ".//.;1;;//.,-=_"
+
+ tt := []struct {
+ user *models.User
+ disableOrgCreation bool
+ }{
+ {&models.User{Name: "GiteaBot", Email: "GiteaBot@gitea.io", Passwd: passwd, MustChangePassword: false}, false},
+ {&models.User{Name: "GiteaBot2", Email: "GiteaBot2@gitea.io", Passwd: passwd, MustChangePassword: false}, true},
+ }
+
+ setting.Service.DefaultAllowCreateOrganization = true
+
+ for _, v := range tt {
+ setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation
+
+ assert.NoError(t, models.CreateUser(v.user))
+
+ u, err := models.GetUserByEmail(v.user.Email)
+ assert.NoError(t, err)
+
+ assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation)
+
+ assert.NoError(t, DeleteUser(v.user))
+ }
+}
diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go
index 2db982a50f..4c8d7dbc53 100644
--- a/services/wiki/wiki.go
+++ b/services/wiki/wiki.go
@@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models"
admin_model "code.gitea.io/gitea/models/admin"
+ "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
@@ -375,6 +376,6 @@ func DeleteWiki(repo *models.Repository) error {
return err
}
- admin_model.RemoveAllWithNotice("Delete repository wiki", repo.WikiPath())
+ admin_model.RemoveAllWithNotice(db.DefaultContext, "Delete repository wiki", repo.WikiPath())
return nil
}