code.gitea.io/gitea@v1.21.7/services/asymkey/ssh_key.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package asymkey
     5  
     6  import (
     7  	"context"
     8  
     9  	asymkey_model "code.gitea.io/gitea/models/asymkey"
    10  	"code.gitea.io/gitea/models/db"
    11  	user_model "code.gitea.io/gitea/models/user"
    12  )
    13  
    14  // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
    15  func DeletePublicKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
    16  	key, err := asymkey_model.GetPublicKeyByID(id)
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	// Check if user has access to delete this key.
    22  	if !doer.IsAdmin && doer.ID != key.OwnerID {
    23  		return asymkey_model.ErrKeyAccessDenied{
    24  			UserID: doer.ID,
    25  			KeyID:  key.ID,
    26  			Note:   "public",
    27  		}
    28  	}
    29  
    30  	dbCtx, committer, err := db.TxContext(ctx)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	defer committer.Close()
    35  
    36  	if err = asymkey_model.DeletePublicKeys(dbCtx, id); err != nil {
    37  		return err
    38  	}
    39  
    40  	if err = committer.Commit(); err != nil {
    41  		return err
    42  	}
    43  	committer.Close()
    44  
    45  	if key.Type == asymkey_model.KeyTypePrincipal {
    46  		return asymkey_model.RewriteAllPrincipalKeys(ctx)
    47  	}
    48  
    49  	return asymkey_model.RewriteAllPublicKeys(ctx)
    50  }