diff --git a/db/1.sqlite b/db/1.sqlite index cbb825f..d67c736 100644 Binary files a/db/1.sqlite and b/db/1.sqlite differ diff --git a/db/1.sqlite-shm b/db/1.sqlite-shm index a0e2931..25bd428 100644 Binary files a/db/1.sqlite-shm and b/db/1.sqlite-shm differ diff --git a/db/1.sqlite-wal b/db/1.sqlite-wal index d35d8df..faa589e 100644 Binary files a/db/1.sqlite-wal and b/db/1.sqlite-wal differ diff --git a/db/auth_copy_2.sqlite-shm b/db/auth_copy_2.sqlite-shm deleted file mode 100644 index fe9ac28..0000000 Binary files a/db/auth_copy_2.sqlite-shm and /dev/null differ diff --git a/db/auth_copy_2.sqlite-wal b/db/auth_copy_2.sqlite-wal deleted file mode 100644 index e69de29..0000000 diff --git a/src/chat/handlers.rs b/src/chat/handlers.rs index c60b24e..d72921a 100644 --- a/src/chat/handlers.rs +++ b/src/chat/handlers.rs @@ -322,7 +322,7 @@ pub async fn send_message( if let Some(hotel_users) = state.ws_map.get(&hotel_id) { let update_msg = serde_json::json!({ - "event-type": "chat-message", + "event_type": "chat_message", "conv_id": payload.conv_id, "sender": user_id, "content": payload.message, diff --git a/src/inventory/handler.rs b/src/inventory/handler.rs index 86b6365..3164ad7 100644 --- a/src/inventory/handler.rs +++ b/src/inventory/handler.rs @@ -77,7 +77,7 @@ pub async fn update_inventory_item( (StatusCode::OK, format!("updated item history")) } - Ok(_) => (StatusCode::NOT_FOUND, "No room found".to_string()), + Ok(_) => (StatusCode::NOT_FOUND, "No item found, err : {_}".to_string()), Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, format!("Error from DB: {err}")), } @@ -104,7 +104,7 @@ pub async fn get_inventory_item( Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Pool error".to_string()), }; - let mut stmt = match conn.prepare("SELECT id, amount, item_name, user_id FROM inventory") { + let mut stmt = match conn.prepare("SELECT id, amount, item_name, user_id, updated_at FROM inventory") { Ok(s) => s, Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Statement error".to_string()), }; @@ -120,7 +120,7 @@ pub async fn get_inventory_item( let item = InventoryItems { id: row.get("id").unwrap_or_default(), amount: row.get("amount").unwrap_or_default(), - name: row.get("name").unwrap_or_default(), + name: row.get("item_name").unwrap_or_default(), user_id: row.get("user_id").unwrap_or_default(), updated_at: row.get("updated_at").unwrap_or_default(), }; diff --git a/src/main.rs b/src/main.rs index fd5a412..e9a4c70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,22 +50,22 @@ async fn main() -> std::io::Result<()> { dotenv().ok(); -std::panic::set_hook(Box::new(|info| { - let msg = format!("Rust panic: {}", info); + std::panic::set_hook(Box::new(|info| { + let msg = format!("Rust panic: {}", info); - // Use blocking client so the process can't exit before sending - let payload = serde_json::json!({ - "content": msg - }); + // Use blocking client so the process can't exit before sending + let payload = serde_json::json!({ + "content": msg + }); - let client = reqwest::blocking::Client::new(); - let _ = client - .post("https://discord.com/api/webhooks/1440912618205347891/Ekg89krDoPm41kA27LA3gXgNWmMWvCCtziYIUsjqaY22Jnw4a6IWhZOht0in5JjnPX-W") - .json(&payload) - .send(); -})); + let client = reqwest::blocking::Client::new(); + let _ = client + .post("https://discord.com/api/webhooks/1440912618205347891/Ekg89krDoPm41kA27LA3gXgNWmMWvCCtziYIUsjqaY22Jnw4a6IWhZOht0in5JjnPX-W") + .json(&payload) + .send(); + })); -//panic!("crash-test"); + //panic!("crash-test"); let hotel_pools = HotelPool::new(); let logs_manager = SqliteConnectionManager::file("db/auth_copy_2.sqlite"); @@ -92,15 +92,15 @@ std::panic::set_hook(Box::new(|info| { decoding: DecodingKey::from_secret(jwt_secret.as_ref()), }; -let allowed_origins = vec![ - "http://82.66.253.209", - "http://localhost:5173", -]; + let allowed_origins = vec![ + "http://82.66.253.209", + "http://localhost:5173", + ]; -let cors = CorsLayer::very_permissive() - .allow_credentials(true) - .allow_methods([Method::GET, Method::POST, Method::PUT, Method::OPTIONS]) - .allow_headers([CONTENT_TYPE, AUTHORIZATION]); + let cors = CorsLayer::very_permissive() + .allow_credentials(true) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::OPTIONS]) + .allow_headers([CONTENT_TYPE, AUTHORIZATION]); let app = create_router(state) .layer(Extension(jwt_keys)) .layer(cors); @@ -110,6 +110,6 @@ let cors = CorsLayer::very_permissive() Ok(()) } -async fn handler() -> &'static str { - "Hiii from localhost" -} \ No newline at end of file + async fn handler() -> &'static str { + "Hiii from localhost" + } \ No newline at end of file diff --git a/src/rooms/handler.rs b/src/rooms/handler.rs index ff7e963..7999583 100644 --- a/src/rooms/handler.rs +++ b/src/rooms/handler.rs @@ -83,7 +83,7 @@ pub async fn clean_db_update( } if let Some(hotel_users) = state.ws_map.get(&hotel_id) { let update_msg = json!({ - "event-type": "room-update", + "event_type": "room_update", "room_id": room_id, "status": payload.status, "updated_by": user_id, diff --git a/src/utils/auth.rs b/src/utils/auth.rs index 41daf63..fb934e9 100644 --- a/src/utils/auth.rs +++ b/src/utils/auth.rs @@ -47,6 +47,8 @@ pub async fn token_tester( ) } + + pub struct AuthUser(pub Claims); //?? #[derive(Debug, Clone)] @@ -56,44 +58,51 @@ pub struct AuthClaims { //pub username: String, } +pub fn auth_claims_from_token( + token: &str, + keys: &JwtKeys, +) -> Result { + let token_data = decode::( + token, + &keys.decoding, + &Validation::new(Algorithm::HS256), + ).map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid token".into()))?; + + Ok(AuthClaims { + user_id: token_data.claims.id, + hotel_id: token_data.claims.hotel_id, + }) +} + + impl FromRequestParts for AuthClaims where S: Send + Sync + 'static, - AppState: Clone + Send + Sync + 'static, AppState: FromRef - { + AppState: FromRef, +{ type Rejection = (StatusCode, String); - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - // We assume your state has a `jwt_secret` field + async fn from_request_parts( + parts: &mut Parts, + state: &S, + ) -> Result { let Extension(keys): Extension = - Extension::from_request_parts(parts, state).await.map_err(|_| (StatusCode::UNAUTHORIZED, "Missing keys".to_string()))?; + Extension::from_request_parts(parts, state) + .await + .map_err(|_| (StatusCode::UNAUTHORIZED, "Missing keys".into()))?; - // 1️⃣ Extract the token from the Authorization header let auth_header = parts .headers - .get("Authorization") - .ok_or((StatusCode::UNAUTHORIZED, "Missing Authorization header".to_string()))? + .get(axum::http::header::AUTHORIZATION) + .ok_or((StatusCode::UNAUTHORIZED, "Missing Authorization header".into()))? .to_str() - .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid Authorization header".to_string()))?; + .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid Authorization header".into()))?; - // Bearer token? let token = auth_header .strip_prefix("Bearer ") - .ok_or((StatusCode::BAD_REQUEST, "Expected Bearer token".to_string()))?; - - // 2️⃣ Decode the token - let token_data = decode::( - token, - &keys.decoding, - &Validation::new(Algorithm::HS256), - ).map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid token".to_string()))?; - - Ok(AuthClaims { - user_id: token_data.claims.id, - hotel_id: token_data.claims.hotel_id, - //username: token_data.claims.username, - }) + .ok_or((StatusCode::BAD_REQUEST, "Expected Bearer token".into()))?; + auth_claims_from_token(token, &keys) } } diff --git a/src/utils/routes.rs b/src/utils/routes.rs index 1e47221..bd0c748 100644 --- a/src/utils/routes.rs +++ b/src/utils/routes.rs @@ -16,7 +16,7 @@ pub fn utils_routes() -> Router { Router::new() .route("/login", put(clean_auth_loging)) .route("/register", put(register_user)) - .route("/ws/", get(ws_handler)) + .route("/tokentest", put(token_tester)) .route("/force_update_password", put(force_update_password)) .route("/update_password", put(update_password)) @@ -27,7 +27,7 @@ pub fn utils_routes() -> Router { .route("/logout_single_device", post(logout_from_single_device)) .route("/logout_all_devices", post(logout_from_all_devices)) - + .route("/ws/{req_token}", get(ws_handler)) //.with_state(state) } \ No newline at end of file diff --git a/src/utils/websocket.rs b/src/utils/websocket.rs index 8c743d6..60b7411 100644 --- a/src/utils/websocket.rs +++ b/src/utils/websocket.rs @@ -1,13 +1,14 @@ use dashmap::DashMap; +use reqwest::StatusCode; use std::sync::Arc; -use axum::extract::{ws::{Message, WebSocket, WebSocketUpgrade}, State}; +use axum::{Extension, extract::{State, ws::{Message, WebSocket, WebSocketUpgrade}}}; use tokio::sync::mpsc; use axum::extract::Path; use axum::response::IntoResponse; //use futures_util::stream::stream::StreamExt; use futures_util::{StreamExt, SinkExt}; -use crate::utils::{auth::AuthClaims, db_pool::{AppState, HotelPool}}; +use crate::utils::{auth::{AuthClaims, JwtKeys, auth_claims_from_token}, db_pool::{AppState, HotelPool}}; @@ -89,12 +90,37 @@ async fn handle_socket( } pub async fn ws_handler( - AuthClaims {user_id, hotel_id}: AuthClaims, + //AuthClaims {user_id, hotel_id}: AuthClaims, ws: WebSocketUpgrade, + Extension(keys): Extension, State(state): State, - //Path((hotel_id, user_id)): Path<(i32, i32)>, + Path((req_token)): Path<(String)>, ) -> impl IntoResponse { - ws.on_upgrade(move |socket| handle_socket(socket, state, hotel_id, user_id)) + + + let token = req_token; + + let claims = match auth_claims_from_token(&token, &keys) { + Err(_) => { + print!("error during auth claims processing"); + return StatusCode::UNAUTHORIZED.into_response(); + + } + Ok(c) => c + + }; + + print!("{token}, web socket tried to connect", ); + + /* + let claims = match auth_claims_from_token(&token, &keys) { + Ok(c) => c, + Err(_) => return StatusCode::UNAUTHORIZED.into_response(), + }; + */ + + + ws.on_upgrade(move |socket| handle_socket(socket, state, claims.hotel_id, claims.user_id)) } fn print_ws_state(state: &AppState) {