auth.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package middleware
  2. import (
  3. "github.com/gin-contrib/sessions"
  4. "github.com/gin-gonic/gin"
  5. "message-pusher/common"
  6. "net/http"
  7. )
  8. func authHelper(c *gin.Context, minRole int) {
  9. session := sessions.Default(c)
  10. username := session.Get("username")
  11. role := session.Get("role")
  12. id := session.Get("id")
  13. status := session.Get("status")
  14. if username == nil {
  15. c.JSON(http.StatusUnauthorized, gin.H{
  16. "success": false,
  17. "message": "无权进行此操作,未登录",
  18. })
  19. c.Abort()
  20. return
  21. }
  22. if status.(int) == common.UserStatusDisabled {
  23. c.JSON(http.StatusOK, gin.H{
  24. "success": false,
  25. "message": "用户已被封禁",
  26. })
  27. c.Abort()
  28. return
  29. }
  30. if role.(int) < minRole {
  31. c.JSON(http.StatusOK, gin.H{
  32. "success": false,
  33. "message": "无权进行此操作,权限不足",
  34. })
  35. c.Abort()
  36. return
  37. }
  38. c.Set("username", username)
  39. c.Set("role", role)
  40. c.Set("id", id)
  41. c.Next()
  42. }
  43. func UserAuth() func(c *gin.Context) {
  44. return func(c *gin.Context) {
  45. authHelper(c, common.RoleCommonUser)
  46. }
  47. }
  48. func AdminAuth() func(c *gin.Context) {
  49. return func(c *gin.Context) {
  50. authHelper(c, common.RoleAdminUser)
  51. }
  52. }
  53. func RootAuth() func(c *gin.Context) {
  54. return func(c *gin.Context) {
  55. authHelper(c, common.RoleRootUser)
  56. }
  57. }