Renamed errors; changed Responser implementation

pull/36/head
Jef Roosens 2021-08-28 22:06:09 +02:00
parent b61b329996
commit dd51d107e3
Signed by: Jef Roosens
GPG Key ID: B580B976584B5F30
6 changed files with 104 additions and 73 deletions

View File

@ -12,7 +12,7 @@ use crate::{
tokens::{NewRefreshToken, RefreshToken}, tokens::{NewRefreshToken, RefreshToken},
users::{NewUser, User}, users::{NewUser, User},
}, },
errors::RBError, errors::RbError,
schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users}, schema::{refresh_tokens::dsl as refresh_tokens, users::dsl as users},
}; };
@ -22,16 +22,16 @@ pub fn verify_user(conn: &PgConnection, username: &str, password: &str) -> crate
let user = users::users let user = users::users
.filter(users::username.eq(username)) .filter(users::username.eq(username))
.first::<User>(conn) .first::<User>(conn)
.map_err(|_| RBError::UnknownUser)?; .map_err(|_| RbError::AuthUnknownUser)?;
// Check if a user is blocked // Check if a user is blocked
if user.blocked { if user.blocked {
return Err(RBError::BlockedUser); return Err(RbError::AuthBlockedUser);
} }
match verify_encoded(user.password.as_str(), password.as_bytes()) { match verify_encoded(user.password.as_str(), password.as_bytes()) {
Ok(true) => Ok(user), Ok(true) => Ok(user),
_ => Err(RBError::InvalidPassword), _ => Err(RbError::AuthInvalidPassword),
} }
} }
@ -54,9 +54,9 @@ pub struct Claims
pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWTResponse> pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWTResponse>
{ {
let secret = std::env::var("JWT_KEY").map_err(|_| RBError::MissingJWTKey)?; let secret = std::env::var("JWT_KEY").map_err(|_| RbError::Custom("Missing JWT key."))?;
let key: Hmac<Sha256> = let key: Hmac<Sha256> = Hmac::new_from_slice(secret.as_bytes())
Hmac::new_from_slice(secret.as_bytes()).map_err(|_| RBError::JWTCreationError)?; .map_err(|_| RbError::Custom("Couldn't create Hmac key."))?;
let current_time = Utc::now(); let current_time = Utc::now();
@ -71,7 +71,7 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWT
// Sign the claims into a new token // Sign the claims into a new token
let token = claims let token = claims
.sign_with_key(&key) .sign_with_key(&key)
.map_err(|_| RBError::JWTCreationError)?; .map_err(|_| RbError::Custom("Couldn't sign JWT."))?;
// Generate a random refresh token // Generate a random refresh token
let mut refresh_token = [0u8; crate::REFRESH_TOKEN_N_BYTES]; let mut refresh_token = [0u8; crate::REFRESH_TOKEN_N_BYTES];
@ -88,7 +88,7 @@ pub fn generate_jwt_token(conn: &PgConnection, user: &User) -> crate::Result<JWT
expires_at: refresh_expire, expires_at: refresh_expire,
}) })
.execute(conn) .execute(conn)
.map_err(|_| RBError::JWTCreationError)?; .map_err(|_| RbError::Custom("Couldn't insert refresh token."))?;
Ok(JWTResponse { Ok(JWTResponse {
token, token,
@ -104,7 +104,8 @@ pub fn hash_password(password: &str) -> crate::Result<String>
// Encode the actual password // Encode the actual password
let config = argon2::Config::default(); let config = argon2::Config::default();
argon2::hash_encoded(password.as_bytes(), &salt, &config).map_err(|_| RBError::PWSaltError) argon2::hash_encoded(password.as_bytes(), &salt, &config)
.map_err(|_| RbError::Custom("Couldn't hash password."))
} }
pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str) pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str)
@ -123,21 +124,22 @@ pub fn create_admin_user(conn: &PgConnection, username: &str, password: &str)
.do_update() .do_update()
.set(&new_user) .set(&new_user)
.execute(conn) .execute(conn)
.map_err(|_| RBError::AdminCreationError)?; .map_err(|_| RbError::Custom("Couldn't create admin."))?;
Ok(true) Ok(true)
} }
pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<JWTResponse> pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<JWTResponse>
{ {
let token_bytes = base64::decode(refresh_token).map_err(|_| RBError::InvalidRefreshToken)?; let token_bytes =
base64::decode(refresh_token).map_err(|_| RbError::AuthInvalidRefreshToken)?;
// First, we request the token from the database to see if it's really a valid token // First, we request the token from the database to see if it's really a valid token
let (token_entry, user) = refresh_tokens::refresh_tokens let (token_entry, user) = refresh_tokens::refresh_tokens
.inner_join(users::users) .inner_join(users::users)
.filter(refresh_tokens::token.eq(token_bytes)) .filter(refresh_tokens::token.eq(token_bytes))
.first::<(RefreshToken, User)>(conn) .first::<(RefreshToken, User)>(conn)
.map_err(|_| RBError::InvalidRefreshToken)?; .map_err(|_| RbError::AuthInvalidRefreshToken)?;
// If we see that the token has already been used before, we block the user. // If we see that the token has already been used before, we block the user.
if token_entry.last_used_at.is_some() { if token_entry.last_used_at.is_some() {
@ -145,16 +147,16 @@ pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<
diesel::update(target) diesel::update(target)
.set(users::blocked.eq(true)) .set(users::blocked.eq(true))
.execute(conn) .execute(conn)
.map_err(|_| RBError::DBError)?; .map_err(|_| RbError::Custom("Couldn't block user."))?;
return Err(RBError::DuplicateRefreshToken); return Err(RbError::AuthDuplicateRefreshToken);
} }
// Now we check if the token has already expired // Now we check if the token has already expired
let cur_time = Utc::now().naive_utc(); let cur_time = Utc::now().naive_utc();
if token_entry.expires_at < cur_time { if token_entry.expires_at < cur_time {
return Err(RBError::TokenExpired); return Err(RbError::AuthTokenExpired);
} }
// We update the last_used_at value for the refresh token // We update the last_used_at value for the refresh token
@ -162,7 +164,7 @@ pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result<
diesel::update(target) diesel::update(target)
.set(refresh_tokens::last_used_at.eq(cur_time)) .set(refresh_tokens::last_used_at.eq(cur_time))
.execute(conn) .execute(conn)
.map_err(|_| RBError::DBError)?; .map_err(|_| RbError::Custom("Couldn't update last used time."))?;
generate_jwt_token(conn, &user) generate_jwt_token(conn, &user)
} }

