account_users.go 1.6 KB

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