impl ValidationMessage using serde_json to build json response body

This commit is contained in:
landrigun 2023-02-16 11:00:11 +00:00
parent 530063f8ff
commit f108c592a9

View File

@ -3,6 +3,7 @@
use http::{HTTPRequest, HTTPResponse, JSONMessage}; use http::{HTTPRequest, HTTPResponse, JSONMessage};
use json::JsonValue; use json::JsonValue;
use serde::Serialize;
use crate::config::Config; use crate::config::Config;
use crate::jwt::{JWTMessage, JWTSigner}; use crate::jwt::{JWTMessage, JWTSigner};
@ -13,6 +14,14 @@ const GET_ROUTE: &'static str = "/get/";
const VALIDATE_ROUTE: &'static str = "/validate/"; const VALIDATE_ROUTE: &'static str = "/validate/";
const PUBKEY_ROUTE: &'static str = "/pubkey/"; 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 { async fn handle_get(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse {
if method.trim().to_lowercase() != "post" { if method.trim().to_lowercase() != "post" {
return HTTPResponse::as_400(); 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 /// * expiration time
/// * signature /// * signature
async fn handle_validate(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse { 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) { match jwt_signer.validate(&token) {
Ok(()) => { Ok(()) => {
message.put("valid", "true"); message.is_valid = true;
} }
Err(e) => { Err(e) => {
message.put("valid", "false"); message.reason = e;
message.put("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)) 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 { async fn handle_public_key(request: HTTPRequest<'_>, config: Config, method: &str) -> HTTPResponse {
if request.get_method().trim().to_lowercase() != method { if request.get_method().trim().to_lowercase() != method {
return HTTPResponse::as_400(); return HTTPResponse::as_400();