diff options
author | KN4CK3R <admin@oldschoolhack.me> | 2021-11-18 18:42:27 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-19 01:42:27 +0800 |
commit | f34151bdb22c8160b0a6eafef20725ebae1768da (patch) | |
tree | 2abcc5845e4a9cf3769deb27ba5a3ecccd2ad8c9 /services/user | |
parent | 55be5fe3399d18b7d2477519707aecf5f99f1de5 (diff) | |
download | gitea-f34151bdb22c8160b0a6eafef20725ebae1768da.tar.gz gitea-f34151bdb22c8160b0a6eafef20725ebae1768da.zip |
Move user/org deletion to services (#17673)
Diffstat (limited to 'services/user')
-rw-r--r-- | services/user/user.go | 106 | ||||
-rw-r--r-- | services/user/user_test.go | 101 |
2 files changed, 207 insertions, 0 deletions
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)) + } +} |