|
| 1 | +package gapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/url" |
| 8 | + "strconv" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +type CreateAPIKeyRequest struct { |
| 13 | + Name string `json:"name"` |
| 14 | + Role string `json:"role"` |
| 15 | + SecondsToLive int64 `json:"secondsToLive,omitempty"` |
| 16 | +} |
| 17 | + |
| 18 | +type CreateAPIKeyResponse struct { |
| 19 | + // ID field only returned after Grafana v7. |
| 20 | + ID int64 `json:"id,omitempty"` |
| 21 | + Name string `json:"name"` |
| 22 | + Key string `json:"key"` |
| 23 | +} |
| 24 | + |
| 25 | +type GetAPIKeysResponse struct { |
| 26 | + ID int64 `json:"id"` |
| 27 | + Name string `json:"name"` |
| 28 | + Role string `json:"role"` |
| 29 | + Expiration time.Time `json:"expiration,omitempty"` |
| 30 | +} |
| 31 | + |
| 32 | +type DeleteAPIKeyResponse struct { |
| 33 | + Message string `json:"message"` |
| 34 | +} |
| 35 | + |
| 36 | +// CreateAPIKey creates a new Grafana API key. |
| 37 | +func (c *Client) CreateAPIKey(request CreateAPIKeyRequest) (CreateAPIKeyResponse, error) { |
| 38 | + response := CreateAPIKeyResponse{} |
| 39 | + |
| 40 | + data, err := json.Marshal(request) |
| 41 | + if err != nil { |
| 42 | + return response, err |
| 43 | + } |
| 44 | + |
| 45 | + err = c.request("POST", "/api/auth/keys", nil, bytes.NewBuffer(data), &response) |
| 46 | + return response, err |
| 47 | +} |
| 48 | + |
| 49 | +// GetAPIKeys retrieves a list of all API keys. |
| 50 | +func (c *Client) GetAPIKeys(includeExpired bool) ([]*GetAPIKeysResponse, error) { |
| 51 | + response := make([]*GetAPIKeysResponse, 0) |
| 52 | + |
| 53 | + query := url.Values{} |
| 54 | + query.Add("includeExpired", strconv.FormatBool(includeExpired)) |
| 55 | + |
| 56 | + err := c.request("GET", "/api/auth/keys", query, nil, &response) |
| 57 | + return response, err |
| 58 | +} |
| 59 | + |
| 60 | +// DeleteAPIKey deletes the Grafana API key with the specified ID. |
| 61 | +func (c *Client) DeleteAPIKey(id int64) (DeleteAPIKeyResponse, error) { |
| 62 | + response := DeleteAPIKeyResponse{} |
| 63 | + |
| 64 | + path := fmt.Sprintf("/api/auth/keys/%d", id) |
| 65 | + err := c.request("DELETE", path, nil, nil, &response) |
| 66 | + return response, err |
| 67 | +} |
0 commit comments