rusty-bever/src/errors.rs

91 lines
2.8 KiB
Rust
Raw Normal View History

2021-08-22 16:45:01 +02:00
use rocket::{
http::Status,
request::Request,
response::{self, Responder},
serde::json::json,
2021-08-22 16:45:01 +02:00
};
2021-08-21 18:05:16 +02:00
#[derive(Debug)]
2021-08-27 08:50:48 +02:00
pub enum RbError
2021-08-22 16:45:01 +02:00
{
2021-08-27 08:50:48 +02:00
AuthUnknownUser,
AuthBlockedUser,
AuthInvalidPassword,
AuthUnauthorized,
AuthTokenExpired,
AuthRefreshTokenExpired,
AuthInvalidRefreshToken,
AuthDuplicateRefreshToken,
2021-09-01 17:29:39 +02:00
AuthMissingHeader,
2021-08-27 08:50:48 +02:00
// UM = User Management
UMDuplicateUser,
UMUnknownUser,
2021-08-27 08:50:48 +02:00
DbError(&'static str),
Custom(&'static str),
2021-08-20 23:09:22 +02:00
}
2021-08-21 15:58:51 +02:00
impl RbError
{
pub fn status(&self) -> Status
{
// Every entry gets its own line for easy editing later when needed
match self {
RbError::AuthUnknownUser => Status::NotFound,
RbError::AuthBlockedUser => Status::Forbidden,
RbError::AuthInvalidPassword => Status::Unauthorized,
RbError::AuthUnauthorized => Status::Unauthorized,
RbError::AuthTokenExpired => Status::Unauthorized,
RbError::AuthRefreshTokenExpired => Status::Unauthorized,
RbError::AuthInvalidRefreshToken => Status::Unauthorized,
RbError::AuthDuplicateRefreshToken => Status::Unauthorized,
2021-09-01 17:29:39 +02:00
RbError::AuthMissingHeader => Status::BadRequest,
RbError::UMDuplicateUser => Status::Conflict,
RbError::Custom(_) => Status::InternalServerError,
_ => Status::InternalServerError,
}
2021-08-27 08:50:48 +02:00
}
pub fn message(&self) -> &'static str
{
2021-08-27 08:50:48 +02:00
match self {
RbError::AuthUnknownUser => "This user doesn't exist.",
RbError::AuthBlockedUser => "This user is blocked.",
RbError::AuthInvalidPassword => "Invalid credentials.",
RbError::AuthUnauthorized => "You are not authorized to access this resource.",
RbError::AuthTokenExpired => "This token is not valid anymore.",
RbError::AuthRefreshTokenExpired => "This refresh token is not valid anymore.",
RbError::AuthInvalidRefreshToken => "This refresh token is not valid.",
RbError::AuthDuplicateRefreshToken => {
"This refresh token has already been used. The user has been blocked."
}
2021-09-01 17:29:39 +02:00
RbError::AuthMissingHeader => "Missing Authorization header.",
RbError::UMDuplicateUser => "This user already exists.",
2021-08-27 08:50:48 +02:00
RbError::Custom(message) => message,
_ => "",
2021-08-27 08:50:48 +02:00
}
}
}
impl<'r> Responder<'r, 'static> for RbError
2021-08-22 16:45:01 +02:00
{
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static>
2021-08-22 16:45:01 +02:00
{
let status = self.status();
let content = json!({
"status": status.code,
"message": self.message(),
});
2021-08-21 15:58:51 +02:00
2021-08-29 19:04:06 +02:00
// TODO add status to response
content.respond_to(req)
2021-08-21 15:58:51 +02:00
}
}
2021-08-29 20:30:33 +02:00
pub type RbResult<T> = std::result::Result<T, RbError>;