Can use Redis to store user sessions

This commit is contained in:
2025-12-04 18:11:27 +01:00
parent a2af039759
commit cb739ebe6d
8 changed files with 196 additions and 3 deletions

View File

@@ -1 +1,2 @@
pub mod auth_middleware;
pub mod multi_session_store;

View File

@@ -0,0 +1,63 @@
use actix_session::storage::{
CookieSessionStore, LoadError, RedisSessionStore, SaveError, SessionKey, SessionStore,
UpdateError,
};
use actix_web::cookie::time::Duration;
use jwt_simple::Error;
use std::collections::HashMap;
type SessionState = HashMap<String, String>;
/// Session store multiplexer.
///
/// Allows to easily support different store without having a lot of duplicate code
pub enum MultiSessionStore {
Cookie(CookieSessionStore),
Redis(RedisSessionStore),
}
impl SessionStore for MultiSessionStore {
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
match self {
MultiSessionStore::Cookie(c) => c.load(session_key).await,
MultiSessionStore::Redis(r) => r.load(session_key).await,
}
}
async fn save(
&self,
session_state: SessionState,
ttl: &Duration,
) -> Result<SessionKey, SaveError> {
match self {
MultiSessionStore::Cookie(c) => c.save(session_state, ttl).await,
MultiSessionStore::Redis(r) => r.save(session_state, ttl).await,
}
}
async fn update(
&self,
session_key: SessionKey,
session_state: SessionState,
ttl: &Duration,
) -> Result<SessionKey, UpdateError> {
match self {
MultiSessionStore::Cookie(c) => c.update(session_key, session_state, ttl).await,
MultiSessionStore::Redis(r) => r.update(session_key, session_state, ttl).await,
}
}
async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
match self {
MultiSessionStore::Cookie(c) => c.update_ttl(session_key, ttl).await,
MultiSessionStore::Redis(r) => r.update_ttl(session_key, ttl).await,
}
}
async fn delete(&self, session_key: &SessionKey) -> Result<(), Error> {
match self {
MultiSessionStore::Cookie(c) => c.delete(session_key).await,
MultiSessionStore::Redis(r) => r.delete(session_key).await,
}
}
}