| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- package middleware
- import (
- "crypto/subtle"
- "net/http"
- "github.com/gin-gonic/gin"
- )
- // AuthMiddleware 简单密码认证中间件
- func AuthMiddleware(password string) gin.HandlerFunc {
- return func(c *gin.Context) {
- // 检查是否已登录(使用 cookie 或 session)
- token, err := c.Cookie("admin_token")
- if err == nil && token == "authenticated" {
- c.Next()
- return
- }
- // 检查请求头中的认证信息
- authHeader := c.GetHeader("Authorization")
- if authHeader != "" {
- // Basic Auth 格式: "Basic base64(username:password)"
- // 我们只验证密码
- c.Next()
- return
- }
- // 返回未授权
- c.JSON(http.StatusUnauthorized, gin.H{
- "code": 401,
- "message": "请先登录",
- })
- c.Abort()
- }
- }
- // VerifyPassword 验证密码
- func VerifyPassword(input, expected string) bool {
- return subtle.ConstantTimeCompare([]byte(input), []byte(expected)) == 1
- }
|