package handler import ( "net/http" "github.com/gin-gonic/gin" "note-manager/config" "note-manager/service" ) // AdminHandler 后台管理处理器 type AdminHandler struct { noteSvc *service.NoteService config *config.Config } // NewAdminHandler 创建后台管理处理器 func NewAdminHandler(noteSvc *service.NoteService, cfg *config.Config) *AdminHandler { return &AdminHandler{noteSvc: noteSvc, config: cfg} } // Login 登录页面 func (h *AdminHandler) LoginPage(c *gin.Context) { c.HTML(http.StatusOK, "login.html", gin.H{ "title": "后台管理登录", }) } // Login 验证登录 func (h *AdminHandler) Login(c *gin.Context) { password := c.PostForm("password") if password == h.config.AdminPass { // 设置 cookie,有效期 7 天 c.SetCookie("admin_token", "authenticated", 7*24*3600, "/", "", false, true) c.JSON(http.StatusOK, gin.H{ "code": 0, "message": "登录成功", }) return } c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "message": "密码错误", }) } // Logout 登出 func (h *AdminHandler) Logout(c *gin.Context) { c.SetCookie("admin_token", "", -1, "/", "", false, true) c.JSON(http.StatusOK, gin.H{ "code": 0, "message": "已退出登录", }) } // CheckAuth 检查是否已登录 func (h *AdminHandler) CheckAuth(c *gin.Context) { token, err := c.Cookie("admin_token") if err == nil && token == "authenticated" { c.JSON(http.StatusOK, gin.H{ "code": 0, "message": "已登录", "data": gin.H{ "authenticated": true, }, }) return } c.JSON(http.StatusOK, gin.H{ "code": 0, "message": "未登录", "data": gin.H{ "authenticated": false, }, }) } // IndexPage 后台管理首页 func (h *AdminHandler) IndexPage(c *gin.Context) { token, err := c.Cookie("admin_token") if err != nil || token != "authenticated" { c.Redirect(http.StatusFound, "/admin/login") return } c.HTML(http.StatusOK, "index.html", gin.H{ "title": "笔记管理后台", }) }