Can use Redis to store user sessions
This commit is contained in:
@@ -1 +1,2 @@
|
||||
pub mod auth_middleware;
|
||||
pub mod multi_session_store;
|
||||
|
||||
63
src/middlewares/multi_session_store.rs
Normal file
63
src/middlewares/multi_session_store.rs
Normal 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user