1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! The flash message lib of Savlo web server framework. Read more: <https://salvo.rs>
#![doc(html_favicon_url = "https://salvo.rs/favicon-32x32.png")]
#![doc(html_logo_url = "https://salvo.rs/images/logo.svg")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(private_in_public, unreachable_pub)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::fmt::{self, Debug, Display, Formatter};
use std::ops::Deref;

use salvo_core::{async_trait, Depot, FlowCtrl, Handler, Request, Response};
use serde::{Deserialize, Serialize};

#[macro_use]
mod cfg;

cfg_feature! {
    #![feature = "cookie-store"]

    mod cookie_store;
    pub use cookie_store::CookieStore;

    /// Helper function to create a `CookieStore`.
    pub fn cookie_store() -> CookieStore {
        CookieStore::new()
    }
}

cfg_feature! {
    #![feature = "session-store"]

    mod session_store;
    pub use session_store::SessionStore;

    /// Helper function to create a `SessionStore`.
    pub fn session_store() -> SessionStore {
        SessionStore::new()
    }
}

/// Key for incoming flash messages in depot.
pub const INCOMING_FLASH_KEY: &str = "::salvo::flash::incoming_flash";

/// Key for outgoing flash messages in depot.
pub const OUTGOING_FLASH_KEY: &str = "::salvo::flash::outgoing_flash";

/// A flash is a list of messages.
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
pub struct Flash(pub Vec<FlashMessage>);
impl Flash {
    /// Add a new message with level `Debug`.
    #[inline]
    pub fn debug(&mut self, message: impl Into<String>) -> &mut Self {
        self.0.push(FlashMessage::debug(message));
        self
    }
    /// Add a new message with level `Info`.
    #[inline]
    pub fn info(&mut self, message: impl Into<String>) -> &mut Self {
        self.0.push(FlashMessage::info(message));
        self
    }
    /// Add a new message with level `Success`.
    #[inline]
    pub fn success(&mut self, message: impl Into<String>) -> &mut Self {
        self.0.push(FlashMessage::success(message));
        self
    }
    /// Add a new message with level `Waring`.
    #[inline]
    pub fn warning(&mut self, message: impl Into<String>) -> &mut Self {
        self.0.push(FlashMessage::warning(message));
        self
    }
    /// Add a new message with level `Error`.
    #[inline]
    pub fn error(&mut self, message: impl Into<String>) -> &mut Self {
        self.0.push(FlashMessage::warning(message));
        self
    }
}

impl Deref for Flash {
    type Target = Vec<FlashMessage>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A flash message.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct FlashMessage {
    /// Flash message level.
    pub level: FlashLevel,
    /// Flash message content.
    pub value: String,
}
impl FlashMessage {
    /// Create a new `FlashMessage` with `FlashLevel::Debug`.
    #[inline]
    pub fn debug(message: impl Into<String>) -> Self {
        Self {
            level: FlashLevel::Debug,
            value: message.into(),
        }
    }
    /// Create a new `FlashMessage` with `FlashLevel::Info`.
    #[inline]
    pub fn info(message: impl Into<String>) -> Self {
        Self {
            level: FlashLevel::Info,
            value: message.into(),
        }
    }
    /// Create a new `FlashMessage` with `FlashLevel::Success`.
    #[inline]
    pub fn success(message: impl Into<String>) -> Self {
        Self {
            level: FlashLevel::Success,
            value: message.into(),
        }
    }
    /// Create a new `FlashMessage` with `FlashLevel::Warning`.
    #[inline]
    pub fn warning(message: impl Into<String>) -> Self {
        Self {
            level: FlashLevel::Warning,
            value: message.into(),
        }
    }
    /// create a new `FlashMessage` with `FlashLevel::Error`.
    #[inline]
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            level: FlashLevel::Error,
            value: message.into(),
        }
    }
}

/// Verbosity level of a flash message.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum FlashLevel {
    #[allow(missing_docs)]
    Debug = 0,
    #[allow(missing_docs)]
    Info = 1,
    #[allow(missing_docs)]
    Success = 2,
    #[allow(missing_docs)]
    Warning = 3,
    #[allow(missing_docs)]
    Error = 4,
}
impl FlashLevel {
    /// Convert a `FlashLevel` to a `&str`.
    pub fn to_str(&self) -> &'static str {
        match self {
            FlashLevel::Debug => "debug",
            FlashLevel::Info => "info",
            FlashLevel::Success => "success",
            FlashLevel::Warning => "warning",
            FlashLevel::Error => "error",
        }
    }
}
impl Debug for FlashLevel {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_str())
    }
}

impl Display for FlashLevel {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_str())
    }
}

/// `FlashStore` is for stores flash messages.
#[async_trait]
pub trait FlashStore: Debug + Send + Sync + 'static {
    /// Get the flash messages from the store.
    async fn load_flash(&self, req: &mut Request, depot: &mut Depot) -> Option<Flash>;
    /// Save the flash messages to the store.
    async fn save_flash(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, flash: Flash);
    /// Clear the flash store.
    async fn clear_flash(&self, depot: &mut Depot, res: &mut Response);
}

/// FlashDepotExt
pub trait FlashDepotExt {
    /// Get incoming flash.
    fn incoming_flash(&mut self) -> Option<&Flash>;

    /// Get outgoing flash.
    fn outgoing_flash(&mut self) -> &Flash;
    /// Get mutable outgoing flash.
    fn outgoing_flash_mut(&mut self) -> &mut Flash;
}

impl FlashDepotExt for Depot {
    #[inline]
    fn incoming_flash(&mut self) -> Option<&Flash> {
        self.get::<Flash>(INCOMING_FLASH_KEY)
    }

