rusty-bever/src/rb/errors.rs

38 lines
1.3 KiB
Rust
Raw Normal View History

2021-08-21 15:58:51 +02:00
use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::http::Status;
use std::io;
pub enum RBError {
/// When the login requests an unknown user
2021-08-20 23:09:22 +02:00
UnknownUser,
2021-08-21 15:58:51 +02:00
/// Invalid login password.
2021-08-20 23:09:22 +02:00
InvalidPassword,
2021-08-21 15:58:51 +02:00
/// When a non-admin user tries to use an admin endpoint
Unauthorized,
/// When an expired JWT token is used for auth.
2021-08-21 16:45:41 +02:00
JWTTokenExpired,
/// Umbrella error for when something goes wrong whilst creating a JWT token pair
JWTCreationError
2021-08-20 23:09:22 +02:00
}
2021-08-21 15:58:51 +02:00
impl<'r> Responder<'r, 'static> for RBError {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
let (status, message): (Status, &str) = match self {
2021-08-21 16:45:41 +02:00
RBError::UnknownUser => (Status::NotFound, "Unknown user"),
RBError::InvalidPassword => (Status::Unauthorized, "Invalid password"),
RBError::Unauthorized => (Status::Unauthorized, "Unauthorized"),
RBError::JWTTokenExpired => (Status::Unauthorized, "Token expired"),
RBError::JWTCreationError => (Status::InternalServerError, "Failed to create tokens."),
2021-08-21 15:58:51 +02:00
};
2021-08-21 16:45:41 +02:00
let mut res = Response::new();
2021-08-21 15:58:51 +02:00
res.set_status(status);
res.set_sized_body(message.len(), io::Cursor::new(message));
Ok(res)
}
}
pub type Result<T> = std::result::Result<T, RBError>;