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
/* Copyright 2016 Joshua Gentry
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */
use std::any::Any;
use std::sync::{Arc, Mutex};

use iron::Request;
use time;

use FeSessionState;
use fe_session::FeSession;

//*************************************************************************************************
/// Helper trait that adds methods for accessing a user's session onto the Iron's Request object.
///
/// This trait provides the main interface for your handler to interact with the user's sessions.
///
/// # Examples
///
/// ```
/// # extern crate iron;
/// # extern crate fe_session;
/// use iron::{Iron, Chain, Request, Response};
/// use iron::status::Status;
/// use fe_session::{FeSessionStorage, FeSessionRequest, FeConnection};
///
/// struct MySession {
///     name : String
/// }
///
/// # fn main() {
/// let mut chain = Chain::new(|req : &mut Request| {
///     if req.url.path()[0] == "login" {
///         req.create_session(MySession { name : "john".to_string() }); // create the session
///         Ok(Response::with((Status::Ok, "hello")))
///     }
///     else if req.url.path()[0] == "view" {
///         let mut access = req.get_session::<MySession>();  // Access the session
///         let session_guard = access.get();
///
///         Ok(Response::with((Status::Ok, session_guard.name.clone())))
///     }
///     else if req.url.path()[0] == "logout" {
///         req.clear_session::<MySession>(); // Delete the session
///         Ok(Response::with((Status::Ok, "bye")))
///     }
///     else {
///         Ok(Response::with(Status::NotFound))
///     }
/// });
/// chain.around(FeSessionStorage::<MySession>::new());
///
/// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
///
/// let mut conn = FeConnection::new("localhost", 3000);
///
/// assert_eq!(conn.get_string("/login"), "hello");
/// assert_eq!(conn.get_string("/view"), "john");
/// assert_eq!(conn.get_string("/logout"), "bye");
///
/// iron.close().unwrap();
/// # }
/// ```
pub trait FeSessionRequest
{
    //********************************************************************************************
    /// Creates a new session on the request, removing the previous session if it exists.
    ///
    /// The client will also get a new session ID.  Any requests that come in with the old
    /// session ID will have a state of of "Expired".  This causes a set-cookie header to be
    /// included in the response so the client knows what cookie to send back in the future for
    /// this session.
    ///
    /// session - The custom session to use for this client.
    ///
    /// Returns the newly created FeSession object with a last access time of now.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeSessionRequest, FeSessionState, FeConnection};
    ///
    /// struct MySession;
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///     if req.url.path()[0] == "login" {
    ///         req.create_session(MySession); // create the session
    ///         Ok(Response::with((Status::Ok, "created")))
    ///     }
    ///     else if req.url.path()[0] == "status" {
    ///         let mut access = req.get_session::<MySession>();
    ///
    ///         let state = match access.state() {
    ///             FeSessionState::Active => "active",
    ///             FeSessionState::Expired => "expired",
    ///             FeSessionState::None => "none"
    ///         };
    ///
    ///         Ok(Response::with((Status::Ok, state)))
    ///     }
    ///     else {
    ///         Ok(Response::with(Status::NotFound))
    ///     }
    /// });
    /// chain.around(FeSessionStorage::<MySession>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn.get_string("/status"), "none");
    /// assert_eq!(conn.get_string("/login"), "created");
    /// assert_eq!(conn.get_string("/status"), "active");
    ///
    /// iron.close().unwrap();
    /// # }
    /// ```
    fn create_session<T : Any>(
        &mut self,
        session : T
        ) -> FeSession<T>;

