Files
mtusi2026lab5/internal/auth/middleware.go
T

49 lines
1.3 KiB
Go

package auth
import (
"strings"
"github.com/gin-gonic/gin"
"messenger/internal/platform/httpx"
)
const keyToken = "messenger.session_token"
// RequireSession admits a request only with Authorization: Bearer <token> of
// a live session and records its owner for the handlers behind it. Any other
// identification, including Basic credentials and X-User-Id, is ignored, so
// it can neither grant access nor change the caller.
func RequireSession(sessions *Service) gin.HandlerFunc {
return func(c *gin.Context) {
token, ok := bearerToken(c.GetHeader("Authorization"))
if !ok {
unauthorized(c, bearerChallenge, ErrUnauthenticated)
return
}
userID, err := sessions.Authenticate(c.Request.Context(), token)
if err != nil {
unauthorized(c, bearerChallenge, err)
return
}
httpx.SetUserID(c, userID)
c.Set(keyToken, token)
c.Next()
}
}
// bearerToken parses "Bearer <token>": the scheme is case-insensitive and
// may be followed by several spaces (RFC 7235); the token itself never
// contains whitespace.
func bearerToken(header string) (string, bool) {
scheme, rest, found := strings.Cut(header, " ")
if !found || !strings.EqualFold(scheme, "Bearer") {
return "", false
}
token := strings.TrimLeft(rest, " ")
if token == "" || strings.ContainsAny(token, " \t") {
return "", false
}
return token, true
}