chore(clippy): fix all clippy warnings

This commit is contained in:
2025-09-06 21:24:52 +04:00
parent edea6c5424
commit 35f707901f
25 changed files with 126 additions and 167 deletions

View File

@@ -11,7 +11,6 @@ use database::query::Query;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::ops::Deref;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Display, MiddlewareError)]
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]

View File

@@ -5,7 +5,6 @@ use std::future::{Ready, ready};
use std::ops;
/// # Async extractor.
/// Asynchronous object extractor from a query.
pub struct AsyncExtractor<T>(T);
@@ -80,7 +79,6 @@ impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
}
/// # Sync extractor.
/// Synchronous object extractor from a query.
pub struct SyncExtractor<T>(T);

View File

@@ -1,25 +1,20 @@
use crate::extractors::authorized_user;
use crate::extractors::base::FromRequestAsync;
use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::dev::{forward_ready, Payload, Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::{Error, HttpRequest, ResponseError};
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
use std::rc::Rc;
use database::entity::User;
use futures_util::future::LocalBoxFuture;
use std::future::{ready, Ready};
use std::rc::Rc;
/// Middleware guard working with JWT tokens.
#[derive(Default)]
pub struct JWTAuthorization {
/// List of ignored endpoints.
pub ignore: &'static [&'static str],
}
impl Default for JWTAuthorization {
fn default() -> Self {
Self { ignore: &[] }
}
}
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
@@ -70,8 +65,8 @@ where
return false;
}
if let Some(other) = path.as_bytes().iter().nth(ignore.len()) {
return ['?' as u8, '/' as u8].contains(other);
if let Some(other) = path.as_bytes().get(ignore.len()) {
return [b'?', b'/'].contains(other);
}
true

View File

@@ -1,10 +1,10 @@
use actix_web::Error;
use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::header;
use actix_web::http::header::HeaderValue;
use actix_web::Error;
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
use std::future::{ready, Ready};
/// Middleware to specify the encoding in the Content-Type header.
pub struct ContentTypeBootstrap;
@@ -30,7 +30,7 @@ pub struct ContentTypeMiddleware<S> {
service: S,
}
impl<'a, S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
impl<S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
@@ -49,13 +49,14 @@ where
let mut response = fut.await?;
let headers = response.response_mut().headers_mut();
if let Some(content_type) = headers.get("Content-Type") {
if content_type == "application/json" {
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf8"),
);
}
if let Some(content_type) = headers.get("Content-Type")
&& content_type == "application/json"
{
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf8"),
);
}
Ok(response.map_into_left_body())

View File

