add admin router

This commit is contained in:
张超
2025-06-18 18:34:08 +08:00
parent 67c85327ee
commit 4c9f6c140f
4 changed files with 32 additions and 86 deletions

View File

@@ -32,10 +32,6 @@ type DataBaseConfig struct {
MaxConns int `mapstructure:"max_conns"` MaxConns int `mapstructure:"max_conns"`
} }
type Jwt struct {
SecretKey string
}
type Project struct { type Project struct {
StaticUrlMapPath []interface{} StaticUrlMapPath []interface{}
TemplateGlob string TemplateGlob string
@@ -56,17 +52,15 @@ type ThemeConfig struct {
AllowUpload bool `mapstructure:"allow_upload"` AllowUpload bool `mapstructure:"allow_upload"`
} }
type SecurityConfig struct { type SecurityConfig struct {
JWTSecret string `mapstructure:"jwt_secret"`
CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"` CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"`
} }
type Config struct { type Config struct {
Env string Env string
Server ServerConfig Server ServerConfig
DataBase DataBaseConfig DataBase DataBaseConfig
Theme ThemeConfig Theme ThemeConfig
JwtSecretKey Jwt Project Project
Project Project Security SecurityConfig
Security SecurityConfig
} }
var globalConfig *Config // 新增全局配置变量 var globalConfig *Config // 新增全局配置变量
@@ -109,11 +103,6 @@ func LoadConfig(configPath string) (*Config, error) {
return nil, fmt.Errorf("配置解析失败: %w", err) return nil, fmt.Errorf("配置解析失败: %w", err)
} }
// 6. 校验必要配置项
// if cfg.Security.JWTSecret == "" {
// return nil, fmt.Errorf("安全配置错误: jwt_secret 必须设置")
// }
// 获取配置值 // 获取配置值
mysqlHost := viper.GetString("database.Host") mysqlHost := viper.GetString("database.Host")
jwtSecretKey := viper.GetString("jwt.SecretKey") jwtSecretKey := viper.GetString("jwt.SecretKey")
@@ -128,25 +117,3 @@ func LoadConfig(configPath string) (*Config, error) {
globalConfig = &cfg // 保存配置到全局变量 globalConfig = &cfg // 保存配置到全局变量
return &cfg, nil return &cfg, nil
} }
func GetCurrentTheme() string {
return "default"
}
func SetCurrentTheme(theme string) error {
return nil
}
// GetJWTSecret 获取 JWT 密钥
// 移除原有的方法定义(如果存在)
// func (c *Config) GetJWTSecret() string {
// 原错误:返回 security.JWTSecret实际应使用 jwtSecretKey.SecretKey
// }
// 新增包级函数获取 JWT 密钥
func GetJWTSecret() string {
if globalConfig == nil {
//panic("配置未加载,请先调用 LoadConfig")
}
return globalConfig.JwtSecretKey.SecretKey
}

View File

@@ -24,26 +24,3 @@ func ShowAdminIndexPage(c *gin.Context) {
c.String(http.StatusInternalServerError, "渲染模板失败: "+err.Error()) c.String(http.StatusInternalServerError, "渲染模板失败: "+err.Error())
} }
} }
// ShowThemeSwitchPage 渲染主题切换页面
func ShowThemeSwitchPage(c *gin.Context) {
// 假设主题列表存储在固定路径或需要手动维护(示例数据,需根据实际情况修改)
themes := []string{"default", "dark", "light"} // 示例主题列表
currentTheme := "default" // 示例当前主题(需根据实际存储方式获取)
// 直接加载 web/admin 目录下的 themes.tmpl 模板(需确保文件存在)
tpl, err := template.ParseFiles("web/admin/themes.tmpl")
if err != nil {
c.String(http.StatusInternalServerError, "加载模板失败: "+err.Error())
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
err = tpl.Execute(c.Writer, gin.H{
"CurrentTheme": currentTheme,
"Themes": themes,
})
if err != nil {
c.String(http.StatusInternalServerError, "渲染模板失败: "+err.Error())
}
}

View File

@@ -1,6 +1,7 @@
package controllers package controllers
import ( import (
"html/template"
"net/http" "net/http"
"go_blog/config" "go_blog/config"
@@ -31,12 +32,14 @@ func ListThemes(c *gin.Context) {
} }
// 渲染管理页面模板 // 渲染管理页面模板
tpl := themeManager.GetTemplate("admin/themes") // 对应 templates/admin/themes.tmpl // 直接加载 web/admin/themes.tmpl 文件(路径相对于项目根目录)
if tpl == nil { const themesTemplatePath = "web/admin/themes.tmpl" // 定义模板路径常量
c.String(http.StatusInternalServerError, "模板 'admin/themes' 未找到")
tpl, err := template.ParseFiles(themesTemplatePath)
if err != nil {
c.String(http.StatusInternalServerError, "模板加载失败: "+err.Error())
return return
} }
c.Header("Content-Type", "text/html; charset=utf-8") c.Header("Content-Type", "text/html; charset=utf-8")
err = tpl.Execute(c.Writer, gin.H{ err = tpl.Execute(c.Writer, gin.H{
"CurrentTheme": themeManager.CurrentTheme(), "CurrentTheme": themeManager.CurrentTheme(),

View File

@@ -19,28 +19,28 @@ import (
// 新增:自定义后台认证中间件(处理页面重定向) // 新增:自定义后台认证中间件(处理页面重定向)
// 自定义后台认证中间件通过Session判断登录状态 // 自定义后台认证中间件通过Session判断登录状态
func CheckAdminAuth() gin.HandlerFunc { func CheckAdminAuth() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
currentPath := c.Request.URL.Path currentPath := c.Request.URL.Path
session := sessions.Default(c) // 获取当前请求的Session session := sessions.Default(c) // 获取当前请求的Session
userID := session.Get("user_id") // 从Session中获取用户ID userID := session.Get("user_id") // 从Session中获取用户ID
loggedIn := userID != nil && userID != "" loggedIn := userID != nil && userID != ""
// 已登录状态访问登录/注册页:重定向到后台首页 // 已登录状态访问登录/注册页:重定向到后台首页
if (currentPath == "/admin/login" || currentPath == "/admin/register") && loggedIn { if (currentPath == "/admin/login" || currentPath == "/admin/register") && loggedIn {
c.Redirect(http.StatusFound, "/admin/index") c.Redirect(http.StatusFound, "/admin/index")
c.Abort() c.Abort()
return return
} }
// 未登录状态访问非登录/注册页:重定向到登录页 // 未登录状态访问非登录/注册页:重定向到登录页
if (currentPath != "/admin/login" && currentPath != "/admin/register") && !loggedIn { if (currentPath != "/admin/login" && currentPath != "/admin/register") && !loggedIn {
c.Redirect(http.StatusFound, "/admin/login") c.Redirect(http.StatusFound, "/admin/login")
c.Abort() c.Abort()
return return
} }
c.Next() c.Next()
} }
} }
// 新增基于Session的认证中间件 // 新增基于Session的认证中间件
@@ -177,7 +177,6 @@ func RegisterRoutes(r *gin.Engine) {
{ {
authAdmin.GET("/index", controllers.ShowAdminIndexPage) authAdmin.GET("/index", controllers.ShowAdminIndexPage)
authAdmin.GET("/themes", controllers.ListThemes) authAdmin.GET("/themes", controllers.ListThemes)
authAdmin.GET("/themes/switch", controllers.ShowThemeSwitchPage)
authAdmin.POST("/themes/switch", controllers.SwitchTheme) authAdmin.POST("/themes/switch", controllers.SwitchTheme)
authAdmin.POST("/setinfo", controllers.UsersSetInfoHandler) authAdmin.POST("/setinfo", controllers.UsersSetInfoHandler)
authAdmin.POST("/setpwd", controllers.UsersSetPwdHandler) authAdmin.POST("/setpwd", controllers.UsersSetPwdHandler)