account.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package api
  2. import (
  3. "github.com/torkelo/grafana-pro/pkg/bus"
  4. "github.com/torkelo/grafana-pro/pkg/middleware"
  5. m "github.com/torkelo/grafana-pro/pkg/models"
  6. )
  7. func GetAccount(c *middleware.Context) {
  8. query := m.GetAccountInfoQuery{Id: c.AccountId}
  9. err := bus.Dispatch(&query)
  10. if err != nil {
  11. c.JsonApiErr(500, "Failed to fetch collaboratos", err)
  12. return
  13. }
  14. c.JSON(200, query.Result)
  15. }
  16. func UpdateAccount(c *middleware.Context) {
  17. cmd := m.UpdateAccountCommand{}
  18. if !c.JsonBody(&cmd) {
  19. c.JsonApiErr(400, "Invalid request", nil)
  20. return
  21. }
  22. cmd.AccountId = c.AccountId
  23. if err := bus.Dispatch(&cmd); err != nil {
  24. c.JsonApiErr(400, "Failed to update account", nil)
  25. return
  26. }
  27. c.JsonOK("Account updated")
  28. }
  29. func GetOtherAccounts(c *middleware.Context) {
  30. query := m.GetOtherAccountsQuery{AccountId: c.AccountId}
  31. err := bus.Dispatch(&query)
  32. if err != nil {
  33. c.JsonApiErr(500, "Failed to get other accounts", err)
  34. return
  35. }
  36. result := append(query.Result, &m.OtherAccountDTO{
  37. AccountId: c.AccountId,
  38. Role: m.ROLE_OWNER,
  39. Email: c.UserEmail,
  40. })
  41. for _, ac := range result {
  42. if ac.AccountId == c.UsingAccountId {
  43. ac.IsUsing = true
  44. break
  45. }
  46. }
  47. c.JSON(200, result)
  48. }
  49. func validateUsingAccount(accountId int64, otherId int64) bool {
  50. if accountId == otherId {
  51. return true
  52. }
  53. query := m.GetOtherAccountsQuery{AccountId: accountId}
  54. err := bus.Dispatch(&query)
  55. if err != nil {
  56. return false
  57. }
  58. // validate that the account id in the list
  59. valid := false
  60. for _, other := range query.Result {
  61. if other.AccountId == otherId {
  62. valid = true
  63. }
  64. }
  65. return valid
  66. }
  67. func SetUsingAccount(c *middleware.Context) {
  68. usingAccountId := c.ParamsInt64(":id")
  69. if !validateUsingAccount(c.AccountId, usingAccountId) {
  70. c.JsonApiErr(401, "Not a valid account", nil)
  71. return
  72. }
  73. cmd := m.SetUsingAccountCommand{
  74. AccountId: c.AccountId,
  75. UsingAccountId: usingAccountId,
  76. }
  77. err := bus.Dispatch(&cmd)
  78. if err != nil {
  79. c.JsonApiErr(500, "Failed to update account", err)
  80. return
  81. }
  82. c.JsonOK("Active account changed")
  83. }