    //********************************************************************************************
    /// Clears out the session from the request.
    ///
    /// If the session is currently active it will be deleted from memory.  The session cookie
    /// will also be cleared.  If the session is not currently active this method will not harm
    /// anything.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeSessionRequest, FeSessionState, FeConnection};
    ///
    /// struct MySession;
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///     if req.url.path()[0] == "login" {
    ///         req.create_session(MySession); // create the session
    ///         Ok(Response::with((Status::Ok, "hello")))
    ///     }
    ///     else if req.url.path()[0] == "status" {
    ///         let mut access = req.get_session::<MySession>();
    ///
    ///         let state = match access.state() {
    ///             FeSessionState::Active => "active",
    ///             FeSessionState::Expired => "expired",
    ///             FeSessionState::None => "none"
    ///         };
    ///
    ///         Ok(Response::with((Status::Ok, state)))
    ///     }
    ///     else if req.url.path()[0] == "logout" {
    ///         req.clear_session::<MySession>(); // Delete the session
    ///         Ok(Response::with((Status::Ok, "bye")))
    ///     }
    ///     else {
    ///         Ok(Response::with(Status::NotFound))
    ///     }
    /// });
    /// chain.around(FeSessionStorage::<MySession>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn.get_string("/login"), "hello");
    /// assert_eq!(conn.get_string("/status"), "active");
    /// assert_eq!(conn.get_string("/logout"), "bye");
    /// assert_eq!(conn.get_string("/status"), "none");
    ///
    /// iron.close().unwrap();
    /// # }
    fn clear_session<T : Any>(
        &mut self
        );

    //********************************************************************************************
    /// Returns the current session for the client.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate iron;
    /// # extern crate fe_session;
    /// use iron::{Iron, Chain, Request, Response};
    /// use iron::status::Status;
    /// use fe_session::{FeSessionStorage, FeSessionRequest, FeConnection};
    ///
    /// struct MySession {
    ///     name : String
    /// }
    ///
    /// # fn main() {
    /// let mut chain = Chain::new(|req : &mut Request| {
    ///     if req.url.path()[0] == "login" {
    ///         req.create_session(MySession { name : "john".to_string() }); // create the session
    ///         Ok(Response::with((Status::Ok, "hello")))
    ///     }
    ///     else if req.url.path()[0] == "view" {
    ///         let mut access = req.get_session::<MySession>();  // Access the session
    ///         let session_guard = access.get();
    ///
    ///         Ok(Response::with((Status::Ok, session_guard.name.clone())))
    ///     }
    ///     else if req.url.path()[0] == "logout" {
    ///         req.clear_session::<MySession>(); // Delete the session
    ///         Ok(Response::with((Status::Ok, "bye")))
    ///     }
    ///     else {
    ///         Ok(Response::with(Status::NotFound))
    ///     }
    /// });
    /// chain.around(FeSessionStorage::<MySession>::new());
    ///
    /// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
    ///
    /// let mut conn = FeConnection::new("localhost", 3000);
    ///
    /// assert_eq!(conn.get_string("/login"), "hello");
    /// assert_eq!(conn.get_string("/view"), "john");
    /// assert_eq!(conn.get_string("/logout"), "bye");
    ///
    /// iron.close().unwrap();
    /// # }
    /// ```
    ///
    /// # Panics
    /// If SessionStorage was not included in the iron chain.
    fn get_session<T : Any>(
        &self
        ) -> FeSession<T>;
}

impl<'a, 'b> FeSessionRequest for Request<'a, 'b>
{
    //*********************************************************************************************
    /// Implementation for create_session().
    ///
    /// Creates a new FeSession object passing it the user's session and stores it in the
    /// extensions object on the request.  Once the request is finished processing FeSessionStorage
    /// will pull the session out and store it in the session map.
    ///
    /// Returns the instance of FeSession that was created.
    fn create_session<T : Any>(
        &mut self,
        session : T
        ) -> FeSession<T>
    {
        let fe_session = FeSession::new(
            None,
            FeSessionState::Active,
            time::get_time(),
            Some(Arc::new(Mutex::new(session)))
            );

        self.extensions.insert::<FeSession<T>>(fe_session.clone());

        fe_session
    }

    //*********************************************************************************************
    /// Implementation for clear_session().
    ///
    /// Inserts an empty FeSession object into the extensions object of the request.  Once the
    /// request is finished processign FeSessionStorage will check the that the session is empty
    /// and tell the client to clear the session key.
    fn clear_session<T : Any>(&mut self)
    {
        self.extensions.insert::<FeSession<T>>(
            FeSession::new(None, FeSessionState::None, time::get_time(), None)
            );
    }

    //*********************************************************************************************
    /// Implementation for get_session().
    ///
    /// Grabs the FeSession instance from the extensions object in the request and returns a
    /// clone of it.
    fn get_session<T : Any>(&self) -> FeSession<T>
    {
        match self.extensions.get::<FeSession<T>>()
        {
            Some(session) => session.clone(),
            None          => panic!("Could not find session, verify that FeSessionStorage was added earlier in the chain.")
        }
    }
}