feat: add private auth foundation

This commit is contained in:
2026-07-18 15:55:55 +08:00
parent cccd0e6ce5
commit 437c070e45
4 changed files with 160 additions and 1 deletions

View File

@@ -0,0 +1,28 @@
package auth
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
const CurrentUserIDKey = "currentUserID"
func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
token := strings.TrimPrefix(header, "Bearer ")
if token == "" || token == header {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
return
}
userID, err := tokenVerifier(token)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"})
return
}
c.Set(CurrentUserIDKey, userID)
c.Next()
}
}