auth.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package middleware
  2. import (
  3. "net/http"
  4. "time"
  5. "easydo-echo_win7/utils"
  6. "github.com/labstack/echo-contrib/session"
  7. "github.com/labstack/echo/v4"
  8. )
  9. // AuthMiddleware 认证中间件
  10. func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
  11. return func(c echo.Context) error {
  12. sess, _ := session.Get("auth_session", c)
  13. // 检查是否已认证
  14. if auth, ok := sess.Values["is_authenticated"].(bool); !ok || !auth {
  15. return c.JSON(http.StatusUnauthorized, utils.ErrorResponse("请先登录", ""))
  16. }
  17. // 检查会话是否过期(超过7天)
  18. if loginTime, ok := sess.Values["login_time"].(int64); ok {
  19. if time.Now().Unix()-loginTime > 7*24*60*60 {
  20. // 清除过期会话
  21. sess.Options.MaxAge = -1
  22. sess.Save(c.Request(), c.Response())
  23. return c.JSON(http.StatusUnauthorized, utils.ErrorResponse("会话已过期,请重新登录", ""))
  24. }
  25. }
  26. // 将用户信息存入上下文
  27. c.Set("user_id", sess.Values["user_id"])
  28. c.Set("username", sess.Values["username"])
  29. return next(c)
  30. }
  31. }
  32. // AdminMiddleware 管理员中间件
  33. func AdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
  34. return func(c echo.Context) error {
  35. role := c.Get("role").(string)
  36. if role != "admin" {
  37. return c.JSON(http.StatusForbidden, utils.ErrorResponse("权限不足", ""))
  38. }
  39. return next(c)
  40. }
  41. }