code.gitea.io/gitea@v1.22.3/services/asymkey/ssh_key_principals.go (about)

     1  // Copyright 2024 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package asymkey
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  
    10  	asymkey_model "code.gitea.io/gitea/models/asymkey"
    11  	"code.gitea.io/gitea/models/db"
    12  	"code.gitea.io/gitea/models/perm"
    13  )
    14  
    15  // AddPrincipalKey adds new principal to database and authorized_principals file.
    16  func AddPrincipalKey(ctx context.Context, ownerID int64, content string, authSourceID int64) (*asymkey_model.PublicKey, error) {
    17  	dbCtx, committer, err := db.TxContext(ctx)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  	defer committer.Close()
    22  
    23  	// Principals cannot be duplicated.
    24  	has, err := db.GetEngine(dbCtx).
    25  		Where("content = ? AND type = ?", content, asymkey_model.KeyTypePrincipal).
    26  		Get(new(asymkey_model.PublicKey))
    27  	if err != nil {
    28  		return nil, err
    29  	} else if has {
    30  		return nil, asymkey_model.ErrKeyAlreadyExist{
    31  			Content: content,
    32  		}
    33  	}
    34  
    35  	key := &asymkey_model.PublicKey{
    36  		OwnerID:       ownerID,
    37  		Name:          content,
    38  		Content:       content,
    39  		Mode:          perm.AccessModeWrite,
    40  		Type:          asymkey_model.KeyTypePrincipal,
    41  		LoginSourceID: authSourceID,
    42  	}
    43  	if err = db.Insert(dbCtx, key); err != nil {
    44  		return nil, fmt.Errorf("addKey: %w", err)
    45  	}
    46  
    47  	if err = committer.Commit(); err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	committer.Close()
    52  
    53  	return key, RewriteAllPrincipalKeys(ctx)
    54  }