Реформат путей к эндпоинтам.

Добавлен экстрактор пользователя с дополнительными полями.

Добавлена связь таблиц User и FCM.

Завершена реализация авторизации с помощью VK ID.

Добавлен эндпоинт fcm/update-callback/{version}.
This commit is contained in:
2025-04-14 22:04:41 +04:00
parent 680419ea78
commit 5b6f5c830f
27 changed files with 406 additions and 106 deletions

View File

@@ -1,3 +1,8 @@
pub mod sign_in;
pub mod sign_up;
mod sign_in;
mod sign_up;
mod shared;
pub use sign_in::*;
pub use sign_up::*;
// TODO: change-password

View File

@@ -11,7 +11,7 @@ use diesel::SaveChangesDsl;
use std::ops::DerefMut;
use web::Json;
async fn sign_in(
async fn sign_in_combined(
data: SignInData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
@@ -55,8 +55,8 @@ async fn sign_in(
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-in")]
pub async fn sign_in_default(data: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
sign_in(Default(data.into_inner()), &app_state).await.into()
pub async fn sign_in(data: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
sign_in_combined(Default(data.into_inner()), &app_state).await.into()
}
#[utoipa::path(responses(
@@ -68,7 +68,7 @@ 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.into(),
Ok(id) => sign_in_combined(Vk(id), &app_state).await.into(),
Err(_) => ErrorCode::InvalidVkAccessToken.into_response(),
}
}
@@ -134,7 +134,7 @@ mod tests {
use super::schema::*;
use crate::database::driver;
use crate::database::models::{User, UserRole};
use crate::routes::auth::sign_in::sign_in_default;
use crate::routes::auth::sign_in::sign_in;
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
use crate::utility;
use actix_test::test_app;
@@ -146,7 +146,7 @@ mod tests {
use std::fmt::Write;
async fn sign_in_client(data: Request) -> ServiceResponse {
let app = test_app(test_app_state(), sign_in_default).await;
let app = test_app(test_app_state(), sign_in).await;
let req = test::TestRequest::with_uri("/sign-in")
.method(Method::POST)

View File

@@ -9,7 +9,7 @@ use actix_web::{post, web};
use rand::{Rng, rng};
use web::Json;
async fn sign_up(
async fn sign_up_combined(
data: SignUpData,
app_state: &web::Data<AppState>,
) -> Result<UserResponse, ErrorCode> {
@@ -50,13 +50,13 @@ async fn sign_up(
(status = NOT_ACCEPTABLE, body = ResponseError<ErrorCode>)
))]
#[post("/sign-up")]
pub async fn sign_up_default(
pub async fn sign_up(
data_json: Json<Request>,
app_state: web::Data<AppState>,
) -> ServiceResponse {
let data = data_json.into_inner();
sign_up(
sign_up_combined(
SignUpData {
username: data.username,
password: data.password,
@@ -83,7 +83,7 @@ pub async fn sign_up_vk(
let data = data_json.into_inner();
match parse_vk_id(&data.access_token) {
Ok(id) => sign_up(
Ok(id) => sign_up_combined(
SignUpData {
username: data.username,
password: rng()
@@ -243,7 +243,7 @@ mod tests {
use crate::database::driver;
use crate::database::models::UserRole;
use crate::routes::auth::sign_up::schema::Request;
use crate::routes::auth::sign_up::sign_up_default;
use crate::routes::auth::sign_up::sign_up;
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
use actix_test::test_app;
use actix_web::dev::ServiceResponse;
@@ -258,7 +258,7 @@ mod tests {
}
async fn sign_up_client(data: SignUpPartial) -> ServiceResponse {
let app = test_app(test_app_state(), sign_up_default).await;
let app = test_app(test_app_state(), sign_up).await;
let req = test::TestRequest::with_uri("/sign-up")
.method(Method::POST)

3
src/routes/fcm/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod update_callback;
pub use update_callback::*;

View File

@@ -0,0 +1,28 @@
use crate::app_state::AppState;
use crate::database::models::User;
use crate::extractors::base::SyncExtractor;
use actix_web::{HttpResponse, Responder, post, web};
use diesel::SaveChangesDsl;
#[utoipa::path(responses(
(status = OK),
(status = INTERNAL_SERVER_ERROR)
))]
#[post("/update-callback/{version}")]
async fn update_callback(
app_state: web::Data<AppState>,
version: web::Path<String>,
user: SyncExtractor<User>,
) -> impl Responder {
let mut user = user.into_inner();
user.version = version.into_inner();
match app_state.lock_connection(|con| user.save_changes::<User>(con)) {
Ok(_) => HttpResponse::Ok(),
Err(e) => {
eprintln!("Failed to update user: {}", e);
HttpResponse::InternalServerError()
}
}
}

View File

@@ -1,4 +1,6 @@
pub mod auth;
pub mod users;
pub mod fcm;
pub mod schedule;
mod schema;
pub mod users;
pub mod vk_id;

View File

@@ -6,7 +6,7 @@ use actix_web::{get, web};
(status = OK, body = CacheStatus),
))]
#[get("/cache-status")]
pub async fn get_cache_status(app_state: web::Data<AppState>) -> CacheStatus {
pub async fn cache_status(app_state: web::Data<AppState>) -> CacheStatus {
// Prevent thread lock
let has_schedule = app_state
.schedule

View File

@@ -25,7 +25,7 @@ use actix_web::{get, web};
),
))]
#[get("/group")]
pub async fn get_group(
pub async fn group(
user: SyncExtractor<User>,
app_state: web::Data<AppState>,
) -> ServiceResponse {

View File

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>),
))]
#[get("/group-names")]
pub async fn get_group_names(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn group_names(app_state: web::Data<AppState>) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();

View File

@@ -1,8 +1,16 @@
pub mod get_cache_status;
pub mod get_schedule;
pub mod get_group;
pub mod get_group_names;
pub mod get_teacher;
pub mod get_teacher_names;
mod cache_status;
mod group;
mod group_names;
mod schedule;
mod teacher;
mod teacher_names;
mod schema;
pub mod update_download_url;
mod update_download_url;
pub use cache_status::*;
pub use group::*;
pub use group_names::*;
pub use schedule::*;
pub use teacher::*;
pub use teacher_names::*;
pub use update_download_url::*;

View File

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>)
))]
#[get("/")]
pub async fn get_schedule(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn schedule(app_state: web::Data<AppState>) -> ServiceResponse {
match ScheduleView::try_from(&app_state) {
Ok(res) => Ok(res).into(),
Err(e) => match e {

View File

@@ -23,7 +23,7 @@ use actix_web::{get, web};
),
))]
#[get("/teacher/{name}")]
pub async fn get_teacher(
pub async fn teacher(
name: web::Path<String>,
app_state: web::Data<AppState>,
) -> ServiceResponse {

View File

@@ -9,7 +9,7 @@ use actix_web::{get, web};
(status = SERVICE_UNAVAILABLE, body = ResponseError<ErrorCode>),
))]
#[get("/teacher-names")]
pub async fn get_teacher_names(app_state: web::Data<AppState>) -> ServiceResponse {
pub async fn teacher_names(app_state: web::Data<AppState>) -> ServiceResponse {
// Prevent thread lock
let schedule_lock = app_state.schedule.lock().unwrap();

View File

@@ -1 +1,6 @@
pub mod me;
mod me;
pub use me::*;
// TODO: change-username
// TODO: change-group

3
src/routes/vk_id/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod oauth;
pub use oauth::*;

114
src/routes/vk_id/oauth.rs Normal file
View File

@@ -0,0 +1,114 @@
use self::schema::*;
use crate::app_state::AppState;
use crate::routes::schema::{IntoResponseAsError, ResponseError};
use actix_web::{post, web};
use serde::Deserialize;
use std::collections::HashMap;
use uuid::Uuid;
#[allow(dead_code)]
#[derive(Deserialize)]
struct VkIdAuthResponse {
refresh_token: String,
access_token: String,
id_token: String,
token_type: String,
expires_in: i32,
user_id: i32,
state: String,
scope: String,
}
#[utoipa::path(responses(
(status = OK, body = Response),
(
status = NOT_ACCEPTABLE,
body = ResponseError<ErrorCode>,
example = json!({
"code": "VK_ID_ERROR",
"message": "VK server returned an error"
})
),
))]
#[post("/oauth")]
async fn oauth(data: web::Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
let data = data.into_inner();
let state = Uuid::new_v4().simple().to_string();
let vk_id = &app_state.vk_id;
let client_id = vk_id.client_id.clone().to_string();
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("client_id", client_id.as_str());
params.insert("state", state.as_str());
params.insert("code_verifier", data.code_verifier.as_str());
params.insert("code", data.code.as_str());
params.insert("device_id", data.device_id.as_str());
params.insert("redirect_uri", vk_id.redirect_url.as_str());
let client = reqwest::Client::new();
match client
.post("https://id.vk.com/oauth2/auth")
.form(&params)
.send()
.await
{
Ok(res) => {
if !res.status().is_success() {
return ErrorCode::VkIdError.into_response();
}
if let Ok(auth_data) = res.json::<VkIdAuthResponse>().await {
Ok(Response {
access_token: auth_data.id_token,
})
.into()
} else {
ErrorCode::VkIdError.into_response()
}
}
Err(_) => ErrorCode::VkIdError.into_response(),
}
}
mod schema {
use actix_macros::{IntoResponseErrorNamed, StatusCode};
use derive_more::Display;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type ServiceResponse = crate::routes::schema::Response<Response, ErrorCode>;
#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Request)]
pub struct Request {
/// Код подтверждения authorization_code
pub code: String,
/// Параметр для защиты передаваемых данных
pub code_verifier: String,
/// Идентификатор устройства
pub device_id: String,
}
#[derive(Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[schema(as = VkIdOAuth::Response)]
pub struct Response {
/// ID токен
pub access_token: String,
}
#[derive(Clone, Serialize, ToSchema, IntoResponseErrorNamed, StatusCode, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[schema(as = VkIdOAuth::ErrorCode)]
#[status_code = "actix_web::http::StatusCode::NOT_ACCEPTABLE"]
pub enum ErrorCode {
/// Сервер VK вернул ошибку
#[display("VK server returned an error")]
VkIdError,
}
}