use async_trait::async_trait;
use vti_common::auth::backend::SessionStore;
use vti_common::auth::session::{Session, SessionState};
use crate::server::auth::session;
use crate::server::error::AppError;
use crate::server::store::KeyspaceHandle;
#[derive(Clone)]
pub struct DidHostingSessionStore {
inner: KeyspaceHandle,
}
impl DidHostingSessionStore {
pub fn new(inner: KeyspaceHandle) -> Self {
Self { inner }
}
pub fn handle(&self) -> &KeyspaceHandle {
&self.inner
}
}
#[async_trait]
impl SessionStore for DidHostingSessionStore {
type Error = AppError;
async fn store_session(&self, s: &Session) -> Result<(), Self::Error> {
session::store_session(&self.inner, s).await
}
async fn get_session(&self, session_id: &str) -> Result<Option<Session>, Self::Error> {
session::get_session(&self.inner, session_id).await
}
async fn delete_session(&self, session_id: &str) -> Result<(), Self::Error> {
session::delete_session(&self.inner, session_id).await
}
async fn take_session(&self, session_id: &str) -> Result<Option<Session>, Self::Error> {
session::take_session(&self.inner, session_id).await
}
async fn store_refresh_index(
&self,
refresh_token: &str,
session_id: &str,
) -> Result<(), Self::Error> {
session::store_refresh_index(&self.inner, refresh_token, session_id).await
}
async fn take_session_id_by_refresh(
&self,
refresh_token: &str,
) -> Result<Option<String>, Self::Error> {
session::take_session_id_by_refresh(&self.inner, refresh_token).await
}
async fn count_pending_challenges(&self, did: &str) -> Result<usize, Self::Error> {
let entries = self.inner.prefix_iter_raw("session:").await?;
let mut count = 0usize;
for (_key, value) in entries {
if let Ok(s) = serde_json::from_slice::<Session>(&value)
&& s.did == did
&& s.state == SessionState::ChallengeSent
{
count += 1;
}
}
Ok(count)
}
}