Skip to content

Commit

Permalink
add proper session mgmt
Browse files Browse the repository at this point in the history
  • Loading branch information
untitaker committed Nov 21, 2024
1 parent 14145ea commit 17255de
Show file tree
Hide file tree
Showing 6 changed files with 225 additions and 22 deletions.
109 changes: 109 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ maud = "0.26.0"
sentry = { version = "0.34.0", features = ["tracing", "reqwest", "rustls"], default-features = false }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tower-sessions = "0.13.0"
time = "0.3.36"
33 changes: 33 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::{request::Parts, StatusCode};
use tower_sessions::Session;

use crate::AccountPk;
use crate::ResponseError;

pub const SESSION_COOKIE_KEY: &str = "auth";

pub struct LoggedIn {
pub account: Option<AccountPk>,
}

impl LoggedIn {
pub fn account(&self) -> Result<AccountPk, ResponseError> {
self.account.clone().ok_or(ResponseError::NeedsAuth)
}
}

#[async_trait]
impl<S> FromRequestParts<S> for LoggedIn
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);

async fn from_request_parts(req: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let session = Session::from_request_parts(req, state).await?;
let account: Option<AccountPk> = session.get(SESSION_COOKIE_KEY).await.unwrap();
Ok(LoggedIn { account })
}
}
15 changes: 12 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
response::{IntoResponse, Redirect, Response},
};
use reqwest::header::InvalidHeaderValue;
use tokio::task::JoinError;
Expand All @@ -17,11 +17,20 @@ pub enum ResponseError {
InvalidHeader(#[from] InvalidHeaderValue),
#[error("invalid JSON input: {0}")]
Json(#[from] serde_json::Error),
#[error("failed to update session")]
Session(#[from] tower_sessions::session::Error),
#[error("no login found")]
NeedsAuth,
}

impl IntoResponse for ResponseError {
fn into_response(self) -> Response {
tracing::error!("error while serving request: {}", self);
(StatusCode::INTERNAL_SERVER_ERROR, format!("{}\n", self)).into_response()
match self {
ResponseError::NeedsAuth => Redirect::to("/").into_response(),
_ => {
tracing::error!("error while serving request: {}", self);
(StatusCode::INTERNAL_SERVER_ERROR, format!("{}\n", self)).into_response()
}
}
}
}
Loading

0 comments on commit 17255de

Please sign in to comment.