56 lines
1.5 KiB
Go
56 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/pkg/auth"
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/pkg/httperror"
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/pkg/httpresponse"
|
|
"git.threesix.ai/jordan/sp4-v2-1770499323/pkg/logging"
|
|
)
|
|
|
|
// Validate handles token validation requests from sibling services.
|
|
type Validate struct {
|
|
validator auth.Validator
|
|
logger *logging.Logger
|
|
}
|
|
|
|
// NewValidate creates a new Validate handler with injected dependencies.
|
|
func NewValidate(validator auth.Validator, logger *logging.Logger) *Validate {
|
|
return &Validate{
|
|
validator: validator,
|
|
logger: logger.WithComponent("ValidateHandler"),
|
|
}
|
|
}
|
|
|
|
// ValidateResponse is the response body for a successful token validation.
|
|
type ValidateResponse struct {
|
|
UserID string `json:"user_id"`
|
|
Email string `json:"email,omitempty"`
|
|
Roles []string `json:"roles,omitempty"`
|
|
Scopes []string `json:"scopes,omitempty"`
|
|
}
|
|
|
|
// Check validates the Bearer token from the Authorization header
|
|
// and returns the authenticated user info.
|
|
func (h *Validate) Check(w http.ResponseWriter, r *http.Request) error {
|
|
token := auth.ExtractBearerToken(r)
|
|
if token == "" {
|
|
return httperror.Unauthorized("missing bearer token")
|
|
}
|
|
|
|
user, err := h.validator.Validate(r.Context(), token)
|
|
if err != nil {
|
|
h.logger.Debug("token validation failed", "error", err)
|
|
return httperror.Unauthorized("invalid token")
|
|
}
|
|
|
|
httpresponse.OK(w, r, ValidateResponse{
|
|
UserID: user.ID,
|
|
Email: user.Email,
|
|
Roles: user.Roles,
|
|
Scopes: user.Scopes,
|
|
})
|
|
return nil
|
|
}
|