validate_token

Function validate_token 

Source
pub async fn validate_token(
    cookies: CookieJar,
    __arg1: State<Arc<AppState>>,
    request: Request<Body>,
    next: Next,
) -> Result<impl IntoResponse, (StatusCode, Json<Value>)>
Expand description

Axum middleware to validate a JWT token present in cookies or Authorization header.

This function extracts a JWT from the request (either from the token cookie or the Authorization: Bearer header), decodes and validates it using decode_token). If valid, it fetches the corresponding User from the database and inserts a FilteredUser (converted via filter_user) into the request extensions for subsequent handlers to use.

If the token is missing, invalid, or the user is not found, it returns an appropriate error response (401 Unauthorized).

§Arguments

  • cookies: The CookieJar from the request, used to extract the token cookie.
  • State(data): Application state containing AppState for database access and token_secret.
  • mut request: The incoming HTTP request, which will have user data injected into its extensions.
  • next: The next middleware or handler in the chain.

§Returns

  • Ok(impl IntoResponse): If validation succeeds, the request proceeds to the next handler.
  • Err((StatusCode, Json<serde_json::Value>)): An error response if validation fails.