atuin/atuin-server/src/router.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

2022-04-12 16:06:19 -06:00
use async_trait::async_trait;
use axum::{
2023-02-10 02:45:20 -07:00
extract::FromRequestParts,
2022-04-12 16:06:19 -06:00
response::IntoResponse,
routing::{get, post},
2023-02-10 02:45:20 -07:00
Router,
2022-04-12 16:06:19 -06:00
};
use eyre::Result;
2023-02-10 02:45:20 -07:00
use http::request::Parts;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
2022-03-13 13:53:49 -06:00
use super::{
database::{Database, Postgres},
handlers,
};
use crate::{models::User, settings::Settings};
2022-04-12 16:06:19 -06:00
#[async_trait]
2023-02-10 02:45:20 -07:00
impl FromRequestParts<AppState> for User {
2022-04-12 16:06:19 -06:00
type Rejection = http::StatusCode;
2023-02-10 02:45:20 -07:00
async fn from_request_parts(
req: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
2022-04-12 16:06:19 -06:00
let auth_header = req
2023-02-10 02:45:20 -07:00
.headers
2022-04-12 16:06:19 -06:00
.get(http::header::AUTHORIZATION)
.ok_or(http::StatusCode::FORBIDDEN)?;
let auth_header = auth_header
.to_str()
.map_err(|_| http::StatusCode::FORBIDDEN)?;
let (typ, token) = auth_header
.split_once(' ')
.ok_or(http::StatusCode::FORBIDDEN)?;
if typ != "Token" {
return Err(http::StatusCode::FORBIDDEN);
}
2023-02-10 02:45:20 -07:00
let user = state
.postgres
2022-04-12 16:06:19 -06:00
.get_session_user(token)
.await
.map_err(|_| http::StatusCode::FORBIDDEN)?;
2022-04-12 16:06:19 -06:00
Ok(user)
}
}
2022-04-12 16:06:19 -06:00
async fn teapot() -> impl IntoResponse {
(http::StatusCode::IM_A_TEAPOT, "")
}
2023-02-10 02:45:20 -07:00
#[derive(Clone)]
pub struct AppState {
pub postgres: Postgres,
pub settings: Settings,
}
2022-04-12 16:06:19 -06:00
pub fn router(postgres: Postgres, settings: Settings) -> Router {
let routes = Router::new()
2022-04-12 16:06:19 -06:00
.route("/", get(handlers::index))
.route("/sync/count", get(handlers::history::count))
.route("/sync/history", get(handlers::history::list))
.route("/sync/calendar/:focus", get(handlers::history::calendar))
2022-04-12 16:06:19 -06:00
.route("/history", post(handlers::history::add))
.route("/user/:username", get(handlers::user::get))
.route("/register", post(handlers::user::register))
.route("/login", post(handlers::user::login));
let path = settings.path.as_str();
if path.is_empty() {
routes
} else {
Router::new().nest(path, routes)
}
2023-02-10 02:45:20 -07:00
.fallback(teapot)
.with_state(AppState { postgres, settings })
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
}