admin_handler.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "note-manager/config"
  6. "note-manager/service"
  7. )
  8. // AdminHandler 后台管理处理器
  9. type AdminHandler struct {
  10. noteSvc *service.NoteService
  11. config *config.Config
  12. }
  13. // NewAdminHandler 创建后台管理处理器
  14. func NewAdminHandler(noteSvc *service.NoteService, cfg *config.Config) *AdminHandler {
  15. return &AdminHandler{noteSvc: noteSvc, config: cfg}
  16. }
  17. // Login 登录页面
  18. func (h *AdminHandler) LoginPage(c *gin.Context) {
  19. c.HTML(http.StatusOK, "login.html", gin.H{
  20. "title": "后台管理登录",
  21. })
  22. }
  23. // Login 验证登录
  24. func (h *AdminHandler) Login(c *gin.Context) {
  25. password := c.PostForm("password")
  26. if password == h.config.AdminPass {
  27. // 设置 cookie,有效期 7 天
  28. c.SetCookie("admin_token", "authenticated", 7*24*3600, "/", "", false, true)
  29. c.JSON(http.StatusOK, gin.H{
  30. "code": 0,
  31. "message": "登录成功",
  32. })
  33. return
  34. }
  35. c.JSON(http.StatusUnauthorized, gin.H{
  36. "code": 401,
  37. "message": "密码错误",
  38. })
  39. }
  40. // Logout 登出
  41. func (h *AdminHandler) Logout(c *gin.Context) {
  42. c.SetCookie("admin_token", "", -1, "/", "", false, true)
  43. c.JSON(http.StatusOK, gin.H{
  44. "code": 0,
  45. "message": "已退出登录",
  46. })
  47. }
  48. // CheckAuth 检查是否已登录
  49. func (h *AdminHandler) CheckAuth(c *gin.Context) {
  50. token, err := c.Cookie("admin_token")
  51. if err == nil && token == "authenticated" {
  52. c.JSON(http.StatusOK, gin.H{
  53. "code": 0,
  54. "message": "已登录",
  55. "data": gin.H{
  56. "authenticated": true,
  57. },
  58. })
  59. return
  60. }
  61. c.JSON(http.StatusOK, gin.H{
  62. "code": 0,
  63. "message": "未登录",
  64. "data": gin.H{
  65. "authenticated": false,
  66. },
  67. })
  68. }
  69. // IndexPage 后台管理首页
  70. func (h *AdminHandler) IndexPage(c *gin.Context) {
  71. token, err := c.Cookie("admin_token")
  72. if err != nil || token != "authenticated" {
  73. c.Redirect(http.StatusFound, "/admin/login")
  74. return
  75. }
  76. c.HTML(http.StatusOK, "index.html", gin.H{
  77. "title": "笔记管理后台",
  78. })
  79. }