From aee45a06a7a9b9e9fb28ffc4b02e2b69c2cb209f Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Sun, 4 May 2025 12:13:41 +0300 Subject: [PATCH] feat: move token to header --- README.md | 4 ++-- src/main.rs | 28 ++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 8c416fb..5078032 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ services = ["gtf_main", "mtx_main"] ### cURL usage: ```sh -curl -XPOST -H"Content-Type: application/json" \ - -d'{"token": "long_token_for_auth", "title": "test title", "message": "this is a message"}' \ +curl -XPOST -H"Content-Type: application/json" -H"Authorization: long_token_for_auth" \ + -d'{"title": "test title", "message": "this is a message"}' \ "http://localhost:8080/message" ``` diff --git a/src/main.rs b/src/main.rs index 347ba52..3cd0202 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use axum::{ Json, Router, + http::HeaderMap, response::{Html, IntoResponse}, routing::{get, post}, }; @@ -73,7 +74,7 @@ async fn main() { "/message", post({ let shared_state = Arc::clone(&state); - move |body| message(shared_state, body) + move |headers, body| message(shared_state, headers, body) }), ) .layer(TraceLayer::new_for_http()) @@ -87,17 +88,28 @@ async fn main() { #[derive(Deserialize)] struct MessageForm { - token: String, title: String, message: String, } -async fn message(state: Arc, Json(message): Json) -> impl IntoResponse { - let notifier = match state - .notifiers - .iter() - .find(|(_k, v)| v.token == message.token) - { +async fn message( + state: Arc, + headers: HeaderMap, + Json(message): Json, +) -> impl IntoResponse { + let token = match headers.get("Authorization") { + Some(token) => match token.to_str() { + Ok(token) => token, + Err(_) => { + return (StatusCode::UNAUTHORIZED, "unauthorized"); + } + }, + None => { + return (StatusCode::UNAUTHORIZED, "unauthorized"); + } + }; + + let notifier = match state.notifiers.iter().find(|(_k, v)| v.token == token) { Some(n) => n, None => return (StatusCode::UNAUTHORIZED, "unauthorized"), }; -- 2.44.1