acme_user.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package model
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/tls"
  8. "github.com/0xJacky/Nginx-UI/settings"
  9. "github.com/go-acme/lego/v4/lego"
  10. "github.com/go-acme/lego/v4/registration"
  11. "math/big"
  12. "net/http"
  13. )
  14. type PrivateKey struct {
  15. X, Y *big.Int
  16. D *big.Int
  17. }
  18. type AcmeUser struct {
  19. Model
  20. Name string `json:"name"`
  21. Email string `json:"email"`
  22. CADir string `json:"ca_dir"`
  23. Registration registration.Resource `json:"registration" gorm:"serializer:json"`
  24. Key PrivateKey `json:"-" gorm:"serializer:json"`
  25. }
  26. func (u *AcmeUser) GetEmail() string {
  27. return u.Email
  28. }
  29. func (u *AcmeUser) GetRegistration() *registration.Resource {
  30. return &u.Registration
  31. }
  32. func (u *AcmeUser) GetPrivateKey() crypto.PrivateKey {
  33. return &ecdsa.PrivateKey{
  34. PublicKey: ecdsa.PublicKey{
  35. Curve: elliptic.P256(),
  36. X: u.Key.X,
  37. Y: u.Key.Y,
  38. },
  39. D: u.Key.D,
  40. }
  41. }
  42. func (u *AcmeUser) Register() error {
  43. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  44. if err != nil {
  45. return err
  46. }
  47. u.Key = PrivateKey{
  48. X: privateKey.PublicKey.X,
  49. Y: privateKey.PublicKey.Y,
  50. D: privateKey.D,
  51. }
  52. config := lego.NewConfig(u)
  53. config.CADirURL = u.CADir
  54. u.Registration = registration.Resource{}
  55. // Skip TLS check
  56. if config.HTTPClient != nil {
  57. config.HTTPClient.Transport = &http.Transport{
  58. Proxy: http.ProxyFromEnvironment,
  59. TLSClientConfig: &tls.Config{InsecureSkipVerify: settings.ServerSettings.InsecureSkipVerify},
  60. }
  61. }
  62. client, err := lego.NewClient(config)
  63. if err != nil {
  64. return err
  65. }
  66. // New users will need to register
  67. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  68. if err != nil {
  69. return err
  70. }
  71. u.Registration = *reg
  72. return nil
  73. }