32 lines
755 B
Go
32 lines
755 B
Go
package api
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"asset-tracker/internal/auth"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AuthRequired(tm *auth.TokenManager) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
|
JSONUnauthorized(c, "AUTH_MISSING_BEARER", "missing bearer token")
|
|
c.Abort()
|
|
return
|
|
}
|
|
token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
|
|
claims, err := tm.ParseAndValidate(token, "access")
|
|
if err != nil {
|
|
JSONUnauthorized(c, "AUTH_INVALID_TOKEN", "invalid token")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
c.Set("timezone", claims.Timezone)
|
|
c.Next()
|
|
}
|
|
}
|