acme_user.go 1.4 KB

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