gitea源码

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