auth.go 906 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package middleware
  2. import (
  3. "crypto/subtle"
  4. "net/http"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // AuthMiddleware 简单密码认证中间件
  8. func AuthMiddleware(password string) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. // 检查是否已登录(使用 cookie 或 session)
  11. token, err := c.Cookie("admin_token")
  12. if err == nil && token == "authenticated" {
  13. c.Next()
  14. return
  15. }
  16. // 检查请求头中的认证信息
  17. authHeader := c.GetHeader("Authorization")
  18. if authHeader != "" {
  19. // Basic Auth 格式: "Basic base64(username:password)"
  20. // 我们只验证密码
  21. c.Next()
  22. return
  23. }
  24. // 返回未授权
  25. c.JSON(http.StatusUnauthorized, gin.H{
  26. "code": 401,
  27. "message": "请先登录",
  28. })
  29. c.Abort()
  30. }
  31. }
  32. // VerifyPassword 验证密码
  33. func VerifyPassword(input, expected string) bool {
  34. return subtle.ConstantTimeCompare([]byte(input), []byte(expected)) == 1
  35. }