|
|
|
use actix_session::Session;
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
|
|
|
|
pub trait SessionExt {
|
|
|
|
/// Get a `value` from the session.
|
|
|
|
fn take<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, actix_web::error::Error>;
|
|
|
|
|
|
|
|
fn render_flash(&self, context: &mut tera::Context);
|
|
|
|
|
|
|
|
fn flash_error(&self, msg: impl AsRef<str>);
|
|
|
|
|
|
|
|
fn flash_success(&self, msg: impl AsRef<str>);
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SessionExt for Session {
|
|
|
|
fn take<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, actix_web::error::Error> {
|
|
|
|
let val = self.get(key);
|
|
|
|
self.remove(key); // Always remove, even if parsing failed
|
|
|
|
Ok(val?)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn render_flash(&self, context: &mut tera::Context) {
|
|
|
|
if let Ok(Some(msg)) = self.take::<String>("flash_error") {
|
|
|
|
context.insert("flash_error", &msg);
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Ok(Some(msg)) = self.take::<String>("flash_success") {
|
|
|
|
context.insert("flash_success", &msg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flash_error(&self, msg: impl AsRef<str>) {
|
|
|
|
self.set("flash_error", msg.as_ref()).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flash_success(&self, msg: impl AsRef<str>) {
|
|
|
|
self.set("flash_success", msg.as_ref()).unwrap();
|
|
|
|
}
|
|
|
|
}
|