acme_user.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. TLSClientConfig: &tls.Config{InsecureSkipVerify: settings.ServerSettings.InsecureSkipVerify},
  59. }
  60. }
  61. client, err := lego.NewClient(config)
  62. if err != nil {
  63. return err
  64. }
  65. // New users will need to register
  66. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  67. if err != nil {
  68. return err
  69. }
  70. u.Registration = *reg
  71. return nil
  72. }