api_account.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "github.com/torkelo/grafana-pro/pkg/middleware"
  4. "github.com/torkelo/grafana-pro/pkg/models"
  5. "github.com/torkelo/grafana-pro/pkg/routes/dtos"
  6. "github.com/torkelo/grafana-pro/pkg/utils"
  7. )
  8. func GetAccount(c *middleware.Context) {
  9. model := dtos.AccountInfo{
  10. Name: c.UserAccount.Name,
  11. Email: c.UserAccount.Email,
  12. }
  13. collaborators, err := models.GetCollaboratorsForAccount(c.UserAccount.Id)
  14. if err != nil {
  15. c.JsonApiErr(500, "Failed to fetch collaboratos", err)
  16. return
  17. }
  18. for _, collaborator := range collaborators {
  19. model.Collaborators = append(model.Collaborators, &dtos.Collaborator{
  20. AccountId: collaborator.AccountId,
  21. Role: collaborator.Role,
  22. Email: collaborator.Email,
  23. })
  24. }
  25. c.JSON(200, model)
  26. }
  27. func AddCollaborator(c *middleware.Context) {
  28. var model dtos.AddCollaboratorCommand
  29. if !c.JsonBody(&model) {
  30. c.JSON(400, utils.DynMap{"message": "Invalid request"})
  31. return
  32. }
  33. accountToAdd, err := models.GetAccountByLogin(model.Email)
  34. if err != nil {
  35. c.JSON(404, utils.DynMap{"message": "Collaborator not found"})
  36. return
  37. }
  38. if accountToAdd.Id == c.UserAccount.Id {
  39. c.JSON(400, utils.DynMap{"message": "Cannot add yourself as collaborator"})
  40. return
  41. }
  42. var collaborator = models.NewCollaborator(accountToAdd.Id, c.UserAccount.Id, models.ROLE_READ_WRITE)
  43. err = models.AddCollaborator(collaborator)
  44. if err != nil {
  45. c.JSON(400, utils.DynMap{"message": err.Error()})
  46. return
  47. }
  48. c.Status(204)
  49. }
  50. func GetOtherAccounts(c *middleware.Context) {
  51. otherAccounts, err := models.GetOtherAccountsFor(c.UserAccount.Id)
  52. if err != nil {
  53. c.JSON(500, utils.DynMap{"message": err.Error()})
  54. return
  55. }
  56. var result []*dtos.OtherAccount
  57. result = append(result, &dtos.OtherAccount{
  58. Id: c.UserAccount.Id,
  59. Role: "owner",
  60. IsUsing: c.UserAccount.Id == c.UserAccount.UsingAccountId,
  61. Name: c.UserAccount.Email,
  62. })
  63. for _, other := range otherAccounts {
  64. result = append(result, &dtos.OtherAccount{
  65. Id: other.Id,
  66. Role: other.Role,
  67. Name: other.Email,
  68. IsUsing: other.Id == c.UserAccount.UsingAccountId,
  69. })
  70. }
  71. c.JSON(200, result)
  72. }