From ed53fbc9097370feeda1c5507878933643a9bcc5 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Sat, 10 Apr 2021 14:16:41 +0300 Subject: Trying to auth --- src/error.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/error.rs (limited to 'src/error.rs') diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..0db26c4 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,63 @@ +use serde::Serialize; +use std::convert::Infallible; +use thiserror::Error; +use warp::{http::StatusCode, Rejection, Reply}; + +#[derive(Error, Debug)] +pub enum Error { + // #[error("wrong credentials")] + // WrongCredentialsError, + #[error("jwt token not valid")] + JWTTokenError, + // #[error("jwt token creation error")] + // JWTTokenCreationError, + #[error("no auth header")] + NoAuthHeaderError, + #[error("invalid auth header")] + InvalidAuthHeaderError, + // #[error("no permission")] + // NoPermissionError, +} + +#[derive(Serialize, Debug)] +struct ErrorResponse { + message: String, + status: String, +} + +impl warp::reject::Reject for Error {} + +pub async fn handle_rejection(err: Rejection) -> std::result::Result { + let (code, message) = if err.is_not_found() { + (StatusCode::NOT_FOUND, "Not Found".to_string()) + } else if let Some(e) = err.find::() { + match e { + // Error::WrongCredentialsError => (StatusCode::FORBIDDEN, e.to_string()), + // Error::NoPermissionError => (StatusCode::UNAUTHORIZED, e.to_string()), + Error::JWTTokenError => (StatusCode::UNAUTHORIZED, e.to_string()), + // Error::JWTTokenCreationError => ( + // StatusCode::INTERNAL_SERVER_ERROR, + // "Internal Server Error".to_string(), + // ), + _ => (StatusCode::BAD_REQUEST, e.to_string()), + } + } else if err.find::().is_some() { + ( + StatusCode::METHOD_NOT_ALLOWED, + "Method Not Allowed".to_string(), + ) + } else { + eprintln!("unhandled error: {:?}", err); + ( + StatusCode::INTERNAL_SERVER_ERROR, + "Internal Server Error".to_string(), + ) + }; + + let json = warp::reply::json(&ErrorResponse { + status: code.to_string(), + message, + }); + + Ok(warp::reply::with_status(json, code)) +} -- cgit v1.2.3-70-g09d2