From f108c592a96dfa8996c4b0a371cc936a615358c3 Mon Sep 17 00:00:00 2001 From: landrigun Date: Thu, 16 Feb 2023 11:00:11 +0000 Subject: [PATCH] impl ValidationMessage using serde_json to build json response body --- src/router/router.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/router/router.rs b/src/router/router.rs index 36e10e8..2182fed 100644 --- a/src/router/router.rs +++ b/src/router/router.rs @@ -3,6 +3,7 @@ use http::{HTTPRequest, HTTPResponse, JSONMessage}; use json::JsonValue; +use serde::Serialize; use crate::config::Config; use crate::jwt::{JWTMessage, JWTSigner}; @@ -13,6 +14,14 @@ const GET_ROUTE: &'static str = "/get/"; const VALIDATE_ROUTE: &'static str = "/validate/"; const PUBKEY_ROUTE: &'static str = "/pubkey/"; +#[derive(Serialize, Default)] +/// ValidationMessage aims to build a JSON HTTP response body for JWT validation +struct ValidationMessage { + is_valid: bool, + #[serde(skip_serializing_if = "String::is_empty")] + reason: String, +} + async fn handle_get(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse { if method.trim().to_lowercase() != "post" { return HTTPResponse::as_400(); @@ -54,7 +63,7 @@ async fn handle_get(request: HTTPRequest<'_>, config: Config, method: &str) -> H } } -/// validates the token by checking: +/// handle_validate validates the token by checking: /// * expiration time /// * signature async fn handle_validate(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse { @@ -87,22 +96,21 @@ async fn handle_validate(request: HTTPRequest<'_>, config: Config, method: &str) } }; - let mut message = JSONMessage::default(); + let mut message = ValidationMessage::default(); match jwt_signer.validate(&token) { Ok(()) => { - message.put("valid", "true"); + message.is_valid = true; } Err(e) => { - message.put("valid", "false"); - message.put("reason", &e); + message.reason = e; } } - let json: JsonValue = message.try_into().unwrap(); + let json: JsonValue = json::parse(&serde_json::to_string(&message).unwrap()).unwrap(); HTTPResponse::as_200(Some(json)) } -/// returns the JWT public key in base64 encoded +/// handle_public_key returns the JWT public key in base64 encoded async fn handle_public_key(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse { if request.get_method().trim().to_lowercase() != method { return HTTPResponse::as_400();