base.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package nginx_controller
  2. import (
  3. "errors"
  4. "github.com/astaxie/beego/logs"
  5. "github.com/astaxie/beego/orm"
  6. "nginx-ui/server/base"
  7. "nginx-ui/server/middleware"
  8. "nginx-ui/server/models"
  9. "strconv"
  10. )
  11. type BaseController struct {
  12. base.Controller
  13. }
  14. // CheckNginxPermission 从path中获取nginx的参数
  15. func (c *BaseController) CheckNginxPermission() (*models.Nginx, error) {
  16. idStr := c.GetParam(":id")
  17. id, err := strconv.Atoi(idStr)
  18. if err != nil {
  19. logs.Warn("strconv.Atoi(idStr) fail", idStr)
  20. c.SetCode(-1).SetMsg("请传递正确的参数!").Json()
  21. return nil, err
  22. }
  23. return c.CheckNginxPermissionById(id)
  24. }
  25. // CheckNginxPermissionById 验证权限,如果无权操作该nginx,返回nil,否则返回
  26. func (c *BaseController) CheckNginxPermissionById(nginxId int) (*models.Nginx, error) {
  27. current := c.RequiredUser()
  28. if current == nil {
  29. middleware.WriteForbidden(c.Ctx.ResponseWriter)
  30. return nil, errors.New("当前未登录,无法操作")
  31. }
  32. if nginxId < 1 {
  33. c.SetCode(-1).SetMsg("Nginx ID must gt 0!").Json()
  34. return nil, errors.New("nginx ID must gt 0!")
  35. }
  36. nginx := models.Nginx{Id: nginxId}
  37. o := orm.NewOrm()
  38. err := o.Read(&nginx)
  39. if err != nil {
  40. c.ErrorJson(err)
  41. return nil, err
  42. }
  43. if !current.IsAdmin() && current.Account != nginx.Uid {
  44. c.Forbidden()
  45. return nil, errors.New("forbidden")
  46. }
  47. return &nginx, nil
  48. }