summaryrefslogtreecommitdiffstats
path: root/crates/auth/src/server/csrf_token_validation.rs
blob: 94424c8993e4365017fbb50b0fd15e52e71863fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use anyhow::{Context, anyhow};
use oauth2::CsrfToken;
use tower_sessions::{CachingSessionStore, SessionStore, session::Id};
use tower_sessions_moka_store::MokaStore;
use tower_sessions_sqlx_store::PostgresStore;

use crate::{
    error::AppError,
    server::{CSRF_TOKEN, routes::authorised::AuthRequest},
};

pub async fn csrf_token_validation_workflow(
    auth_request: &AuthRequest,
    store: &CachingSessionStore<MokaStore, PostgresStore>,
    oauth_session_id: Id,
) -> Result<(), AppError> {
    let oauth_session = store.load(&oauth_session_id).await.unwrap().unwrap();

    // Extract the CSRF token from the session
    let csrf_token_serialized = oauth_session
        .data
        .get(CSRF_TOKEN)
        .context("failed to get value from session")?;
    let csrf_token = serde_json::from_value::<CsrfToken>(csrf_token_serialized.clone())
        .context("CSRF token not found in session")?
        .to_owned();

    // Cleanup the CSRF token session
    store
        .delete(&oauth_session_id)
        .await
        .context("Failed to destroy old session")?;

    // Validate CSRF token is the same as the one in the auth request
    if *csrf_token.secret() != auth_request.state {
        return Err(anyhow!("CSRF token mismatch").into());
    }

    Ok(())
}