Default catcher now returns json

develop
Jef Roosens 2021-09-01 17:29:39 +02:00
parent f50008ff99
commit 505907d3a1
Signed by untrusted user: Jef Roosens
GPG Key ID: B580B976584B5F30
3 changed files with 19 additions and 14 deletions

View File

@ -16,6 +16,7 @@ pub enum RbError
AuthRefreshTokenExpired, AuthRefreshTokenExpired,
AuthInvalidRefreshToken, AuthInvalidRefreshToken,
AuthDuplicateRefreshToken, AuthDuplicateRefreshToken,
AuthMissingHeader,
// UM = User Management // UM = User Management
UMDuplicateUser, UMDuplicateUser,
@ -39,6 +40,7 @@ impl RbError
RbError::AuthRefreshTokenExpired => Status::Unauthorized, RbError::AuthRefreshTokenExpired => Status::Unauthorized,
RbError::AuthInvalidRefreshToken => Status::Unauthorized, RbError::AuthInvalidRefreshToken => Status::Unauthorized,
RbError::AuthDuplicateRefreshToken => Status::Unauthorized, RbError::AuthDuplicateRefreshToken => Status::Unauthorized,
RbError::AuthMissingHeader => Status::BadRequest,
RbError::UMDuplicateUser => Status::Conflict, RbError::UMDuplicateUser => Status::Conflict,
@ -60,6 +62,7 @@ impl RbError
RbError::AuthDuplicateRefreshToken => { RbError::AuthDuplicateRefreshToken => {
"This refresh token has already been used. The user has been blocked." "This refresh token has already been used. The user has been blocked."
} }
RbError::AuthMissingHeader => "Missing Authorization header.",
RbError::UMDuplicateUser => "This user already exists.", RbError::UMDuplicateUser => "This user already exists.",

View File

@ -1,5 +1,3 @@
use std::convert::From;
use hmac::{Hmac, NewMac}; use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey; use jwt::VerifyWithKey;
use rocket::{ use rocket::{
@ -24,7 +22,7 @@ impl<'r> FromRequest<'r> for Bearer<'r>
{ {
// If the header isn't present, just forward to the next route // If the header isn't present, just forward to the next route
let header = match req.headers().get_one("Authorization") { let header = match req.headers().get_one("Authorization") {
None => return Outcome::Forward(()), None => return Outcome::Failure((Status::BadRequest, Self::Error::AuthMissingHeader)),
Some(val) => val, Some(val) => val,
}; };
@ -35,7 +33,7 @@ impl<'r> FromRequest<'r> for Bearer<'r>
// Extract the jwt token from the header // Extract the jwt token from the header
let auth_string = match header.get(7..) { let auth_string = match header.get(7..) {
Some(s) => s, Some(s) => s,
None => return Outcome::Forward(()), None => return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)),
}; };
Outcome::Success(Self(auth_string)) Outcome::Success(Self(auth_string))
@ -45,14 +43,6 @@ impl<'r> FromRequest<'r> for Bearer<'r>
/// Verifies the provided JWT is valid. /// Verifies the provided JWT is valid.
pub struct Jwt(Claims); pub struct Jwt(Claims);
impl From<()> for RbError
{
fn from(_: ()) -> Self
{
RbError::Custom("Couldn't get config guard.")
}
}
#[rocket::async_trait] #[rocket::async_trait]
impl<'r> FromRequest<'r> for Jwt impl<'r> FromRequest<'r> for Jwt
{ {
@ -123,7 +113,7 @@ impl<'r> FromRequest<'r> for Admin
if user.admin { if user.admin {
Outcome::Success(Self(user)) Outcome::Success(Self(user))
} else { } else {
Outcome::Forward(()) Outcome::Failure((Status::Unauthorized, RbError::AuthUnauthorized))
} }
} }
} }

View File

@ -12,7 +12,12 @@ use figment::{
providers::{Env, Format, Yaml}, providers::{Env, Format, Yaml},
Figment, Figment,
}; };
use rocket::{fairing::AdHoc, Build, Rocket}; use rocket::{
fairing::AdHoc,
http::Status,
serde::json::{json, Value},
Build, Request, Rocket,
};
use rocket_sync_db_pools::database; use rocket_sync_db_pools::database;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -26,6 +31,12 @@ pub(crate) mod schema;
#[database("postgres_rb")] #[database("postgres_rb")]
pub struct RbDbConn(diesel::PgConnection); pub struct RbDbConn(diesel::PgConnection);
#[catch(default)]
fn default_catcher(status: Status, _: &Request) -> Value
{
json!({"status": status.code, "message": ""})
}
embed_migrations!(); embed_migrations!();
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
@ -88,6 +99,7 @@ fn rocket() -> _
)) ))
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user)) .attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
.attach(AdHoc::config::<RbConfig>()) .attach(AdHoc::config::<RbConfig>())
.register("/", catchers![default_catcher])
.mount( .mount(
"/api/auth", "/api/auth",
routes![auth::already_logged_in, auth::login, auth::refresh_token,], routes![auth::already_logged_in, auth::login, auth::refresh_token,],