| 36 | } |
| 37 | |
| 38 | func NewClient(keys *crypto.KeyPair) *Client { |
| 39 | cli := &Client{ |
| 40 | cli: &http.Client{ |
| 41 | Timeout: time.Duration(ClientTimeout) * time.Second, |
| 42 | }, |
| 43 | keys: keys, |
| 44 | data: make(map[string]interface{}), |
| 45 | } |
| 46 | |
| 47 | if info, err := os.Stat(ClientTokenFile); err == nil { |
| 48 | if time.Since(info.ModTime()) < models.TokenTTL { |
| 49 | log.Debug("loading token from %s ...", ClientTokenFile) |
| 50 | var data map[string]interface{} |
| 51 | if raw, err := ioutil.ReadFile(ClientTokenFile); err == nil { |
| 52 | if err := json.Unmarshal(raw, &data); err == nil { |
| 53 | cli.token = data["token"].(string) |
| 54 | cli.tokenAt = info.ModTime() |
| 55 | log.Debug("token: %s", cli.token) |
| 56 | } else { |
| 57 | log.Warning("error decoding %s: %v", ClientTokenFile, err) |
| 58 | } |
| 59 | } else { |
| 60 | log.Warning("error reading %s: %v", ClientTokenFile, err) |
| 61 | } |
| 62 | } else { |
| 63 | log.Debug("token in %s is expired", ClientTokenFile) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | return cli |
| 68 | } |
| 69 | |
| 70 | func (c *Client) enroll() error { |
| 71 | identity := fmt.Sprintf("%s@%s", utils.Hostname(), c.keys.FingerprintHex) |