You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.go 2.1 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package controllers
  15. import "github.com/astaxie/beego/context"
  16. type Response struct {
  17. Status string `json:"status"`
  18. Msg string `json:"msg"`
  19. Data interface{} `json:"data"`
  20. Data2 interface{} `json:"data2"`
  21. }
  22. func (c *ApiController) ResponseOk(data ...interface{}) {
  23. resp := Response{Status: "ok"}
  24. switch len(data) {
  25. case 2:
  26. resp.Data2 = data[1]
  27. fallthrough
  28. case 1:
  29. resp.Data = data[0]
  30. }
  31. c.Data["json"] = resp
  32. c.ServeJSON()
  33. }
  34. func (c *ApiController) ResponseError(error string, data ...interface{}) {
  35. resp := Response{Status: "error", Msg: error}
  36. switch len(data) {
  37. case 2:
  38. resp.Data2 = data[1]
  39. fallthrough
  40. case 1:
  41. resp.Data = data[0]
  42. }
  43. c.Data["json"] = resp
  44. c.ServeJSON()
  45. }
  46. func (c *ApiController) RequireSignedIn() (string, bool) {
  47. userId := c.GetSessionUsername()
  48. if userId == "" {
  49. c.ResponseError("Please sign in first")
  50. return "", false
  51. }
  52. return userId, true
  53. }
  54. func (c *ApiController) RequireAdmin() bool {
  55. user := c.GetSessionUser()
  56. if user == nil || !user.IsAdmin {
  57. c.ResponseError("this operation requires admin privilege")
  58. return true
  59. }
  60. return false
  61. }
  62. func DenyRequest(ctx *context.Context) {
  63. responseError(ctx, "Unauthorized operation")
  64. }
  65. func responseError(ctx *context.Context, error string, data ...interface{}) {
  66. resp := Response{Status: "error", Msg: error}
  67. switch len(data) {
  68. case 2:
  69. resp.Data2 = data[1]
  70. fallthrough
  71. case 1:
  72. resp.Data = data[0]
  73. }
  74. err := ctx.Output.JSON(resp, true, false)
  75. if err != nil {
  76. panic(err)
  77. }
  78. }