account.go 1.9 KB

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