mirror of
https://github.com/woodchen-ink/aimodels-prices.git
synced 2025-07-18 21:51:59 +08:00
- 将数据库操作从原生 SQL 迁移到 GORM ORM - 更新模型定义,添加 GORM 标签和关系 - 移除手动创建表的 SQL 方法,改用 AutoMigrate - 更新所有数据库相关处理逻辑以适配 GORM - 升级 Go 版本和依赖库 - 移除数据库和路由中间件,简化项目结构
82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"aimodels-prices/database"
|
|
"aimodels-prices/models"
|
|
)
|
|
|
|
func AuthRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
cookie, err := c.Cookie("session")
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Not logged in"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
var session models.Session
|
|
if err := database.DB.Preload("User").Where("id = ? AND expires_at > ?", cookie, time.Now()).First(&session).Error; err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired session"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("user", &session.User)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func AdminRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
user, exists := c.Get("user")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Not logged in"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if u, ok := user.(*models.User); !ok || u.Role != "admin" {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func RequireAuth() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
_, exists := c.Get("user")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func RequireAdmin() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
user, exists := c.Get("user")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if u, ok := user.(*models.User); !ok || u.Role != "admin" {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|