Добавлена возможность создания ResponseError с описанием ошибки.

Добавлен макрос для трансформации ErrorCode в Response, а также для имплементации треита PartialStatusCode.
This commit is contained in:
2025-03-28 15:42:45 +04:00
parent 70a7480ea3
commit 30c985a3d7
12 changed files with 296 additions and 122 deletions

View File

@@ -4,14 +4,17 @@ use crate::database::models::User;
use crate::routes::auth::shared::parse_vk_id;
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
use crate::routes::schema::user::UserResponse;
use crate::routes::schema::ResponseError;
use crate::{utility, AppState};
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use crate::{AppState, utility};
use actix_web::{post, web};
use diesel::SaveChangesDsl;
use std::ops::DerefMut;
use web::Json;
async fn sign_in(data: SignInData, app_state: &web::Data<AppState>) -> Response {
async fn sign_in(
data: SignInData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
let user = match &data {
Default(data) => driver::users::get_by_username(&app_state.database, &data.username),
Vk(id) => driver::users::get_by_vk_id(&app_state.database, *id),
@@ -23,11 +26,11 @@ async fn sign_in(data: SignInData, app_state: &web::Data<AppState>) -> Response
match bcrypt::verify(&data.password, &user.password) {
Ok(result) => {
if !result {
return ErrorCode::IncorrectCredentials.into();
return Err(ErrorCode::IncorrectCredentials);
}
}
Err(_) => {
return ErrorCode::IncorrectCredentials.into();
return Err(ErrorCode::IncorrectCredentials);
}
}
}
@@ -40,10 +43,10 @@ async fn sign_in(data: SignInData, app_state: &web::Data<AppState>) -> Response
user.save_changes::<User>(conn)
.expect("Failed to update user");
UserResponse::from(&user).into()
Ok(user.into())
}
Err(_) => ErrorCode::IncorrectCredentials.into(),
Err(_) => Err(ErrorCode::IncorrectCredentials),
}
}
@@ -53,7 +56,7 @@ async fn sign_in(data: SignInData, app_state: &web::Data<AppState>) -> Response
))]
#[post("/sign-in")]
pub async fn sign_in_default(data: Json<Request>, app_state: web::Data<AppState>) -> Response {
sign_in(Default(data.into_inner()), &app_state).await
sign_in(Default(data.into_inner()), &app_state).await.into()
}
#[utoipa::path(responses(
@@ -65,14 +68,15 @@ pub async fn sign_in_vk(data_json: Json<vk::Request>, app_state: web::Data<AppSt
let data = data_json.into_inner();
match parse_vk_id(&data.access_token) {
Ok(id) => sign_in(Vk(id), &app_state).await,
Err(_) => ErrorCode::InvalidVkAccessToken.into(),
Ok(id) => sign_in(Vk(id), &app_state).await.into(),
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
}
}
mod schema {
use crate::routes::schema::PartialStatusCode;
use crate::routes::schema::user::UserResponse;
use crate::routes::schema::{HttpStatusCode, IResponse};
use actix_macros::IntoResponseError;
use actix_web::http::StatusCode;
use serde::{Deserialize, Serialize};
@@ -95,9 +99,9 @@ mod schema {
}
}
pub type Response = IResponse<UserResponse, ErrorCode>;
pub type Response = crate::routes::schema::Response<UserResponse, ErrorCode>;
#[derive(Serialize, utoipa::ToSchema, Clone)]
#[derive(Serialize, utoipa::ToSchema, Clone, IntoResponseError)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = SignIn::ErrorCode)]
pub enum ErrorCode {
@@ -105,7 +109,7 @@ mod schema {
InvalidVkAccessToken,
}
impl HttpStatusCode for ErrorCode {
impl PartialStatusCode for ErrorCode {
fn status_code(&self) -> StatusCode {
StatusCode::NOT_ACCEPTABLE
}

View File

@@ -3,16 +3,19 @@ use crate::AppState;
use crate::database::driver;
use crate::database::models::UserRole;
use crate::routes::auth::shared::{Error, parse_vk_id};
use crate::routes::schema::ResponseError;
use crate::routes::schema::user::UserResponse;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use actix_web::{post, web};
use rand::{Rng, rng};
use web::Json;
async fn sign_up(data: SignUpData, app_state: &web::Data<AppState>) -> Response {
async fn sign_up(
data: SignUpData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
// If user selected forbidden role.
if data.role == UserRole::Admin {
return ErrorCode::DisallowedRole.into();
return Err(ErrorCode::DisallowedRole);
}
// If specified group doesn't exist in schedule.
@@ -20,26 +23,26 @@ async fn sign_up(data: SignUpData, app_state: &web::Data<AppState>) -> Response
if let Some(schedule) = &*schedule_opt {
if !schedule.data.groups.contains_key(&data.group) {
return ErrorCode::InvalidGroupName.into();
return Err(ErrorCode::InvalidGroupName);
}
}
// If user with specified username already exists.
if driver::users::contains_by_username(&app_state.database, &data.username) {
return ErrorCode::UsernameAlreadyExists.into();
return Err(ErrorCode::UsernameAlreadyExists);
}
// If user with specified VKID already exists.
if let Some(id) = data.vk_id {
if driver::users::contains_by_vk_id(&app_state.database, id) {
return ErrorCode::VkAlreadyExists.into();
return Err(ErrorCode::VkAlreadyExists);
}
}
let user = data.into();
driver::users::insert(&app_state.database, &user).unwrap();
UserResponse::from(&user).into()
Ok(UserResponse::from(&user)).into()
}
#[utoipa::path(responses(
@@ -62,6 +65,7 @@ pub async fn sign_up_default(data_json: Json<Request>, app_state: web::Data<AppS
&app_state,
)
.await
.into()
}
#[utoipa::path(responses(
@@ -69,47 +73,44 @@ pub async fn sign_up_default(data_json: Json<Request>, app_state: web::Data<AppS
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-up-vk")]
pub async fn sign_up_vk(
data_json: Json<vk::Request>,
app_state: web::Data<AppState>,
) -> Response {
pub async fn sign_up_vk(data_json: Json<vk::Request>, app_state: web::Data<AppState>) -> Response {
let data = data_json.into_inner();
match parse_vk_id(&data.access_token) {
Ok(id) => {
sign_up(
SignUpData {
username: data.username,
password: rng()
.sample_iter(&rand::distr::Alphanumeric)
.take(16)
.map(char::from)
.collect(),
vk_id: Some(id),
group: data.group,
role: data.role,
version: data.version,
},
&app_state,
)
.await
}
Ok(id) => sign_up(
SignUpData {
username: data.username,
password: rng()
.sample_iter(&rand::distr::Alphanumeric)
.take(16)
.map(char::from)
.collect(),
vk_id: Some(id),
group: data.group,
role: data.role,
version: data.version,
},
&app_state,
)
.await
.into(),
Err(err) => {
if err != Error::Expired {
eprintln!("Failed to parse vk id token!");
eprintln!("{:?}", err);
}
ErrorCode::InvalidVkAccessToken.into()
ErrorCode::InvalidVkAccessToken.into_response()
}
}
}
mod schema {
use crate::database::models::{User, UserRole};
use crate::routes::schema::PartialStatusCode;
use crate::routes::schema::user::UserResponse;
use crate::routes::schema::{HttpStatusCode, IResponse};
use crate::utility;
use actix_macros::{IntoResponseError, StatusCode};
use actix_web::http::StatusCode;
use objectid::ObjectId;
use serde::{Deserialize, Serialize};
@@ -156,9 +157,10 @@ mod schema {
}
}
pub type Response = IResponse<UserResponse, ErrorCode>;
pub type Response = crate::routes::schema::Response<UserResponse, ErrorCode>;
#[derive(Clone, Serialize, utoipa::ToSchema)]
#[derive(Clone, Serialize, utoipa::ToSchema, IntoResponseError, StatusCode)]
#[status_code = "StatusCode::NOT_ACCEPTABLE"]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = SignUp::ErrorCode)]
pub enum ErrorCode {
@@ -169,12 +171,6 @@ mod schema {
VkAlreadyExists,
}
impl HttpStatusCode for ErrorCode {
fn status_code(&self) -> StatusCode {
StatusCode::NOT_ACCEPTABLE
}
}
/// Internal
pub struct SignUpData {

View File

@@ -1,3 +1,4 @@
pub mod auth;
pub mod users;
pub mod schedule;
mod schema;

View File

@@ -0,0 +1,38 @@
use self::schema::*;
use crate::app_state::AppState;
use crate::routes::schedule::schema::{Error, ScheduleView};
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use actix_web::{get, web};
#[utoipa::path(responses(
(status = OK, body = ScheduleView),
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>)
))]
#[get("/")]
pub async fn get_schedule(app_state: web::Data<AppState>) -> Response {
match ScheduleView::try_from(app_state.get_ref()) {
Ok(res) => Ok(res).into(),
Err(e) => match e {
Error::NoSchedule => ErrorCode::NoSchedule.into_response(),
},
}
}
mod schema {
use crate::routes::schedule::schema::ScheduleView;
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::Serialize;
use utoipa::ToSchema;
pub type Response = crate::routes::schema::Response<ScheduleView, ErrorCode>;
#[derive(Clone, Serialize, ToSchema, StatusCode, Display, IntoResponseErrorNamed)]
#[status_code = "actix_web::http::StatusCode::SERVICE_UNAVAILABLE"]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = ScheduleView::ErrorCode)]
pub enum ErrorCode {
#[display("Schedule not parsed yet")]
NoSchedule,
}
}

View File

@@ -0,0 +1,2 @@
pub mod get_schedule;
mod schema;

View File

@@ -0,0 +1,47 @@
use crate::app_state::AppState;
use crate::parser::schema::ScheduleEntry;
use chrono::{DateTime, Utc};
use serde::Serialize;
use std::collections::HashMap;
use utoipa::ToSchema;
#[derive(Serialize, ToSchema)]
pub struct ScheduleView {
etag: String,
replacer_id: Option<String>,
uploaded_at: DateTime<Utc>,
downloaded_at: DateTime<Utc>,
groups: HashMap<String, ScheduleEntry>,
teachers: HashMap<String, ScheduleEntry>,
updated_groups: Vec<Vec<i32>>,
updated_teachers: Vec<Vec<i32>>,
}
pub enum Error {
NoSchedule,
}
impl TryFrom<&AppState> for ScheduleView {
type Error = Error;
fn try_from(app_state: &AppState) -> Result<Self, Self::Error> {
let schedule_lock = app_state.schedule.lock().unwrap();
if let Some(schedule_ref) = schedule_lock.as_ref() {
let schedule = schedule_ref.clone();
Ok(Self {
etag: schedule.etag,
replacer_id: None,
uploaded_at: schedule.updated_at,
downloaded_at: schedule.parsed_at,
groups: schedule.data.groups,
teachers: schedule.data.teachers,
updated_groups: vec![],
updated_teachers: vec![],
})
} else {
Err(Error::NoSchedule)
}
}
}

View File

@@ -3,51 +3,45 @@ use actix_web::error::JsonPayloadError;
use actix_web::http::StatusCode;
use actix_web::{HttpRequest, HttpResponse, Responder};
use serde::{Serialize, Serializer};
use std::convert::Into;
use utoipa::PartialSchema;
pub struct IResponse<T, E>(pub Result<T, E>)
pub struct Response<T, E>(pub Result<T, E>)
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode;
E: Serialize + PartialSchema + Clone + PartialStatusCode;
impl<T, E> Into<Result<T, E>> for IResponse<T, E>
pub trait PartialStatusCode {
fn status_code(&self) -> StatusCode;
}
/// Transform Response<T, E> into Result<T, E>
impl<T, E> Into<Result<T, E>> for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode,
E: Serialize + PartialSchema + Clone + PartialStatusCode,
{
fn into(self) -> Result<T, E> {
self.0
}
}
impl<T, E> From<E> for IResponse<T, E>
/// Transform T into Response<T, E>
impl<T, E> From<Result<T, E>> for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode,
E: Serialize + PartialSchema + Clone + PartialStatusCode,
{
fn from(value: E) -> Self {
IResponse(Err(value))
fn from(value: Result<T, E>) -> Self {
Response(value)
}
}
pub trait HttpStatusCode {
fn status_code(&self) -> StatusCode;
}
impl<T, E> IResponse<T, E>
/// Serialize Response<T, E>
impl<T, E> Serialize for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode,
{
pub fn new(result: Result<T, E>) -> Self {
IResponse(result)
}
}
impl<T, E> Serialize for IResponse<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode,
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
@@ -55,15 +49,17 @@ where
{
match &self.0 {
Ok(ok) => serializer.serialize_some::<T>(&ok),
Err(err) => serializer.serialize_some::<ResponseError<E>>(&ResponseError::new(err)),
Err(err) => serializer
.serialize_some::<ResponseError<E>>(&ResponseError::<E>::from(err.clone().into())),
}
}
}
impl<T, E> Responder for IResponse<T, E>
/// Transform Response<T, E> to HttpResponse<String>
impl<T, E> Responder for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + HttpStatusCode,
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
{
type Body = EitherBody<String>;
@@ -91,25 +87,36 @@ where
}
}
/// ResponseError<T>
///
/// Field `message` is optional for backwards compatibility with Android App, that produces error if new fields will be added to JSON response.
#[derive(Serialize, utoipa::ToSchema)]
pub struct ResponseError<T: Serialize + PartialSchema> {
code: T,
pub code: T,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
impl<T: Serialize + PartialSchema + Clone> ResponseError<T> {
fn new(status_code: &T) -> Self {
ResponseError {
code: status_code.clone(),
}
pub trait IntoResponseAsError<T>
where
T: Serialize + PartialSchema,
Self: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<Self>>,
{
fn into_response(self) -> Response<T, Self> {
Response(Err(self))
}
}
pub mod user {
use crate::database::models::{User, UserRole};
use actix_macros::{IntoIResponse, ResponderJson};
use actix_macros::ResponderJson;
use serde::Serialize;
#[derive(Serialize, utoipa::ToSchema, IntoIResponse, ResponderJson)]
/// UserResponse
///
/// Uses for stripping sensitive fields (password, fcm, etc.) from response.
#[derive(Serialize, utoipa::ToSchema, ResponderJson)]
#[serde(rename_all = "camelCase")]
pub struct UserResponse {
#[schema(examples("67dcc9a9507b0000772744a2"))]
@@ -132,6 +139,7 @@ pub mod user {
access_token: String,
}
/// Create UserResponse from User ref.
impl From<&User> for UserResponse {
fn from(user: &User) -> Self {
UserResponse {
@@ -145,6 +153,7 @@ pub mod user {
}
}
/// Transform User to UserResponse.
impl From<User> for UserResponse {
fn from(user: User) -> Self {
UserResponse {