1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00
actix-web/src/guard.rs

376 lines
10 KiB
Rust
Raw Normal View History

2019-03-03 21:09:38 +01:00
//! Route match guards.
2019-03-08 00:37:39 +01:00
//!
//! Guards are one of the way how actix-web router chooses
//! handler service. In essence it just function that accepts
//! reference to a `RequestHead` instance and returns boolean.
//! It is possible to add guards to *scopes*, *resources*
//! and *routes*. Actix provide several guards by default, like various
//! http methods, header, etc. To become a guard, type must implement `Guard`
//! trait. Simple functions coulds guards as well.
//!
//! Guard can not modify request object. But it is possible to
//! to store extra attributes on a request by using `Extensions` container.
//! Extensions container available via `RequestHead::extensions()` method.
//!
//! ```rust
//! use actix_web::{web, http, dev, guard, App, HttpResponse};
//!
//! fn main() {
//! App::new().service(web::resource("/index.html").route(
//! web::route()
//! .guard(guard::Post())
//! .guard(|head: &dev::RequestHead| head.method == http::Method::GET)
//! .to(|| HttpResponse::MethodNotAllowed()))
//! );
//! }
//! ```
2019-03-02 07:51:32 +01:00
#![allow(non_snake_case)]
use actix_http::http::{self, header, HttpTryFrom};
use actix_http::RequestHead;
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
/// Trait defines resource guards. Guards are used for routes selection.
///
/// Guard can not modify request object. But it is possible to
2019-03-02 07:51:32 +01:00
/// to store extra attributes on request by using `Extensions` container,
2019-03-03 21:09:38 +01:00
/// Extensions container available via `RequestHead::extensions()` method.
pub trait Guard {
2019-03-02 07:51:32 +01:00
/// Check if request matches predicate
fn check(&self, request: &RequestHead) -> bool;
2019-03-02 07:51:32 +01:00
}
2019-03-08 00:37:39 +01:00
#[doc(hidden)]
pub struct FnGuard<F: Fn(&RequestHead) -> bool + 'static>(F);
impl<F> Guard for F
where
F: Fn(&RequestHead) -> bool + 'static,
{
fn check(&self, head: &RequestHead) -> bool {
(*self)(head)
}
}
2019-03-03 21:09:38 +01:00
/// Return guard that matches if any of supplied guards.
2019-03-02 07:51:32 +01:00
///
/// ```rust
2019-03-03 21:09:38 +01:00
/// use actix_web::{web, guard, App, HttpResponse};
2019-03-02 07:51:32 +01:00
///
/// fn main() {
/// App::new().service(web::resource("/index.html").route(
/// web::route()
/// .guard(guard::Any(guard::Get()).or(guard::Post()))
/// .to(|| HttpResponse::MethodNotAllowed()))
/// );
2019-03-02 07:51:32 +01:00
/// }
/// ```
2019-03-03 21:09:38 +01:00
pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
AnyGuard(vec![Box::new(guard)])
2019-03-02 07:51:32 +01:00
}
2019-03-03 21:09:38 +01:00
/// Matches if any of supplied guards matche.
pub struct AnyGuard(Vec<Box<Guard>>);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
impl AnyGuard {
/// Add guard to a list of guards to check
pub fn or<F: Guard + 'static>(mut self, guard: F) -> Self {
self.0.push(Box::new(guard));
2019-03-02 07:51:32 +01:00
self
}
}
2019-03-03 21:09:38 +01:00
impl Guard for AnyGuard {
fn check(&self, req: &RequestHead) -> bool {
2019-03-02 07:51:32 +01:00
for p in &self.0 {
if p.check(req) {
return true;
}
}
false
}
}
2019-03-03 21:09:38 +01:00
/// Return guard that matches if all of the supplied guards.
2019-03-02 07:51:32 +01:00
///
2019-03-03 01:24:14 +01:00
/// ```rust
2019-03-02 07:51:32 +01:00
/// # extern crate actix_web;
2019-03-03 21:09:38 +01:00
/// use actix_web::{guard, web, App, HttpResponse};
2019-03-02 07:51:32 +01:00
///
/// fn main() {
/// App::new().service(web::resource("/index.html").route(
/// web::route()
2019-03-03 21:09:38 +01:00
/// .guard(
/// guard::All(guard::Get()).and(guard::Header("content-type", "text/plain")))
2019-03-03 01:24:14 +01:00
/// .to(|| HttpResponse::MethodNotAllowed()))
/// );
2019-03-02 07:51:32 +01:00
/// }
/// ```
2019-03-03 21:09:38 +01:00
pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
AllGuard(vec![Box::new(guard)])
2019-03-02 07:51:32 +01:00
}
2019-03-03 21:09:38 +01:00
/// Matches if all of supplied guards.
pub struct AllGuard(Vec<Box<Guard>>);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
impl AllGuard {
/// Add new guard to the list of guards to check
pub fn and<F: Guard + 'static>(mut self, guard: F) -> Self {
self.0.push(Box::new(guard));
2019-03-02 07:51:32 +01:00
self
}
}
2019-03-03 21:09:38 +01:00
impl Guard for AllGuard {
fn check(&self, request: &RequestHead) -> bool {
2019-03-02 07:51:32 +01:00
for p in &self.0 {
if !p.check(request) {
return false;
}
}
true
}
}
2019-03-03 21:09:38 +01:00
/// Return guard that matches if supplied guard does not match.
pub fn Not<F: Guard + 'static>(guard: F) -> NotGuard {
NotGuard(Box::new(guard))
2019-03-02 07:51:32 +01:00
}
#[doc(hidden)]
2019-03-03 21:09:38 +01:00
pub struct NotGuard(Box<Guard>);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
impl Guard for NotGuard {
fn check(&self, request: &RequestHead) -> bool {
2019-03-02 07:51:32 +01:00
!self.0.check(request)
}
}
2019-03-03 21:09:38 +01:00
/// Http method guard
2019-03-02 07:51:32 +01:00
#[doc(hidden)]
2019-03-03 21:09:38 +01:00
pub struct MethodGuard(http::Method);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
impl Guard for MethodGuard {
fn check(&self, request: &RequestHead) -> bool {
request.method == self.0
2019-03-02 07:51:32 +01:00
}
}
2019-03-03 21:09:38 +01:00
/// Guard to match *GET* http method
pub fn Get() -> MethodGuard {
MethodGuard(http::Method::GET)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *POST* http method
2019-03-03 21:09:38 +01:00
pub fn Post() -> MethodGuard {
MethodGuard(http::Method::POST)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *PUT* http method
2019-03-03 21:09:38 +01:00
pub fn Put() -> MethodGuard {
MethodGuard(http::Method::PUT)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *DELETE* http method
2019-03-03 21:09:38 +01:00
pub fn Delete() -> MethodGuard {
MethodGuard(http::Method::DELETE)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *HEAD* http method
2019-03-03 21:09:38 +01:00
pub fn Head() -> MethodGuard {
MethodGuard(http::Method::HEAD)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *OPTIONS* http method
2019-03-03 21:09:38 +01:00
pub fn Options() -> MethodGuard {
MethodGuard(http::Method::OPTIONS)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *CONNECT* http method
2019-03-03 21:09:38 +01:00
pub fn Connect() -> MethodGuard {
MethodGuard(http::Method::CONNECT)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *PATCH* http method
2019-03-03 21:09:38 +01:00
pub fn Patch() -> MethodGuard {
MethodGuard(http::Method::PATCH)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match *TRACE* http method
2019-03-03 21:09:38 +01:00
pub fn Trace() -> MethodGuard {
MethodGuard(http::Method::TRACE)
2019-03-02 07:51:32 +01:00
}
/// Predicate to match specified http method
2019-03-03 21:09:38 +01:00
pub fn Method(method: http::Method) -> MethodGuard {
MethodGuard(method)
2019-03-02 07:51:32 +01:00
}
/// Return predicate that matches if request contains specified header and
/// value.
2019-03-03 21:09:38 +01:00
pub fn Header(name: &'static str, value: &'static str) -> HeaderGuard {
HeaderGuard(
2019-03-02 07:51:32 +01:00
header::HeaderName::try_from(name).unwrap(),
header::HeaderValue::from_static(value),
)
}
#[doc(hidden)]
2019-03-03 21:09:38 +01:00
pub struct HeaderGuard(header::HeaderName, header::HeaderValue);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
impl Guard for HeaderGuard {
fn check(&self, req: &RequestHead) -> bool {
if let Some(val) = req.headers.get(&self.0) {
2019-03-02 07:51:32 +01:00
return val == self.1;
}
false
}
}
2019-03-03 01:24:14 +01:00
// /// Return predicate that matches if request contains specified Host name.
// ///
// /// ```rust,ignore
// /// # extern crate actix_web;
// /// use actix_web::{pred, App, HttpResponse};
// ///
// /// fn main() {
// /// App::new().resource("/index.html", |r| {
// /// r.route()
2019-03-03 21:09:38 +01:00
// /// .guard(pred::Host("www.rust-lang.org"))
2019-03-03 01:24:14 +01:00
// /// .f(|_| HttpResponse::MethodNotAllowed())
// /// });
// /// }
// /// ```
2019-03-03 21:09:38 +01:00
// pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {
// HostGuard(host.as_ref().to_string(), None)
2019-03-03 01:24:14 +01:00
// }
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
// #[doc(hidden)]
2019-03-03 21:09:38 +01:00
// pub struct HostGuard(String, Option<String>);
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
// impl HostGuard {
2019-03-03 01:24:14 +01:00
// /// Set reuest scheme to match
// pub fn scheme<H: AsRef<str>>(&mut self, scheme: H) {
// self.1 = Some(scheme.as_ref().to_string())
2019-03-02 07:51:32 +01:00
// }
2019-03-03 01:24:14 +01:00
// }
2019-03-02 07:51:32 +01:00
2019-03-03 21:09:38 +01:00
// impl Guard for HostGuard {
// fn check(&self, _req: &RequestHead) -> bool {
2019-03-03 01:24:14 +01:00
// // let info = req.connection_info();
// // if let Some(ref scheme) = self.1 {
// // self.0 == info.host() && scheme == info.scheme()
// // } else {
// // self.0 == info.host()
// // }
// false
2019-03-02 07:51:32 +01:00
// }
2019-03-03 01:24:14 +01:00
// }
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
#[cfg(test)]
mod tests {
use actix_http::http::{header, Method};
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
use super::*;
2019-03-03 07:03:45 +01:00
use crate::test::TestRequest;
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
#[test]
fn test_header() {
2019-03-03 07:03:45 +01:00
let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked")
.to_http_request();
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
let pred = Header("transfer-encoding", "chunked");
assert!(pred.check(&req));
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
let pred = Header("transfer-encoding", "other");
assert!(!pred.check(&req));
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
let pred = Header("content-type", "other");
assert!(!pred.check(&req));
}
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
// #[test]
// fn test_host() {
// let req = TestServiceRequest::default()
// .header(
// header::HOST,
// header::HeaderValue::from_static("www.rust-lang.org"),
// )
// .request();
// let pred = Host("www.rust-lang.org");
// assert!(pred.check(&req));
// let pred = Host("localhost");
// assert!(!pred.check(&req));
// }
#[test]
fn test_methods() {
let req = TestRequest::default().to_http_request();
2019-03-03 07:03:45 +01:00
let req2 = TestRequest::default()
2019-03-03 01:24:14 +01:00
.method(Method::POST)
.to_http_request();
2019-03-03 01:24:14 +01:00
assert!(Get().check(&req));
assert!(!Get().check(&req2));
assert!(Post().check(&req2));
assert!(!Post().check(&req));
let r = TestRequest::default().method(Method::PUT).to_http_request();
assert!(Put().check(&r));
assert!(!Put().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::DELETE)
.to_http_request();
assert!(Delete().check(&r));
assert!(!Delete().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::HEAD)
.to_http_request();
assert!(Head().check(&r));
assert!(!Head().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::OPTIONS)
.to_http_request();
assert!(Options().check(&r));
assert!(!Options().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::CONNECT)
.to_http_request();
assert!(Connect().check(&r));
assert!(!Connect().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::PATCH)
.to_http_request();
assert!(Patch().check(&r));
assert!(!Patch().check(&req));
2019-03-03 01:24:14 +01:00
let r = TestRequest::default()
.method(Method::TRACE)
.to_http_request();
assert!(Trace().check(&r));
assert!(!Trace().check(&req));
2019-03-03 01:24:14 +01:00
}
2019-03-02 07:51:32 +01:00
2019-03-03 01:24:14 +01:00
#[test]
fn test_preds() {
2019-03-04 06:02:01 +01:00
let r = TestRequest::default()
.method(Method::TRACE)
.to_http_request();
2019-03-02 07:51:32 +01:00
assert!(Not(Get()).check(&r));
assert!(!Not(Trace()).check(&r));
2019-03-02 07:51:32 +01:00
assert!(All(Trace()).and(Trace()).check(&r));
assert!(!All(Get()).and(Trace()).check(&r));
2019-03-02 07:51:32 +01:00
assert!(Any(Get()).or(Trace()).check(&r));
assert!(!Any(Get()).or(Get()).check(&r));
2019-03-03 01:24:14 +01:00
}
}