From 27d985114a3825ea1f9f4a284d56badf30dfb990 Mon Sep 17 00:00:00 2001
From: Awiteb
Date: Mon, 12 Aug 2024 13:15:47 +0000
Subject: [PATCH] feat: Add new memory storage
Signed-off-by: Awiteb
---
src/storage/memory_storage.rs | 182 ++++++++++++++++++++++++++++++++++
src/storage/mod.rs | 2 +
2 files changed, 184 insertions(+)
create mode 100644 src/storage/memory_storage.rs
diff --git a/src/storage/memory_storage.rs b/src/storage/memory_storage.rs
new file mode 100644
index 0000000..42e6b12
--- /dev/null
+++ b/src/storage/memory_storage.rs
@@ -0,0 +1,182 @@
+// Copyright (c) 2024, Awiteb
+// A captcha middleware for Salvo framework.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#![allow(warnings)]
+
+use std::{
+ collections::HashMap,
+ convert::Infallible,
+ time::{Duration, SystemTime},
+};
+use tokio::sync::RwLock;
+
+use crate::CaptchaStorage;
+
+/// Captcha storage implementation using an in-memory HashMap.
+#[derive(Debug)]
+pub struct MemoryStorage(RwLock>);
+
+impl MemoryStorage {
+ /// Create a new instance of [`MemoryStorage`].
+ pub fn new() -> Self {
+ Self(RwLock::new(HashMap::new()))
+ }
+}
+
+impl CaptchaStorage for MemoryStorage {
+ type Error = Infallible;
+
+ async fn store_answer(&self, answer: String) -> Result {
+ let token = uuid::Uuid::new_v4().to_string();
+ let mut write_lock = self.0.write().await;
+ write_lock.insert(token.clone(), (now(), answer));
+
+ Ok(token)
+ }
+
+ async fn get_answer(&self, token: &str) -> Result