middleware.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package router
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "time"
  8. "github.com/mhaya/game/game_cluster/internal/constant"
  9. "github.com/mhaya/game/game_cluster/internal/mdb/models"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "github.com/gin-gonic/gin"
  12. "github.com/mhaya/game/game_cluster/internal/mdb"
  13. )
  14. func Auth() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. tokenString := c.GetHeader("Token")
  17. if tokenString == "" {
  18. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  19. "msg": "token is empty",
  20. })
  21. return
  22. }
  23. result, err := mdb.RDB.Get(context.Background(), tokenString).Result()
  24. if err != nil {
  25. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  26. "msg": "token is empty",
  27. })
  28. return
  29. }
  30. if result == "" {
  31. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  32. "msg": "token is invalid",
  33. })
  34. return
  35. }
  36. // 获取请求URL
  37. url := c.Request.URL.Path
  38. s, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, url).Result()
  39. ss, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
  40. fmt.Println(ss)
  41. // 检查是否有权限
  42. if s == "" && result == "" {
  43. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  44. "msg": "token is no auth",
  45. })
  46. return
  47. }
  48. if result == "" {
  49. if err := checkIP(c); err != nil {
  50. c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
  51. "msg": "ip is no auth",
  52. })
  53. return
  54. }
  55. }
  56. c.Next()
  57. }
  58. }
  59. // checkIP
  60. func checkIP(c *gin.Context) error {
  61. // 获取请求的ip
  62. ip := c.ClientIP()
  63. whitelistModel := &models.Whitelist{}
  64. collection := mdb.MDB.Collection(whitelistModel.TableName())
  65. // 设置超时时间
  66. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  67. defer cancel() // 确保在函数退出时取消上下文
  68. // 示例:查询 IP 是否在白名单中
  69. err := collection.FindOne(ctx, bson.M{"ip": ip}).Decode(&whitelistModel)
  70. if err != nil {
  71. // 处理查询错误
  72. return fmt.Errorf("failed to check IP in whitelist: %w", err)
  73. }
  74. // 根据查询结果决定是否允许访问
  75. if whitelistModel != nil {
  76. return nil // 允许访问
  77. } else {
  78. return errors.New("IP not in whitelist") // 拒绝访问
  79. }
  80. }