first commit
This commit is contained in:
43
backend/internal/auth/middleware.go
Normal file
43
backend/internal/auth/middleware.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const ContextClaimsKey = "auth_claims"
|
||||
const ContextUserIDKey = "auth_user_id"
|
||||
const ContextRoleKey = "auth_role"
|
||||
|
||||
func RequireAuth(tokens TokenService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
header := c.GetHeader("Authorization")
|
||||
if header == "" || !strings.HasPrefix(header, "Bearer ") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Autenticacao obrigatoria."})
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := tokens.ParseAccessToken(strings.TrimPrefix(header, "Bearer "))
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Sessao invalida ou expirada."})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(ContextClaimsKey, claims)
|
||||
c.Set(ContextUserIDKey, claims.UserID)
|
||||
c.Set(ContextRoleKey, claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func ClaimsFromContext(c *gin.Context) (Claims, bool) {
|
||||
value, ok := c.Get(ContextClaimsKey)
|
||||
if !ok {
|
||||
return Claims{}, false
|
||||
}
|
||||
|
||||
claims, ok := value.(Claims)
|
||||
return claims, ok
|
||||
}
|
||||
Reference in New Issue
Block a user