View File

@ -1,5 +1,5 @@
pub mod tokens; pub mod tokens;
pub mod users; pub mod users;
pub use users::{User, NewUser}; pub use tokens::{NewRefreshToken, RefreshToken};
pub use tokens::{RefreshToken, NewRefreshToken}; pub use users::{NewUser, User};

View File

@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid; use uuid::Uuid;
use crate::{ use crate::{
errors::RBError, errors::RbError,
schema::{users, users::dsl::*}, schema::{users, users::dsl::*},
}; };
@ -30,7 +30,9 @@ pub struct NewUser
pub fn all(conn: &PgConnection) -> crate::Result<Vec<User>> pub fn all(conn: &PgConnection) -> crate::Result<Vec<User>>
{ {
users.load::<User>(conn).map_err(|_| RBError::DBError) users
.load::<User>(conn)
.map_err(|_| RbError::DbError("Couldn't get all users."))
} }
pub fn find(conn: &PgConnection, user_id: Uuid) -> Option<User> pub fn find(conn: &PgConnection, user_id: Uuid) -> Option<User>
@ -43,10 +45,10 @@ pub fn create(conn: &PgConnection, new_user: &NewUser) -> crate::Result<()>
let count = diesel::insert_into(users) let count = diesel::insert_into(users)
.values(new_user) .values(new_user)
.execute(conn) .execute(conn)
.map_err(|_| RBError::DBError)?; .map_err(|_| RbError::DbError("Couldn't create user."))?;
if count == 0 { if count == 0 {
return Err(RBError::DuplicateUser); return Err(RbError::UMDuplicateUser);
} }
Ok(()) Ok(())
@ -56,7 +58,7 @@ pub fn delete(conn: &PgConnection, user_id: Uuid) -> crate::Result<()>
{ {
diesel::delete(users.filter(id.eq(user_id))) diesel::delete(users.filter(id.eq(user_id)))
.execute(conn) .execute(conn)
.map_err(|_| RBError::DBError)?; .map_err(|_| RbError::DbError("Couldn't delete user."))?;
Ok(()) Ok(())
} }

