account.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package sqlstore
  2. import (
  3. "time"
  4. "github.com/go-xorm/xorm"
  5. "github.com/torkelo/grafana-pro/pkg/bus"
  6. "github.com/torkelo/grafana-pro/pkg/events"
  7. m "github.com/torkelo/grafana-pro/pkg/models"
  8. )
  9. func init() {
  10. bus.AddHandler("sql", GetAccountById)
  11. bus.AddHandler("sql", CreateAccount)
  12. bus.AddHandler("sql", SetUsingAccount)
  13. bus.AddHandler("sql", UpdateAccount)
  14. bus.AddHandler("sql", GetAccountByName)
  15. }
  16. func GetAccountById(query *m.GetAccountByIdQuery) error {
  17. var account m.Account
  18. exists, err := x.Id(query.Id).Get(&account)
  19. if err != nil {
  20. return err
  21. }
  22. if !exists {
  23. return m.ErrAccountNotFound
  24. }
  25. query.Result = &account
  26. return nil
  27. }
  28. func GetAccountByName(query *m.GetAccountByNameQuery) error {
  29. var account m.Account
  30. exists, err := x.Where("name=?", query.Name).Get(&account)
  31. if err != nil {
  32. return err
  33. }
  34. if !exists {
  35. return m.ErrAccountNotFound
  36. }
  37. query.Result = &account
  38. return nil
  39. }
  40. func CreateAccount(cmd *m.CreateAccountCommand) error {
  41. return inTransaction2(func(sess *session) error {
  42. account := m.Account{
  43. Name: cmd.Name,
  44. Created: time.Now(),
  45. Updated: time.Now(),
  46. }
  47. if _, err := sess.Insert(&account); err != nil {
  48. return err
  49. }
  50. user := m.AccountUser{
  51. AccountId: account.Id,
  52. UserId: cmd.UserId,
  53. Role: m.ROLE_ADMIN,
  54. Created: time.Now(),
  55. Updated: time.Now(),
  56. }
  57. _, err := sess.Insert(&user)
  58. cmd.Result = account
  59. sess.publishAfterCommit(&events.AccountCreated{
  60. Name: account.Name,
  61. })
  62. // silently ignore failures to publish events.
  63. _ = bus.Publish(&m.Notification{
  64. EventType: "account.create",
  65. Timestamp: account.Created,
  66. Priority: m.PRIO_INFO,
  67. Payload: account,
  68. })
  69. return err
  70. })
  71. }
  72. func UpdateAccount(cmd *m.UpdateAccountCommand) error {
  73. return inTransaction(func(sess *xorm.Session) error {
  74. account := m.Account{
  75. Name: cmd.Name,
  76. Updated: time.Now(),
  77. }
  78. _, err := sess.Id(cmd.AccountId).Update(&account)
  79. if err == nil {
  80. // silently ignore failures to publish events.
  81. account.Id = cmd.AccountId
  82. _ = bus.Publish(&m.Notification{
  83. EventType: "account.update",
  84. Timestamp: account.Updated,
  85. Priority: m.PRIO_INFO,
  86. Payload: account,
  87. })
  88. }
  89. return err
  90. })
  91. }