Continuing with error refactoring.
This commit is contained in:
@@ -27,4 +27,7 @@ pub enum DomainError {
|
||||
|
||||
#[error(transparent)]
|
||||
Schedule(#[from] ScheduleError),
|
||||
|
||||
#[error(transparent)]
|
||||
UserAppSecret(#[from] UserAppSecretError),
|
||||
}
|
||||
|
||||
@@ -200,6 +200,33 @@ mod tests {
|
||||
.next_occurrence(from)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_schedule_and_exposes_fields() {
|
||||
let start = at(2026, 9, 24, 12);
|
||||
let end = at(2027, 9, 24, 12);
|
||||
let weekly = recurrence(2, RecurrenceUnit::Week);
|
||||
|
||||
let schedule = Schedule::new(
|
||||
start,
|
||||
Some(end),
|
||||
weekly,
|
||||
Some(WeekendAdjustment::PreviousBusinessDay),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(schedule.start(), start);
|
||||
assert_eq!(schedule.end(), Some(end));
|
||||
assert_eq!(schedule.recurrence(), weekly);
|
||||
assert_eq!(
|
||||
schedule.weekend_adjustment(),
|
||||
Some(WeekendAdjustment::PreviousBusinessDay)
|
||||
);
|
||||
|
||||
let open_ended = Schedule::new(start, None, weekly, None).unwrap();
|
||||
assert_eq!(open_ended.end(), None);
|
||||
assert_eq!(open_ended.weekend_adjustment(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_at_start_and_includes_exact_matches() {
|
||||
let start = at(2026, 9, 24, 12);
|
||||
|
||||
@@ -3,9 +3,133 @@ use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UserAppSecret {
|
||||
pub id: Uuid,
|
||||
pub app_id: Uuid,
|
||||
pub secret_hash: Vec<u8>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
id: Uuid,
|
||||
app_id: Uuid,
|
||||
secret_hash: Vec<u8>,
|
||||
expires_at: DateTime<Utc>,
|
||||
created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl UserAppSecret {
|
||||
pub fn new(
|
||||
id: Uuid,
|
||||
app_id: Uuid,
|
||||
secret_hash: Vec<u8>,
|
||||
expires_at: DateTime<Utc>,
|
||||
created_at: DateTime<Utc>,
|
||||
) -> Result<Self, UserAppSecretError> {
|
||||
if expires_at <= created_at {
|
||||
return Err(UserAppSecretError::ExpiresInThePast);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
app_id,
|
||||
secret_hash,
|
||||
expires_at,
|
||||
created_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn id(&self) -> Uuid {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn app_id(&self) -> Uuid {
|
||||
self.app_id
|
||||
}
|
||||
|
||||
pub fn secret_hash(&self) -> &Vec<u8> {
|
||||
&self.secret_hash
|
||||
}
|
||||
|
||||
pub fn expires_at(&self) -> DateTime<Utc> {
|
||||
self.expires_at
|
||||
}
|
||||
|
||||
pub fn created_at(&self) -> DateTime<Utc> {
|
||||
self.created_at
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum UserAppSecretError {
|
||||
#[error("Expiration date is in the past")]
|
||||
ExpiresInThePast,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{UserAppSecret, UserAppSecretError};
|
||||
|
||||
fn now() -> DateTime<Utc> {
|
||||
DateTime::from_timestamp(1_700_000_000, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_secret_and_exposes_fields() {
|
||||
let id = Uuid::new_v4();
|
||||
let app_id = Uuid::new_v4();
|
||||
let created_at = now();
|
||||
let expires_at = created_at + Duration::days(1);
|
||||
|
||||
let secret = UserAppSecret::new(id, app_id, vec![1, 2, 3], expires_at, created_at).unwrap();
|
||||
|
||||
assert_eq!(secret.id(), id);
|
||||
assert_eq!(secret.app_id(), app_id);
|
||||
assert_eq!(secret.secret_hash(), &vec![1, 2, 3]);
|
||||
assert_eq!(secret.expires_at(), expires_at);
|
||||
assert_eq!(secret.created_at(), created_at);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_expiry_one_nanosecond_after_creation() {
|
||||
let created_at = now();
|
||||
|
||||
assert!(
|
||||
UserAppSecret::new(
|
||||
Uuid::new_v4(),
|
||||
Uuid::new_v4(),
|
||||
vec![],
|
||||
created_at + Duration::nanoseconds(1),
|
||||
created_at,
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_expiry_equal_to_creation() {
|
||||
let created_at = now();
|
||||
|
||||
assert!(matches!(
|
||||
UserAppSecret::new(
|
||||
Uuid::new_v4(),
|
||||
Uuid::new_v4(),
|
||||
vec![],
|
||||
created_at,
|
||||
created_at
|
||||
),
|
||||
Err(UserAppSecretError::ExpiresInThePast)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_expiry_before_creation() {
|
||||
let created_at = now();
|
||||
|
||||
assert!(matches!(
|
||||
UserAppSecret::new(
|
||||
Uuid::new_v4(),
|
||||
Uuid::new_v4(),
|
||||
vec![],
|
||||
created_at - Duration::seconds(1),
|
||||
created_at,
|
||||
),
|
||||
Err(UserAppSecretError::ExpiresInThePast)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+56
-34
@@ -8,34 +8,40 @@ use axum::{
|
||||
use crate::{
|
||||
domain::DomainError,
|
||||
repository::RepositoryError,
|
||||
routes::extractors::auth::{AuthError, AuthHeaderError, BearerError},
|
||||
routes::extractors::{
|
||||
ExtractorError,
|
||||
auth::{AuthError, AuthHeaderError, BearerError},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AppError {
|
||||
#[error("bad request")]
|
||||
BadRequest(String),
|
||||
#[error("invalid client credentials")]
|
||||
InvalidClientCredentials,
|
||||
|
||||
#[error("conflict")]
|
||||
Conflict(String),
|
||||
#[error("invalid refresh token")]
|
||||
InvalidRefreshToken,
|
||||
|
||||
#[error("app id is already in use")]
|
||||
AppIdAlreadyExists,
|
||||
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
|
||||
#[error("unauthorized")]
|
||||
Unauthorized(String),
|
||||
#[error("unknown")]
|
||||
Unknown,
|
||||
|
||||
#[error("authorization error")]
|
||||
Authorization(#[from] AuthError),
|
||||
|
||||
#[error("domain error")]
|
||||
#[error(transparent)]
|
||||
Domain(#[from] DomainError),
|
||||
|
||||
#[error("repository error")]
|
||||
#[error(transparent)]
|
||||
Extractor(#[from] ExtractorError),
|
||||
|
||||
#[error(transparent)]
|
||||
Repository(#[from] RepositoryError),
|
||||
|
||||
#[error("internal server error")]
|
||||
Internal,
|
||||
#[error(transparent)]
|
||||
Internal(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
@@ -44,8 +50,6 @@ impl IntoResponse for AppError {
|
||||
|
||||
if status.is_server_error() {
|
||||
tracing::error!(error = ?self, %status, "request failed");
|
||||
} else if matches!(self, Self::Conflict(_)) {
|
||||
tracing::warn!(error = ?self, %status, "request rejected");
|
||||
} else {
|
||||
tracing::debug!(error = ?self, %status, "request rejected");
|
||||
}
|
||||
@@ -57,14 +61,29 @@ impl IntoResponse for AppError {
|
||||
impl ClientError for AppError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
match self {
|
||||
Self::BadRequest(message) => (StatusCode::BAD_REQUEST, message.as_str().into()),
|
||||
Self::Unauthorized(message) => (StatusCode::UNAUTHORIZED, message.as_str().into()),
|
||||
Self::InvalidClientCredentials => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid client credentials".into(),
|
||||
),
|
||||
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".into()),
|
||||
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App ID already exists".into()),
|
||||
Self::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
|
||||
Self::Conflict(message) => (StatusCode::CONFLICT, message.as_str().into()),
|
||||
Self::Authorization(error) => error.client_response(),
|
||||
Self::Domain(error) => error.client_response(),
|
||||
Self::Extractor(error) => error.client_response(),
|
||||
Self::Repository(error) => error.client_response(),
|
||||
Self::Internal => internal_error(),
|
||||
Self::Internal(_) | Self::Unknown => internal_error(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientError for ExtractorError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
match self {
|
||||
Self::Authorization(error) => error.client_response(),
|
||||
Self::Form(_) => (StatusCode::BAD_REQUEST, "Form error".into()),
|
||||
Self::Json(_) => (StatusCode::BAD_REQUEST, "Json error".into()),
|
||||
Self::Path(_) => (StatusCode::BAD_REQUEST, "Path error".into()),
|
||||
Self::Query(_) => (StatusCode::BAD_REQUEST, "Query error".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +99,15 @@ impl ClientError for AuthError {
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientError for BearerError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
match self {
|
||||
Self::InvalidCredentials => (StatusCode::UNAUTHORIZED, "Invalid credentials".into()),
|
||||
Self::Repository(error) => error.client_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientError for AuthHeaderError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
let message = match self {
|
||||
@@ -94,21 +122,15 @@ impl ClientError for AuthHeaderError {
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientError for BearerError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
match self {
|
||||
Self::InvalidCredentials => (StatusCode::UNAUTHORIZED, "Invalid credentials".into()),
|
||||
Self::Repository(error) => error.client_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientError for DomainError {
|
||||
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
|
||||
match self {
|
||||
Self::Amount(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
|
||||
Self::Schedule(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
|
||||
}
|
||||
let message: String = match self {
|
||||
Self::Amount(error) => error.to_string(),
|
||||
Self::Schedule(error) => error.to_string(),
|
||||
Self::UserAppSecret(error) => error.to_string(),
|
||||
};
|
||||
|
||||
(StatusCode::UNPROCESSABLE_ENTITY, message.into())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
database::DatabaseError,
|
||||
domain::{CentsError, ScheduleError},
|
||||
domain::{CentsError, ScheduleError, UserAppSecretError},
|
||||
};
|
||||
|
||||
pub mod accounts;
|
||||
@@ -50,11 +50,14 @@ pub enum DecodeError {
|
||||
#[error("invalid recurrence_unit value: {0}")]
|
||||
RecurrenceUnit(String),
|
||||
|
||||
#[error("invalid weekend_adjustment value: {0}")]
|
||||
WeekendAdjustment(String),
|
||||
|
||||
#[error(transparent)]
|
||||
Schedule(#[from] ScheduleError),
|
||||
|
||||
#[error("invalid weekend_adjustment value: {0}")]
|
||||
WeekendAdjustment(String),
|
||||
#[error(transparent)]
|
||||
UserAppSecret(#[from] UserAppSecretError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
|
||||
@@ -116,38 +116,40 @@ where
|
||||
}
|
||||
|
||||
fn decode(row: UserAppSecretRow) -> Result<UserAppSecret, DecodeError> {
|
||||
Ok(UserAppSecret {
|
||||
id: row.id,
|
||||
app_id: row.app_id,
|
||||
secret_hash: row.secret_hash,
|
||||
expires_at: row.expires_at,
|
||||
created_at: row.created_at,
|
||||
})
|
||||
Ok(UserAppSecret::new(
|
||||
row.id,
|
||||
row.app_id,
|
||||
row.secret_hash,
|
||||
row.expires_at,
|
||||
row.created_at,
|
||||
)?)
|
||||
}
|
||||
|
||||
fn encode(secret: UserAppSecret) -> UserAppSecretRow {
|
||||
UserAppSecretRow {
|
||||
id: secret.id,
|
||||
app_id: secret.app_id,
|
||||
secret_hash: secret.secret_hash,
|
||||
expires_at: secret.expires_at,
|
||||
created_at: secret.created_at,
|
||||
id: secret.id(),
|
||||
app_id: secret.app_id(),
|
||||
secret_hash: secret.secret_hash().clone(),
|
||||
expires_at: secret.expires_at(),
|
||||
created_at: secret.created_at(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use chrono::{Duration, Utc};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn row() -> UserAppSecretRow {
|
||||
let created_at = Utc::now();
|
||||
|
||||
UserAppSecretRow {
|
||||
id: Uuid::new_v4(),
|
||||
app_id: Uuid::new_v4(),
|
||||
secret_hash: vec![0; 32],
|
||||
expires_at: Utc::now(),
|
||||
created_at: Utc::now(),
|
||||
expires_at: created_at + Duration::days(1),
|
||||
created_at,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,16 +43,12 @@ async fn issue_token(
|
||||
.map_err(repository::RepositoryError::from)?;
|
||||
|
||||
if !repository::user_app_secrets::verify(&mut *tx, client_id, &secret_hash).await? {
|
||||
return Err(AppError::Unauthorized(
|
||||
"Invalid client credentials".to_string(),
|
||||
));
|
||||
return Err(AppError::InvalidClientCredentials);
|
||||
}
|
||||
|
||||
let user_app = repository::user_apps::get_by_id(&mut *tx, client_id)
|
||||
.await?
|
||||
.ok_or(AppError::Unauthorized(
|
||||
"Invalid client credentials".to_string(),
|
||||
))?;
|
||||
.ok_or(AppError::InvalidClientCredentials)?;
|
||||
|
||||
repository::tokens::issue(
|
||||
&mut *tx,
|
||||
@@ -86,7 +82,7 @@ async fn issue_token(
|
||||
)
|
||||
.await?;
|
||||
if !rotated {
|
||||
return Err(AppError::Unauthorized("Invalid refresh token".to_string()));
|
||||
return Err(AppError::InvalidRefreshToken);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
@@ -119,8 +115,8 @@ struct TokenPair {
|
||||
}
|
||||
|
||||
fn generate_token_pair() -> Result<TokenPair, AppError> {
|
||||
let access_token = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let refresh_token = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let access_token = generate_secret().map_err(|_| AppError::Unknown)?;
|
||||
let refresh_token = generate_secret().map_err(|_| AppError::Unknown)?;
|
||||
let now = Utc::now();
|
||||
Ok(TokenPair {
|
||||
access_token_hash: hash_secret(&access_token),
|
||||
|
||||
@@ -9,6 +9,24 @@ pub struct UserAppSecretRequest {
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl UserAppSecretRequest {
|
||||
pub fn into_domain(
|
||||
self,
|
||||
id: Uuid,
|
||||
app_id: Uuid,
|
||||
secret_hash: Vec<u8>,
|
||||
created_at: DateTime<Utc>,
|
||||
) -> Result<domain::UserAppSecret, domain::DomainError> {
|
||||
Ok(domain::UserAppSecret::new(
|
||||
id,
|
||||
app_id,
|
||||
secret_hash,
|
||||
self.expires_at,
|
||||
created_at,
|
||||
)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserAppSecretResponse {
|
||||
pub id: Uuid,
|
||||
@@ -20,10 +38,10 @@ pub struct UserAppSecretResponse {
|
||||
impl From<domain::UserAppSecret> for UserAppSecretResponse {
|
||||
fn from(secret: domain::UserAppSecret) -> Self {
|
||||
Self {
|
||||
id: secret.id,
|
||||
app_id: secret.app_id,
|
||||
expires_at: secret.expires_at,
|
||||
created_at: secret.created_at,
|
||||
id: secret.id(),
|
||||
app_id: secret.app_id(),
|
||||
expires_at: secret.expires_at(),
|
||||
created_at: secret.created_at(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
pub mod auth;
|
||||
pub mod form;
|
||||
pub mod json;
|
||||
pub mod path;
|
||||
pub mod query;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExtractorError {
|
||||
#[error(transparent)]
|
||||
Authorization(#[from] auth::AuthError),
|
||||
|
||||
#[error(transparent)]
|
||||
Form(#[from] form::FormError),
|
||||
|
||||
#[error(transparent)]
|
||||
Json(#[from] json::JsonError),
|
||||
|
||||
#[error(transparent)]
|
||||
Path(#[from] path::PathError),
|
||||
|
||||
#[error(transparent)]
|
||||
Query(#[from] query::QueryError),
|
||||
}
|
||||
|
||||
impl IntoResponse for ExtractorError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
AppError::from(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ pub use bearer::*;
|
||||
pub use header::*;
|
||||
pub use principal::*;
|
||||
|
||||
use crate::{error::AppError, repository::RepositoryError};
|
||||
use crate::{repository::RepositoryError, routes::extractors::ExtractorError};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Auth<T = Bearer>(pub Principal<T>);
|
||||
@@ -55,7 +55,7 @@ pub enum AuthError {
|
||||
|
||||
impl IntoResponse for AuthError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
AppError::from(self).into_response()
|
||||
ExtractorError::from(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use axum::extract::{FromRequest, Request};
|
||||
use axum::{
|
||||
extract::{FromRequest, Request},
|
||||
response::IntoResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::routes::extractors::ExtractorError;
|
||||
|
||||
pub struct Form<T>(pub T);
|
||||
|
||||
@@ -10,12 +13,22 @@ where
|
||||
T: DeserializeOwned,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
type Rejection = FormError;
|
||||
|
||||
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
axum::Form::<T>::from_request(request, state)
|
||||
.await
|
||||
.map(|axum::Form(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("form error")]
|
||||
pub struct FormError(#[from] axum::extract::rejection::FormRejection);
|
||||
|
||||
impl IntoResponse for FormError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
ExtractorError::Form(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use axum::response::IntoResponse;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::routes::extractors::ExtractorError;
|
||||
|
||||
pub struct Json<T>(pub T);
|
||||
|
||||
@@ -12,13 +12,13 @@ where
|
||||
T: DeserializeOwned,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
type Rejection = JsonError;
|
||||
|
||||
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
axum::Json::<T>::from_request(request, state)
|
||||
.await
|
||||
.map(|axum::Json(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,3 +30,13 @@ where
|
||||
axum::Json(self.0).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("json error")]
|
||||
pub struct JsonError(#[from] axum::extract::rejection::JsonRejection);
|
||||
|
||||
impl IntoResponse for JsonError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
ExtractorError::Json(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::response::IntoResponse;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::routes::extractors::ExtractorError;
|
||||
|
||||
pub struct Path<T>(pub T);
|
||||
|
||||
@@ -10,7 +11,7 @@ where
|
||||
T: DeserializeOwned + Send,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
type Rejection = PathError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut axum::http::request::Parts,
|
||||
@@ -19,6 +20,16 @@ where
|
||||
axum::extract::Path::<T>::from_request_parts(parts, state)
|
||||
.await
|
||||
.map(|axum::extract::Path(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("path error")]
|
||||
pub struct PathError(#[from] axum::extract::rejection::PathRejection);
|
||||
|
||||
impl IntoResponse for PathError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
ExtractorError::Path(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::response::IntoResponse;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::routes::extractors::ExtractorError;
|
||||
|
||||
pub struct Query<T>(pub T);
|
||||
|
||||
@@ -10,7 +11,7 @@ where
|
||||
T: DeserializeOwned + Send,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = AppError;
|
||||
type Rejection = QueryError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut axum::http::request::Parts,
|
||||
@@ -19,6 +20,16 @@ where
|
||||
axum::extract::Query::<T>::from_request_parts(parts, state)
|
||||
.await
|
||||
.map(|axum::extract::Query(value)| Self(value))
|
||||
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("query error")]
|
||||
pub struct QueryError(#[from] axum::extract::rejection::QueryRejection);
|
||||
|
||||
impl IntoResponse for QueryError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
ExtractorError::Query(self).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ fn create_response(
|
||||
let account = accounts
|
||||
.get(&transaction.account_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Internal)?;
|
||||
.ok_or(AppError::Unknown)?;
|
||||
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ fn create_response(
|
||||
let account = accounts
|
||||
.get(&transaction.account_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Internal)?;
|
||||
.ok_or(AppError::Unknown)?;
|
||||
|
||||
Ok(TransactionResponse::new(transaction, account))
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ use super::{
|
||||
};
|
||||
use crate::{
|
||||
crypto::{generate_secret, hash_secret},
|
||||
domain::UserAppSecret,
|
||||
error::AppError,
|
||||
repository::{self, RepositoryError},
|
||||
};
|
||||
@@ -97,20 +96,9 @@ async fn upsert_user_app_secret(
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
if request.expires_at <= now {
|
||||
return Err(AppError::BadRequest(
|
||||
"expires_at must be in the future".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let generated_secret = generate_secret().map_err(|_| AppError::Internal)?;
|
||||
let secret = UserAppSecret {
|
||||
id: secret_id,
|
||||
app_id,
|
||||
secret_hash: hash_secret(&generated_secret),
|
||||
expires_at: request.expires_at,
|
||||
created_at: now,
|
||||
};
|
||||
let generated_secret = generate_secret().map_err(|_| AppError::Unknown)?;
|
||||
let hashed_secret = hash_secret(&generated_secret);
|
||||
let secret = request.into_domain(secret_id, app_id, hashed_secret, now)?;
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_app_ownership(&mut tx, user_id, app_id).await?;
|
||||
|
||||
@@ -96,7 +96,7 @@ async fn upsert_user_app(
|
||||
.as_ref()
|
||||
.is_some_and(|previous| previous.user_id != user_id)
|
||||
{
|
||||
return Err(AppError::Conflict("User app ID is already in use".into()));
|
||||
return Err(AppError::AppIdAlreadyExists);
|
||||
}
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user