code.gitea.io/gitea@v1.21.7/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  	); err != nil {
    96  		return fmt.Errorf("deleteBeans: %w", err)
    97  	}
    98  
    99  	if err := auth_model.DeleteOAuth2RelictsByUserID(ctx, u.ID); err != nil {
   100  		return err
   101  	}
   102  
   103  	if purge || (setting.Service.UserDeleteWithCommentsMaxTime != 0 &&
   104  		u.CreatedUnix.AsTime().Add(setting.Service.UserDeleteWithCommentsMaxTime).After(time.Now())) {
   105  
   106  		// Delete Comments
   107  		const batchSize = 50
   108  		for {
   109  			comments := make([]*issues_model.Comment, 0, batchSize)
   110  			if err = e.Where("type=? AND poster_id=?", issues_model.CommentTypeComment, u.ID).Limit(batchSize, 0).Find(&comments); err != nil {
   111  				return err
   112  			}
   113  			if len(comments) == 0 {
   114  				break
   115  			}
   116  
   117  			for _, comment := range comments {
   118  				if err = issues_model.DeleteComment(ctx, comment); err != nil {
   119  					return err
   120  				}
   121  			}
   122  		}
   123  
   124  		// Delete Reactions
   125  		if err = issues_model.DeleteReaction(ctx, &issues_model.ReactionOptions{DoerID: u.ID}); err != nil {
   126  			return err
   127  		}
   128  	}
   129  
   130  	// ***** START: Branch Protections *****
   131  	{
   132  		const batchSize = 50
   133  		for start := 0; ; start += batchSize {
   134  			protections := make([]*git_model.ProtectedBranch, 0, batchSize)
   135  			// @perf: We can't filter on DB side by u.ID, as those IDs are serialized as JSON strings.
   136  			//   We could filter down with `WHERE repo_id IN (reposWithPushPermission(u))`,
   137  			//   though that query will be quite complex and tricky to maintain (compare `getRepoAssignees()`).
   138  			// Also, as we didn't update branch protections when removing entries from `access` table,
   139  			//   it's safer to iterate all protected branches.
   140  			if err = e.Limit(batchSize, start).Find(&protections); err != nil {
   141  				return fmt.Errorf("findProtectedBranches: %w", err)
   142  			}
   143  			if len(protections) == 0 {
   144  				break
   145  			}
   146  			for _, p := range protections {
   147  				if err := git_model.RemoveUserIDFromProtectedBranch(ctx, p, u.ID); err != nil {
   148  					return err
   149  				}
   150  			}
   151  		}
   152  	}
   153  	// ***** END: Branch Protections *****
   154  
   155  	// ***** START: PublicKey *****
   156  	if _, err = db.DeleteByBean(ctx, &asymkey_model.PublicKey{OwnerID: u.ID}); err != nil {
   157  		return fmt.Errorf("deletePublicKeys: %w", err)
   158  	}
   159  	// ***** END: PublicKey *****
   160  
   161  	// ***** START: GPGPublicKey *****
   162  	keys, err := asymkey_model.ListGPGKeys(ctx, u.ID, db.ListOptions{})
   163  	if err != nil {
   164  		return fmt.Errorf("ListGPGKeys: %w", err)
   165  	}
   166  	// Delete GPGKeyImport(s).
   167  	for _, key := range keys {
   168  		if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKeyImport{KeyID: key.KeyID}); err != nil {
   169  			return fmt.Errorf("deleteGPGKeyImports: %w", err)
   170  		}
   171  	}
   172  	if _, err = db.DeleteByBean(ctx, &asymkey_model.GPGKey{OwnerID: u.ID}); err != nil {
   173  		return fmt.Errorf("deleteGPGKeys: %w", err)
   174  	}
   175  	// ***** END: GPGPublicKey *****
   176  
   177  	// Clear assignee.
   178  	if _, err = db.DeleteByBean(ctx, &issues_model.IssueAssignees{AssigneeID: u.ID}); err != nil {
   179  		return fmt.Errorf("clear assignee: %w", err)
   180  	}
   181  
   182  	// ***** START: ExternalLoginUser *****
   183  	if err = user_model.RemoveAllAccountLinks(ctx, u); err != nil {
   184  		return fmt.Errorf("ExternalLoginUser: %w", err)
   185  	}
   186  	// ***** END: ExternalLoginUser *****
   187  
   188  	if _, err = db.DeleteByID(ctx, u.ID, new(user_model.User)); err != nil {
   189  		return fmt.Errorf("delete: %w", err)
   190  	}
   191  
   192  	return nil
   193  }