enrollment_key.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package models
  2. import (
  3. "time"
  4. )
  5. const (
  6. Undefined KeyType = iota
  7. TimeExpiration
  8. Uses
  9. Unlimited
  10. )
  11. // KeyType - the type of enrollment key
  12. type KeyType int
  13. // String - returns the string representation of a KeyType
  14. func (k KeyType) String() string {
  15. return [...]string{"Undefined", "TimeExpiration", "Uses", "Unlimited"}[k]
  16. }
  17. // EnrollmentToken - the tokenized version of an enrollmentkey;
  18. // to be used for host registration
  19. type EnrollmentToken struct {
  20. Server string `json:"server"`
  21. Value string `json:"value"`
  22. }
  23. // EnrollmentKeyLength - the length of an enrollment key - 62^16 unique possibilities
  24. const EnrollmentKeyLength = 32
  25. // EnrollmentKey - the key used to register hosts and join them to specific networks
  26. type EnrollmentKey struct {
  27. Expiration time.Time `json:"expiration"`
  28. UsesRemaining int `json:"uses_remaining"`
  29. Value string `json:"value"`
  30. Networks []string `json:"networks"`
  31. Unlimited bool `json:"unlimited"`
  32. Tags []string `json:"tags"`
  33. Token string `json:"token,omitempty"` // B64 value of EnrollmentToken
  34. Type KeyType `json:"type"`
  35. }
  36. // APIEnrollmentKey - used to create enrollment keys via API
  37. type APIEnrollmentKey struct {
  38. Expiration int64 `json:"expiration"`
  39. UsesRemaining int `json:"uses_remaining"`
  40. Networks []string `json:"networks"`
  41. Unlimited bool `json:"unlimited"`
  42. Tags []string `json:"tags"`
  43. Type KeyType `json:"type"`
  44. }
  45. // RegisterResponse - the response to a successful enrollment register
  46. type RegisterResponse struct {
  47. ServerConf ServerConfig `json:"server_config"`
  48. RequestedHost Host `json:"requested_host"`
  49. }
  50. // EnrollmentKey.IsValid - checks if the key is still valid to use
  51. func (k *EnrollmentKey) IsValid() bool {
  52. if k == nil {
  53. return false
  54. }
  55. if k.UsesRemaining > 0 {
  56. return true
  57. }
  58. if !k.Expiration.IsZero() && time.Now().Before(k.Expiration) {
  59. return true
  60. }
  61. if k.Type == Undefined {
  62. return false
  63. }
  64. return k.Unlimited
  65. }
  66. // EnrollmentKey.Validate - validate's an EnrollmentKey
  67. // should be used during creation
  68. func (k *EnrollmentKey) Validate() bool {
  69. return k.Networks != nil &&
  70. k.Tags != nil &&
  71. len(k.Value) == EnrollmentKeyLength &&
  72. k.IsValid()
  73. }