fmt
Some checks failed
Deploy / deploy (push) Has been skipped
CI / lint (push) Failing after 7m37s
CI / test (push) Has been cancelled

This commit is contained in:
2025-09-01 22:58:03 +03:00
parent d6b286f478
commit 112f102bb5
14 changed files with 444 additions and 316 deletions

View File

@@ -1,12 +1,12 @@
use actix_web::error::ErrorInternalServerError;
use redis::{aio::MultiplexedConnection, AsyncCommands};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, env, error::Error};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use log::{info, warn};
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use redis::{AsyncCommands, aio::MultiplexedConnection};
use reqwest::Client as HTTPClient;
use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{collections::HashMap, env, error::Error};
// Старые структуры для совместимости с get_id_by_token
#[derive(Deserialize)]
@@ -106,30 +106,33 @@ fn decode_jwt_token(token: &str) -> Result<TokenClaims, Box<dyn Error>> {
// В реальном приложении здесь должен быть настоящий секретный ключ
let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "your-secret-key".to_string());
let key = DecodingKey::from_secret(secret.as_ref());
let mut validation = Validation::new(Algorithm::HS256);
validation.validate_exp = true; // Включаем проверку истечения срока действия
match decode::<TokenClaims>(token, &key, &validation) {
Ok(token_data) => {
let claims = token_data.claims;
// Дополнительная проверка exp если поле присутствует
if let Some(exp) = claims.exp {
let current_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as usize;
if exp < current_time {
warn!("JWT token expired: exp={}, current={}", exp, current_time);
return Err(Box::new(std::io::Error::other("Token expired")));
}
info!("JWT token valid until: {} (current: {})", exp, current_time);
}
info!("Successfully decoded and validated JWT token for user: {}", claims.user_id);
info!(
"Successfully decoded and validated JWT token for user: {}",
claims.user_id
);
Ok(claims)
}
Err(e) => {
@@ -164,9 +167,9 @@ pub async fn get_user_by_token(
// Декодируем JWT токен для получения user_id
let claims = decode_jwt_token(token)?;
let user_id = &claims.user_id;
info!("Extracted user_id from JWT token: {}", user_id);
// Проверяем валидность токена через сессию в Redis (опционально)
let token_key = format!("session:{}:{}", user_id, token);
let session_exists: bool = redis
@@ -177,14 +180,14 @@ pub async fn get_user_by_token(
// Не критичная ошибка, продолжаем с базовыми данными
})
.unwrap_or(false);
if session_exists {
// Обновляем last_activity если сессия существует
let current_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let _: () = redis
.hset(&token_key, "last_activity", current_time.to_string())
.await
@@ -192,12 +195,12 @@ pub async fn get_user_by_token(
warn!("Failed to update last_activity: {}", e);
})
.unwrap_or(());
info!("Updated last_activity for session: {}", token_key);
} else {
info!("Session not found in Redis, proceeding with JWT-only data");
}
// Создаем базовый объект Author с данными из JWT
let author = Author {
user_id: user_id.clone(),
@@ -209,12 +212,12 @@ pub async fn get_user_by_token(
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string()
.to_string(),
),
auth_data: None,
device_info: None,
};
info!("Successfully created author data for user_id: {}", user_id);
Ok(author)
}