View File

@ -1,9 +1,8 @@
use std::io;
use rocket::{ use rocket::{
http::Status, http::Status,
request::Request, request::Request,
response::{self, Responder, Response}, response::{self, Responder},
serde::json::json,
}; };
#[derive(Debug)] #[derive(Debug)]
@ -18,51 +17,70 @@ pub enum RbError
AuthInvalidRefreshToken, AuthInvalidRefreshToken,
AuthDuplicateRefreshToken, AuthDuplicateRefreshToken,
Custom(&'static str), // UM = User Management
UMDuplicateUser,
UMUnknownUser,
AdminCreationError, DbError(&'static str),
DBError, Custom(&'static str),
DuplicateUser,
} }
impl RbError { impl RbError
pub fn status(&self) -> Status { {
Status::NotFound 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,
RbError::UMDuplicateUser => Status::Conflict,
RbError::Custom(_) => Status::InternalServerError,
_ => Status::InternalServerError,
}
} }
pub fn message(&self) -> &'static str { pub fn message(&self) -> &'static str
{
match self { 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."
}
RbError::UMDuplicateUser => "This user already exists.",
RbError::Custom(message) => message,
_ => "",
} }
} }
} }
impl<'r> Responder<'r, 'static> for RBError impl<'r> Responder<'r, 'static> for RbError
{ {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static>
{ {
let (status, message): (Status, &'static str) = match self { let status = self.status();
RBError::UnknownUser => (Status::NotFound, "Unknown user"), let content = json!({
RBError::BlockedUser => (Status::Unauthorized, "This user is blocked"), "status": status.code,
RBError::InvalidPassword => (Status::Unauthorized, "Invalid password"), "message": self.message(),
RBError::Unauthorized => (Status::Unauthorized, "Unauthorized"), });
RBError::JWTTokenExpired => (Status::Unauthorized, "Token expired"),
RBError::JWTCreationError | RBError::MissingJWTKey => {
(Status::InternalServerError, "Failed to create tokens.")
}
RBError::InvalidRefreshToken | RBError::DuplicateRefreshToken => {
(Status::Unauthorized, "Invalid refresh token.")
}
RBError::DuplicateUser => (Status::Conflict, "User already exists"),
_ => (Status::InternalServerError, "Internal server error"),
};
let mut res = Response::new(); content.respond_to(req)
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>; pub type Result<T> = std::result::Result<T, RbError>;

View File

@ -14,7 +14,7 @@ pub struct Bearer<'a>(&'a str);
#[rocket::async_trait] #[rocket::async_trait]
impl<'r> FromRequest<'r> for Bearer<'r> impl<'r> FromRequest<'r> for Bearer<'r>
{ {
type Error = rb::errors::RBError; type Error = rb::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{ {
@ -44,7 +44,7 @@ pub struct JWT(Claims);
#[rocket::async_trait] #[rocket::async_trait]
impl<'r> FromRequest<'r> for JWT impl<'r> FromRequest<'r> for JWT
{ {
type Error = rb::errors::RBError; type Error = rb::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{ {
@ -54,19 +54,27 @@ impl<'r> FromRequest<'r> for JWT
let secret = match std::env::var("JWT_KEY") { let secret = match std::env::var("JWT_KEY") {
Ok(key) => key, Ok(key) => key,
Err(_) => { Err(_) => {
return Outcome::Failure((Status::InternalServerError, Self::Error::MissingJWTKey)) return Outcome::Failure((
Status::InternalServerError,
Self::Error::AuthUnauthorized,
))
} }
}; };
let key: Hmac<Sha256> = match Hmac::new_from_slice(secret.as_bytes()) { let key: Hmac<Sha256> = match Hmac::new_from_slice(secret.as_bytes()) {
Ok(key) => key, Ok(key) => key,
Err(_) => { Err(_) => {
return Outcome::Failure((Status::InternalServerError, Self::Error::JWTError)) return Outcome::Failure((
Status::InternalServerError,
Self::Error::Custom("Failed to do Hmac thing."),
))
} }
}; };
// Verify token using key // Verify token using key
let claims: Claims = match bearer.verify_with_key(&key) { let claims: Claims = match bearer.verify_with_key(&key) {
Ok(claims) => claims, Ok(claims) => claims,
Err(_) => return Outcome::Failure((Status::Unauthorized, Self::Error::Unauthorized)), Err(_) => {
return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized))
}
}; };
Outcome::Success(Self(claims)) Outcome::Success(Self(claims))
@ -79,7 +87,7 @@ pub struct User(Claims);
#[rocket::async_trait] #[rocket::async_trait]
impl<'r> FromRequest<'r> for User impl<'r> FromRequest<'r> for User
{ {
type Error = rb::errors::RBError; type Error = rb::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{ {
@ -87,7 +95,7 @@ impl<'r> FromRequest<'r> for User
// Verify key hasn't yet expired // Verify key hasn't yet expired
if chrono::Utc::now().timestamp() > claims.exp { if chrono::Utc::now().timestamp() > claims.exp {
return Outcome::Failure((Status::Forbidden, Self::Error::TokenExpired)); return Outcome::Failure((Status::Forbidden, Self::Error::AuthTokenExpired));
} }
Outcome::Success(Self(claims)) Outcome::Success(Self(claims))
@ -100,7 +108,7 @@ pub struct Admin(Claims);
#[rocket::async_trait] #[rocket::async_trait]
impl<'r> FromRequest<'r> for Admin impl<'r> FromRequest<'r> for Admin
{ {
type Error = rb::errors::RBError; type Error = rb::errors::RbError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
{ {

View File

@ -1,7 +1,4 @@
use rb::{ use rb::{db, errors::RbError};
db,
errors::RBError,
};
use rocket::serde::json::Json; use rocket::serde::json::Json;
use uuid::Uuid; use uuid::Uuid;
@ -27,12 +24,16 @@ async fn create_user(admin: Admin, conn: RbDbConn, user: Json<db::NewUser>) -> r
} }
#[get("/users/<user_id_str>")] #[get("/users/<user_id_str>")]
async fn get_user_info(_admin: Admin, conn: RbDbConn, user_id_str: &str) -> rb::Result<Json<db::User>> async fn get_user_info(
_admin: Admin,
conn: RbDbConn,
user_id_str: &str,
) -> rb::Result<Json<db::User>>
{ {
let user_id = Uuid::parse_str(user_id_str).map_err(|_| RBError::UnknownUser)?; let user_id = Uuid::parse_str(user_id_str).map_err(|_| RbError::UMUnknownUser)?;
match conn.run(move |c| db::users::find(c, user_id)).await { match conn.run(move |c| db::users::find(c, user_id)).await {
Some(user) => Ok(Json(user)), Some(user) => Ok(Json(user)),
None => Err(RBError::UnknownUser), None => Err(RbError::UMUnknownUser),
} }
} }