@@ -22,7 +22,7 @@ struct Claims {
#[derive(Debug, PartialEq)]
pub enum Error {
JwtError(ErrorKind),
Jwt(ErrorKind),
InvalidSignature,
InvalidToken,
Expired,
@@ -49,10 +49,10 @@ const VK_PUBLIC_KEY: &str = concat!(
"-----END PUBLIC KEY-----"
);
pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
pub fn parse_vk_id(token_str: &str, client_id: i32) -> Result<i32, Error> {
let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap();
match decode::<Claims>(&token_str, &dkey, &Validation::new(Algorithm::RS256)) {
match decode::<Claims>(token_str, &dkey, &Validation::new(Algorithm::RS256)) {
Ok(token_data) => {
let claims = token_data.claims;
@@ -77,7 +77,7 @@ pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
ErrorKind::Base64(_) => Error::InvalidToken,
ErrorKind::Json(_) => Error::InvalidToken,
ErrorKind::Utf8(_) => Error::InvalidToken,
kind => Error::JwtError(kind),
kind => Error::Jwt(kind),
}),
}
}

View File

@@ -28,7 +28,7 @@ async fn sign_in_combined(
return Err(ErrorCode::IncorrectCredentials);
}
match bcrypt::verify(&data.password, &user.password.as_ref().unwrap()) {
match bcrypt::verify(&data.password, user.password.as_ref().unwrap()) {
Ok(result) => {
if !result {
return Err(ErrorCode::IncorrectCredentials);
@@ -124,8 +124,6 @@ mod schema {
InvalidVkAccessToken,
}
/// Internal
/// Type of authorization.
pub enum SignInData {
/// User and password name and password.

View File

@@ -8,7 +8,6 @@ use database::entity::sea_orm_active_enums::UserRole;
use database::entity::ActiveUser;
use database::query::Query;
use database::sea_orm::ActiveModelTrait;
use std::ops::Deref;
use web::Json;
async fn sign_up_combined(
@@ -42,13 +41,12 @@ async fn sign_up_combined(
}
// If user with specified VKID already exists.
if let Some(id) = data.vk_id {
if Query::find_user_by_vk_id(db, id)
if let Some(id) = data.vk_id
&& Query::is_user_exists_by_vk_id(db, id)
.await
.is_ok_and(|user| user.is_some())
{
return Err(ErrorCode::VkAlreadyExists);
}
.expect("Failed to check user existence")
{
return Err(ErrorCode::VkAlreadyExists);
}
let active_user: ActiveUser = data.into();
@@ -202,8 +200,6 @@ mod schema {
VkAlreadyExists,
}
/// Internal
/// Data for registration.
pub struct SignUpData {
// TODO: сделать ограничение на минимальную и максимальную длину при регистрации и смене.
@@ -228,21 +224,21 @@ mod schema {
pub version: String,
}
impl Into<ActiveUser> for SignUpData {
fn into(self) -> ActiveUser {
assert_ne!(self.password.is_some(), self.vk_id.is_some());
impl From<SignUpData> for ActiveUser {
fn from(value: SignUpData) -> Self {
assert_ne!(value.password.is_some(), value.vk_id.is_some());
ActiveUser {
id: Set(ObjectId::new().unwrap().to_string()),
username: Set(self.username),
password: Set(self
username: Set(value.username),
password: Set(value
.password
.map(|x| bcrypt::hash(x, bcrypt::DEFAULT_COST).unwrap())),
vk_id: Set(self.vk_id),
vk_id: Set(value.vk_id),
telegram_id: Set(None),
group: Set(Some(self.group)),
role: Set(self.role),
android_version: Set(Some(self.version)),
group: Set(Some(value.group)),
role: Set(value.role),
android_version: Set(Some(value.version)),
}
}
}
@@ -262,7 +258,6 @@ mod tests {
use database::entity::{UserColumn, UserEntity};
use database::sea_orm::ColumnTrait;
use database::sea_orm::{EntityTrait, QueryFilter};
use std::ops::Deref;
struct SignUpPartial<'a> {
username: &'a str,

View File

@@ -9,7 +9,6 @@ use database::entity::ActiveUser;
use database::query::Query;
use database::sea_orm::{ActiveModelTrait, Set};
use objectid::ObjectId;
use std::ops::Deref;
use std::sync::Arc;
use web::Json;
@@ -122,7 +121,7 @@ mod schema {
&mut self,
request: &HttpRequest,
response: &mut HttpResponse<EitherBody<String>>,
) -> () {
) {
let access_token = &self.access_token;
let app_state = request.app_data::<web::Data<AppState>>().unwrap();

View File

@@ -6,7 +6,6 @@ use actix_web::{post, web};
use database::entity::User;
use database::query::Query;
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
use std::ops::Deref;
use web::Json;
#[utoipa::path(responses(

View File

@@ -1,11 +1,17 @@
use crate::AppState;
use crate::routes::schedule::schema::CacheStatus;
use crate::AppState;
use actix_web::{get, web};
use std::ops::Deref;
#[utoipa::path(responses(
(status = OK, body = CacheStatus),
))]
#[get("/cache-status")]
pub async fn cache_status(app_state: web::Data<AppState>) -> CacheStatus {
CacheStatus::from(&app_state).await.into()
app_state
.get_schedule_snapshot("eng_polytechnic")
.await
.unwrap()
.deref()
.into()
}

View File

@@ -1,7 +1,7 @@
mod cache_status;
mod group;
mod group_names;
mod schedule;
mod get;
mod schema;
mod teacher;
mod teacher_names;
@@ -9,6 +9,6 @@ mod teacher_names;
pub use cache_status::*;
pub use group::*;
pub use group_names::*;
pub use schedule::*;
pub use get::*;
pub use teacher::*;
pub use teacher_names::*;

View File

@@ -63,18 +63,6 @@ pub struct CacheStatus {
pub updated_at: i64,
}
impl CacheStatus {
pub async fn from(value: &web::Data<AppState>) -> Self {
From::<&ScheduleSnapshot>::from(
value
.get_schedule_snapshot("eng_polytechnic")
.await
.unwrap()
.deref(),
)
}
}
impl From<&ScheduleSnapshot> for CacheStatus {
fn from(value: &ScheduleSnapshot) -> Self {
Self {

View File

@@ -13,13 +13,13 @@ where
E: Serialize + PartialSchema + Display + PartialErrResponse;
/// Transform Response<T, E> into Result<T, E>
impl<T, E> Into<Result<T, E>> for Response<T, E>
impl<T, E> From<Response<T, E>> for Result<T, E>
where
T: Serialize + PartialSchema + PartialOkResponse,
E: Serialize + PartialSchema + Display + PartialErrResponse,
{
fn into(self) -> Result<T, E> {
self.0
fn from(value: Response<T, E>) -> Self {
value.0
}
}
@@ -46,7 +46,7 @@ where
{
match &self.0 {
Ok(ok) => serializer.serialize_some(&ok),
Err(err) => serializer.serialize_some(&ResponseError::<E>::from(err.clone().into())),
Err(err) => serializer.serialize_some(&err.clone().into()),
}
}
}
@@ -95,7 +95,7 @@ pub trait PartialOkResponse {
&mut self,
_request: &HttpRequest,
_response: &mut HttpResponse<EitherBody<String>>,
) -> () {
) {
}
}
@@ -173,8 +173,8 @@ pub mod user {
username: user.username.clone(),
group: user.group.clone(),
role: user.role.clone(),
vk_id: user.vk_id.clone(),
telegram_id: user.telegram_id.clone(),
vk_id: user.vk_id,
telegram_id: user.telegram_id,
access_token: Some(access_token),
}
}
@@ -188,8 +188,8 @@ pub mod user {
username: user.username.clone(),
group: user.group.clone(),
role: user.role.clone(),
vk_id: user.vk_id.clone(),
telegram_id: user.telegram_id.clone(),
vk_id: user.vk_id,
telegram_id: user.telegram_id,
access_token: None,
}
}

View File

@@ -4,7 +4,6 @@ use crate::state::AppState;
use actix_web::{post, web};
use database::entity::User;
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
use std::ops::Deref;
#[utoipa::path(responses((status = OK)))]
#[post("/change-group")]

View File

@@ -5,7 +5,6 @@ use actix_web::{post, web};
use database::entity::User;
use database::query::Query;
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
use std::ops::Deref;
#[utoipa::path(responses((status = OK)))]
#[post("/change-username")]

View File

@@ -23,7 +23,7 @@ impl AppState {
let env = AppEnv::default();
let providers: HashMap<String, Arc<dyn ScheduleProvider>> = HashMap::from([(
"eng_polytechnic".to_string(),
providers::EngelsPolytechnicProvider::new({
providers::EngelsPolytechnicProvider::get({
#[cfg(test)]
{
providers::EngelsPolytechnicUpdateSource::Prepared(ScheduleSnapshot {
@@ -64,7 +64,7 @@ impl AppState {
};
if this.env.schedule.auto_update {
for (_, provider) in &this.providers {
for provider in this.providers.values() {
let provider = provider.clone();
let cancel_token = this.cancel_token.clone();
@@ -93,6 +93,8 @@ impl AppState {
}
/// Create a new object web::Data<AppState>.
pub async fn new_app_state(database: Option<DatabaseConnection>) -> Result<web::Data<AppState>, Box<dyn std::error::Error>> {
pub async fn new_app_state(
database: Option<DatabaseConnection>,
) -> Result<web::Data<AppState>, Box<dyn std::error::Error>> {
Ok(web::Data::new(AppState::new(database).await?))
}

View File

@@ -63,13 +63,13 @@ struct Claims {
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
/// Checking the token and extracting the UUID of the user account from it.
pub fn verify_and_decode(token: &String) -> Result<String, Error> {
pub fn verify_and_decode(token: &str) -> Result<String, Error> {
let mut validation = Validation::new(DEFAULT_ALGORITHM);
validation.required_spec_claims.remove("exp");
validation.validate_exp = false;
let result = decode::<Claims>(&token, &*DECODING_KEY, &validation);
let result = decode::<Claims>(token, &DECODING_KEY, &validation);
match result {
Ok(token_data) => {
@@ -88,7 +88,7 @@ pub fn verify_and_decode(token: &String) -> Result<String, Error> {
}
/// Creating a user token.
pub fn encode(id: &String) -> String {
pub fn encode(id: &str) -> String {
let header = Header {
typ: Some(String::from("JWT")),
..Default::default()
@@ -98,12 +98,12 @@ pub fn encode(id: &String) -> String {
let exp = iat + Duration::days(365 * 4);
let claims = Claims {
id: id.clone(),
id: id.to_string(),
iat: iat.timestamp().unsigned_abs(),
exp: exp.timestamp().unsigned_abs(),
};
jsonwebtoken::encode(&header, &claims, &*ENCODING_KEY).unwrap()
jsonwebtoken::encode(&header, &claims, &ENCODING_KEY).unwrap()
}
#[cfg(test)]

View File

@@ -33,7 +33,7 @@ impl WebAppInitDataMap {
};
data.split('&')
.map(|kv| kv.split_once('=').unwrap_or_else(|| (kv, "")))
.map(|kv| kv.split_once('=').unwrap_or((kv, "")))
.for_each(|(key, value)| {
this.data_map.insert(key.to_string(), value.to_string());
});