apikey.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package sqlstore
  2. import (
  3. "time"
  4. "github.com/go-xorm/xorm"
  5. "github.com/grafana/grafana/pkg/bus"
  6. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. func init() {
  9. bus.AddHandler("sql", GetApiKeys)
  10. bus.AddHandler("sql", GetApiKeyByKey)
  11. bus.AddHandler("sql", UpdateApiKey)
  12. bus.AddHandler("sql", DeleteApiKey)
  13. bus.AddHandler("sql", AddApiKey)
  14. }
  15. func GetApiKeys(query *m.GetApiKeysQuery) error {
  16. sess := x.Limit(100, 0).Where("account_id=?", query.AccountId).Asc("name")
  17. query.Result = make([]*m.ApiKey, 0)
  18. return sess.Find(&query.Result)
  19. }
  20. func DeleteApiKey(cmd *m.DeleteApiKeyCommand) error {
  21. return inTransaction(func(sess *xorm.Session) error {
  22. var rawSql = "DELETE FROM api_key WHERE id=? and account_id=?"
  23. _, err := sess.Exec(rawSql, cmd.Id, cmd.AccountId)
  24. return err
  25. })
  26. }
  27. func AddApiKey(cmd *m.AddApiKeyCommand) error {
  28. return inTransaction(func(sess *xorm.Session) error {
  29. t := m.ApiKey{
  30. AccountId: cmd.AccountId,
  31. Name: cmd.Name,
  32. Role: cmd.Role,
  33. Key: cmd.Key,
  34. Created: time.Now(),
  35. Updated: time.Now(),
  36. }
  37. if _, err := sess.Insert(&t); err != nil {
  38. return err
  39. }
  40. cmd.Result = &t
  41. return nil
  42. })
  43. }
  44. func UpdateApiKey(cmd *m.UpdateApiKeyCommand) error {
  45. return inTransaction(func(sess *xorm.Session) error {
  46. t := m.ApiKey{
  47. Id: cmd.Id,
  48. AccountId: cmd.AccountId,
  49. Name: cmd.Name,
  50. Role: cmd.Role,
  51. Updated: time.Now(),
  52. }
  53. _, err := sess.Where("id=? and account_id=?", t.Id, t.AccountId).Update(&t)
  54. return err
  55. })
  56. }
  57. func GetApiKeyByKey(query *m.GetApiKeyByKeyQuery) error {
  58. var apikey m.ApiKey
  59. has, err := x.Where("`key`=?", query.Key).Get(&apikey)
  60. if err != nil {
  61. return err
  62. } else if has == false {
  63. return m.ErrInvalidApiKey
  64. }
  65. query.Result = &apikey
  66. return nil
  67. }