style: apply rustfmt to backend codebase
- Apply rustfmt to all Rust source files in backend/ - Fix trailing whitespace inconsistencies - Standardize formatting across handlers, models, and services - Improve code readability with consistent formatting These changes are purely stylistic and do not affect functionality. All CI checks now pass with proper formatting.
This commit is contained in:
parent
6b7e4d4016
commit
ee0feb77ef
41 changed files with 1266 additions and 819 deletions
|
|
@ -99,11 +99,7 @@ impl JwtService {
|
|||
|
||||
/// Validate access token
|
||||
pub fn validate_token(&self, token: &str) -> Result<Claims> {
|
||||
let token_data = decode::<Claims>(
|
||||
token,
|
||||
&self.decoding_key,
|
||||
&Validation::default()
|
||||
)
|
||||
let token_data = decode::<Claims>(token, &self.decoding_key, &Validation::default())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid token: {}", e))?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
|
|
@ -111,11 +107,7 @@ impl JwtService {
|
|||
|
||||
/// Validate refresh token
|
||||
pub fn validate_refresh_token(&self, token: &str) -> Result<RefreshClaims> {
|
||||
let token_data = decode::<RefreshClaims>(
|
||||
token,
|
||||
&self.decoding_key,
|
||||
&Validation::default()
|
||||
)
|
||||
let token_data = decode::<RefreshClaims>(token, &self.decoding_key, &Validation::default())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid refresh token: {}", e))?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
|
|
@ -124,7 +116,8 @@ impl JwtService {
|
|||
/// Store refresh token for a user
|
||||
pub async fn store_refresh_token(&self, user_id: &str, token: &str) -> Result<()> {
|
||||
let mut tokens = self.refresh_tokens.write().await;
|
||||
tokens.entry(user_id.to_string())
|
||||
tokens
|
||||
.entry(user_id.to_string())
|
||||
.or_insert_with(Vec::new)
|
||||
.push(token.to_string());
|
||||
|
||||
|
|
@ -151,7 +144,12 @@ impl JwtService {
|
|||
}
|
||||
|
||||
/// Rotate refresh token (remove old, add new)
|
||||
pub async fn rotate_refresh_token(&self, user_id: &str, old_token: &str, new_token: &str) -> Result<()> {
|
||||
pub async fn rotate_refresh_token(
|
||||
&self,
|
||||
user_id: &str,
|
||||
old_token: &str,
|
||||
new_token: &str,
|
||||
) -> Result<()> {
|
||||
// Remove old token
|
||||
self.revoke_refresh_token(old_token).await?;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,7 @@
|
|||
use anyhow::Result;
|
||||
use pbkdf2::{
|
||||
password_hash::{
|
||||
rand_core::OsRng,
|
||||
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
|
||||
},
|
||||
Pbkdf2
|
||||
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
Pbkdf2,
|
||||
};
|
||||
|
||||
pub struct PasswordService;
|
||||
|
|
@ -12,7 +9,8 @@ pub struct PasswordService;
|
|||
impl PasswordService {
|
||||
pub fn hash_password(password: &str) -> Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let password_hash = Pbkdf2.hash_password(password.as_bytes(), &salt)
|
||||
let password_hash = Pbkdf2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to hash password: {}", e))?;
|
||||
Ok(password_hash.to_string())
|
||||
}
|
||||
|
|
@ -21,7 +19,8 @@ impl PasswordService {
|
|||
let parsed_hash = PasswordHash::new(hash)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to parse password hash: {}", e))?;
|
||||
|
||||
Pbkdf2.verify_password(password.as_bytes(), &parsed_hash)
|
||||
Pbkdf2
|
||||
.verify_password(password.as_bytes(), &parsed_hash)
|
||||
.map(|_| true)
|
||||
.map_err(|e| anyhow::anyhow!("Password verification failed: {}", e))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use std::sync::Arc;
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
|
|
@ -74,8 +74,10 @@ impl Config {
|
|||
.parse()?,
|
||||
},
|
||||
database: DatabaseConfig {
|
||||
uri: std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string()),
|
||||
database: std::env::var("MONGODB_DATABASE").unwrap_or_else(|_| "normogen".to_string()),
|
||||
uri: std::env::var("MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://localhost:27017".to_string()),
|
||||
database: std::env::var("MONGODB_DATABASE")
|
||||
.unwrap_or_else(|_| "normogen".to_string()),
|
||||
},
|
||||
jwt: JwtConfig {
|
||||
secret: std::env::var("JWT_SECRET").unwrap_or_else(|_| "secret".to_string()),
|
||||
|
|
@ -87,7 +89,8 @@ impl Config {
|
|||
.parse()?,
|
||||
},
|
||||
encryption: EncryptionConfig {
|
||||
key: std::env::var("ENCRYPTION_KEY").unwrap_or_else(|_| "default_key_32_bytes_long!".to_string()),
|
||||
key: std::env::var("ENCRYPTION_KEY")
|
||||
.unwrap_or_else(|_| "default_key_32_bytes_long!".to_string()),
|
||||
},
|
||||
cors: CorsConfig {
|
||||
allowed_origins: std::env::var("CORS_ALLOWED_ORIGINS")
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
use mongodb::{Client, Database, Collection, bson::doc, options::ClientOptions};
|
||||
use anyhow::Result;
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use mongodb::{bson::doc, options::ClientOptions, Client, Collection, Database};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::models::{
|
||||
user::{User, UserRepository},
|
||||
share::{Share, ShareRepository},
|
||||
medication::{Medication, MedicationDose, MedicationRepository, UpdateMedicationRequest},
|
||||
permission::Permission,
|
||||
medication::{Medication, MedicationRepository, MedicationDose, UpdateMedicationRequest},
|
||||
share::{Share, ShareRepository},
|
||||
user::{User, UserRepository},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -33,17 +33,25 @@ impl MongoDb {
|
|||
eprintln!("[MongoDB] ERROR: Failed to parse URI: {}", e);
|
||||
|
||||
let error_msg = e.to_string().to_lowercase();
|
||||
if error_msg.contains("dns") || error_msg.contains("resolution") || error_msg.contains("lookup") {
|
||||
if error_msg.contains("dns")
|
||||
|| error_msg.contains("resolution")
|
||||
|| error_msg.contains("lookup")
|
||||
{
|
||||
eprintln!("[MongoDB] DNS RESOLUTION ERROR DETECTED!");
|
||||
eprintln!("[MongoDB] Cannot resolve hostname in: {}", uri);
|
||||
eprintln!("[MongoDB] Error: {}", e);
|
||||
}
|
||||
eprintln!("[MongoDB] Will continue in degraded mode (database operations will fail)");
|
||||
eprintln!(
|
||||
"[MongoDB] Will continue in degraded mode (database operations will fail)"
|
||||
);
|
||||
|
||||
// Create a minimal configuration that will allow the server to start
|
||||
// but database operations will fail gracefully
|
||||
let mut opts = ClientOptions::parse("mongodb://localhost:27017").await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create fallback client options: {}", e))?;
|
||||
let mut opts = ClientOptions::parse("mongodb://localhost:27017")
|
||||
.await
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("Failed to create fallback client options: {}", e)
|
||||
})?;
|
||||
opts.server_selection_timeout = Some(Duration::from_secs(1));
|
||||
opts.connect_timeout = Some(Duration::from_secs(1));
|
||||
|
||||
|
|
@ -78,8 +86,11 @@ impl MongoDb {
|
|||
eprintln!("[MongoDB] Will continue in degraded mode");
|
||||
|
||||
// Create a fallback client
|
||||
let fallback_opts = ClientOptions::parse("mongodb://localhost:27017").await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create fallback client options: {}", e))?;
|
||||
let fallback_opts = ClientOptions::parse("mongodb://localhost:27017")
|
||||
.await
|
||||
.map_err(|e| {
|
||||
anyhow::anyhow!("Failed to create fallback client options: {}", e)
|
||||
})?;
|
||||
let fallback_client = Client::with_options(fallback_opts)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create MongoDB client: {}", e))?;
|
||||
let database = fallback_client.database(db_name);
|
||||
|
|
@ -249,7 +260,10 @@ impl MongoDb {
|
|||
let resource_types = ["profiles", "health_data", "lab_results", "medications"];
|
||||
|
||||
for resource_type in resource_types {
|
||||
if self.check_user_permission(user_id, resource_type, resource_id, permission).await? {
|
||||
if self
|
||||
.check_user_permission(user_id, resource_type, resource_id, permission)
|
||||
.await?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -261,7 +275,8 @@ impl MongoDb {
|
|||
|
||||
pub async fn create_medication(&self, medication: &Medication) -> Result<Option<ObjectId>> {
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
let created = repo.create(medication.clone())
|
||||
let created = repo
|
||||
.create(medication.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create medication: {}", e))?;
|
||||
Ok(created.id)
|
||||
|
|
@ -270,28 +285,40 @@ impl MongoDb {
|
|||
pub async fn get_medication(&self, id: &str) -> Result<Option<Medication>> {
|
||||
let object_id = ObjectId::parse_str(id)?;
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
Ok(repo.find_by_id(&object_id)
|
||||
Ok(repo
|
||||
.find_by_id(&object_id)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to get medication: {}", e))?)
|
||||
}
|
||||
|
||||
pub async fn list_medications(&self, user_id: &str, profile_id: Option<&str>) -> Result<Vec<Medication>> {
|
||||
pub async fn list_medications(
|
||||
&self,
|
||||
user_id: &str,
|
||||
profile_id: Option<&str>,
|
||||
) -> Result<Vec<Medication>> {
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
if let Some(profile_id) = profile_id {
|
||||
Ok(repo.find_by_user_and_profile(user_id, profile_id)
|
||||
Ok(repo
|
||||
.find_by_user_and_profile(user_id, profile_id)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to list medications by profile: {}", e))?)
|
||||
} else {
|
||||
Ok(repo.find_by_user(user_id)
|
||||
Ok(repo
|
||||
.find_by_user(user_id)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to list medications: {}", e))?)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_medication(&self, id: &str, updates: UpdateMedicationRequest) -> Result<Option<Medication>> {
|
||||
pub async fn update_medication(
|
||||
&self,
|
||||
id: &str,
|
||||
updates: UpdateMedicationRequest,
|
||||
) -> Result<Option<Medication>> {
|
||||
let object_id = ObjectId::parse_str(id)?;
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
Ok(repo.update(&object_id, updates)
|
||||
Ok(repo
|
||||
.update(&object_id, updates)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to update medication: {}", e))?)
|
||||
}
|
||||
|
|
@ -299,22 +326,30 @@ impl MongoDb {
|
|||
pub async fn delete_medication(&self, id: &str) -> Result<bool> {
|
||||
let object_id = ObjectId::parse_str(id)?;
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
Ok(repo.delete(&object_id)
|
||||
Ok(repo
|
||||
.delete(&object_id)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to delete medication: {}", e))?)
|
||||
}
|
||||
|
||||
pub async fn log_medication_dose(&self, dose: &MedicationDose) -> Result<Option<ObjectId>> {
|
||||
// Insert the dose into the medication_doses collection
|
||||
let result = self.medication_doses.insert_one(dose.clone(), None)
|
||||
let result = self
|
||||
.medication_doses
|
||||
.insert_one(dose.clone(), None)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to log dose: {}", e))?;
|
||||
Ok(result.inserted_id.as_object_id())
|
||||
}
|
||||
|
||||
pub async fn get_medication_adherence(&self, medication_id: &str, days: i64) -> Result<crate::models::medication::AdherenceStats> {
|
||||
pub async fn get_medication_adherence(
|
||||
&self,
|
||||
medication_id: &str,
|
||||
days: i64,
|
||||
) -> Result<crate::models::medication::AdherenceStats> {
|
||||
let repo = MedicationRepository::new(self.medications.clone());
|
||||
Ok(repo.calculate_adherence(medication_id, days)
|
||||
Ok(repo
|
||||
.calculate_adherence(medication_id, days)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to calculate adherence: {}", e))?)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,9 @@
|
|||
use axum::{
|
||||
extract::{State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
|
||||
use crate::{
|
||||
auth::jwt::Claims,
|
||||
config::AppState,
|
||||
models::user::User,
|
||||
models::audit_log::AuditEventType,
|
||||
auth::jwt::Claims, config::AppState, models::audit_log::AuditEventType, models::user::User,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Validate)]
|
||||
|
|
@ -39,25 +31,37 @@ pub async fn register(
|
|||
Json(req): Json<RegisterRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
match state.db.find_user_by_email(&req.email).await {
|
||||
Ok(Some(_)) => {
|
||||
return (StatusCode::CONFLICT, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::CONFLICT,
|
||||
Json(serde_json::json!({
|
||||
"error": "user already exists"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Ok(None) => {},
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to check user existence: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -71,9 +75,13 @@ pub async fn register(
|
|||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create user"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -85,27 +93,37 @@ pub async fn register(
|
|||
Ok(Some(id)) => {
|
||||
// Log registration (Phase 2.6)
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let _ = audit.log_event(
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::LoginSuccess, // Using LoginSuccess as registration event
|
||||
Some(id),
|
||||
Some(req.email.clone()),
|
||||
"0.0.0.0".to_string(),
|
||||
None,
|
||||
None,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
}
|
||||
id
|
||||
},
|
||||
}
|
||||
Ok(None) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create user"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to save user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -115,9 +133,13 @@ pub async fn register(
|
|||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to generate token: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to generate token"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -144,22 +166,30 @@ pub async fn login(
|
|||
Json(req): Json<LoginRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Check account lockout status (Phase 2.6)
|
||||
if let Some(ref lockout) = state.account_lockout {
|
||||
match lockout.check_lockout(&req.email).await {
|
||||
Ok(true) => {
|
||||
return (StatusCode::TOO_MANY_REQUESTS, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Json(serde_json::json!({
|
||||
"error": "account is temporarily locked due to too many failed attempts",
|
||||
"retry_after": "please try again later"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Ok(false) => {},
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to check lockout status: {}", e);
|
||||
}
|
||||
|
|
@ -177,33 +207,49 @@ pub async fn login(
|
|||
|
||||
// Log failed login (Phase 2.6)
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let _ = audit.log_event(
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::LoginFailed,
|
||||
None,
|
||||
Some(req.email.clone()),
|
||||
"0.0.0.0".to_string(), // TODO: Extract real IP
|
||||
None,
|
||||
None,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid credentials"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to find user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let user_id = user.id.ok_or_else(|| {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
let user_id = user
|
||||
.id
|
||||
.ok_or_else(|| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid user state"
|
||||
})))
|
||||
}).unwrap();
|
||||
})),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Verify password
|
||||
match user.verify_password(&req.password) {
|
||||
|
|
@ -212,7 +258,7 @@ pub async fn login(
|
|||
if let Some(ref lockout) = state.account_lockout {
|
||||
let _ = lockout.reset_attempts(&req.email).await;
|
||||
}
|
||||
},
|
||||
}
|
||||
Ok(false) => {
|
||||
// Record failed attempt (Phase 2.6)
|
||||
if let Some(ref lockout) = state.account_lockout {
|
||||
|
|
@ -221,25 +267,35 @@ pub async fn login(
|
|||
|
||||
// Log failed login (Phase 2.6)
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let _ = audit.log_event(
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::LoginFailed,
|
||||
Some(user_id),
|
||||
Some(req.email.clone()),
|
||||
"0.0.0.0".to_string(), // TODO: Extract real IP
|
||||
None,
|
||||
None,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid credentials"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to verify password: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "authentication error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -251,22 +307,28 @@ pub async fn login(
|
|||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to generate token: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to generate token"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Log successful login (Phase 2.6)
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let _ = audit.log_event(
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::LoginSuccess,
|
||||
Some(user_id),
|
||||
Some(req.email.clone()),
|
||||
"0.0.0.0".to_string(), // TODO: Extract real IP
|
||||
None,
|
||||
None,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let response = AuthResponse {
|
||||
|
|
@ -294,52 +356,76 @@ pub async fn recover_password(
|
|||
Json(req): Json<RecoverPasswordRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Find user by email
|
||||
let mut user = match state.db.find_user_by_email(&req.email).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid credentials"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to find user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Verify recovery phrase
|
||||
match user.verify_recovery_phrase(&req.recovery_phrase) {
|
||||
Ok(true) => {},
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid credentials"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to verify recovery phrase: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "authentication error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
// Update password
|
||||
match user.update_password(req.new_password) {
|
||||
Ok(_) => {},
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update password: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update password"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -349,23 +435,29 @@ pub async fn recover_password(
|
|||
// Log password recovery (Phase 2.6)
|
||||
if let Some(ref audit) = state.audit_logger {
|
||||
let user_id_for_log = user.id;
|
||||
let _ = audit.log_event(
|
||||
let _ = audit
|
||||
.log_event(
|
||||
AuditEventType::PasswordRecovery,
|
||||
user_id_for_log,
|
||||
Some(req.email.clone()),
|
||||
"0.0.0.0".to_string(),
|
||||
None,
|
||||
None,
|
||||
).await;
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
(StatusCode::NO_CONTENT, ()).into_response()
|
||||
},
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to save user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use crate::config::AppState;
|
||||
use axum::{extract::State, response::Json};
|
||||
use serde_json::{json, Value};
|
||||
use crate::config::AppState;
|
||||
|
||||
pub async fn health_check(State(state): State<AppState>) -> Json<Value> {
|
||||
let status = if let Ok(_) = state.db.health_check().await {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
use axum::{Extension, Json, extract::{Path, State, Query}, http::StatusCode, response::IntoResponse};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::Deserialize;
|
||||
use crate::models::health_stats::HealthStatistic;
|
||||
use crate::auth::jwt::Claims;
|
||||
use crate::config::AppState;
|
||||
use crate::models::health_stats::HealthStatistic;
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Extension, Json,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateHealthStatRequest {
|
||||
|
|
@ -41,7 +46,7 @@ pub async fn create_health_stat(
|
|||
// For complex objects like blood pressure, use a default
|
||||
0.0
|
||||
}
|
||||
_ => 0.0
|
||||
_ => 0.0,
|
||||
};
|
||||
|
||||
let stat = HealthStatistic {
|
||||
|
|
@ -61,7 +66,11 @@ pub async fn create_health_stat(
|
|||
Ok(created) => (StatusCode::CREATED, Json(created)).into_response(),
|
||||
Err(e) => {
|
||||
eprintln!("Error creating health stat: {:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to create health stat").into_response()
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to create health stat",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -75,7 +84,11 @@ pub async fn list_health_stats(
|
|||
Ok(stats) => (StatusCode::OK, Json(stats)).into_response(),
|
||||
Err(e) => {
|
||||
eprintln!("Error fetching health stats: {:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch health stats").into_response()
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to fetch health stats",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -101,7 +114,11 @@ pub async fn get_health_stat(
|
|||
Ok(None) => (StatusCode::NOT_FOUND, "Health stat not found").into_response(),
|
||||
Err(e) => {
|
||||
eprintln!("Error fetching health stat: {:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch health stat").into_response()
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to fetch health stat",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -121,7 +138,13 @@ pub async fn update_health_stat(
|
|||
let mut stat = match repo.find_by_id(&object_id).await {
|
||||
Ok(Some(s)) => s,
|
||||
Ok(None) => return (StatusCode::NOT_FOUND, "Health stat not found").into_response(),
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch health stat").into_response(),
|
||||
Err(_) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to fetch health stat",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
|
||||
if stat.user_id != claims.sub {
|
||||
|
|
@ -131,7 +154,7 @@ pub async fn update_health_stat(
|
|||
if let Some(value) = req.value {
|
||||
let value_num = match value {
|
||||
serde_json::Value::Number(n) => n.as_f64().unwrap_or(0.0),
|
||||
_ => 0.0
|
||||
_ => 0.0,
|
||||
};
|
||||
stat.value = value_num;
|
||||
}
|
||||
|
|
@ -145,7 +168,11 @@ pub async fn update_health_stat(
|
|||
match repo.update(&object_id, &stat).await {
|
||||
Ok(Some(updated)) => (StatusCode::OK, Json(updated)).into_response(),
|
||||
Ok(None) => (StatusCode::NOT_FOUND, "Failed to update").into_response(),
|
||||
Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Failed to update health stat").into_response(),
|
||||
Err(_) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to update health stat",
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -163,7 +190,13 @@ pub async fn delete_health_stat(
|
|||
let stat = match repo.find_by_id(&object_id).await {
|
||||
Ok(Some(s)) => s,
|
||||
Ok(None) => return (StatusCode::NOT_FOUND, "Health stat not found").into_response(),
|
||||
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch health stat").into_response(),
|
||||
Err(_) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to fetch health stat",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
};
|
||||
|
||||
if stat.user_id != claims.sub {
|
||||
|
|
@ -172,7 +205,11 @@ pub async fn delete_health_stat(
|
|||
|
||||
match repo.delete(&object_id).await {
|
||||
Ok(true) => StatusCode::NO_CONTENT.into_response(),
|
||||
_ => (StatusCode::INTERNAL_SERVER_ERROR, "Failed to delete health stat").into_response(),
|
||||
_ => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to delete health stat",
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -192,11 +229,15 @@ pub async fn get_health_trends(
|
|||
|
||||
// Calculate basic trend statistics
|
||||
if filtered.is_empty() {
|
||||
return (StatusCode::OK, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"stat_type": query.stat_type,
|
||||
"count": 0,
|
||||
"data": []
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let values: Vec<f64> = filtered.iter().map(|s| s.value).collect();
|
||||
|
|
@ -217,7 +258,11 @@ pub async fn get_health_trends(
|
|||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error fetching health trends: {:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Failed to fetch health trends").into_response()
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to fetch health trends",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,9 @@ pub async fn check_interactions(
|
|||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let interaction_service = state.interaction_service.as_ref()
|
||||
let interaction_service = state
|
||||
.interaction_service
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
|
||||
match interaction_service
|
||||
|
|
@ -76,7 +78,9 @@ pub async fn check_new_medication(
|
|||
State(state): State<AppState>,
|
||||
Json(request): Json<CheckNewMedicationRequest>,
|
||||
) -> Result<Json<InteractionResponse>, StatusCode> {
|
||||
let interaction_service = state.interaction_service.as_ref()
|
||||
let interaction_service = state
|
||||
.interaction_service
|
||||
.as_ref()
|
||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
|
||||
match interaction_service
|
||||
|
|
|
|||
|
|
@ -1,14 +1,17 @@
|
|||
use axum::{
|
||||
extract::{Path, Query, State, Extension, Json},
|
||||
extract::{Extension, Json, Path, Query, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use crate::{
|
||||
models::medication::{Medication, MedicationRepository, CreateMedicationRequest, UpdateMedicationRequest, LogDoseRequest},
|
||||
auth::jwt::Claims, // Fixed: import from auth::jwt instead of handlers::auth
|
||||
config::AppState,
|
||||
models::medication::{
|
||||
CreateMedicationRequest, LogDoseRequest, Medication, MedicationRepository,
|
||||
UpdateMedicationRequest,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
|
|
@ -59,12 +62,15 @@ pub async fn create_medication(
|
|||
user_id: claims.sub,
|
||||
profile_id: req.profile_id.clone(),
|
||||
medication_data,
|
||||
reminders: req.reminder_times.unwrap_or_default().into_iter().map(|time| {
|
||||
crate::models::medication::MedicationReminder {
|
||||
reminders: req
|
||||
.reminder_times
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|time| crate::models::medication::MedicationReminder {
|
||||
reminder_id: uuid::Uuid::new_v4().to_string(),
|
||||
scheduled_time: time,
|
||||
}
|
||||
}).collect(),
|
||||
})
|
||||
.collect(),
|
||||
created_at: now.into(),
|
||||
updated_at: now.into(),
|
||||
pill_identification: req.pill_identification, // Phase 2.8
|
||||
|
|
@ -86,10 +92,7 @@ pub async fn list_medications(
|
|||
|
||||
let _limit = query.limit.unwrap_or(100);
|
||||
|
||||
match repo
|
||||
.find_by_user(&claims.sub)
|
||||
.await
|
||||
{
|
||||
match repo.find_by_user(&claims.sub).await {
|
||||
Ok(medications) => Ok(Json(medications)),
|
||||
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
}
|
||||
|
|
@ -170,7 +173,11 @@ pub async fn log_dose(
|
|||
notes: req.notes,
|
||||
};
|
||||
|
||||
match database.collection("medication_doses").insert_one(dose.clone(), None).await {
|
||||
match database
|
||||
.collection("medication_doses")
|
||||
.insert_one(dose.clone(), None)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(StatusCode::CREATED),
|
||||
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,28 @@
|
|||
pub mod auth;
|
||||
pub mod health;
|
||||
pub mod health_stats;
|
||||
pub mod interactions;
|
||||
pub mod medications;
|
||||
pub mod permissions;
|
||||
pub mod sessions;
|
||||
pub mod shares;
|
||||
pub mod users;
|
||||
pub mod sessions;
|
||||
pub mod medications;
|
||||
pub mod interactions;
|
||||
|
||||
// Re-export commonly used handler functions
|
||||
pub use auth::{register, login, recover_password};
|
||||
pub use auth::{login, recover_password, register};
|
||||
pub use health::{health_check, ready_check};
|
||||
pub use shares::{create_share, list_shares, update_share, delete_share};
|
||||
pub use permissions::check_permission;
|
||||
pub use users::{get_profile, update_profile, delete_account, change_password, get_settings, update_settings};
|
||||
pub use sessions::{get_sessions, revoke_session, revoke_all_sessions};
|
||||
pub use medications::{create_medication, list_medications, get_medication, update_medication, delete_medication, log_dose, get_adherence};
|
||||
pub use health_stats::{create_health_stat, list_health_stats, get_health_stat, update_health_stat, delete_health_stat, get_health_trends};
|
||||
pub use health_stats::{
|
||||
create_health_stat, delete_health_stat, get_health_stat, get_health_trends, list_health_stats,
|
||||
update_health_stat,
|
||||
};
|
||||
pub use interactions::{check_interactions, check_new_medication};
|
||||
pub use medications::{
|
||||
create_medication, delete_medication, get_adherence, get_medication, list_medications,
|
||||
log_dose, update_medication,
|
||||
};
|
||||
pub use permissions::check_permission;
|
||||
pub use sessions::{get_sessions, revoke_all_sessions, revoke_session};
|
||||
pub use shares::{create_share, delete_share, list_shares, update_share};
|
||||
pub use users::{
|
||||
change_password, delete_account, get_profile, get_settings, update_profile, update_settings,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,15 +2,11 @@ use axum::{
|
|||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
Extension,
|
||||
Extension, Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
auth::jwt::Claims,
|
||||
config::AppState,
|
||||
};
|
||||
use crate::{auth::jwt::Claims, config::AppState};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CheckPermissionQuery {
|
||||
|
|
@ -32,18 +28,26 @@ pub async fn check_permission(
|
|||
Query(params): Query<CheckPermissionQuery>,
|
||||
Extension(claims): Extension<Claims>,
|
||||
) -> impl IntoResponse {
|
||||
let has_permission = match state.db.check_user_permission(
|
||||
let has_permission = match state
|
||||
.db
|
||||
.check_user_permission(
|
||||
&claims.sub,
|
||||
¶ms.resource_type,
|
||||
¶ms.resource_id,
|
||||
¶ms.permission,
|
||||
).await {
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to check permission: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to check permission"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
use axum::{extract::{Path, State, Extension}, http::StatusCode, Json};
|
||||
use crate::auth::jwt::Claims;
|
||||
use crate::config::AppState;
|
||||
use axum::{
|
||||
extract::{Extension, Path, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
|
|
|
|||
|
|
@ -2,17 +2,16 @@ use axum::{
|
|||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
Extension,
|
||||
Extension, Json,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
|
||||
use crate::{
|
||||
auth::jwt::Claims,
|
||||
config::AppState,
|
||||
models::{share::Share, permission::Permission},
|
||||
models::{permission::Permission, share::Share},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Validate)]
|
||||
|
|
@ -46,7 +45,11 @@ impl TryFrom<Share> for ShareResponse {
|
|||
target_user_id: share.target_user_id.to_string(),
|
||||
resource_type: share.resource_type,
|
||||
resource_id: share.resource_id.map(|id| id.to_string()),
|
||||
permissions: share.permissions.into_iter().map(|p| p.to_string()).collect(),
|
||||
permissions: share
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|p| p.to_string())
|
||||
.collect(),
|
||||
expires_at: share.expires_at.map(|dt| dt.timestamp_millis()),
|
||||
created_at: share.created_at.timestamp_millis(),
|
||||
active: share.active,
|
||||
|
|
@ -60,63 +63,86 @@ pub async fn create_share(
|
|||
Json(req): Json<CreateShareRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Find target user by email
|
||||
let target_user = match state.db.find_user_by_email(&req.target_user_email).await {
|
||||
Ok(Some(user)) => user,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "target user not found"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to find target user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let target_user_id = match target_user.id {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "target user has no ID"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let owner_id = match ObjectId::parse_str(&claims.sub) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid user ID format"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Parse resource_id if provided
|
||||
let resource_id = match req.resource_id {
|
||||
Some(id) => {
|
||||
match ObjectId::parse_str(&id) {
|
||||
Some(id) => match ObjectId::parse_str(&id) {
|
||||
Ok(oid) => Some(oid),
|
||||
Err(_) => {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid resource_id format"
|
||||
}))).into_response();
|
||||
}
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
// Parse permissions - support all permission types
|
||||
let permissions: Vec<Permission> = req.permissions
|
||||
let permissions: Vec<Permission> = req
|
||||
.permissions
|
||||
.into_iter()
|
||||
.filter_map(|p| match p.to_lowercase().as_str() {
|
||||
"read" => Some(Permission::Read),
|
||||
|
|
@ -153,18 +179,26 @@ pub async fn create_share(
|
|||
let response: ShareResponse = match share.try_into() {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create share response"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
(StatusCode::CREATED, Json(response)).into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to create share: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -185,39 +219,50 @@ pub async fn list_shares(
|
|||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to list shares: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to list shares"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_share(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
pub async fn get_share(State(state): State<AppState>, Path(id): Path<String>) -> impl IntoResponse {
|
||||
match state.db.get_share(&id).await {
|
||||
Ok(Some(share)) => {
|
||||
let response: ShareResponse = match share.try_into() {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create share response"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
(StatusCode::OK, Json(response)).into_response()
|
||||
}
|
||||
Ok(None) => {
|
||||
(StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
Ok(None) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "share not found"
|
||||
}))).into_response()
|
||||
}
|
||||
})),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get share: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to get share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -241,15 +286,23 @@ pub async fn update_share(
|
|||
let mut share = match state.db.get_share(&id).await {
|
||||
Ok(Some(s)) => s,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "share not found"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get share: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to get share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -257,16 +310,24 @@ pub async fn update_share(
|
|||
let owner_id = match ObjectId::parse_str(&claims.sub) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid user ID format"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
if share.owner_id != owner_id {
|
||||
return (StatusCode::FORBIDDEN, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(serde_json::json!({
|
||||
"error": "not authorized to modify this share"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Update fields
|
||||
|
|
@ -289,7 +350,9 @@ pub async fn update_share(
|
|||
}
|
||||
|
||||
if let Some(days) = req.expires_days {
|
||||
share.expires_at = Some(mongodb::bson::DateTime::now().saturating_add_millis(days as i64 * 24 * 60 * 60 * 1000));
|
||||
share.expires_at = Some(
|
||||
mongodb::bson::DateTime::now().saturating_add_millis(days as i64 * 24 * 60 * 60 * 1000),
|
||||
);
|
||||
}
|
||||
|
||||
match state.db.update_share(&share).await {
|
||||
|
|
@ -297,18 +360,26 @@ pub async fn update_share(
|
|||
let response: ShareResponse = match share.try_into() {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to create share response"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
(StatusCode::OK, Json(response)).into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update share: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -322,15 +393,23 @@ pub async fn delete_share(
|
|||
let share = match state.db.get_share(&id).await {
|
||||
Ok(Some(s)) => s,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "share not found"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get share: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to get share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -338,25 +417,37 @@ pub async fn delete_share(
|
|||
let owner_id = match ObjectId::parse_str(&claims.sub) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "invalid user ID format"
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
if share.owner_id != owner_id {
|
||||
return (StatusCode::FORBIDDEN, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(serde_json::json!({
|
||||
"error": "not authorized to delete this share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
match state.db.delete_share(&id).await {
|
||||
Ok(_) => (StatusCode::NO_CONTENT, ()).into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to delete share: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to delete share"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,19 +1,9 @@
|
|||
use axum::{
|
||||
extract::{State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
Extension,
|
||||
};
|
||||
use axum::{extract::State, http::StatusCode, response::IntoResponse, Extension, Json};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
|
||||
use crate::{
|
||||
auth::jwt::Claims,
|
||||
config::AppState,
|
||||
models::user::User,
|
||||
};
|
||||
use crate::{auth::jwt::Claims, config::AppState, models::user::User};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UserProfileResponse {
|
||||
|
|
@ -57,16 +47,22 @@ pub async fn get_profile(
|
|||
let response: UserProfileResponse = user.try_into().unwrap();
|
||||
(StatusCode::OK, Json(response)).into_response()
|
||||
}
|
||||
Ok(None) => {
|
||||
(StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
Ok(None) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "user not found"
|
||||
}))).into_response()
|
||||
}
|
||||
})),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get user profile: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to get profile"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -77,10 +73,14 @@ pub async fn update_profile(
|
|||
Json(req): Json<UpdateProfileRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let user_id = ObjectId::parse_str(&claims.sub).unwrap();
|
||||
|
|
@ -88,15 +88,23 @@ pub async fn update_profile(
|
|||
let mut user = match state.db.find_user_by_id(&user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "user not found"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -111,9 +119,13 @@ pub async fn update_profile(
|
|||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update profile"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -128,9 +140,13 @@ pub async fn delete_account(
|
|||
Ok(_) => (StatusCode::NO_CONTENT, ()).into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to delete user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to delete account"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -149,10 +165,14 @@ pub async fn change_password(
|
|||
Json(req): Json<ChangePasswordRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(errors) = req.validate() {
|
||||
return (StatusCode::BAD_REQUEST, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "validation failed",
|
||||
"details": errors.to_string()
|
||||
}))).into_response();
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let user_id = ObjectId::parse_str(&claims.sub).unwrap();
|
||||
|
|
@ -160,42 +180,62 @@ pub async fn change_password(
|
|||
let mut user = match state.db.find_user_by_id(&user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "user not found"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Verify current password
|
||||
match user.verify_password(&req.current_password) {
|
||||
Ok(true) => {},
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({
|
||||
"error": "current password is incorrect"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to verify password: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to verify password"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
// Update password
|
||||
match user.update_password(req.new_password) {
|
||||
Ok(_) => {},
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to hash new password: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update password"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -203,9 +243,13 @@ pub async fn change_password(
|
|||
Ok(_) => (StatusCode::NO_CONTENT, ()).into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update password"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -236,16 +280,22 @@ pub async fn get_settings(
|
|||
let response: UserSettingsResponse = user.into();
|
||||
(StatusCode::OK, Json(response)).into_response()
|
||||
}
|
||||
Ok(None) => {
|
||||
(StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
Ok(None) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "user not found"
|
||||
}))).into_response()
|
||||
}
|
||||
})),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to get settings"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -265,15 +315,23 @@ pub async fn update_settings(
|
|||
let mut user = match state.db.find_user_by_id(&user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
return (StatusCode::NOT_FOUND, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": "user not found"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get user: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "database error"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -291,9 +349,13 @@ pub async fn update_settings(
|
|||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to update user: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": "failed to update settings"
|
||||
}))).into_response()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,20 @@
|
|||
mod auth;
|
||||
mod config;
|
||||
mod db;
|
||||
mod models;
|
||||
mod auth;
|
||||
mod handlers;
|
||||
mod middleware;
|
||||
mod models;
|
||||
mod security;
|
||||
mod services;
|
||||
|
||||
use axum::{
|
||||
routing::{get, post, put, delete},
|
||||
routing::{delete, get, post, put},
|
||||
Router,
|
||||
};
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{
|
||||
cors::CorsLayer,
|
||||
trace::TraceLayer,
|
||||
};
|
||||
use config::Config;
|
||||
use std::sync::Arc;
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{cors::CorsLayer, trace::TraceLayer};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
|
|
@ -43,7 +40,10 @@ async fn main() -> anyhow::Result<()> {
|
|||
eprintln!("Connecting to MongoDB...");
|
||||
let db = match db::MongoDb::new(&config.database.uri, &config.database.database).await {
|
||||
Ok(db) => {
|
||||
tracing::info!("Connected to MongoDB database: {}", config.database.database);
|
||||
tracing::info!(
|
||||
"Connected to MongoDB database: {}",
|
||||
config.database.database
|
||||
);
|
||||
eprintln!("MongoDB connection successful");
|
||||
db
|
||||
}
|
||||
|
|
@ -107,11 +107,17 @@ async fn main() -> anyhow::Result<()> {
|
|||
|
||||
// Build public routes (no auth required)
|
||||
let public_routes = Router::new()
|
||||
.route("/health", get(handlers::health_check).head(handlers::health_check))
|
||||
.route(
|
||||
"/health",
|
||||
get(handlers::health_check).head(handlers::health_check),
|
||||
)
|
||||
.route("/ready", get(handlers::ready_check))
|
||||
.route("/api/auth/register", post(handlers::register))
|
||||
.route("/api/auth/login", post(handlers::login))
|
||||
.route("/api/auth/recover-password", post(handlers::recover_password));
|
||||
.route(
|
||||
"/api/auth/recover-password",
|
||||
post(handlers::recover_password),
|
||||
);
|
||||
|
||||
// Build protected routes (auth required)
|
||||
let protected_routes = Router::new()
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
use crate::auth::jwt::Claims;
|
||||
use crate::config::AppState;
|
||||
use axum::{
|
||||
extract::{Request, State},
|
||||
http::StatusCode,
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use crate::auth::jwt::Claims;
|
||||
use crate::config::AppState;
|
||||
|
||||
pub async fn jwt_auth_middleware(
|
||||
State(state): State<AppState>,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
pub mod auth;
|
||||
pub mod rate_limit;
|
||||
|
||||
pub use rate_limit::general_rate_limit_middleware;
|
||||
pub use auth::jwt_auth_middleware;
|
||||
pub use rate_limit::general_rate_limit_middleware;
|
||||
|
||||
// Simple security headers middleware
|
||||
pub async fn security_headers_middleware(
|
||||
|
|
@ -15,8 +15,14 @@ pub async fn security_headers_middleware(
|
|||
headers.insert("X-Content-Type-Options", "nosniff".parse().unwrap());
|
||||
headers.insert("X-Frame-Options", "DENY".parse().unwrap());
|
||||
headers.insert("X-XSS-Protection", "1; mode=block".parse().unwrap());
|
||||
headers.insert("Strict-Transport-Security", "max-age=31536000; includeSubDomains".parse().unwrap());
|
||||
headers.insert("Content-Security-Policy", "default-src 'self'".parse().unwrap());
|
||||
headers.insert(
|
||||
"Strict-Transport-Security",
|
||||
"max-age=31536000; includeSubDomains".parse().unwrap(),
|
||||
);
|
||||
headers.insert(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'".parse().unwrap(),
|
||||
);
|
||||
|
||||
response
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
use axum::{
|
||||
extract::Request,
|
||||
http::StatusCode,
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
|
||||
|
||||
/// Middleware for general rate limiting
|
||||
/// NOTE: Currently a stub implementation. TODO: Implement IP-based rate limiting
|
||||
|
|
@ -18,10 +13,7 @@ pub async fn general_rate_limit_middleware(
|
|||
|
||||
/// Middleware for auth endpoint rate limiting
|
||||
/// NOTE: Currently a stub implementation. TODO: Implement IP-based rate limiting
|
||||
pub async fn auth_rate_limit_middleware(
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
pub async fn auth_rate_limit_middleware(req: Request, next: Next) -> Result<Response, StatusCode> {
|
||||
// TODO: Implement proper rate limiting with IP-based tracking
|
||||
// For now, just pass through
|
||||
Ok(next.run(req).await)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
use mongodb::{
|
||||
Collection,
|
||||
bson::{doc, oid::ObjectId},
|
||||
};
|
||||
use futures::stream::TryStreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use anyhow::Result;
|
||||
use futures::stream::TryStreamExt;
|
||||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId},
|
||||
Collection,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum AuditEventType {
|
||||
|
|
@ -87,7 +87,8 @@ impl AuditLogRepository {
|
|||
}
|
||||
|
||||
pub async fn find_by_user(&self, user_id: &ObjectId) -> Result<Vec<AuditLog>> {
|
||||
let cursor = self.collection
|
||||
let cursor = self
|
||||
.collection
|
||||
.find(
|
||||
doc! {
|
||||
"user_id": user_id
|
||||
|
|
@ -108,9 +109,7 @@ impl AuditLogRepository {
|
|||
.limit(limit as i64)
|
||||
.build();
|
||||
|
||||
let cursor = self.collection
|
||||
.find(doc! {}, opts)
|
||||
.await?;
|
||||
let cursor = self.collection.find(doc! {}, opts).await?;
|
||||
|
||||
let logs: Vec<AuditLog> = cursor.try_collect().await?;
|
||||
Ok(logs)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId, DateTime},
|
||||
Collection,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::{bson::{doc, oid::ObjectId, DateTime}, Collection};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Family {
|
||||
|
|
@ -35,7 +38,10 @@ impl FamilyRepository {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn find_by_family_id(&self, family_id: &str) -> mongodb::error::Result<Option<Family>> {
|
||||
pub async fn find_by_family_id(
|
||||
&self,
|
||||
family_id: &str,
|
||||
) -> mongodb::error::Result<Option<Family>> {
|
||||
self.collection
|
||||
.find_one(doc! { "familyId": family_id }, None)
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::bson::{oid::ObjectId, DateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthData {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
use mongodb::Collection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::{bson::{oid::ObjectId, doc}, error::Error as MongoError};
|
||||
use futures::stream::TryStreamExt;
|
||||
use mongodb::Collection;
|
||||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId},
|
||||
error::Error as MongoError,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthStatistic {
|
||||
|
|
@ -46,7 +49,11 @@ impl HealthStatisticsRepository {
|
|||
self.collection.find_one(filter, None).await
|
||||
}
|
||||
|
||||
pub async fn update(&self, id: &ObjectId, stat: &HealthStatistic) -> Result<Option<HealthStatistic>, MongoError> {
|
||||
pub async fn update(
|
||||
&self,
|
||||
id: &ObjectId,
|
||||
stat: &HealthStatistic,
|
||||
) -> Result<Option<HealthStatistic>, MongoError> {
|
||||
let filter = doc! { "_id": id };
|
||||
self.collection.replace_one(filter, stat, None).await?;
|
||||
Ok(Some(stat.clone()))
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@
|
|||
//!
|
||||
//! Database models for drug interactions
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::bson::{oid::ObjectId, DateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DrugInteraction {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::{bson::oid::ObjectId, Collection};
|
||||
use futures::stream::TryStreamExt;
|
||||
use mongodb::{bson::oid::ObjectId, Collection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LabResult {
|
||||
|
|
@ -41,12 +41,18 @@ impl LabResultRepository {
|
|||
Self { collection }
|
||||
}
|
||||
|
||||
pub async fn create(&self, lab_result: LabResult) -> Result<LabResult, Box<dyn std::error::Error>> {
|
||||
pub async fn create(
|
||||
&self,
|
||||
lab_result: LabResult,
|
||||
) -> Result<LabResult, Box<dyn std::error::Error>> {
|
||||
self.collection.insert_one(lab_result.clone(), None).await?;
|
||||
Ok(lab_result)
|
||||
}
|
||||
|
||||
pub async fn list_by_user(&self, user_id: &str) -> Result<Vec<LabResult>, Box<dyn std::error::Error>> {
|
||||
pub async fn list_by_user(
|
||||
&self,
|
||||
user_id: &str,
|
||||
) -> Result<Vec<LabResult>, Box<dyn std::error::Error>> {
|
||||
let filter = mongodb::bson::doc! {
|
||||
"userId": user_id
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::bson::{oid::ObjectId, DateTime, doc};
|
||||
use mongodb::Collection;
|
||||
use futures::stream::StreamExt;
|
||||
use super::health_data::EncryptedField;
|
||||
use futures::stream::StreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, DateTime};
|
||||
use mongodb::Collection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ============================================================================
|
||||
// PILL IDENTIFICATION (Phase 2.8)
|
||||
|
|
@ -217,12 +217,18 @@ impl MedicationRepository {
|
|||
Self { collection }
|
||||
}
|
||||
|
||||
pub async fn create(&self, medication: Medication) -> Result<Medication, Box<dyn std::error::Error>> {
|
||||
pub async fn create(
|
||||
&self,
|
||||
medication: Medication,
|
||||
) -> Result<Medication, Box<dyn std::error::Error>> {
|
||||
let _result = self.collection.insert_one(medication.clone(), None).await?;
|
||||
Ok(medication)
|
||||
}
|
||||
|
||||
pub async fn find_by_user(&self, user_id: &str) -> Result<Vec<Medication>, Box<dyn std::error::Error>> {
|
||||
pub async fn find_by_user(
|
||||
&self,
|
||||
user_id: &str,
|
||||
) -> Result<Vec<Medication>, Box<dyn std::error::Error>> {
|
||||
let filter = doc! { "userId": user_id };
|
||||
let mut cursor = self.collection.find(filter, None).await?;
|
||||
let mut medications = Vec::new();
|
||||
|
|
@ -232,7 +238,11 @@ impl MedicationRepository {
|
|||
Ok(medications)
|
||||
}
|
||||
|
||||
pub async fn find_by_user_and_profile(&self, user_id: &str, profile_id: &str) -> Result<Vec<Medication>, Box<dyn std::error::Error>> {
|
||||
pub async fn find_by_user_and_profile(
|
||||
&self,
|
||||
user_id: &str,
|
||||
profile_id: &str,
|
||||
) -> Result<Vec<Medication>, Box<dyn std::error::Error>> {
|
||||
let filter = doc! {
|
||||
"userId": user_id,
|
||||
"profileId": profile_id
|
||||
|
|
@ -245,13 +255,20 @@ impl MedicationRepository {
|
|||
Ok(medications)
|
||||
}
|
||||
|
||||
pub async fn find_by_id(&self, id: &ObjectId) -> Result<Option<Medication>, Box<dyn std::error::Error>> {
|
||||
pub async fn find_by_id(
|
||||
&self,
|
||||
id: &ObjectId,
|
||||
) -> Result<Option<Medication>, Box<dyn std::error::Error>> {
|
||||
let filter = doc! { "_id": id };
|
||||
let medication = self.collection.find_one(filter, None).await?;
|
||||
Ok(medication)
|
||||
}
|
||||
|
||||
pub async fn update(&self, id: &ObjectId, updates: UpdateMedicationRequest) -> Result<Option<Medication>, Box<dyn std::error::Error>> {
|
||||
pub async fn update(
|
||||
&self,
|
||||
id: &ObjectId,
|
||||
updates: UpdateMedicationRequest,
|
||||
) -> Result<Option<Medication>, Box<dyn std::error::Error>> {
|
||||
let mut update_doc = doc! {};
|
||||
|
||||
if let Some(name) = updates.name {
|
||||
|
|
@ -305,7 +322,10 @@ impl MedicationRepository {
|
|||
update_doc.insert("updatedAt", mongodb::bson::DateTime::now());
|
||||
|
||||
let filter = doc! { "_id": id };
|
||||
let medication = self.collection.find_one_and_update(filter, doc! { "$set": update_doc }, None).await?;
|
||||
let medication = self
|
||||
.collection
|
||||
.find_one_and_update(filter, doc! { "$set": update_doc }, None)
|
||||
.await?;
|
||||
Ok(medication)
|
||||
}
|
||||
|
||||
|
|
@ -315,7 +335,11 @@ impl MedicationRepository {
|
|||
Ok(result.deleted_count > 0)
|
||||
}
|
||||
|
||||
pub async fn calculate_adherence(&self, medication_id: &str, days: i64) -> Result<AdherenceStats, Box<dyn std::error::Error>> {
|
||||
pub async fn calculate_adherence(
|
||||
&self,
|
||||
medication_id: &str,
|
||||
days: i64,
|
||||
) -> Result<AdherenceStats, Box<dyn std::error::Error>> {
|
||||
// For now, return a placeholder adherence calculation
|
||||
// In a full implementation, this would query the medication_doses collection
|
||||
Ok(AdherenceStats {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ pub mod audit_log;
|
|||
pub mod family;
|
||||
pub mod health_data;
|
||||
pub mod health_stats;
|
||||
pub mod interactions;
|
||||
pub mod lab_result;
|
||||
pub mod medication;
|
||||
pub mod permission;
|
||||
|
|
@ -10,4 +11,3 @@ pub mod refresh_token;
|
|||
pub mod session;
|
||||
pub mod share;
|
||||
pub mod user;
|
||||
pub mod interactions;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId, DateTime},
|
||||
Collection,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::{bson::{doc, oid::ObjectId, DateTime}, Collection};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Profile {
|
||||
|
|
@ -41,7 +44,10 @@ impl ProfileRepository {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn find_by_profile_id(&self, profile_id: &str) -> mongodb::error::Result<Option<Profile>> {
|
||||
pub async fn find_by_profile_id(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
) -> mongodb::error::Result<Option<Profile>> {
|
||||
self.collection
|
||||
.find_one(doc! { "profileId": profile_id }, None)
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::bson::{oid::ObjectId, DateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RefreshToken {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
use mongodb::{
|
||||
Collection,
|
||||
bson::{doc, oid::ObjectId},
|
||||
};
|
||||
use futures::stream::TryStreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use anyhow::Result;
|
||||
use futures::stream::TryStreamExt;
|
||||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId},
|
||||
Collection,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
|
|
@ -65,11 +65,17 @@ impl SessionRepository {
|
|||
is_revoked: false,
|
||||
};
|
||||
|
||||
self.collection.insert_one(session, None).await?.inserted_id.as_object_id().ok_or_else(|| anyhow::anyhow!("Failed to get inserted id"))
|
||||
self.collection
|
||||
.insert_one(session, None)
|
||||
.await?
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to get inserted id"))
|
||||
}
|
||||
|
||||
pub async fn find_by_user(&self, user_id: &ObjectId) -> Result<Vec<Session>> {
|
||||
let cursor = self.collection
|
||||
let cursor = self
|
||||
.collection
|
||||
.find(
|
||||
doc! {
|
||||
"user_id": user_id,
|
||||
|
|
@ -110,7 +116,8 @@ impl SessionRepository {
|
|||
}
|
||||
|
||||
pub async fn cleanup_expired(&self) -> Result<u64> {
|
||||
let result = self.collection
|
||||
let result = self
|
||||
.collection
|
||||
.delete_many(
|
||||
doc! {
|
||||
"expires_at": { "$lt": mongodb::bson::DateTime::now() }
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use mongodb::bson::DateTime;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use mongodb::Collection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use mongodb::bson::DateTime;
|
||||
|
||||
use super::permission::Permission;
|
||||
|
||||
|
|
@ -90,11 +90,17 @@ impl ShareRepository {
|
|||
.map_err(|e| mongodb::error::Error::from(e))
|
||||
}
|
||||
|
||||
pub async fn find_by_target(&self, target_user_id: &ObjectId) -> mongodb::error::Result<Vec<Share>> {
|
||||
pub async fn find_by_target(
|
||||
&self,
|
||||
target_user_id: &ObjectId,
|
||||
) -> mongodb::error::Result<Vec<Share>> {
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
self.collection
|
||||
.find(doc! { "target_user_id": target_user_id, "active": true }, None)
|
||||
.find(
|
||||
doc! { "target_user_id": target_user_id, "active": true },
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
.try_collect()
|
||||
.await
|
||||
|
|
@ -103,13 +109,17 @@ impl ShareRepository {
|
|||
|
||||
pub async fn update(&self, share: &Share) -> mongodb::error::Result<()> {
|
||||
if let Some(id) = &share.id {
|
||||
self.collection.replace_one(doc! { "_id": id }, share, None).await?;
|
||||
self.collection
|
||||
.replace_one(doc! { "_id": id }, share, None)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete(&self, share_id: &ObjectId) -> mongodb::error::Result<()> {
|
||||
self.collection.delete_one(doc! { "_id": share_id }, None).await?;
|
||||
self.collection
|
||||
.delete_one(doc! { "_id": share_id }, None)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ use mongodb::bson::{doc, oid::ObjectId};
|
|||
use mongodb::Collection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use mongodb::bson::DateTime;
|
||||
use crate::auth::password::verify_password;
|
||||
use mongodb::bson::DateTime;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct User {
|
||||
|
|
@ -156,13 +156,14 @@ impl UserRepository {
|
|||
|
||||
/// Find a user by ID
|
||||
pub async fn find_by_id(&self, id: &ObjectId) -> mongodb::error::Result<Option<User>> {
|
||||
self.collection
|
||||
.find_one(doc! { "_id": id }, None)
|
||||
.await
|
||||
self.collection.find_one(doc! { "_id": id }, None).await
|
||||
}
|
||||
|
||||
/// Find a user by verification token
|
||||
pub async fn find_by_verification_token(&self, token: &str) -> mongodb::error::Result<Option<User>> {
|
||||
pub async fn find_by_verification_token(
|
||||
&self,
|
||||
token: &str,
|
||||
) -> mongodb::error::Result<Option<User>> {
|
||||
self.collection
|
||||
.find_one(doc! { "verification_token": token }, None)
|
||||
.await
|
||||
|
|
@ -177,7 +178,11 @@ impl UserRepository {
|
|||
}
|
||||
|
||||
/// Update the token version - silently fails if ObjectId is invalid
|
||||
pub async fn update_token_version(&self, user_id: &str, version: i32) -> mongodb::error::Result<()> {
|
||||
pub async fn update_token_version(
|
||||
&self,
|
||||
user_id: &str,
|
||||
version: i32,
|
||||
) -> mongodb::error::Result<()> {
|
||||
let oid = match ObjectId::parse_str(user_id) {
|
||||
Ok(id) => id,
|
||||
Err(_) => return Ok(()), // Silently fail if invalid ObjectId
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use anyhow::Result;
|
||||
use mongodb::bson::{doc, DateTime};
|
||||
use mongodb::Collection;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AccountLockout {
|
||||
|
|
@ -29,12 +29,7 @@ impl AccountLockout {
|
|||
|
||||
pub async fn check_lockout(&self, email: &str) -> Result<bool> {
|
||||
let collection = self.user_collection.read().await;
|
||||
let user = collection
|
||||
.find_one(
|
||||
doc! { "email": email },
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let user = collection.find_one(doc! { "email": email }, None).await?;
|
||||
|
||||
if let Some(user_doc) = user {
|
||||
if let Some(locked_until_val) = user_doc.get("locked_until") {
|
||||
|
|
@ -54,15 +49,11 @@ impl AccountLockout {
|
|||
let collection = self.user_collection.write().await;
|
||||
|
||||
// Get current failed attempts
|
||||
let user = collection
|
||||
.find_one(
|
||||
doc! { "email": email },
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let user = collection.find_one(doc! { "email": email }, None).await?;
|
||||
|
||||
let current_attempts = if let Some(user_doc) = user {
|
||||
user_doc.get("failed_login_attempts")
|
||||
user_doc
|
||||
.get("failed_login_attempts")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0) as u32
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use crate::models::audit_log::{AuditEventType, AuditLog, AuditLogRepository};
|
||||
use anyhow::Result;
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use crate::models::audit_log::{AuditLog, AuditLogRepository, AuditEventType};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuditLogger {
|
||||
|
|
@ -24,7 +24,14 @@ impl AuditLogger {
|
|||
resource_id: Option<String>,
|
||||
) -> Result<ObjectId> {
|
||||
self.repository
|
||||
.log(event_type, user_id, email, ip_address, resource_type, resource_id)
|
||||
.log(
|
||||
event_type,
|
||||
user_id,
|
||||
email,
|
||||
ip_address,
|
||||
resource_type,
|
||||
resource_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
pub mod account_lockout;
|
||||
pub mod audit_logger;
|
||||
pub mod session_manager;
|
||||
pub mod account_lockout;
|
||||
|
||||
pub use account_lockout::AccountLockout;
|
||||
pub use audit_logger::AuditLogger;
|
||||
pub use session_manager::SessionManager;
|
||||
pub use account_lockout::AccountLockout;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::models::session::{DeviceInfo, Session, SessionRepository};
|
||||
use anyhow::Result;
|
||||
use crate::models::session::{Session, SessionRepository, DeviceInfo};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -21,7 +21,9 @@ impl SessionManager {
|
|||
token_hash: String,
|
||||
duration_hours: i64,
|
||||
) -> Result<ObjectId> {
|
||||
self.repository.create(user_id, device_info, token_hash, duration_hours).await
|
||||
self.repository
|
||||
.create(user_id, device_info, token_hash, duration_hours)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_user_sessions(&self, user_id: &ObjectId) -> Result<Vec<Session>> {
|
||||
|
|
|
|||
|
|
@ -40,16 +40,15 @@ impl IngredientMapper {
|
|||
pub fn map_to_us(&self, eu_name: &str) -> String {
|
||||
let normalized = eu_name.to_lowercase().trim().to_string();
|
||||
|
||||
self.mappings.get(&normalized)
|
||||
self.mappings
|
||||
.get(&normalized)
|
||||
.unwrap_or(&eu_name.to_string())
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Map multiple EU drug names to US names
|
||||
pub fn map_many_to_us(&self, eu_names: &[String]) -> Vec<String> {
|
||||
eu_names.iter()
|
||||
.map(|name| self.map_to_us(name))
|
||||
.collect()
|
||||
eu_names.iter().map(|name| self.map_to_us(name)).collect()
|
||||
}
|
||||
|
||||
/// Add a custom mapping
|
||||
|
|
|
|||
|
|
@ -4,9 +4,8 @@
|
|||
//! Provides a unified API for checking drug interactions
|
||||
|
||||
use crate::services::{
|
||||
IngredientMapper,
|
||||
OpenFDAService,
|
||||
openfda_service::{DrugInteraction, InteractionSeverity}
|
||||
openfda_service::{DrugInteraction, InteractionSeverity},
|
||||
IngredientMapper, OpenFDAService,
|
||||
};
|
||||
use mongodb::bson::oid::ObjectId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -28,7 +27,7 @@ impl InteractionService {
|
|||
/// Maps EU names to US names, then checks interactions
|
||||
pub async fn check_eu_medications(
|
||||
&self,
|
||||
eu_medications: &[String]
|
||||
eu_medications: &[String],
|
||||
) -> Result<Vec<DrugInteraction>, Box<dyn std::error::Error>> {
|
||||
// Step 1: Map EU names to US names
|
||||
let us_medications: Vec<String> = self.mapper.map_many_to_us(eu_medications);
|
||||
|
|
@ -42,10 +41,18 @@ impl InteractionService {
|
|||
.map(|mut interaction| {
|
||||
// Map US names back to EU names if they were mapped
|
||||
for (i, eu_name) in eu_medications.iter().enumerate() {
|
||||
if us_medications.get(i).map(|us| us == &interaction.drug1).unwrap_or(false) {
|
||||
if us_medications
|
||||
.get(i)
|
||||
.map(|us| us == &interaction.drug1)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
interaction.drug1 = eu_name.clone();
|
||||
}
|
||||
if us_medications.get(i).map(|us| us == &interaction.drug2).unwrap_or(false) {
|
||||
if us_medications
|
||||
.get(i)
|
||||
.map(|us| us == &interaction.drug2)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
interaction.drug2 = eu_name.clone();
|
||||
}
|
||||
}
|
||||
|
|
@ -60,7 +67,7 @@ impl InteractionService {
|
|||
pub async fn check_new_medication(
|
||||
&self,
|
||||
new_medication: &str,
|
||||
existing_medications: &[String]
|
||||
existing_medications: &[String],
|
||||
) -> Result<DrugInteractionCheckResult, Box<dyn std::error::Error>> {
|
||||
let all_meds = {
|
||||
let mut meds = vec![new_medication.to_string()];
|
||||
|
|
@ -70,7 +77,8 @@ impl InteractionService {
|
|||
|
||||
let interactions = self.check_eu_medications(&all_meds).await?;
|
||||
|
||||
let has_severe = interactions.iter()
|
||||
let has_severe = interactions
|
||||
.iter()
|
||||
.any(|i| matches!(i.severity, InteractionSeverity::Severe));
|
||||
|
||||
Ok(DrugInteractionCheckResult {
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@
|
|||
//! - Interaction Checker (combined service)
|
||||
|
||||
pub mod ingredient_mapper;
|
||||
pub mod openfda_service;
|
||||
pub mod interaction_service;
|
||||
pub mod openfda_service;
|
||||
|
||||
pub use ingredient_mapper::IngredientMapper;
|
||||
pub use openfda_service::OpenFDAService;
|
||||
pub use interaction_service::InteractionService;
|
||||
pub use openfda_service::OpenFDAService;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ const BASE_URL: &str = "http://127.0.0.1:8000";
|
|||
#[tokio::test]
|
||||
async fn test_health_check() {
|
||||
let client = Client::new();
|
||||
let response = client.get(&format!("{}/health", BASE_URL))
|
||||
let response = client
|
||||
.get(&format!("{}/health", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
|
@ -17,7 +18,8 @@ async fn test_health_check() {
|
|||
#[tokio::test]
|
||||
async fn test_ready_check() {
|
||||
let client = Client::new();
|
||||
let response = client.get(&format!("{}/ready", BASE_URL))
|
||||
let response = client
|
||||
.get(&format!("{}/ready", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
|
@ -38,7 +40,8 @@ async fn test_register_user() {
|
|||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
|
||||
let response = client.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
let response = client
|
||||
.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
|
|
@ -65,7 +68,8 @@ async fn test_login() {
|
|||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
|
||||
let _reg_response = client.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
let _reg_response = client
|
||||
.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
.json(®ister_payload)
|
||||
.send()
|
||||
.await
|
||||
|
|
@ -77,7 +81,8 @@ async fn test_login() {
|
|||
"password_hash": "hashed_password_placeholder"
|
||||
});
|
||||
|
||||
let response = client.post(&format!("{}/api/auth/login", BASE_URL))
|
||||
let response = client
|
||||
.post(&format!("{}/api/auth/login", BASE_URL))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
|
|
@ -95,7 +100,8 @@ async fn test_login() {
|
|||
async fn test_get_profile_without_auth() {
|
||||
let client = Client::new();
|
||||
|
||||
let response = client.get(&format!("{}/api/users/me", BASE_URL))
|
||||
let response = client
|
||||
.get(&format!("{}/api/users/me", BASE_URL))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
|
@ -118,7 +124,8 @@ async fn test_get_profile_with_auth() {
|
|||
"recovery_phrase_auth_tag": "auth_tag_placeholder"
|
||||
});
|
||||
|
||||
client.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
client
|
||||
.post(&format!("{}/api/auth/register", BASE_URL))
|
||||
.json(®ister_payload)
|
||||
.send()
|
||||
.await
|
||||
|
|
@ -129,17 +136,21 @@ async fn test_get_profile_with_auth() {
|
|||
"password_hash": "hashed_password_placeholder"
|
||||
});
|
||||
|
||||
let login_response = client.post(&format!("{}/api/auth/login", BASE_URL))
|
||||
let login_response = client
|
||||
.post(&format!("{}/api/auth/login", BASE_URL))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
||||
let login_json: Value = login_response.json().await.expect("Failed to parse JSON");
|
||||
let access_token = login_json["access_token"].as_str().expect("No access token");
|
||||
let access_token = login_json["access_token"]
|
||||
.as_str()
|
||||
.expect("No access token");
|
||||
|
||||
// Get profile with auth token
|
||||
let response = client.get(&format!("{}/api/users/me", BASE_URL))
|
||||
let response = client
|
||||
.get(&format!("{}/api/users/me", BASE_URL))
|
||||
.header("Authorization", format!("Bearer {}", access_token))
|
||||
.send()
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -47,7 +47,10 @@ mod medication_tests {
|
|||
async fn test_get_medication_requires_auth() {
|
||||
let client = Client::new();
|
||||
let response = client
|
||||
.get(&format!("{}/api/medications/507f1f77bcf86cd799439011", BASE_URL))
|
||||
.get(&format!(
|
||||
"{}/api/medications/507f1f77bcf86cd799439011",
|
||||
BASE_URL
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send request");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue