Skip to content

Commit

Permalink
Process InvalidationErrors directly
Browse files Browse the repository at this point in the history
  • Loading branch information
wsxiaoys committed Dec 2, 2023
1 parent 0f2f90f commit 7764f2e
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 54 deletions.
12 changes: 6 additions & 6 deletions ee/tabby-webserver/src/schema/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use juniper::{FieldError, GraphQLObject, IntoFieldError, ScalarValue};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use validator::ValidationError;
use validator::ValidationErrors;

use super::ValidationErrors;
use super::from_validation_errors;

lazy_static! {
static ref JWT_ENCODING_KEY: jwt::EncodingKey = jwt::EncodingKey::from_secret(
Expand Down Expand Up @@ -55,7 +55,7 @@ impl RegisterResponse {
#[derive(Error, Debug)]
pub enum RegisterError {
#[error("Invalid input parameters")]
InvalidInput(Vec<ValidationError>),
InvalidInput(#[from] ValidationErrors),

#[error("Invitation code is not valid")]
InvalidInvitationCode,
Expand All @@ -73,7 +73,7 @@ pub enum RegisterError {
impl<S: ScalarValue> IntoFieldError<S> for RegisterError {
fn into_field_error(self) -> FieldError<S> {
match self {
Self::InvalidInput(errors) => ValidationErrors(errors).into_field_error(),
Self::InvalidInput(errors) => from_validation_errors(errors),
_ => self.into(),
}
}
Expand All @@ -97,7 +97,7 @@ impl TokenAuthResponse {
#[derive(Error, Debug)]
pub enum TokenAuthError {
#[error("Invalid input parameters")]
InvalidInput(Vec<ValidationError>),
InvalidInput(#[from] ValidationErrors),

#[error("User not found")]
UserNotFound,
Expand All @@ -115,7 +115,7 @@ pub enum TokenAuthError {
impl<S: ScalarValue> IntoFieldError<S> for TokenAuthError {
fn into_field_error(self) -> FieldError<S> {
match self {
Self::InvalidInput(errors)=> ValidationErrors(errors).into_field_error(),
Self::InvalidInput(errors) => from_validation_errors(errors),
_ => self.into(),
}
}
Expand Down
53 changes: 25 additions & 28 deletions ee/tabby-webserver/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use std::sync::Arc;

use auth::AuthenticationService;
use juniper::{
graphql_object, graphql_value, EmptySubscription, FieldError, FieldResult, IntoFieldError,
Object, RootNode, ScalarValue, Value,
graphql_object, graphql_value, EmptySubscription, FieldError, FieldResult, Object, RootNode,
ScalarValue, Value,
};
use juniper_axum::FromAuth;
use tabby_common::api::{code::CodeSearch, event::RawEventLogger};
use validator::ValidationError;
use validator::ValidationErrors;

use self::{
auth::{validate_jwt, Invitation, RegisterError, TokenAuthError},
Expand Down Expand Up @@ -95,8 +95,7 @@ impl Mutation {
password2: String,
invitation_code: Option<String>,
) -> Result<RegisterResponse, RegisterError> {
ctx
.locator
ctx.locator
.auth()
.register(email, password1, password2, invitation_code)
.await
Expand Down Expand Up @@ -133,29 +132,27 @@ impl Mutation {
}
}

struct ValidationErrors(Vec<ValidationError>);

impl<S: ScalarValue> IntoFieldError<S> for ValidationErrors {
fn into_field_error(self) -> FieldError<S> {
let errors = self
.0
.into_iter()
.map(|err| {
let mut obj = Object::with_capacity(2);
obj.add_field("path", Value::scalar(err.code.to_string()));
obj.add_field(
"message",
Value::scalar(err.message.unwrap_or_default().to_string()),
);
obj.into()
})
.collect::<Vec<_>>();
let mut ext = Object::with_capacity(2);
ext.add_field("code", Value::scalar("validation-error".to_string()));
ext.add_field("errors", Value::list(errors));

FieldError::new("Invalid input parameters", ext.into())
}
fn from_validation_errors<S: ScalarValue>(error: ValidationErrors) -> FieldError<S> {
let errors = error
.field_errors()
.into_iter()
.flat_map(|(_, errs)| errs)
.cloned()
.map(|err| {
let mut obj = Object::with_capacity(2);
obj.add_field("path", Value::scalar(err.code.to_string()));
obj.add_field(
"message",
Value::scalar(err.message.unwrap_or_default().to_string()),
);
obj.into()
})
.collect::<Vec<_>>();
let mut ext = Object::with_capacity(2);
ext.add_field("code", Value::scalar("validation-error".to_string()));
ext.add_field("errors", Value::list(errors));

FieldError::new("Invalid input parameters", ext.into())
}

pub type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Context>>;
Expand Down
22 changes: 2 additions & 20 deletions ee/tabby-webserver/src/service/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,7 @@ impl AuthenticationService for DbConn {
password1,
password2,
};
input.validate().map_err(|err| {
let errors = err
.field_errors()
.into_iter()
.flat_map(|(_, errs)| errs)
.cloned()
.collect();

RegisterError::InvalidInput { errors }
})?;
input.validate()?;

let is_admin_initialized = self.is_admin_initialized().await?;
if is_admin_initialized {
Expand Down Expand Up @@ -172,16 +163,7 @@ impl AuthenticationService for DbConn {
password: String,
) -> std::result::Result<TokenAuthResponse, TokenAuthError> {
let input = TokenAuthInput { email, password };
input.validate().map_err(|err| {
let errors = err
.field_errors()
.into_iter()
.flat_map(|(_, errs)| errs)
.cloned()
.collect();

TokenAuthError::InvalidInput { errors }
})?;
input.validate()?;

let Some(user) = self.get_user_by_email(&input.email).await? else {
return Err(TokenAuthError::UserNotFound);
Expand Down

0 comments on commit 7764f2e

Please sign in to comment.