    #[inline]
    fn outgoing_flash(&mut self) -> &Flash {
        self.get::<Flash>(OUTGOING_FLASH_KEY)
            .expect("Flash should be initialized")
    }

    #[inline]
    fn outgoing_flash_mut(&mut self) -> &mut Flash {
        self.get_mut::<Flash>(OUTGOING_FLASH_KEY)
            .expect("Flash should be initialized")
    }
}

/// FlashHandler
pub struct FlashHandler<S> {
    store: S,
    /// Minimum level of messages to be displayed.
    pub minimum_level: Option<FlashLevel>,
}
impl<S> FlashHandler<S> {
    /// Create a new `FlashHandler` with the given `FlashStore`.
    #[inline]
    pub fn new(store: S) -> Self {
        Self {
            store,
            minimum_level: None,
        }
    }

    /// Sets the minimum level of messages to be displayed.
    #[inline]
    pub fn minimum_level(&mut self, level: impl Into<Option<FlashLevel>>) -> &mut Self {
        self.minimum_level = level.into();
        self
    }
}
impl<S: FlashStore> fmt::Debug for FlashHandler<S> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("FlashHandler").field("store", &self.store).finish()
    }
}
#[async_trait]
impl<S> Handler for FlashHandler<S>
where
    S: FlashStore,
{
    async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
        let mut has_incoming = false;
        if let Some(flash) = self.store.load_flash(req, depot).await {
            has_incoming = !flash.is_empty();
            depot.insert(INCOMING_FLASH_KEY, flash);
        }
        depot.insert(OUTGOING_FLASH_KEY, Flash(vec![]));

        ctrl.call_next(req, depot, res).await;
        if ctrl.is_ceased() {
            return;
        }

        let mut flash = depot.remove::<Flash>(OUTGOING_FLASH_KEY).unwrap_or_default();
        if let Some(min_level) = self.minimum_level {
            flash.0.retain(|msg| msg.level >= min_level);
        }
        if !flash.is_empty() {
            self.store.save_flash(req, depot, res, flash).await;
        } else if has_incoming {
            self.store.clear_flash(depot, res).await;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write;

    use salvo_core::http::header::{COOKIE, SET_COOKIE};
    use salvo_core::prelude::*;
    use salvo_core::test::{ResponseExt, TestClient};
    use salvo_core::writer::Redirect;

    use super::*;

    #[handler]
    pub async fn set_flash(depot: &mut Depot, res: &mut Response) {
        let flash = depot.outgoing_flash_mut();
        flash.info("Hey there!").debug("How is it going?");
        res.render(Redirect::other("/get"));
    }

    #[handler]
    pub async fn get_flash(depot: &mut Depot, _res: &mut Response) -> String {
        let mut body = String::new();
        if let Some(flash) = depot.incoming_flash() {
            for message in flash.iter() {
                writeln!(body, "{} - {}", message.value, message.level).unwrap();
            }
        }
        body
    }

    #[cfg(feature = "cookie-store")]
    #[tokio::test]
    async fn test_cookie_store() {
        let cookie_name = "my-custom-cookie-name".to_string();
        let router = Router::new()
            .hoop(CookieStore::new().with_name(&cookie_name).into_handler())
            .push(Router::with_path("get").get(get_flash))
            .push(Router::with_path("set").get(set_flash));
        let service = Service::new(router);

        let respone = TestClient::get("http://127.0.0.1:7878/set").send(&service).await;
        assert_eq!(respone.status_code(), Some(StatusCode::SEE_OTHER));

        let cookie = respone.headers().get(SET_COOKIE).unwrap();
        assert!(cookie.to_str().unwrap().contains(&cookie_name));

        let mut respone = TestClient::get("http://127.0.0.1:7878/get")
            .add_header(COOKIE, cookie, true)
            .send(&service)
            .await;
        assert!(respone.take_string().await.unwrap().contains("Hey there!"));

        let cookie = respone.headers().get(SET_COOKIE).unwrap();
        assert!(cookie.to_str().unwrap().contains(&cookie_name));

        let mut respone = TestClient::get("http://127.0.0.1:7878/get")
            .add_header(COOKIE, cookie, true)
            .send(&service)
            .await;
        assert!(respone.take_string().await.unwrap().is_empty());
    }

    #[cfg(feature = "session-store")]
    #[tokio::test]
    async fn test_session_store() {
        let session_handler = salvo_session::SessionHandler::builder(
            salvo_session::MemoryStore::new(),
            b"secretabsecretabsecretabsecretabsecretabsecretabsecretabsecretab",
        )
        .build()
        .unwrap();

        let session_name = "my-custom-session-name".to_string();
        let router = Router::new()
            .hoop(session_handler)
            .hoop(SessionStore::new().with_name(&session_name).into_handler())
            .push(Router::with_path("get").get(get_flash))
            .push(Router::with_path("set").get(set_flash));
        let service = Service::new(router);

        let respone = TestClient::get("http://127.0.0.1:7878/set").send(&service).await;
        assert_eq!(respone.status_code(), Some(StatusCode::SEE_OTHER));

        let cookie = respone.headers().get(SET_COOKIE).unwrap();

        let mut respone = TestClient::get("http://127.0.0.1:7878/get")
            .add_header(COOKIE, cookie, true)
            .send(&service)
            .await;
        assert!(respone.take_string().await.unwrap().contains("Hey there!"));

        let mut respone = TestClient::get("http://127.0.0.1:7878/get")
            .add_header(COOKIE, cookie, true)
            .send(&service)
            .await;
        assert!(respone.take_string().await.unwrap().is_empty());
    }
}