mirror of
https://github.com/n08i40k/schedule-parser-rusted.git
synced 2025-12-06 09:47:50 +03:00
Добавлена возможность создания ResponseError с описанием ошибки.
Добавлен макрос для трансформации ErrorCode в Response, а также для имплементации треита PartialStatusCode.
This commit is contained in:
@@ -32,7 +32,7 @@ serde_repr = "0.1.20"
|
|||||||
sha2 = "0.11.0-pre.5"
|
sha2 = "0.11.0-pre.5"
|
||||||
tokio = { version = "1.44.1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.44.1", features = ["macros", "rt-multi-thread"] }
|
||||||
rand = "0.9.0"
|
rand = "0.9.0"
|
||||||
utoipa = { version = "5", features = ["actix_extras"] }
|
utoipa = { version = "5", features = ["actix_extras", "chrono"] }
|
||||||
utoipa-rapidoc = { version = "6.0.0", features = ["actix-web"] }
|
utoipa-rapidoc = { version = "6.0.0", features = ["actix-web"] }
|
||||||
utoipa-actix-web = "0.1"
|
utoipa-actix-web = "0.1"
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ extern crate proc_macro;
|
|||||||
|
|
||||||
use proc_macro::TokenStream;
|
use proc_macro::TokenStream;
|
||||||
|
|
||||||
mod response_error_message {
|
mod shared {
|
||||||
use proc_macro::TokenStream;
|
|
||||||
use quote::{ToTokens, quote};
|
use quote::{ToTokens, quote};
|
||||||
use syn::Attribute;
|
use syn::{Attribute, DeriveInput};
|
||||||
|
|
||||||
pub fn find_status_code(attrs: &Vec<Attribute>) -> Option<proc_macro2::TokenStream> {
|
pub fn find_status_code(attrs: &Vec<Attribute>) -> Option<proc_macro2::TokenStream> {
|
||||||
attrs
|
attrs
|
||||||
@@ -31,7 +30,7 @@ mod response_error_message {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fmt(ast: &syn::DeriveInput) -> TokenStream {
|
pub fn get_arms(ast: &DeriveInput) -> Vec<proc_macro2::TokenStream> {
|
||||||
let name = &ast.ident;
|
let name = &ast.ident;
|
||||||
|
|
||||||
let variants = if let syn::Data::Enum(data) = &ast.data {
|
let variants = if let syn::Data::Enum(data) = &ast.data {
|
||||||
@@ -54,21 +53,56 @@ mod response_error_message {
|
|||||||
|
|
||||||
if status_code_arms.len() < variants.len() {
|
if status_code_arms.len() < variants.len() {
|
||||||
let status_code = find_status_code(&ast.attrs)
|
let status_code = find_status_code(&ast.attrs)
|
||||||
.unwrap_or_else(|| quote! { actix_web::http::StatusCode::INTERNAL_SERVER_ERROR });
|
.unwrap_or_else(|| quote! { ::actix_web::http::StatusCode::INTERNAL_SERVER_ERROR });
|
||||||
|
|
||||||
status_code_arms.push(quote! { _ => #status_code });
|
status_code_arms.push(quote! { _ => #status_code });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
status_code_arms
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod response_error_message {
|
||||||
|
use proc_macro::TokenStream;
|
||||||
|
use quote::quote;
|
||||||
|
|
||||||
|
pub fn fmt(ast: &syn::DeriveInput) -> TokenStream {
|
||||||
|
let name = &ast.ident;
|
||||||
|
|
||||||
|
let status_code_arms = super::shared::get_arms(ast);
|
||||||
|
|
||||||
TokenStream::from(quote! {
|
TokenStream::from(quote! {
|
||||||
impl actix_web::ResponseError for #name {
|
impl ::actix_web::ResponseError for #name {
|
||||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
fn status_code(&self) -> ::actix_web::http::StatusCode {
|
||||||
match self {
|
match self {
|
||||||
#(#status_code_arms)*
|
#(#status_code_arms)*
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn error_response(&self) -> actix_web::HttpResponse<BoxBody> {
|
fn error_response(&self) -> ::actix_web::HttpResponse<BoxBody> {
|
||||||
actix_web::HttpResponse::build(self.status_code()).json(crate::utility::error::ResponseErrorMessage::new(self.clone()))
|
::actix_web::HttpResponse::build(self.status_code())
|
||||||
|
.json(crate::utility::error::ResponseErrorMessage::new(self.clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod status_code {
|
||||||
|
use proc_macro::TokenStream;
|
||||||
|
use quote::quote;
|
||||||
|
|
||||||
|
pub fn fmt(ast: &syn::DeriveInput) -> TokenStream {
|
||||||
|
let name = &ast.ident;
|
||||||
|
|
||||||
|
let status_code_arms = super::shared::get_arms(ast);
|
||||||
|
|
||||||
|
TokenStream::from(quote! {
|
||||||
|
impl crate::routes::schema::PartialStatusCode for #name {
|
||||||
|
fn status_code(&self) -> ::actix_web::http::StatusCode {
|
||||||
|
match self {
|
||||||
|
#(#status_code_arms)*
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -103,7 +137,7 @@ mod responder_json {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mod into_iresponse {
|
mod into_response_error {
|
||||||
use proc_macro::TokenStream;
|
use proc_macro::TokenStream;
|
||||||
use quote::quote;
|
use quote::quote;
|
||||||
|
|
||||||
@@ -111,17 +145,37 @@ mod into_iresponse {
|
|||||||
let name = &ast.ident;
|
let name = &ast.ident;
|
||||||
|
|
||||||
TokenStream::from(quote! {
|
TokenStream::from(quote! {
|
||||||
impl<E> ::core::convert::Into<crate::routes::schema::IResponse<#name, E>> for #name
|
impl ::core::convert::Into<crate::routes::schema::ResponseError<#name>> for #name {
|
||||||
where
|
fn into(self) -> crate::routes::schema::ResponseError<#name> {
|
||||||
E: ::serde::ser::Serialize
|
crate::routes::schema::ResponseError {
|
||||||
+ ::utoipa::PartialSchema
|
code: self,
|
||||||
+ ::core::clone::Clone
|
message: ::core::option::Option::None,
|
||||||
+ crate::routes::schema::HttpStatusCode,
|
}
|
||||||
{
|
|
||||||
fn into(self) -> crate::routes::schema::IResponse<#name, E> {
|
|
||||||
crate::routes::schema::IResponse(Ok(self))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T> crate::routes::schema::IntoResponseAsError<T> for #name
|
||||||
|
where
|
||||||
|
T: ::serde::ser::Serialize + ::utoipa::PartialSchema {}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fmt_named(ast: &syn::DeriveInput) -> TokenStream {
|
||||||
|
let name = &ast.ident;
|
||||||
|
|
||||||
|
TokenStream::from(quote! {
|
||||||
|
impl ::core::convert::Into<crate::routes::schema::ResponseError<#name>> for #name {
|
||||||
|
fn into(self) -> crate::routes::schema::ResponseError<#name> {
|
||||||
|
crate::routes::schema::ResponseError {
|
||||||
|
message: ::core::option::Option::Some(format!("{}", self)),
|
||||||
|
code: self,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> crate::routes::schema::IntoResponseAsError<T> for #name
|
||||||
|
where
|
||||||
|
T: ::serde::ser::Serialize + ::utoipa::PartialSchema {}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,9 +194,23 @@ pub fn responser_json_derive(input: TokenStream) -> TokenStream {
|
|||||||
responder_json::fmt(&ast)
|
responder_json::fmt(&ast)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[proc_macro_derive(IntoIResponse)]
|
#[proc_macro_derive(IntoResponseError)]
|
||||||
pub fn into_iresponse_derive(input: TokenStream) -> TokenStream {
|
pub fn into_response_error_derive(input: TokenStream) -> TokenStream {
|
||||||
let ast = syn::parse(input).unwrap();
|
let ast = syn::parse(input).unwrap();
|
||||||
|
|
||||||
into_iresponse::fmt(&ast)
|
into_response_error::fmt(&ast)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(IntoResponseErrorNamed)]
|
||||||
|
pub fn into_response_error_named_derive(input: TokenStream) -> TokenStream {
|
||||||
|
let ast = syn::parse(input).unwrap();
|
||||||
|
|
||||||
|
into_response_error::fmt_named(&ast)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(StatusCode, attributes(status_code))]
|
||||||
|
pub fn status_code_derive(input: TokenStream) -> TokenStream {
|
||||||
|
let ast = syn::parse(input).unwrap();
|
||||||
|
|
||||||
|
status_code::fmt(&ast)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
|
use crate::parser::schema::ParseResult;
|
||||||
use crate::xls_downloader::basic_impl::BasicXlsDownloader;
|
use crate::xls_downloader::basic_impl::BasicXlsDownloader;
|
||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use diesel::{Connection, PgConnection};
|
use diesel::{Connection, PgConnection};
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::sync::{Mutex, MutexGuard};
|
use std::sync::{Mutex, MutexGuard};
|
||||||
use crate::parser::schema::ParseResult;
|
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct Schedule {
|
pub struct Schedule {
|
||||||
pub etag: String,
|
pub etag: String,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use actix_web::{App, HttpServer};
|
|||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
use utoipa_actix_web::AppExt;
|
use utoipa_actix_web::AppExt;
|
||||||
use utoipa_rapidoc::RapiDoc;
|
use utoipa_rapidoc::RapiDoc;
|
||||||
|
use crate::routes::schedule::get_schedule::get_schedule;
|
||||||
|
|
||||||
mod app_state;
|
mod app_state;
|
||||||
|
|
||||||
@@ -41,9 +42,14 @@ async fn main() {
|
|||||||
.wrap(Authorization)
|
.wrap(Authorization)
|
||||||
.service(me);
|
.service(me);
|
||||||
|
|
||||||
|
let schedule_scope = utoipa_actix_web::scope("/schedule")
|
||||||
|
.wrap(Authorization)
|
||||||
|
.service(get_schedule);
|
||||||
|
|
||||||
let api_scope = utoipa_actix_web::scope("/api/v1")
|
let api_scope = utoipa_actix_web::scope("/api/v1")
|
||||||
.service(auth_scope)
|
.service(auth_scope)
|
||||||
.service(users_scope);
|
.service(users_scope)
|
||||||
|
.service(schedule_scope);
|
||||||
|
|
||||||
let (app, api) = App::new()
|
let (app, api) = App::new()
|
||||||
.into_utoipa_app()
|
.into_utoipa_app()
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ use serde::{Deserialize, Serialize};
|
|||||||
use serde_repr::{Deserialize_repr, Serialize_repr};
|
use serde_repr::{Deserialize_repr, Serialize_repr};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone, utoipa::ToSchema)]
|
||||||
pub struct LessonTime {
|
pub struct LessonTime {
|
||||||
pub start: DateTime<Utc>,
|
pub start: DateTime<Utc>,
|
||||||
pub end: DateTime<Utc>,
|
pub end: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize_repr, Deserialize_repr, Debug, PartialEq, Clone)]
|
#[derive(Serialize_repr, Deserialize_repr, Debug, PartialEq, Clone, utoipa::ToSchema)]
|
||||||
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum LessonType {
|
pub enum LessonType {
|
||||||
Default = 0, // Обычная
|
Default = 0, // Обычная
|
||||||
@@ -22,7 +23,7 @@ pub enum LessonType {
|
|||||||
ExamDefault, // Экзамен
|
ExamDefault, // Экзамен
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive( Serialize, Deserialize, Debug, Clone, utoipa::ToSchema)]
|
||||||
pub struct LessonSubGroup {
|
pub struct LessonSubGroup {
|
||||||
/**
|
/**
|
||||||
* Номер подгруппы.
|
* Номер подгруппы.
|
||||||
@@ -40,7 +41,8 @@ pub struct LessonSubGroup {
|
|||||||
pub teacher: String,
|
pub teacher: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone, utoipa::ToSchema)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Lesson {
|
pub struct Lesson {
|
||||||
/**
|
/**
|
||||||
* Тип занятия.
|
* Тип занятия.
|
||||||
@@ -51,7 +53,6 @@ pub struct Lesson {
|
|||||||
/**
|
/**
|
||||||
* Индексы пар, если присутствуют.
|
* Индексы пар, если присутствуют.
|
||||||
*/
|
*/
|
||||||
#[serde(rename = "defaultRange")]
|
|
||||||
pub default_range: Option<[u8; 2]>,
|
pub default_range: Option<[u8; 2]>,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,7 +77,7 @@ pub struct Lesson {
|
|||||||
pub group: Option<String>,
|
pub group: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone, utoipa::ToSchema)]
|
||||||
pub struct Day {
|
pub struct Day {
|
||||||
/**
|
/**
|
||||||
* День недели.
|
* День недели.
|
||||||
@@ -99,7 +100,7 @@ pub struct Day {
|
|||||||
pub lessons: Vec<Lesson>,
|
pub lessons: Vec<Lesson>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Clone, Serialize, Deserialize, Debug, utoipa::ToSchema)]
|
||||||
pub struct ScheduleEntry {
|
pub struct ScheduleEntry {
|
||||||
/**
|
/**
|
||||||
* Название группы или ФИО преподавателя.
|
* Название группы или ФИО преподавателя.
|
||||||
@@ -112,6 +113,7 @@ pub struct ScheduleEntry {
|
|||||||
pub days: Vec<Day>,
|
pub days: Vec<Day>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct ParseResult {
|
pub struct ParseResult {
|
||||||
/**
|
/**
|
||||||
* Список групп.
|
* Список групп.
|
||||||
|
|||||||
@@ -4,14 +4,17 @@ use crate::database::models::User;
|
|||||||
use crate::routes::auth::shared::parse_vk_id;
|
use crate::routes::auth::shared::parse_vk_id;
|
||||||
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
|
use crate::routes::auth::sign_in::schema::SignInData::{Default, Vk};
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::routes::schema::ResponseError;
|
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
||||||
use crate::{utility, AppState};
|
use crate::{AppState, utility};
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use diesel::SaveChangesDsl;
|
use diesel::SaveChangesDsl;
|
||||||
use std::ops::DerefMut;
|
use std::ops::DerefMut;
|
||||||
use web::Json;
|
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 {
|
let user = match &data {
|
||||||
Default(data) => driver::users::get_by_username(&app_state.database, &data.username),
|
Default(data) => driver::users::get_by_username(&app_state.database, &data.username),
|
||||||
Vk(id) => driver::users::get_by_vk_id(&app_state.database, *id),
|
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) {
|
match bcrypt::verify(&data.password, &user.password) {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
if !result {
|
if !result {
|
||||||
return ErrorCode::IncorrectCredentials.into();
|
return Err(ErrorCode::IncorrectCredentials);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
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)
|
user.save_changes::<User>(conn)
|
||||||
.expect("Failed to update user");
|
.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")]
|
#[post("/sign-in")]
|
||||||
pub async fn sign_in_default(data: Json<Request>, app_state: web::Data<AppState>) -> Response {
|
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(
|
#[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();
|
let data = data_json.into_inner();
|
||||||
|
|
||||||
match parse_vk_id(&data.access_token) {
|
match parse_vk_id(&data.access_token) {
|
||||||
Ok(id) => sign_in(Vk(id), &app_state).await,
|
Ok(id) => sign_in(Vk(id), &app_state).await.into(),
|
||||||
Err(_) => ErrorCode::InvalidVkAccessToken.into(),
|
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mod schema {
|
mod schema {
|
||||||
|
use crate::routes::schema::PartialStatusCode;
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::routes::schema::{HttpStatusCode, IResponse};
|
use actix_macros::IntoResponseError;
|
||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use serde::{Deserialize, Serialize};
|
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")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = SignIn::ErrorCode)]
|
#[schema(as = SignIn::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
@@ -105,7 +109,7 @@ mod schema {
|
|||||||
InvalidVkAccessToken,
|
InvalidVkAccessToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpStatusCode for ErrorCode {
|
impl PartialStatusCode for ErrorCode {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
StatusCode::NOT_ACCEPTABLE
|
StatusCode::NOT_ACCEPTABLE
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,16 +3,19 @@ use crate::AppState;
|
|||||||
use crate::database::driver;
|
use crate::database::driver;
|
||||||
use crate::database::models::UserRole;
|
use crate::database::models::UserRole;
|
||||||
use crate::routes::auth::shared::{Error, parse_vk_id};
|
use crate::routes::auth::shared::{Error, parse_vk_id};
|
||||||
use crate::routes::schema::ResponseError;
|
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
|
use crate::routes::schema::{IntoResponseAsError, ResponseError};
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use rand::{Rng, rng};
|
use rand::{Rng, rng};
|
||||||
use web::Json;
|
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 user selected forbidden role.
|
||||||
if data.role == UserRole::Admin {
|
if data.role == UserRole::Admin {
|
||||||
return ErrorCode::DisallowedRole.into();
|
return Err(ErrorCode::DisallowedRole);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If specified group doesn't exist in schedule.
|
// 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 let Some(schedule) = &*schedule_opt {
|
||||||
if !schedule.data.groups.contains_key(&data.group) {
|
if !schedule.data.groups.contains_key(&data.group) {
|
||||||
return ErrorCode::InvalidGroupName.into();
|
return Err(ErrorCode::InvalidGroupName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If user with specified username already exists.
|
// If user with specified username already exists.
|
||||||
if driver::users::contains_by_username(&app_state.database, &data.username) {
|
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 user with specified VKID already exists.
|
||||||
if let Some(id) = data.vk_id {
|
if let Some(id) = data.vk_id {
|
||||||
if driver::users::contains_by_vk_id(&app_state.database, id) {
|
if driver::users::contains_by_vk_id(&app_state.database, id) {
|
||||||
return ErrorCode::VkAlreadyExists.into();
|
return Err(ErrorCode::VkAlreadyExists);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = data.into();
|
let user = data.into();
|
||||||
driver::users::insert(&app_state.database, &user).unwrap();
|
driver::users::insert(&app_state.database, &user).unwrap();
|
||||||
|
|
||||||
UserResponse::from(&user).into()
|
Ok(UserResponse::from(&user)).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
@@ -62,6 +65,7 @@ pub async fn sign_up_default(data_json: Json<Request>, app_state: web::Data<AppS
|
|||||||
&app_state,
|
&app_state,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[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>)
|
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
|
||||||
))]
|
))]
|
||||||
#[post("/sign-up-vk")]
|
#[post("/sign-up-vk")]
|
||||||
pub async fn sign_up_vk(
|
pub async fn sign_up_vk(data_json: Json<vk::Request>, app_state: web::Data<AppState>) -> Response {
|
||||||
data_json: Json<vk::Request>,
|
|
||||||
app_state: web::Data<AppState>,
|
|
||||||
) -> Response {
|
|
||||||
let data = data_json.into_inner();
|
let data = data_json.into_inner();
|
||||||
|
|
||||||
match parse_vk_id(&data.access_token) {
|
match parse_vk_id(&data.access_token) {
|
||||||
Ok(id) => {
|
Ok(id) => sign_up(
|
||||||
sign_up(
|
SignUpData {
|
||||||
SignUpData {
|
username: data.username,
|
||||||
username: data.username,
|
password: rng()
|
||||||
password: rng()
|
.sample_iter(&rand::distr::Alphanumeric)
|
||||||
.sample_iter(&rand::distr::Alphanumeric)
|
.take(16)
|
||||||
.take(16)
|
.map(char::from)
|
||||||
.map(char::from)
|
.collect(),
|
||||||
.collect(),
|
vk_id: Some(id),
|
||||||
vk_id: Some(id),
|
group: data.group,
|
||||||
group: data.group,
|
role: data.role,
|
||||||
role: data.role,
|
version: data.version,
|
||||||
version: data.version,
|
},
|
||||||
},
|
&app_state,
|
||||||
&app_state,
|
)
|
||||||
)
|
.await
|
||||||
.await
|
.into(),
|
||||||
}
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if err != Error::Expired {
|
if err != Error::Expired {
|
||||||
eprintln!("Failed to parse vk id token!");
|
eprintln!("Failed to parse vk id token!");
|
||||||
eprintln!("{:?}", err);
|
eprintln!("{:?}", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
ErrorCode::InvalidVkAccessToken.into()
|
ErrorCode::InvalidVkAccessToken.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mod schema {
|
mod schema {
|
||||||
use crate::database::models::{User, UserRole};
|
use crate::database::models::{User, UserRole};
|
||||||
|
use crate::routes::schema::PartialStatusCode;
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::routes::schema::{HttpStatusCode, IResponse};
|
|
||||||
use crate::utility;
|
use crate::utility;
|
||||||
|
use actix_macros::{IntoResponseError, StatusCode};
|
||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use objectid::ObjectId;
|
use objectid::ObjectId;
|
||||||
use serde::{Deserialize, Serialize};
|
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")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = SignUp::ErrorCode)]
|
#[schema(as = SignUp::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
@@ -169,12 +171,6 @@ mod schema {
|
|||||||
VkAlreadyExists,
|
VkAlreadyExists,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpStatusCode for ErrorCode {
|
|
||||||
fn status_code(&self) -> StatusCode {
|
|
||||||
StatusCode::NOT_ACCEPTABLE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Internal
|
/// Internal
|
||||||
|
|
||||||
pub struct SignUpData {
|
pub struct SignUpData {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod users;
|
pub mod users;
|
||||||
|
pub mod schedule;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
|||||||
38
src/routes/schedule/get_schedule.rs
Normal file
38
src/routes/schedule/get_schedule.rs
Normal 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
2
src/routes/schedule/mod.rs
Normal file
2
src/routes/schedule/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod get_schedule;
|
||||||
|
mod schema;
|
||||||
47
src/routes/schedule/schema.rs
Normal file
47
src/routes/schedule/schema.rs
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,51 +3,45 @@ use actix_web::error::JsonPayloadError;
|
|||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::{HttpRequest, HttpResponse, Responder};
|
use actix_web::{HttpRequest, HttpResponse, Responder};
|
||||||
use serde::{Serialize, Serializer};
|
use serde::{Serialize, Serializer};
|
||||||
|
use std::convert::Into;
|
||||||
use utoipa::PartialSchema;
|
use utoipa::PartialSchema;
|
||||||
|
|
||||||
pub struct IResponse<T, E>(pub Result<T, E>)
|
pub struct Response<T, E>(pub Result<T, E>)
|
||||||
where
|
where
|
||||||
T: Serialize + PartialSchema,
|
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
|
where
|
||||||
T: Serialize + PartialSchema,
|
T: Serialize + PartialSchema,
|
||||||
E: Serialize + PartialSchema + Clone + HttpStatusCode,
|
E: Serialize + PartialSchema + Clone + PartialStatusCode,
|
||||||
{
|
{
|
||||||
fn into(self) -> Result<T, E> {
|
fn into(self) -> Result<T, E> {
|
||||||
self.0
|
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
|
where
|
||||||
T: Serialize + PartialSchema,
|
T: Serialize + PartialSchema,
|
||||||
E: Serialize + PartialSchema + Clone + HttpStatusCode,
|
E: Serialize + PartialSchema + Clone + PartialStatusCode,
|
||||||
{
|
{
|
||||||
fn from(value: E) -> Self {
|
fn from(value: Result<T, E>) -> Self {
|
||||||
IResponse(Err(value))
|
Response(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait HttpStatusCode {
|
/// Serialize Response<T, E>
|
||||||
fn status_code(&self) -> StatusCode;
|
impl<T, E> Serialize for Response<T, E>
|
||||||
}
|
|
||||||
|
|
||||||
impl<T, E> IResponse<T, E>
|
|
||||||
where
|
where
|
||||||
T: Serialize + PartialSchema,
|
T: Serialize + PartialSchema,
|
||||||
E: Serialize + PartialSchema + Clone + HttpStatusCode,
|
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
|
||||||
{
|
|
||||||
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,
|
|
||||||
{
|
{
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where
|
where
|
||||||
@@ -55,15 +49,17 @@ where
|
|||||||
{
|
{
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
Ok(ok) => serializer.serialize_some::<T>(&ok),
|
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
|
where
|
||||||
T: Serialize + PartialSchema,
|
T: Serialize + PartialSchema,
|
||||||
E: Serialize + PartialSchema + Clone + HttpStatusCode,
|
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
|
||||||
{
|
{
|
||||||
type Body = EitherBody<String>;
|
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)]
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
pub struct ResponseError<T: Serialize + PartialSchema> {
|
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> {
|
pub trait IntoResponseAsError<T>
|
||||||
fn new(status_code: &T) -> Self {
|
where
|
||||||
ResponseError {
|
T: Serialize + PartialSchema,
|
||||||
code: status_code.clone(),
|
Self: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<Self>>,
|
||||||
}
|
{
|
||||||
|
fn into_response(self) -> Response<T, Self> {
|
||||||
|
Response(Err(self))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod user {
|
pub mod user {
|
||||||
use crate::database::models::{User, UserRole};
|
use crate::database::models::{User, UserRole};
|
||||||
use actix_macros::{IntoIResponse, ResponderJson};
|
use actix_macros::ResponderJson;
|
||||||
use serde::Serialize;
|
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")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct UserResponse {
|
pub struct UserResponse {
|
||||||
#[schema(examples("67dcc9a9507b0000772744a2"))]
|
#[schema(examples("67dcc9a9507b0000772744a2"))]
|
||||||
@@ -132,6 +139,7 @@ pub mod user {
|
|||||||
access_token: String,
|
access_token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create UserResponse from User ref.
|
||||||
impl From<&User> for UserResponse {
|
impl From<&User> for UserResponse {
|
||||||
fn from(user: &User) -> Self {
|
fn from(user: &User) -> Self {
|
||||||
UserResponse {
|
UserResponse {
|
||||||
@@ -145,6 +153,7 @@ pub mod user {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Transform User to UserResponse.
|
||||||
impl From<User> for UserResponse {
|
impl From<User> for UserResponse {
|
||||||
fn from(user: User) -> Self {
|
fn from(user: User) -> Self {
|
||||||
UserResponse {
|
UserResponse {
|
||||||
|
|||||||
Reference in New Issue
Block a user