Skip to content

Commit

Permalink
chore: refactor auth handlers and errors http response
Browse files Browse the repository at this point in the history
  • Loading branch information
pnwatin committed Mar 29, 2024
1 parent e8a37da commit 59eca6d
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 15 deletions.
29 changes: 22 additions & 7 deletions src/handlers/auth/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use axum::{http::StatusCode, response::IntoResponse};

#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error("Invalid token.")]
InvalidToken,
#[error("Invalid refresh token.")]
InvalidRefreshToken,
#[error("Invalid credentials.")]
InvalidCredentials,
#[error("This email is already used.")]
Expand All @@ -19,19 +19,34 @@ pub enum AuthError {
impl IntoResponse for AuthError {
fn into_response(self) -> axum::response::Response {
match self {
AuthError::InvalidCredentials => (StatusCode::UNAUTHORIZED).into_response(),
AuthError::InvalidToken => (StatusCode::UNAUTHORIZED).into_response(),
AuthError::InvalidCredentials => problemdetails::new(StatusCode::UNAUTHORIZED)
.with_title("Invalid credentials.")
.with_detail("Provided credentials are invalid - please provide invalid.")
.into_response(),
AuthError::InvalidRefreshToken => problemdetails::new(StatusCode::UNAUTHORIZED)
.with_title("Invalid refresh token.")
.with_detail("Provided refresh token is invalid - please re-authenticate.")
.into_response(),
// TODO: mitigate this privacy risk (return 201 and send confirmation mail ?)
AuthError::EmailTaken => (StatusCode::CONFLICT).into_response(),
AuthError::EmailTaken => problemdetails::new(StatusCode::CONFLICT)
.with_title("Email already used.")
.with_detail("Provided email is already used - please choose another email.")
.into_response(),
AuthError::DatabaseError(e) => {
tracing::error!("Database error : {:?}", e);

(StatusCode::INTERNAL_SERVER_ERROR).into_response()
problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
.with_title("Something went wrong.")
.with_detail("An error occured - please retry later.")
.into_response()
}
AuthError::UnexpectedError(e) => {
tracing::error!("Unexpected error : {:?}", e);

(StatusCode::INTERNAL_SERVER_ERROR).into_response()
problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
.with_title("Something went wrong.")
.with_detail("An error occured - please retry later.")
.into_response()
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ impl RefreshToken {
.execute(pool)
.await?;

return Err(AuthError::InvalidToken);
return Err(AuthError::InvalidRefreshToken);
}

Ok(self)
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/auth/sign_in.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use anyhow::Context;
use argon2::{Argon2, PasswordHash, PasswordVerifier};
use axum::{response::IntoResponse, Extension, Json};
use axum::{response::IntoResponse, Extension};
use secrecy::{ExposeSecret, Secret};
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;

use crate::{domain::Email, telemetry::spawn_blocking_with_tracing};
use crate::{domain::Email, extractors::Json, telemetry::spawn_blocking_with_tracing};

use super::{AccessToken, AuthError, RefreshToken, TokensPair, TokensResponse};

#[tracing::instrument(name = "HANDLER - SIGN IN", skip(payload))]
#[tracing::instrument(name = "HANDLER - SIGN UP", skip(pool, payload))]
pub async fn sign_in_handler(
Extension(pool): Extension<PgPool>,
Json(payload): Json<SignInPayload>,
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/auth/sign_up.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use anyhow::Context;
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
use axum::{http::StatusCode, response::IntoResponse, Extension, Json};
use axum::{http::StatusCode, response::IntoResponse, Extension};
use secrecy::{ExposeSecret, Secret};
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;

use crate::domain::Email;
use crate::{domain::Email, extractors::Json};

use super::AuthError;

Expand Down
6 changes: 4 additions & 2 deletions src/handlers/auth/tokens.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use anyhow::Context;
use axum::{response::IntoResponse, Extension, Json};
use axum::{response::IntoResponse, Extension};
use serde::Deserialize;
use sqlx::PgPool;

use crate::extractors::Json;

use super::{AccessToken, AuthError, RefreshToken, Token, TokensPair, TokensResponse};

#[tracing::instrument(name = "HANDLER - REFRESH TOKENS", skip(pool, payload))]
Expand All @@ -20,7 +22,7 @@ pub async fn refresh_tokens_handler(
#[tracing::instrument(name = "REFRESH TOKENS", skip(refresh_token, pool))]
async fn refresh_tokens(refresh_token: &str, pool: &PgPool) -> Result<TokensPair, AuthError> {
let refresh_token_claims =
RefreshToken::decode(refresh_token).map_err(|_| AuthError::InvalidToken)?;
RefreshToken::decode(refresh_token).map_err(|_| AuthError::InvalidRefreshToken)?;

let user_id = refresh_token_claims.sub;
let family = refresh_token_claims.family;
Expand Down

0 comments on commit 59eca6d

Please sign in to comment.