From ffd2c04cd385fdb8bc215e04a45a42e4ff58cd31 Mon Sep 17 00:00:00 2001
From: Nikolay Kim <fafhrd91@gmail.com>
Date: Sun, 28 Apr 2019 09:08:51 -0700
Subject: [PATCH] Add helper trait UserSession which allows to get session for
 ServiceRequest and HttpRequest

---
 actix-session/CHANGES.md |  4 ++++
 actix-session/src/lib.rs | 31 +++++++++++++++++++++++++++++++
 2 files changed, 35 insertions(+)

diff --git a/actix-session/CHANGES.md b/actix-session/CHANGES.md
index a60d1e66..8e06a562 100644
--- a/actix-session/CHANGES.md
+++ b/actix-session/CHANGES.md
@@ -1,5 +1,9 @@
 # Changes
 
+## [0.1.0-beta.2] - 2019-04-28
+
+* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
+
 ## [0.1.0-beta.1] - 2019-04-20
 
 * Update actix-web to beta.1
diff --git a/actix-session/src/lib.rs b/actix-session/src/lib.rs
index b8202964..0e783144 100644
--- a/actix-session/src/lib.rs
+++ b/actix-session/src/lib.rs
@@ -79,6 +79,23 @@ pub use crate::cookie::CookieSession;
 /// ```
 pub struct Session(Rc<RefCell<SessionInner>>);
 
+/// Helper trait that allows to get session
+pub trait UserSession {
+    fn get_session(&mut self) -> Session;
+}
+
+impl UserSession for HttpRequest {
+    fn get_session(&mut self) -> Session {
+        Session::get_session(&mut *self.extensions_mut())
+    }
+}
+
+impl UserSession for ServiceRequest {
+    fn get_session(&mut self) -> Session {
+        Session::get_session(&mut *self.extensions_mut())
+    }
+}
+
 #[derive(Default)]
 struct SessionInner {
     state: HashMap<String, String>,
@@ -208,4 +225,18 @@ mod tests {
         let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
         assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
     }
+
+    #[test]
+    fn get_session() {
+        let mut req = test::TestRequest::default().to_srv_request();
+
+        Session::set_session(
+            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
+            &mut req,
+        );
+
+        let session = req.get_session();
+        let res = session.get::<String>("key").unwrap();
+        assert_eq!(res, Some("value".to_string()));
+    }
 }