1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 13:51:50 +01:00
This commit is contained in:
Nikolay Kim 2018-04-18 20:16:29 -07:00
parent ce1081432b
commit 48b02abee7
4 changed files with 31 additions and 32 deletions

View File

@ -3,8 +3,8 @@
//! [**IdentityService**](struct.IdentityService.html) middleware can be //! [**IdentityService**](struct.IdentityService.html) middleware can be
//! used with different policies types to store identity information. //! used with different policies types to store identity information.
//! //!
//! Bu default, only cookie identity policy is implemented. Other backend implementations //! Bu default, only cookie identity policy is implemented. Other backend
//! can be added separately. //! implementations can be added separately.
//! //!
//! [**CookieIdentityPolicy**](struct.CookieIdentityPolicy.html) //! [**CookieIdentityPolicy**](struct.CookieIdentityPolicy.html)
//! uses cookies as identity storage. //! uses cookies as identity storage.
@ -14,9 +14,9 @@
//! *HttpRequest* implements *RequestIdentity* trait. //! *HttpRequest* implements *RequestIdentity* trait.
//! //!
//! ```rust //! ```rust
//! use actix_web::*;
//! use actix_web::middleware::identity::RequestIdentity; //! use actix_web::middleware::identity::RequestIdentity;
//! use actix_web::middleware::identity::{IdentityService, CookieIdentityPolicy}; //! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
//! use actix_web::*;
//! //!
//! fn index(req: HttpRequest) -> Result<String> { //! fn index(req: HttpRequest) -> Result<String> {
//! // access request identity //! // access request identity
@ -33,17 +33,17 @@
//! } //! }
//! //!
//! fn logout(mut req: HttpRequest) -> HttpResponse { //! fn logout(mut req: HttpRequest) -> HttpResponse {
//! req.forget(); // <- remove identity //! req.forget(); // <- remove identity
//! HttpResponse::Ok().finish() //! HttpResponse::Ok().finish()
//! } //! }
//! //!
//! fn main() { //! fn main() {
//! let app = App::new().middleware( //! let app = App::new().middleware(IdentityService::new(
//! IdentityService::new( // <- create identity middleware //! // <- create identity middleware
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend //! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
//! .name("auth-cookie") //! .name("auth-cookie")
//! .secure(false)) //! .secure(false),
//! ); //! ));
//! } //! }
//! ``` //! ```
use std::rc::Rc; use std::rc::Rc;
@ -53,13 +53,12 @@ use futures::Future;
use futures::future::{FutureResult, err as FutErr, ok as FutOk}; use futures::future::{FutureResult, err as FutErr, ok as FutOk};
use time::Duration; use time::Duration;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use error::{Error, Result}; use error::{Error, Result};
use http::header::{self, HeaderValue}; use http::header::{self, HeaderValue};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use middleware::{Middleware, Response, Started}; use middleware::{Middleware, Response, Started};
/// The helper trait to obtain your identity from a request. /// The helper trait to obtain your identity from a request.
/// ///
/// ```rust /// ```rust
@ -87,7 +86,6 @@ use middleware::{Middleware, Response, Started};
/// # fn main() {} /// # fn main() {}
/// ``` /// ```
pub trait RequestIdentity { pub trait RequestIdentity {
/// Return the claimed identity of the user associated request or /// Return the claimed identity of the user associated request or
/// ``None`` if no identity can be found associated with the request. /// ``None`` if no identity can be found associated with the request.
fn identity(&self) -> Option<&str>; fn identity(&self) -> Option<&str>;
@ -95,34 +93,34 @@ pub trait RequestIdentity {
/// Remember identity. /// Remember identity.
fn remember(&mut self, identity: String); fn remember(&mut self, identity: String);
/// This method is used to 'forget' the current identity on subsequent requests. /// This method is used to 'forget' the current identity on subsequent
/// requests.
fn forget(&mut self); fn forget(&mut self);
} }
impl<S> RequestIdentity for HttpRequest<S> { impl<S> RequestIdentity for HttpRequest<S> {
fn identity(&self) -> Option<&str> { fn identity(&self) -> Option<&str> {
if let Some(id) = self.extensions_ro().get::<IdentityBox>() { if let Some(id) = self.extensions_ro().get::<IdentityBox>() {
return id.0.identity() return id.0.identity();
} }
None None
} }
fn remember(&mut self, identity: String) { fn remember(&mut self, identity: String) {
if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() { if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() {
return id.0.remember(identity) return id.0.remember(identity);
} }
} }
fn forget(&mut self) { fn forget(&mut self) {
if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() { if let Some(id) = self.extensions_mut().get_mut::<IdentityBox>() {
return id.0.forget() return id.0.forget();
} }
} }
} }
/// An identity /// An identity
pub trait Identity: 'static { pub trait Identity: 'static {
fn identity(&self) -> Option<&str>; fn identity(&self) -> Option<&str>;
fn remember(&mut self, key: String); fn remember(&mut self, key: String);
@ -177,7 +175,6 @@ unsafe impl Send for IdentityBox {}
#[doc(hidden)] #[doc(hidden)]
unsafe impl Sync for IdentityBox {} unsafe impl Sync for IdentityBox {}
impl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> { impl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> { fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
let mut req = req.clone(); let mut req = req.clone();
@ -194,7 +191,9 @@ impl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> {
Ok(Started::Future(Box::new(fut))) Ok(Started::Future(Box::new(fut)))
} }
fn response(&self, req: &mut HttpRequest<S>, resp: HttpResponse) -> Result<Response> { fn response(
&self, req: &mut HttpRequest<S>, resp: HttpResponse
) -> Result<Response> {
if let Some(mut id) = req.extensions().remove::<IdentityBox>() { if let Some(mut id) = req.extensions().remove::<IdentityBox>() {
id.0.write(resp) id.0.write(resp)
} else { } else {
@ -298,7 +297,7 @@ impl CookieIdentityInner {
let cookie_opt = jar.private(&self.key).get(&self.name); let cookie_opt = jar.private(&self.key).get(&self.name);
if let Some(cookie) = cookie_opt { if let Some(cookie) = cookie_opt {
return Some(cookie.value().into()) return Some(cookie.value().into());
} }
} }
} }
@ -334,7 +333,6 @@ impl CookieIdentityInner {
pub struct CookieIdentityPolicy(Rc<CookieIdentityInner>); pub struct CookieIdentityPolicy(Rc<CookieIdentityInner>);
impl CookieIdentityPolicy { impl CookieIdentityPolicy {
/// Construct new `CookieIdentityPolicy` instance. /// Construct new `CookieIdentityPolicy` instance.
/// ///
/// Panics if key length is less than 32 bytes. /// Panics if key length is less than 32 bytes.

View File

@ -9,11 +9,11 @@ mod logger;
pub mod cors; pub mod cors;
pub mod csrf; pub mod csrf;
#[cfg(feature = "session")]
pub mod identity;
mod defaultheaders; mod defaultheaders;
mod errhandlers; mod errhandlers;
#[cfg(feature = "session")] #[cfg(feature = "session")]
pub mod identity;
#[cfg(feature = "session")]
pub mod session; pub mod session;
pub use self::defaultheaders::DefaultHeaders; pub use self::defaultheaders::DefaultHeaders;
pub use self::errhandlers::ErrorHandlers; pub use self::errhandlers::ErrorHandlers;
@ -21,7 +21,8 @@ pub use self::logger::Logger;
#[cfg(feature = "session")] #[cfg(feature = "session")]
#[doc(hidden)] #[doc(hidden)]
#[deprecated(since = "0.5.4", note="please use `actix_web::middleware::session` instead")] #[deprecated(since = "0.5.4",
note = "please use `actix_web::middleware::session` instead")]
pub use self::session::{CookieSessionBackend, CookieSessionError, RequestSession, pub use self::session::{CookieSessionBackend, CookieSessionError, RequestSession,
Session, SessionBackend, SessionImpl, SessionStorage}; Session, SessionBackend, SessionImpl, SessionStorage};

View File

@ -9,10 +9,10 @@
//! backend implementations can be added. //! backend implementations can be added.
//! //!
//! [**CookieSessionBackend**](struct.CookieSessionBackend.html) //! [**CookieSessionBackend**](struct.CookieSessionBackend.html)
//! uses cookies as session storage. `CookieSessionBackend` creates sessions which //! uses cookies as session storage. `CookieSessionBackend` creates sessions
//! are limited to storing fewer than 4000 bytes of data, as the payload must fit into a //! which are limited to storing fewer than 4000 bytes of data, as the payload
//! single cookie. An internal server error is generated if a session contains //! must fit into a single cookie. An internal server error is generated if a
//! more than 4000 bytes. //! session contains more than 4000 bytes.
//! //!
//! A cookie may have a security policy of *signed* or *private*. Each has //! A cookie may have a security policy of *signed* or *private*. Each has
//! a respective `CookieSessionBackend` constructor. //! a respective `CookieSessionBackend` constructor.

View File

@ -916,7 +916,6 @@ fn test_resource_middlewares() {
// assert_eq!(num3.load(Ordering::Relaxed), 1); // assert_eq!(num3.load(Ordering::Relaxed), 1);
} }
fn index_test_middleware_async_error(_: HttpRequest) -> FutureResponse<HttpResponse> { fn index_test_middleware_async_error(_: HttpRequest) -> FutureResponse<HttpResponse> {
future::result(Err(error::ErrorBadRequest("TEST"))).responder() future::result(Err(error::ErrorBadRequest("TEST"))).responder()
} }
@ -936,7 +935,8 @@ fn test_middleware_async_error() {
start: Arc::clone(&act_req), start: Arc::clone(&act_req),
response: Arc::clone(&act_resp), response: Arc::clone(&act_resp),
finish: Arc::clone(&act_fin), finish: Arc::clone(&act_fin),
}).handler(index_test_middleware_async_error)}); }).handler(index_test_middleware_async_error)
});
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();