apikey.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/apikeygen"
  6. "github.com/grafana/grafana/pkg/models"
  7. "time"
  8. )
  9. func GetAPIKeys(c *models.ReqContext) Response {
  10. query := models.GetApiKeysQuery{OrgId: c.OrgId}
  11. if err := bus.Dispatch(&query); err != nil {
  12. return Error(500, "Failed to list api keys", err)
  13. }
  14. result := make([]*models.ApiKeyDTO, len(query.Result))
  15. for i, t := range query.Result {
  16. var expiration *time.Time = nil
  17. if t.Expires != nil {
  18. v := time.Unix(*t.Expires, 0)
  19. expiration = &v
  20. }
  21. result[i] = &models.ApiKeyDTO{
  22. Id: t.Id,
  23. Name: t.Name,
  24. Role: t.Role,
  25. Expiration: expiration,
  26. }
  27. }
  28. return JSON(200, result)
  29. }
  30. func DeleteAPIKey(c *models.ReqContext) Response {
  31. id := c.ParamsInt64(":id")
  32. cmd := &models.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId}
  33. err := bus.Dispatch(cmd)
  34. if err != nil {
  35. return Error(500, "Failed to delete API key", err)
  36. }
  37. return Success("API key deleted")
  38. }
  39. func (hs *HTTPServer) AddAPIKey(c *models.ReqContext, cmd models.AddApiKeyCommand) Response {
  40. if !cmd.Role.IsValid() {
  41. return Error(400, "Invalid role specified", nil)
  42. }
  43. if hs.Cfg.ApiKeyMaxSecondsToLive != -1 {
  44. if cmd.SecondsToLive == 0 {
  45. return Error(400, "Number of seconds before expiration should be set", nil)
  46. }
  47. if cmd.SecondsToLive > hs.Cfg.ApiKeyMaxSecondsToLive {
  48. return Error(400, "Number of seconds before expiration is greater than the global limit", nil)
  49. }
  50. }
  51. cmd.OrgId = c.OrgId
  52. newKeyInfo := apikeygen.New(cmd.OrgId, cmd.Name)
  53. cmd.Key = newKeyInfo.HashedKey
  54. if err := bus.Dispatch(&cmd); err != nil {
  55. if err == models.ErrInvalidApiKeyExpiration {
  56. return Error(400, err.Error(), nil)
  57. }
  58. return Error(500, "Failed to add API key", err)
  59. }
  60. result := &dtos.NewApiKeyResult{
  61. Name: cmd.Result.Name,
  62. Key: newKeyInfo.ClientSecret}
  63. return JSON(200, result)
  64. }