user.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package service
  2. import (
  3. "context"
  4. "go-common/app/admin/main/apm/model/user"
  5. "go-common/library/ecode"
  6. "go-common/library/log"
  7. "github.com/jinzhu/gorm"
  8. )
  9. // Permit check user permission.
  10. func (s *Service) Permit(c context.Context, username string, rule string) (err error) {
  11. for _, man := range s.c.Superman {
  12. if username == man {
  13. return
  14. }
  15. }
  16. usr := &user.User{}
  17. if err = s.DB.Where("username=?", username).First(usr).Error; err != nil {
  18. log.Error("s.DB.User(%s) user error(%v)", username, err)
  19. err = ecode.AccessDenied
  20. return
  21. }
  22. if user.Rules[rule].Permit == user.PermitDefault {
  23. return
  24. }
  25. cnt := 0
  26. if err = s.DB.Model(&user.Rule{}).Where("user_id=? AND rule=?", usr.ID, rule).Count(&cnt).Error; err != nil {
  27. log.Error("s.DB.User(%s) count error(%v)", username, err)
  28. err = ecode.AccessDenied
  29. return
  30. }
  31. if cnt == 0 {
  32. log.Warn("s.DB.User(%s) count=0", username)
  33. err = ecode.AccessDenied
  34. }
  35. return
  36. }
  37. // GetDefaultPermission get the modules and rules which have default permission
  38. func (s *Service) GetDefaultPermission(c context.Context) (modules []string, rules []string) {
  39. for m, mp := range user.Modules {
  40. if mp.Permit == user.PermitDefault {
  41. modules = append(modules, m)
  42. }
  43. }
  44. for r, rp := range user.Rules {
  45. if rp.Permit == user.PermitDefault {
  46. rules = append(rules, r)
  47. }
  48. }
  49. return
  50. }
  51. // GetUser get user info by username if it exists, otherwise create the user info
  52. func (s *Service) GetUser(c context.Context, username string) (usr *user.User, err error) {
  53. usr = &user.User{}
  54. err = s.DB.Where("username = ?", username).First(usr).Error
  55. if err == gorm.ErrRecordNotFound {
  56. usr.UserName = username
  57. usr.NickName = username
  58. err = s.DB.Create(usr).Error
  59. }
  60. if err != nil {
  61. log.Error("apmSvc.GetUser error(%v)", err)
  62. return
  63. }
  64. s.ranksCache.Lock()
  65. if s.ranksCache.Map[username] != nil {
  66. usr.AvatarURL = s.ranksCache.Map[username].AvatarURL
  67. } else {
  68. usr.AvatarURL, _ = s.dao.GitLabFace(c, username)
  69. }
  70. s.ranksCache.Unlock()
  71. return
  72. }