主要更改: - 新增管理员权限系统:添加 AdminAuth 中间件和 AdminRoute 组件,限制题库管理功能仅 yanlongqi 用户可访问 - UI 全面改版为白色毛玻璃风格(macOS 风格):应用毛玻璃效果、优化圆角和阴影、统一配色方案 - 登录页优化:将注册功能改为模态框形式,简化登录界面 - 首页优化:题库管理入口仅对管理员用户显示,优化响应式布局和卡片排列 - 移除底部导航栏:简化布局,改善用户体验 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
package middleware
|
||
|
||
import (
|
||
"ankao/internal/database"
|
||
"ankao/internal/models"
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// Auth 认证中间件
|
||
func Auth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// 从请求头获取token
|
||
authHeader := c.GetHeader("Authorization")
|
||
if authHeader == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "未登录",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 解析Bearer token
|
||
parts := strings.SplitN(authHeader, " ", 2)
|
||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "token格式错误",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
token := parts[1]
|
||
|
||
// 从数据库查找token对应的用户
|
||
db := database.GetDB()
|
||
var user models.User
|
||
if err := db.Where("token = ?", token).First(&user).Error; err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "token无效或已过期",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 将用户ID设置到上下文
|
||
c.Set("user_id", user.ID)
|
||
c.Set("username", user.Username)
|
||
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// AdminAuth 管理员认证中间件(必须在Auth中间件之后使用)
|
||
func AdminAuth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// 获取用户名(由 Auth 中间件设置)
|
||
username, exists := c.Get("username")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "未登录",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 检查是否为管理员用户
|
||
if username != "yanlongqi" {
|
||
c.JSON(http.StatusForbidden, gin.H{
|
||
"success": false,
|
||
"message": "无权限访问",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
c.Next()
|
||
}
|
||
}
|