route_service.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package settings
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/astaxie/beego/orm"
  6. "nginx-ui/server/models"
  7. "strings"
  8. )
  9. type RouteService struct {
  10. }
  11. // Save 保存或者修改
  12. func (c *RouteService) Save(body *models.SettingRoute) (*models.SettingRoute, error) {
  13. o := orm.NewOrm()
  14. _, err := models.InsertOrUpdate[models.SettingRoute](o, body)
  15. return body, err
  16. }
  17. // GetList 获取指定用户的全部路由
  18. // Uid为0表示系统菜单,大于0表示用户个人菜单
  19. func (c *RouteService) GetList(vo RouteListVo) ([]models.SettingRoute, error) {
  20. o := orm.NewOrm()
  21. qs := o.QueryTable(&models.SettingRoute{})
  22. if vo.Uid > -1 {
  23. qs = qs.FilterRaw("Uid", fmt.Sprintf("=%d", vo.Uid))
  24. }
  25. if vo.NonType != "" {
  26. qs = qs.FilterRaw("Type", fmt.Sprintf("<>'%s'", vo.NonType))
  27. }
  28. qs = qs.OrderBy("Uid", "-SortNum")
  29. var list []models.SettingRoute
  30. _, err := qs.All(&list)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return list, nil
  35. }
  36. // GetUserRoutes 获取用户的菜单
  37. func (c *RouteService) GetUserRoutes(user *models.User) ([]models.SettingRoute, error) {
  38. o := orm.NewOrm()
  39. qs := o.QueryTable(&models.SettingRoute{})
  40. qs = qs.FilterRaw("Uid", fmt.Sprintf("=%d OR uid=0", user.Id))
  41. qs = qs.OrderBy("-SortNum")
  42. var list []models.SettingRoute
  43. _, err := qs.All(&list)
  44. if err != nil {
  45. return nil, err
  46. }
  47. if !user.IsAdmin() {
  48. userRoles := strings.Split(user.Roles, ",")
  49. var routes []models.SettingRoute
  50. for _, route := range list {
  51. if route.Roles == "" || strings.Contains(route.Roles, "USER") {
  52. routes = append(routes, route)
  53. continue
  54. }
  55. for _, role := range userRoles {
  56. if strings.Contains(route.Roles, role) {
  57. routes = append(routes, route)
  58. continue
  59. }
  60. }
  61. }
  62. return routes, nil
  63. }
  64. return list, nil
  65. }
  66. // Delete 获取全部组织
  67. func (c *RouteService) Delete(id string) error {
  68. o := orm.NewOrm()
  69. _, err := o.Delete(&models.SettingRoute{Id: id})
  70. return err
  71. }
  72. // InsertWhenNotExist 插入如果当ID不存在时
  73. func (c *RouteService) InsertWhenNotExist(route models.SettingRoute) error {
  74. o := orm.NewOrm()
  75. err := o.Read(&route, "Id")
  76. if err != nil && errors.Is(err, orm.ErrNoRows) {
  77. _, err = o.Insert(&route)
  78. }
  79. return err
  80. }
  81. var Route = new(RouteService)