81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.threesix.ai/jordan/sp4-verify-1770325799/pkg/auth"
|
|
"git.threesix.ai/jordan/sp4-verify-1770325799/pkg/httperror"
|
|
"git.threesix.ai/jordan/sp4-verify-1770325799/pkg/httpresponse"
|
|
"git.threesix.ai/jordan/sp4-verify-1770325799/pkg/logging"
|
|
)
|
|
|
|
// Validate handles token validation requests from sibling services.
|
|
type Validate struct {
|
|
validator *auth.JWTValidator
|
|
logger *logging.Logger
|
|
}
|
|
|
|
// NewValidate creates a new Validate handler.
|
|
func NewValidate(validator *auth.JWTValidator, logger *logging.Logger) *Validate {
|
|
return &Validate{
|
|
validator: validator,
|
|
logger: logger.WithComponent("ValidateHandler"),
|
|
}
|
|
}
|
|
|
|
// ValidateRequest is the request body for token validation.
|
|
type ValidateRequest struct {
|
|
Token string `json:"token" validate:"required"`
|
|
}
|
|
|
|
// ValidateResponse is the response for token validation.
|
|
type ValidateResponse struct {
|
|
Valid bool `json:"valid"`
|
|
User *auth.User `json:"user,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
// Check validates a JWT token and returns the user information.
|
|
func (h *Validate) Check(w http.ResponseWriter, r *http.Request) error {
|
|
// Extract token from Authorization header or request body
|
|
token := extractToken(r)
|
|
if token == "" {
|
|
return httperror.BadRequest("token is required")
|
|
}
|
|
|
|
// Validate the token
|
|
user, err := h.validator.Validate(r.Context(), token)
|
|
if err != nil {
|
|
h.logger.Debug("token validation failed", "error", err)
|
|
httpresponse.OK(w, r, ValidateResponse{
|
|
Valid: false,
|
|
Error: err.Error(),
|
|
})
|
|
return nil
|
|
}
|
|
|
|
httpresponse.OK(w, r, ValidateResponse{
|
|
Valid: true,
|
|
User: user,
|
|
})
|
|
return nil
|
|
}
|
|
|
|
// extractToken extracts the JWT token from the request.
|
|
// Checks Authorization header first, then falls back to query parameter.
|
|
func extractToken(r *http.Request) string {
|
|
// Check Authorization header
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader != "" {
|
|
// Handle "Bearer <token>" format
|
|
if strings.HasPrefix(authHeader, "Bearer ") {
|
|
return strings.TrimPrefix(authHeader, "Bearer ")
|
|
}
|
|
return authHeader
|
|
}
|
|
|
|
// Check query parameter
|
|
return r.URL.Query().Get("token")
|
|
}
|