From 2f35026022827cd86615135c6397f03b74fe1b46 Mon Sep 17 00:00:00 2001 From: Kjetil Orbekk Date: Fri, 25 Nov 2022 14:09:09 -0500 Subject: Hook up fake authenticator backend for testing --- server/src/fake_auth.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 6 deletions(-) (limited to 'server/src/fake_auth.rs') diff --git a/server/src/fake_auth.rs b/server/src/fake_auth.rs index 5ef9cc8..d19d858 100644 --- a/server/src/fake_auth.rs +++ b/server/src/fake_auth.rs @@ -1,13 +1,31 @@ -use std::collections::HashMap; +use std::{ + collections::HashMap, + env, + sync::{Arc, Mutex}, +}; use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use openidconnect::{RefreshToken, AccessToken}; +use reqwest::Url; +use tracing::info; use crate::{ - auth::{AuthenticatedSession, Authenticator, SessionId}, + auth::{AuthenticatedSession, Authenticator, SessionId, store_authenticated_session}, error::{self, BridgeError}, }; -pub struct FakeAuthenticator {} +pub struct FakeAuthenticator { + login_cache: Arc>>>, +} + +impl FakeAuthenticator { + pub fn new() -> Self { + Self { + login_cache: Arc::new(Mutex::new(HashMap::new())), + } + } +} #[async_trait] impl Authenticator for FakeAuthenticator { @@ -15,7 +33,15 @@ impl Authenticator for FakeAuthenticator { &self, session: &mut AuthenticatedSession, ) -> Result { - Err(BridgeError::NotLoggedIn) + let user: String = self + .login_cache + .lock() + .unwrap() + .get(&session.session_id) + .and_then(|u| u.as_ref()) + .ok_or(BridgeError::NotLoggedIn)? + .clone(); + Ok(user) } async fn authenticate( @@ -24,10 +50,34 @@ impl Authenticator for FakeAuthenticator { session_id: SessionId, auth_params: HashMap, ) -> Result { - Err(BridgeError::Internal("not implemented".to_string())) + let user = auth_params + .get("user") + .ok_or(BridgeError::Internal("missing 'user' param".to_string()))?; + self.login_cache + .lock() + .unwrap() + .insert(session_id.clone(), Some(user.clone())); + + let mut session = AuthenticatedSession::new( + user.clone(), + session_id, + Utc::now() + chrono::Duration::days(10000), + AccessToken::new("fake".to_string()), + RefreshToken::new("fake".to_string()), + ); + + store_authenticated_session(pool, &mut session).await?; + Ok(session) } async fn get_login_url(&self) -> (SessionId, reqwest::Url) { - todo!() + let auth_url = + Url::parse(&format!("{}/api/fake_login", env::var("APP_URL").unwrap())).unwrap(); + let user_id = SessionId::new(); + self.login_cache + .lock() + .unwrap() + .insert(user_id.clone(), None); + (user_id, auth_url) } } -- cgit v1.2.3