diff options
author | rtkay123 <dev@kanjala.com> | 2025-07-23 18:54:11 +0200 |
---|---|---|
committer | rtkay123 <dev@kanjala.com> | 2025-07-23 18:54:11 +0200 |
commit | 579883b66bceefe7b50157401bccbf66a6c5d58e (patch) | |
tree | 709787bc94f512a8446f6d3650486ec6d5027bd0 /crates/auth/src/server/routes/discord | |
parent | 089efa225cc0a4e7be12608129ddbff28d11f320 (diff) | |
download | sellershut-579883b66bceefe7b50157401bccbf66a6c5d58e.tar.bz2 sellershut-579883b66bceefe7b50157401bccbf66a6c5d58e.zip |
feat(auth): tower session
Diffstat (limited to 'crates/auth/src/server/routes/discord')
-rw-r--r-- | crates/auth/src/server/routes/discord/discord_auth.rs | 41 |
1 files changed, 40 insertions, 1 deletions
diff --git a/crates/auth/src/server/routes/discord/discord_auth.rs b/crates/auth/src/server/routes/discord/discord_auth.rs index b07fa7a..5257a33 100644 --- a/crates/auth/src/server/routes/discord/discord_auth.rs +++ b/crates/auth/src/server/routes/discord/discord_auth.rs @@ -1,11 +1,24 @@ +use std::time::Duration; + +use anyhow::Context; use axum::{ extract::State, http::HeaderMap, response::{IntoResponse, Redirect}, }; use oauth2::{CsrfToken, Scope}; +use reqwest::header::SET_COOKIE; +use sqlx::types::uuid; +use tower_sessions::{ + SessionStore, + session::{Id, Record}, +}; -use crate::{error::AppError, state::AppHandle}; +use crate::{ + error::AppError, + server::{CSRF_TOKEN, OAUTH_CSRF_COOKIE}, + state::AppHandle, +}; pub async fn discord_auth(State(state): State<AppHandle>) -> Result<impl IntoResponse, AppError> { let (auth_url, csrf_token) = state @@ -14,7 +27,33 @@ pub async fn discord_auth(State(state): State<AppHandle>) -> Result<impl IntoRes .add_scope(Scope::new("identify".to_string())) .url(); + // Store the token in the session and retrieve the session cookie. + let session_id = Id(i128::from_le_bytes(uuid::Uuid::new_v4().to_bytes_le())); + let store = state.session_store.clone(); + + store + .create(&mut Record { + id: session_id, + data: [( + CSRF_TOKEN.to_string(), + serde_json::to_value(csrf_token).unwrap(), + )] + .into(), + expiry_date: time::OffsetDateTime::now_utc() + + Duration::from_secs(state.local_config.oauth.session_lifespan), + }) + .await + .unwrap(); + // .context("failed in inserting CSRF token into session")?; + + // Attach the session cookie to the response header + let cookie = + format!("{OAUTH_CSRF_COOKIE}={session_id}; SameSite=Lax; HttpOnly; Secure; Path=/"); let mut headers = HeaderMap::new(); + headers.insert( + SET_COOKIE, + cookie.parse().context("failed to parse cookie")?, + ); Ok((headers, Redirect::to(auth_url.as_ref()))) } |