acme_user.go 1.7 KB

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