apikey.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. func GetAPIKeys(c *m.ReqContext) Response {
  9. query := m.GetApiKeysQuery{OrgId: c.OrgId}
  10. if err := bus.Dispatch(&query); err != nil {
  11. return ApiError(500, "Failed to list api keys", err)
  12. }
  13. result := make([]*m.ApiKeyDTO, len(query.Result))
  14. for i, t := range query.Result {
  15. result[i] = &m.ApiKeyDTO{
  16. Id: t.Id,
  17. Name: t.Name,
  18. Role: t.Role,
  19. }
  20. }
  21. return Json(200, result)
  22. }
  23. func DeleteAPIKey(c *m.ReqContext) Response {
  24. id := c.ParamsInt64(":id")
  25. cmd := &m.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId}
  26. err := bus.Dispatch(cmd)
  27. if err != nil {
  28. return ApiError(500, "Failed to delete API key", err)
  29. }
  30. return ApiSuccess("API key deleted")
  31. }
  32. func AddAPIKey(c *m.ReqContext, cmd m.AddApiKeyCommand) Response {
  33. if !cmd.Role.IsValid() {
  34. return ApiError(400, "Invalid role specified", nil)
  35. }
  36. cmd.OrgId = c.OrgId
  37. newKeyInfo := apikeygen.New(cmd.OrgId, cmd.Name)
  38. cmd.Key = newKeyInfo.HashedKey
  39. if err := bus.Dispatch(&cmd); err != nil {
  40. return ApiError(500, "Failed to add API key", err)
  41. }
  42. result := &dtos.NewApiKeyResult{
  43. Name: cmd.Result.Name,
  44. Key: newKeyInfo.ClientSecret}
  45. return Json(200, result)
  46. }