diff options
author | Cara Salter <cara@devcara.com> | 2022-05-30 00:24:40 -0400 |
---|---|---|
committer | Cara Salter <cara@devcara.com> | 2022-05-30 00:24:40 -0400 |
commit | ecca0e8cef755899049e7f541c86b9d06b2438a4 (patch) | |
tree | 1b86c9667a3044b885a468744780effee1ed401f /src/handlers/ships.rs | |
parent | b7752eef57e008c0d2a7dad868e98ff8b802bd22 (diff) | |
download | homeworld-ecca0e8cef755899049e7f541c86b9d06b2438a4.tar.gz homeworld-ecca0e8cef755899049e7f541c86b9d06b2438a4.zip |
meta: Add Bearer authentication
Makes use of a pre-shared key. Do not expose this to the internet!
Diffstat (limited to 'src/handlers/ships.rs')
-rw-r--r-- | src/handlers/ships.rs | 24 |
1 files changed, 21 insertions, 3 deletions
diff --git a/src/handlers/ships.rs b/src/handlers/ships.rs index 75f5dc5..42367ea 100644 --- a/src/handlers/ships.rs +++ b/src/handlers/ships.rs @@ -4,13 +4,13 @@ use axum::{Json, extract::Path, Extension}; use hyper::StatusCode; use solarlib::ship::{Ship, DbShip, Sha256}; use sqlx::{query_as, query, Error as SqlxError}; +use axum_auth::AuthBearer; +use tracing::log::warn; use crate::{errors::{JsonResult, StringResult, ServiceError}, State}; pub async fn list(state: Extension<Arc<State>>) -> JsonResult<Json<Vec<Ship>>> { - let mut result: Vec<Ship> = Vec::new(); - let mut conn = state.conn.acquire().await?; let db_ships = query_as!(DbShip, "SELECT * FROM ships").fetch_all(&mut conn).await?; @@ -20,7 +20,8 @@ pub async fn list(state: Extension<Arc<State>>) -> JsonResult<Json<Vec<Ship>>> { Ok(Json(ships)) } -pub async fn new(Json(new_ship): Json<Ship>, state: Extension<Arc<State>>) -> StringResult { +pub async fn new(Json(new_ship): Json<Ship>, state: Extension<Arc<State>>, AuthBearer(token): AuthBearer) -> StringResult { + check_bearer(token)?; let mut conn = state.conn.acquire().await?; query!("INSERT INTO ships (name, shasum, download_url, version) VALUES ($1, $2, $3, $4)", new_ship.name, new_ship.shasum.to_string(), new_ship.download_url, new_ship.version).execute(&mut conn).await?; @@ -29,6 +30,7 @@ pub async fn new(Json(new_ship): Json<Ship>, state: Extension<Arc<State>>) -> St } pub async fn delete(Path(shasum): Path<Sha256>, state: Extension<Arc<State>>) -> StringResult { + check_bearer(token)?; let mut conn = state.conn.acquire().await?; query!("DELETE FROM ships WHERE shasum=$1", shasum.to_string()).execute(&mut conn).await?; @@ -55,3 +57,19 @@ pub async fn get(Path(shasum): Path<Sha256>, state: Extension<Arc<State>>) -> Js Ok(Json(db_ship)) } + +fn check_bearer(token: String) -> Result<(), ServiceError> { + let expected_token = match std::env::var("SHARED_KEY") { + Ok(t) => t, + Err(_) => { + warn!("No pre-shared key set in environment. This is not secure!"); + "bad-key".into() + } + }; + + if token != expected_token { + Err(ServiceError::NotAuthorized) + } else { + Ok(()) + } +} |