From ee769832cf5b8dfafbd2543bdb46c949c670f05c Mon Sep 17 00:00:00 2001 From: Bob Date: Wed, 12 Jun 2019 11:26:46 +0800 Subject: [PATCH] get_identity from HttpMessage (#908) * get_identity from HttpMessage * more doc for RequestIdentity --- CHANGES.md | 11 +++++++++++ src/middleware/identity.rs | 34 ++++++++++++++++++++++++++++------ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 07991142e..3e9265258 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,16 @@ # Changes +## [1.0.x] - 2019-xx-xx + +### Add + +* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`. + +### Changes + +### Fixed + + ## [1.0.0] - 2019-06-05 ### Add diff --git a/src/middleware/identity.rs b/src/middleware/identity.rs index 82ae01542..304df9eb2 100644 --- a/src/middleware/identity.rs +++ b/src/middleware/identity.rs @@ -61,7 +61,10 @@ use crate::cookie::{Cookie, CookieJar, Key, SameSite}; use crate::error::{Error, Result}; use crate::http::header::{self, HeaderValue}; use crate::service::{ServiceRequest, ServiceResponse}; -use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest}; +use crate::{ + dev::{Extensions, Payload}, + FromRequest, HttpMessage, HttpRequest, +}; /// The extractor type to obtain your identity from a request. /// @@ -96,11 +99,7 @@ impl Identity { /// Return the claimed identity of the user associated request or /// ``None`` if no identity can be found associated with the request. pub fn identity(&self) -> Option { - if let Some(id) = self.0.extensions().get::() { - id.id.clone() - } else { - None - } + Identity::get_identity(&self.0.extensions()) } /// Remember identity. @@ -119,6 +118,14 @@ impl Identity { id.changed = true; } } + + fn get_identity(extensions: &Extensions) -> Option { + if let Some(id) = extensions.get::() { + id.id.clone() + } else { + None + } + } } struct IdentityItem { @@ -126,6 +133,21 @@ struct IdentityItem { changed: bool, } +/// Helper trait that allows to get Identity. +/// It could be used in middleware but identity policy must be set before any other middleware that needs identity +pub trait RequestIdentity { + fn get_identity(&self) -> Option; +} + +impl RequestIdentity for T +where + T: HttpMessage, +{ + fn get_identity(&self) -> Option { + Identity::get_identity(&self.extensions()) + } +} + /// Extractor implementation for Identity type. /// /// ```rust