account.go 1.9 KB

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