feat!: add telegram auth and async refactor

- Removed "/schedule/update-download-url" endpoint, this mechanism was replaced by Yandex Cloud FaaS. Ура :)
- Improved schedule caching mechanism.
- Added Telegram WebApp authentication support.
- Reworked endpoints responses and errors mechanism.
- Refactored application state management.
- Make synchronous database operations, middlewares and extractors to asynchronous.
- Made user password field optional to support multiple auth methods.
- Renamed users table column "version" to "android_version" and made it nullable.
This commit is contained in:
2025-06-08 01:29:21 +04:00
parent 6a106a366c
commit e64011ba16
66 changed files with 1842 additions and 1243 deletions

View File

@@ -4,22 +4,19 @@ use actix_web::http::StatusCode;
use actix_web::{HttpRequest, HttpResponse, Responder};
use serde::{Serialize, Serializer};
use std::convert::Into;
use std::fmt::Display;
use utoipa::PartialSchema;
pub struct Response<T, E>(pub Result<T, E>)
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + PartialStatusCode;
pub trait PartialStatusCode {
fn status_code(&self) -> StatusCode;
}
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse;
/// 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 + PartialStatusCode,
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse,
{
fn into(self) -> Result<T, E> {
self.0
@@ -29,8 +26,8 @@ where
/// 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 + PartialStatusCode,
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse,
{
fn from(value: Result<T, E>) -> Self {
Response(value)
@@ -40,17 +37,16 @@ where
/// Serialize Response<T, E>
impl<T, E> Serialize for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse + Clone + Into<ResponseError<E>>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match &self.0 {
Ok(ok) => serializer.serialize_some::<T>(&ok),
Err(err) => serializer
.serialize_some::<ResponseError<E>>(&ResponseError::<E>::from(err.clone().into())),
Ok(ok) => serializer.serialize_some(&ok),
Err(err) => serializer.serialize_some(&ResponseError::<E>::from(err.clone().into())),
}
}
}
@@ -58,12 +54,12 @@ where
/// Transform Response<T, E> to HttpResponse<String>
impl<T, E> Responder for Response<T, E>
where
T: Serialize + PartialSchema,
E: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<E>>,
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse + Clone + Into<ResponseError<E>>,
{
type Body = EitherBody<String>;
fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
fn respond_to(mut self, request: &HttpRequest) -> HttpResponse<Self::Body> {
match serde_json::to_string(&self) {
Ok(body) => {
let code = match &self.0 {
@@ -71,13 +67,19 @@ where
Err(e) => e.status_code(),
};
match HttpResponse::build(code)
let mut response = match HttpResponse::build(code)
.content_type(mime::APPLICATION_JSON)
.message_body(body)
{
Ok(res) => res.map_into_left_body(),
Err(err) => HttpResponse::from_error(err).map_into_right_body(),
};
if let Ok(ok) = &mut self.0 {
ok.post_process(request, &mut response);
}
response
}
Err(err) => {
@@ -87,61 +89,80 @@ 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> {
pub code: T,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// Трейт для всех положительных ответов от сервера
pub trait PartialOkResponse {
fn post_process(
&mut self,
_request: &HttpRequest,
_response: &mut HttpResponse<EitherBody<String>>,
) -> () {
}
}
pub trait IntoResponseAsError<T>
impl PartialOkResponse for () {}
/// Трейт для всех отрицательных ответов от сервера
pub trait PartialErrResponse {
fn status_code(&self) -> StatusCode;
}
/// ResponseError<T>
#[derive(Serialize, utoipa::ToSchema)]
pub struct ResponseError<T: Serialize + PartialSchema + Clone> {
pub code: T,
pub message: String,
}
impl<T> From<T> for ResponseError<T>
where
T: Serialize + PartialSchema,
Self: Serialize + PartialSchema + Clone + PartialStatusCode + Into<ResponseError<Self>>,
T: Serialize + PartialSchema + Display + Clone,
{
fn into_response(self) -> Response<T, Self> {
Response(Err(self))
fn from(code: T) -> Self {
Self {
message: format!("{}", code),
code,
}
}
}
pub mod user {
use crate::database::models::{User, UserRole};
use actix_macros::ResponderJson;
use actix_macros::{OkResponse, ResponderJson};
use serde::Serialize;
//noinspection SpellCheckingInspection
/// Используется для скрытия чувствительных полей, таких как хеш пароля или FCM
#[derive(Serialize, utoipa::ToSchema, ResponderJson)]
#[derive(Serialize, utoipa::ToSchema, ResponderJson, OkResponse)]
#[serde(rename_all = "camelCase")]
pub struct UserResponse {
/// UUID
#[schema(examples("67dcc9a9507b0000772744a2"))]
id: String,
pub id: String,
/// Имя пользователя
#[schema(examples("n08i40k"))]
username: String,
pub username: String,
/// Группа
#[schema(examples("ИС-214/23"))]
group: String,
pub group: Option<String>,
/// Роль
role: UserRole,
pub role: UserRole,
/// Идентификатор привязанного аккаунта VK
#[schema(examples(498094647, json!(null)))]
vk_id: Option<i32>,
pub vk_id: Option<i32>,
/// Идентификатор привязанного аккаунта Telegram
#[schema(examples(996004735, json!(null)))]
pub telegram_id: Option<i64>,
/// JWT токен доступа
#[schema(examples(
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjY3ZGNjOWE5NTA3YjAwMDA3NzI3NDRhMiIsImlhdCI6IjE3NDMxMDgwOTkiLCJleHAiOiIxODY5MjUyMDk5In0.rMgXRb3JbT9AvLK4eiY9HMB5LxgUudkpQyoWKOypZFY"
))]
access_token: String,
pub access_token: Option<String>,
}
/// Create UserResponse from User ref.
@@ -153,6 +174,7 @@ pub mod user {
group: user.group.clone(),
role: user.role.clone(),
vk_id: user.vk_id.clone(),
telegram_id: user.telegram_id.clone(),
access_token: user.access_token.clone(),
}
}
@@ -167,6 +189,7 @@ pub mod user {
group: user.group,
role: user.role,
vk_id: user.vk_id,
telegram_id: user.telegram_id,
access_token: user.access_token,
}
}