Apply Session middleware to all but /notify with separate router, improve /notify key error handling

This commit is contained in:
2024-12-23 19:53:26 -06:00
parent de3dacda77
commit bc39909f3c

View File

@@ -203,7 +203,7 @@ pub async fn download(req: &mut Request, res: &mut Response, depot: &mut Depot)
} }
#[handler] #[handler]
pub async fn notify(req: &mut Request, res: &mut Response, depot: &mut Depot) { pub async fn notify(req: &mut Request, res: &mut Response) {
let key = req.query::<String>("key"); let key = req.query::<String>("key");
match key { match key {
@@ -219,8 +219,10 @@ pub async fn notify(req: &mut Request, res: &mut Response, depot: &mut Depot) {
}; };
let store = &mut *STORE.lock().await; let store = &mut *STORE.lock().await;
let session = store.sessions.get_mut(&key).expect("Session not found"); let session = store.sessions.get_mut(&key);
match session {
Some(session) => {
let message = OutgoingMessage::TokenAlert { token: key }; let message = OutgoingMessage::TokenAlert { token: key };
session session
.send_message(message) .send_message(message)
@@ -228,6 +230,13 @@ pub async fn notify(req: &mut Request, res: &mut Response, depot: &mut Depot) {
res.render("Notification sent"); res.render("Notification sent");
} }
None => {
tracing::warn!("Session not found for key while attempting notify: {}", key);
res.status_code(StatusCode::UNAUTHORIZED);
return;
}
}
}
None => { None => {
res.status_code(StatusCode::BAD_REQUEST); res.status_code(StatusCode::BAD_REQUEST);
} }
@@ -337,12 +346,18 @@ async fn main() {
let router = Router::new() let router = Router::new()
.hoop(CatchPanic::new()) .hoop(CatchPanic::new())
.hoop(cors) .hoop(cors)
// /notify does not need a session, nor should it have one
.push(Router::with_path("notify").post(notify))
.push(
Router::new()
.hoop(session_middleware) .hoop(session_middleware)
.push(Router::with_path("download/<id>").get(download)) .push(Router::with_path("download/<id>").get(download))
.push(Router::with_path("session").get(get_session)) .push(Router::with_path("session").get(get_session))
// websocket /ws
.push(Router::with_path("ws").goal(connect)) .push(Router::with_path("ws").goal(connect))
.push(Router::with_path("notify").post(notify)) // static files
.push(Router::with_path("<**path>").get(static_dir)); .push(Router::with_path("<**path>").get(static_dir)),
);
let service = Service::new(router).hoop(Logger::new()); let service = Service::new(router).hoop(Logger::new());