Files
blind-select/backend/internal/middleware/auth.go
T
admin 06488f0237 Initial commit: 帮我选盲选应用
功能:
- Go后端 (Gin + GORM + PostgreSQL)
- UniApp用户端 (iOS/Android/小程序)
- DaisyUI5后台管理
- JWT认证 + 微信登录
- 盲选加权算法
- 会员系统 + 优惠券
- 打分评价 + 偏好学习
2026-06-08 20:18:31 +00:00

81 lines
1.7 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/blind-select/backend/internal/utils"
"github.com/gin-gonic/gin"
)
// JWTAuth requires valid JWT
func JWTAuth(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
JSONError(c, http.StatusUnauthorized, "missing authorization header")
c.Abort()
return
}
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
if tokenStr == authHeader {
JSONError(c, http.StatusUnauthorized, "invalid authorization format")
c.Abort()
return
}
claims, err := utils.ParseToken(tokenStr, secret)
if err != nil {
JSONError(c, http.StatusUnauthorized, "invalid or expired token")
c.Abort()
return
}
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
}
}
// AdminOnly restricts access to admin role only
func AdminOnly(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
role, exists := c.Get("role")
if !exists || role != "admin" {
JSONError(c, http.StatusForbidden, "admin access required")
c.Abort()
return
}
c.Next()
}
}
// BlindDailyLimit limits blind selections per day
func BlindDailyLimit(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, _ := c.Get("user_id")
uid := userID.(uint)
limit := getDailyLimit(uid)
used := getTodayBlindCount(uid)
if used >= limit {
JSONError(c, http.StatusTooManyRequests, "daily blind selection limit reached. Upgrade to VIP for more!")
c.Abort()
return
}
c.Next()
}
}
func getDailyLimit(userID uint) int {
return 3 // TODO: check membership
}
func getTodayBlindCount(userID uint) int {
return 0 // TODO: check Redis
}