acme_user.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package model
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "math/big"
  8. "github.com/0xJacky/Nginx-UI/internal/transport"
  9. "github.com/go-acme/lego/v4/lego"
  10. "github.com/go-acme/lego/v4/registration"
  11. )
  12. type PrivateKey struct {
  13. X, Y *big.Int
  14. D *big.Int
  15. }
  16. type AcmeUser struct {
  17. Model
  18. Name string `json:"name"`
  19. Email string `json:"email"`
  20. CADir string `json:"ca_dir"`
  21. Registration registration.Resource `json:"registration" gorm:"serializer:json"`
  22. Key PrivateKey `json:"-" gorm:"serializer:json"`
  23. Proxy string `json:"proxy"`
  24. RegisterOnStartup bool `json:"register_on_startup"`
  25. EABKeyID string `json:"eab_key_id"`
  26. EABHMACKey string `json:"eab_hmac_key"`
  27. }
  28. func (u *AcmeUser) GetEmail() string {
  29. return u.Email
  30. }
  31. func (u *AcmeUser) GetRegistration() *registration.Resource {
  32. return &u.Registration
  33. }
  34. func (u *AcmeUser) GetPrivateKey() crypto.PrivateKey {
  35. return &ecdsa.PrivateKey{
  36. PublicKey: ecdsa.PublicKey{
  37. Curve: elliptic.P256(),
  38. X: u.Key.X,
  39. Y: u.Key.Y,
  40. },
  41. D: u.Key.D,
  42. }
  43. }
  44. func (u *AcmeUser) Register() error {
  45. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  46. if err != nil {
  47. return err
  48. }
  49. u.Key = PrivateKey{
  50. X: privateKey.PublicKey.X,
  51. Y: privateKey.PublicKey.Y,
  52. D: privateKey.D,
  53. }
  54. config := lego.NewConfig(u)
  55. config.CADirURL = u.CADir
  56. u.Registration = registration.Resource{}
  57. // Skip TLS check
  58. if config.HTTPClient != nil {
  59. t, err := transport.NewTransport(
  60. transport.WithProxy(u.Proxy))
  61. if err != nil {
  62. return err
  63. }
  64. config.HTTPClient.Transport = t
  65. }
  66. client, err := lego.NewClient(config)
  67. if err != nil {
  68. return err
  69. }
  70. // New users will need to register
  71. var reg *registration.Resource
  72. // Check if EAB credentials are provided
  73. if u.EABKeyID != "" && u.EABHMACKey != "" {
  74. // Register with External Account Binding
  75. reg, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
  76. TermsOfServiceAgreed: true,
  77. Kid: u.EABKeyID,
  78. HmacEncoded: u.EABHMACKey,
  79. })
  80. } else {
  81. // Register without EAB
  82. reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  83. }
  84. if err != nil {
  85. return err
  86. }
  87. u.Registration = *reg
  88. return nil
  89. }