DEVELOPMENT ENVIRONMENT

~liljamo/canwa

aee45a06a7a9b9e9fb28ffc4b02e2b69c2cb209f — Jonni Liljamo a month ago f4acfed
feat: move token to header
2 files changed, 22 insertions(+), 10 deletions(-)

M README.md
M src/main.rs
M README.md => README.md +2 -2
@@ 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"
```

M src/main.rs => src/main.rs +20 -8
@@ 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<State>, Json(message): Json<MessageForm>) -> impl IntoResponse {
    let notifier = match state
        .notifiers
        .iter()
        .find(|(_k, v)| v.token == message.token)
    {
async fn message(
    state: Arc<State>,
    headers: HeaderMap,
    Json(message): Json<MessageForm>,
) -> 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"),
    };