account_users.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package sqlstore
  2. import (
  3. "time"
  4. "github.com/go-xorm/xorm"
  5. "github.com/torkelo/grafana-pro/pkg/bus"
  6. m "github.com/torkelo/grafana-pro/pkg/models"
  7. )
  8. func init() {
  9. bus.AddHandler("sql", AddAccountUser)
  10. bus.AddHandler("sql", RemoveAccountUser)
  11. bus.AddHandler("sql", GetAccountUsers)
  12. }
  13. func AddAccountUser(cmd *m.AddAccountUserCommand) error {
  14. return inTransaction(func(sess *xorm.Session) error {
  15. entity := m.AccountUser{
  16. AccountId: cmd.AccountId,
  17. UserId: cmd.UserId,
  18. Role: cmd.Role,
  19. Created: time.Now(),
  20. Updated: time.Now(),
  21. }
  22. _, err := sess.Insert(&entity)
  23. return err
  24. })
  25. }
  26. func GetAccountUsers(query *m.GetAccountUsersQuery) error {
  27. query.Result = make([]*m.AccountUserDTO, 0)
  28. sess := x.Table("account_user")
  29. sess.Join("INNER", "user", "account_user.user_id=user.id")
  30. sess.Where("account_user.account_id=?", query.AccountId)
  31. sess.Cols("account_user.account_id", "account_user.user_id", "user.email", "user.login", "account_user.role")
  32. sess.Asc("user.email", "user.login")
  33. err := sess.Find(&query.Result)
  34. return err
  35. }
  36. func RemoveAccountUser(cmd *m.RemoveAccountUserCommand) error {
  37. return inTransaction(func(sess *xorm.Session) error {
  38. var rawSql = "DELETE FROM account_user WHERE account_id=? and user_id=?"
  39. _, err := sess.Exec(rawSql, cmd.AccountId, cmd.UserId)
  40. if err != nil {
  41. return err
  42. }
  43. // validate that there is an admin user left
  44. res, err := sess.Query("SELECT 1 from account_user WHERE account_id=? and role='Admin'", cmd.AccountId)
  45. if err != nil {
  46. return err
  47. }
  48. if len(res) == 0 {
  49. return m.ErrLastAccountAdmin
  50. }
  51. return err
  52. })
  53. }