2022-04-12 16:06:19 -06:00
|
|
|
use async_trait::async_trait;
|
|
|
|
use axum::{
|
|
|
|
extract::{FromRequest, RequestParts},
|
|
|
|
handler::Handler,
|
|
|
|
response::IntoResponse,
|
|
|
|
routing::{get, post},
|
|
|
|
Extension, Router,
|
|
|
|
};
|
2021-04-20 10:07:11 -06:00
|
|
|
use eyre::Result;
|
2021-04-20 14:53:07 -06:00
|
|
|
|
2022-03-13 13:53:49 -06:00
|
|
|
use super::{
|
|
|
|
database::{Database, Postgres},
|
|
|
|
handlers,
|
|
|
|
};
|
|
|
|
use crate::{models::User, settings::Settings};
|
2021-04-20 10:07:11 -06:00
|
|
|
|
2022-04-12 16:06:19 -06:00
|
|
|
#[async_trait]
|
|
|
|
impl<B> FromRequest<B> for User
|
|
|
|
where
|
|
|
|
B: Send,
|
|
|
|
{
|
|
|
|
type Rejection = http::StatusCode;
|
|
|
|
|
|
|
|
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
|
|
|
|
let postgres = req
|
|
|
|
.extensions()
|
|
|
|
.get::<Postgres>()
|
|
|
|
.ok_or(http::StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
|
|
|
|
|
|
let auth_header = req
|
|
|
|
.headers()
|
|
|
|
.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);
|
2021-04-20 10:07:11 -06:00
|
|
|
}
|
|
|
|
|
2022-04-12 16:06:19 -06:00
|
|
|
let user = postgres
|
|
|
|
.get_session_user(token)
|
|
|
|
.await
|
|
|
|
.map_err(|_| http::StatusCode::FORBIDDEN)?;
|
2021-04-20 10:07:11 -06:00
|
|
|
|
2022-04-12 16:06:19 -06:00
|
|
|
Ok(user)
|
|
|
|
}
|
|
|
|
}
|
2021-04-20 10:07:11 -06:00
|
|
|
|
2022-04-12 16:06:19 -06:00
|
|
|
async fn teapot() -> impl IntoResponse {
|
|
|
|
(http::StatusCode::IM_A_TEAPOT, "☕")
|
|
|
|
}
|
|
|
|
pub fn router(postgres: Postgres, settings: Settings) -> Router {
|
|
|
|
Router::new()
|
|
|
|
.route("/", get(handlers::index))
|
|
|
|
.route("/sync/count", get(handlers::history::count))
|
|
|
|
.route("/sync/history", get(handlers::history::list))
|
2022-04-13 11:29:18 -06:00
|
|
|
.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))
|
|
|
|
.fallback(teapot.into_service())
|
|
|
|
.layer(Extension(postgres))
|
|
|
|
.layer(Extension(settings))
|
2021-04-20 10:07:11 -06:00
|
|
|
}
|