code.gitea.io/gitea@v1.22.3/services/user/delete.go (about)

     1  // Copyright 2023 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package user
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"time"
    10  
    11  	_ "image/jpeg" // Needed for jpeg support
    12  
    13  	actions_model "code.gitea.io/gitea/models/actions"
    14  	activities_model "code.gitea.io/gitea/models/activities"
    15  	asymkey_model "code.gitea.io/gitea/models/asymkey"
    16  	auth_model "code.gitea.io/gitea/models/auth"
    17  	"code.gitea.io/gitea/models/db"
    18  	git_model "code.gitea.io/gitea/models/git"
    19  	issues_model "code.gitea.io/gitea/models/issues"
    20  	"code.gitea.io/gitea/models/organization"
    21  	access_model "code.gitea.io/gitea/models/perm/access"
    22  	pull_model "code.gitea.io/gitea/models/pull"
    23  	repo_model "code.gitea.io/gitea/models/repo"
    24  	user_model "code.gitea.io/gitea/models/user"
    25  	"code.gitea.io/gitea/modules/setting"
    26  
    27  	"xorm.io/builder"
    28  )
    29  
    30  // deleteUser deletes models associated to an user.
    31  func deleteUser(ctx context.Context, u *user_model.User, purge bool) (err error) {
    32  	e := db.GetEngine(ctx)
    33  
    34  	// ***** START: Watch *****
    35  	watchedRepoIDs, err := db.FindIDs(ctx, "watch", "watch.repo_id",
    36  		builder.Eq{"watch.user_id": u.ID}.
    37  			And(builder.Neq{"watch.mode": repo_model.WatchModeDont}))
    38  	if err != nil {
    39  		return fmt.Errorf("get all watches: %w", err)
    40  	}
    41  	if err = db.DecrByIDs(ctx, watchedRepoIDs, "num_watches", new(repo_model.Repository)); err != nil {
    42  		return fmt.Errorf("decrease repository num_watches: %w", err)
    43  	}
    44  	// ***** END: Watch *****
    45  
    46  	// ***** START: Star *****
    47  	starredRepoIDs, err := db.FindIDs(ctx, "star", "star.repo_id",
    48  		builder.Eq{"star.uid": u.ID})
    49  	if err != nil {
    50  		return fmt.Errorf("get all stars: %w", err)
    51  	} else if err = db.DecrByIDs(ctx, starredRepoIDs, "num_stars", new(repo_model.Repository)); err != nil {
    52  		return fmt.Errorf("decrease repository num_stars: %w", err)
    53  	}
    54  	// ***** END: Star *****
    55  
    56  	// ***** START: Follow *****
    57  	followeeIDs, err := db.FindIDs(ctx, "follow", "follow.follow_id",
    58  		builder.Eq{"follow.user_id": u.ID})
    59  	if err != nil {
    60  		return fmt.Errorf("get all followees: %w", err)
    61  	} else if err = db.DecrByIDs(ctx, followeeIDs, "num_followers", new(user_model.User)); err != nil {
    62  		return fmt.Errorf("decrease user num_followers: %w", err)
    63  	}
    64  
    65  	followerIDs, err := db.FindIDs(ctx, "follow", "follow.user_id",
    66  		builder.Eq{"follow.follow_id": u.ID})
    67  	if err != nil {
    68  		return fmt.Errorf("get all followers: %w", err)
    69  	} else if err = db.DecrByIDs(ctx, followerIDs, "num_following", new(user_model.User)); err != nil {
    70  		return fmt.Errorf("decrease user num_following: %w", err)
    71  	}
    72  	// ***** END: Follow *****
    73  
    74  	if err = db.DeleteBeans(ctx,
    75  		&auth_model.AccessToken{UID: u.ID},
    76  		&repo_model.Collaboration{UserID: u.ID},
    77  		&access_model.Access{UserID: u.ID},
    78  		&repo_model.Watch{UserID: u.ID},
    79  		&repo_model.Star{UID: u.ID},
    80  		&user_model.Follow{UserID: u.ID},
    81  		&user_model.Follow{FollowID: u.ID},
    82  		&activities_model.Action{UserID: u.ID},
    83  		&issues_model.IssueUser{UID: u.ID},
    84  		&user_model.EmailAddress{UID: u.ID},
    85  		&user_model.UserOpenID{UID: u.ID},
    86  		&issues_model.Reaction{UserID: u.ID},
    87  		&organization.TeamUser{UID: u.ID},
    88  		&issues_model.Stopwatch{UserID: u.ID},
    89  		&user_model.Setting{UserID: u.ID},
    90  		&user_model.UserBadge{UserID: u.ID},
    91  		&pull_model.AutoMerge{DoerID: u.ID},
    92  		&pull_model.ReviewState{UserID: u.ID},
    93  		&user_model.Redirect{RedirectUserID: u.ID},
    94  		&actions_model.ActionRunner{OwnerID: u.ID},
    95  		&user_model.Blocking{BlockerID: u.ID},
    96  		&user_model.Blocking{BlockeeID: u.ID},
    97  		&actions_model.ActionRunnerToken{OwnerID: u.ID},
    98  	); err != nil {
    99  		return fmt.Errorf("deleteBeans: %w", err)
   100  	}
   101  
   102  	if err := auth_model.DeleteOAuth2RelictsByUserID(ctx, u.ID); err != nil {
   103  		return err
   104  	}
   105  
   106  	if purge || (setting.Service.UserDeleteWithCommentsMaxTime != 0 &&
   107  		u.CreatedUnix.AsTime().Add(setting.Service.UserDeleteWithCommentsMaxTime).After(time.Now())) {
   108  		// Delete Comments
   109  		const batchSize = 50
   110  		for {
   111  			comments := make([]*issues_model.Comment, 0, batchSize)
   112  			if err = e.Where("type=? AND poster_id=?", issues_model.CommentTypeComment, u.ID).Limit(batchSize, 0).Find(&comments); err != nil {
   113  				return err
   114  			}
   115  			if len(comments) == 0 {
   116  				break
   117  			}
   118  
   119  			for _, comment := range comments {
   120  				if err = issues_model.DeleteComment(ctx, comment); err != nil {
   121  					return err
   122  				}
   123  			}
   124  		}
   125  
   126  		// Delete Reactions
   127  		if err = issues_model.DeleteReaction(ctx, &issues_model.ReactionOptions{DoerID: u.ID}); err != nil {
   128  			return err
   129  		}
   130  	}
   131  
   132  	// ***** START: Branch Protections *****
   133  	{
   134  		const batchSize = 50
   135  		for start := 0; ; start += batchSize {
   136  			protections := make([]*git_model.ProtectedBranch, 0, batchSize)
   137  			// @perf: We can't filter on DB side by u.ID, as those IDs are serialized as JSON strings.
   138  			//   We could filter down with `WHERE repo_id IN (reposWithPushPermission(u))`,
   139  			//   though that query will be quite complex and tricky to maintain (compare `getRepoAssignees()`).
   140  			// Also, as we didn't update branch protections when removing entries from `access` table,
   141  			//   it's safer to iterate all protected branches.
   142  			if err = e.Limit(batchSize, start).Find(&protections); err != nil {
   143  				return fmt.Errorf("findProtectedBranches: %w", err)
   144  			}
   145  			if len(protections) == 0 {
   146  				break
   147  			}
   148  			for _, p := range protections {
   149  				if err := git_model.RemoveUserIDFromProtectedBranch(ctx, p, u.ID); err != nil {
   150  					return err
   151  				}
   152  			}
   153  		}
   154  	}
   155  	// ***** END: Branch Protections *****
   156  
   157  	// ***** START: PublicKey *****
   158  	if _, err = db.DeleteByBean(ctx, &asymkey_model.PublicKey{OwnerID: u.ID}); err != nil {
   159  		return fmt.Errorf("deletePublicKeys: %w", err)
   160  	}
   161  	// ***** END: PublicKey *****
   162  
   163  	// ***** START: GPGPublicKey *****
   164  	keys, err := db.Find[asymkey_model.GPGKey](ctx, asymkey_model.FindGPGKeyOptions{
   165  		OwnerID: u.ID,
   166  	})
   167  	if err != nil {
   168  		return fmt.Errorf("ListGPGKeys: %w", err)
   169  	}
   170  	// Delete GPGKeyImport(s).
   171  	for _, key := range keys {
   172  		if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKeyImport{KeyID: key.KeyID}); err != nil {
   173  			return fmt.Errorf("deleteGPGKeyImports: %w", err)
   174  		}
   175  	}
   176  	if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKey{OwnerID: u.ID}); err != nil {
   177  		return fmt.Errorf("deleteGPGKeys: %w", err)
   178  	}
   179  	// ***** END: GPGPublicKey *****
   180  
   181  	// Clear assignee.
   182  	if _, err = db.DeleteByBean(ctx, &issues_model.IssueAssignees{AssigneeID: u.ID}); err != nil {
   183  		return fmt.Errorf("clear assignee: %w", err)
   184  	}
   185  
   186  	// ***** START: ExternalLoginUser *****
   187  	if err = user_model.RemoveAllAccountLinks(ctx, u); err != nil {
   188  		return fmt.Errorf("ExternalLoginUser: %w", err)
   189  	}
   190  	// ***** END: ExternalLoginUser *****
   191  
   192  	if err := auth_model.DeleteAuthTokensByUserID(ctx, u.ID); err != nil {
   193  		return fmt.Errorf("DeleteAuthTokensByUserID: %w", err)
   194  	}
   195  
   196  	if _, err = db.DeleteByID[user_model.User](ctx, u.ID); err != nil {
   197  		return fmt.Errorf("delete: %w", err)
   198  	}
   199  
   200  	return nil
   201  }