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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Route match predicates
#![allow(non_snake_case)]
use std::marker::PhantomData;

use http;
use http::{header, HttpTryFrom};
use server::message::Request;

/// Trait defines resource route predicate.
/// Predicate can modify request object. It is also possible to
/// to store extra attributes on request by using `Extensions` container,
/// Extensions container available via `HttpRequest::extensions()` method.
pub trait Predicate<S> {
    /// Check if request matches predicate
    fn check(&self, &Request, &S) -> bool;
}

/// Return predicate that matches if any of supplied predicate matches.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{pred, App, HttpResponse};
///
/// fn main() {
///     App::new().resource("/index.html", |r| {
///         r.route()
///             .filter(pred::Any(pred::Get()).or(pred::Post()))
///             .f(|r| HttpResponse::MethodNotAllowed())
///     });
/// }
/// ```
pub fn Any<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AnyPredicate<S> {
    AnyPredicate(vec![Box::new(pred)])
}

/// Matches if any of supplied predicate matches.
pub struct AnyPredicate<S>(Vec<Box<Predicate<S>>>);

impl<S> AnyPredicate<S> {
    /// Add new predicate to list of predicates to check
    pub fn or<P: Predicate<S> + 'static>(mut self, pred: P) -> Self {
        self.0.push(Box::new(pred));
        self
    }
}

impl<S: 'static> Predicate<S> for AnyPredicate<S> {
    fn check(&self, req: &Request, state: &S) -> bool {
        for p in &self.0 {
            if p.check(req, state) {
                return true;
            }
        }
        false
    }
}

/// Return predicate that matches if all of supplied predicate matches.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{pred, App, HttpResponse};
///
/// fn main() {
///     App::new().resource("/index.html", |r| {
///         r.route()
///             .filter(
///                 pred::All(pred::Get())
///                     .and(pred::Header("content-type", "text/plain")),
///             )
///             .f(|_| HttpResponse::MethodNotAllowed())
///     });
/// }
/// ```
pub fn All<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AllPredicate<S> {
    AllPredicate(vec![Box::new(pred)])
}

/// Matches if all of supplied predicate matches.
pub struct AllPredicate<S>(Vec<Box<Predicate<S>>>);

impl<S> AllPredicate<S> {
    /// Add new predicate to list of predicates to check
    pub fn and<P: Predicate<S> + 'static>(mut self, pred: P) -> Self {
        self.0.push(Box::new(pred));
        self
    }
}

impl<S: 'static> Predicate<S> for AllPredicate<S> {
    fn check(&self, req: &Request, state: &S) -> bool {
        for p in &self.0 {
            if !p.check(req, state) {
                return false;
            }
        }
        true
    }
}

/// Return predicate that matches if supplied predicate does not match.
pub fn Not<S: 'static, P: Predicate<S> + 'static>(pred: P) -> NotPredicate<S> {
    NotPredicate(Box::new(pred))
}

#[doc(hidden)]
pub struct NotPredicate<S>(Box<Predicate<S>>);

impl<S: 'static> Predicate<S> for NotPredicate<S> {
    fn check(&self, req: &Request, state: &S) -> bool {
        !self.0.check(req, state)
    }
}

/// Http method predicate
#[doc(hidden)]
pub struct MethodPredicate<S>(http::Method, PhantomData<S>);

impl<S: 'static> Predicate<S> for MethodPredicate<S> {
    fn check(&self, req: &Request, _: &S) -> bool {
        *req.method() == self.0
    }
}

/// Predicate to match *GET* http method
pub fn Get<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::GET, PhantomData)
}

/// Predicate to match *POST* http method
pub fn Post<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::POST, PhantomData)
}

/// Predicate to match *PUT* http method
pub fn Put<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::PUT, PhantomData)
}

/// Predicate to match *DELETE* http method
pub fn Delete<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::DELETE, PhantomData)
}

/// Predicate to match *HEAD* http method
pub fn Head<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::HEAD, PhantomData)
}

/// Predicate to match *OPTIONS* http method
pub fn Options<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::OPTIONS, PhantomData)
}

/// Predicate to match *CONNECT* http method
pub fn Connect<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::CONNECT, PhantomData)
}

/// Predicate to match *PATCH* http method
pub fn Patch<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::PATCH, PhantomData)
}

/// Predicate to match *TRACE* http method
pub fn Trace<S: 'static>() -> MethodPredicate<S> {
    MethodPredicate(http::Method::TRACE, PhantomData)
}

/// Predicate to match specified http method
pub fn Method<S: 'static>(method: http::Method) -> MethodPredicate<S> {
    MethodPredicate(method, PhantomData)
}

/// Return predicate that matches if request contains specified header and
/// value.
pub fn Header<S: 'static>(
    name: &'static str, value: &'static str,
) -> HeaderPredicate<S> {
    HeaderPredicate(
        header::HeaderName::try_from(name).unwrap(),
        header::HeaderValue::from_static(value),
        PhantomData,
    )
}

#[doc(hidden)]
pub struct HeaderPredicate<S>(header::HeaderName, header::HeaderValue, PhantomData<S>);

impl<S: 'static> Predicate<S> for HeaderPredicate<S> {
    fn check(&self, req: &Request, _: &S) -> bool {
        if let Some(val) = req.headers().get(&self.0) {
            return val == self.1;
        }
        false
    }
}

/// Return predicate that matches if request contains specified Host name.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{pred, App, HttpResponse};
///
/// fn main() {
///     App::new().resource("/index.html", |r| {
///         r.route()
///             .filter(pred::Host("www.rust-lang.org"))
///             .f(|_| HttpResponse::MethodNotAllowed())
///     });
/// }
/// ```
pub fn Host<S: 'static, H: AsRef<str>>(host: H) -> HostPredicate<S> {
    HostPredicate(host.as_ref().to_string(), None, PhantomData)
}

#[doc(hidden)]
pub struct HostPredicate<S>(String, Option<String>, PhantomData<S>);

impl<S> HostPredicate<S> {
    /// Set reuest scheme to match
    pub fn scheme<H: AsRef<str>>(&mut self, scheme: H) {
        self.1 = Some(scheme.as_ref().to_string())
    }
}

impl<S: 'static> Predicate<S> for HostPredicate<S> {
    fn check(&self, req: &Request, _: &S) -> bool {
        let info = req.connection_info();
        if let Some(ref scheme) = self.1 {
            self.0 == info.host() && scheme == info.scheme()
        } else {
            self.0 == info.host()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::{header, Method};
    use test::TestRequest;

    #[test]
    fn test_header() {
        let req = TestRequest::with_header(
            header::TRANSFER_ENCODING,
            header::HeaderValue::from_static("chunked"),
        ).finish();

        let pred = Header("transfer-encoding", "chunked");
        assert!(pred.check(&req, req.state()));

        let pred = Header("transfer-encoding", "other");
        assert!(!pred.check(&req, req.state()));

        let pred = Header("content-type", "other");
        assert!(!pred.check(&req, req.state()));
    }

    #[test]
    fn test_host() {
        let req = TestRequest::default()
            .header(
                header::HOST,
                header::HeaderValue::from_static("www.rust-lang.org"),
            ).finish();

        let pred = Host("www.rust-lang.org");
        assert!(pred.check(&req, req.state()));

        let pred = Host("localhost");
        assert!(!pred.check(&req, req.state()));
    }

    #[test]
    fn test_methods() {
        let req = TestRequest::default().finish();
        let req2 = TestRequest::default().method(Method::POST).finish();

        assert!(Get().check(&req, req.state()));
        assert!(!Get().check(&req2, req2.state()));
        assert!(Post().check(&req2, req2.state()));
        assert!(!Post().check(&req, req.state()));

        let r = TestRequest::default().method(Method::PUT).finish();
        assert!(Put().check(&r, r.state()));
        assert!(!Put().check(&req, req.state()));

        let r = TestRequest::default().method(Method::DELETE).finish();
        assert!(Delete().check(&r, r.state()));
        assert!(!Delete().check(&req, req.state()));

        let r = TestRequest::default().method(Method::HEAD).finish();
        assert!(Head().check(&r, r.state()));
        assert!(!Head().check(&req, req.state()));

        let r = TestRequest::default().method(Method::OPTIONS).finish();
        assert!(Options().check(&r, r.state()));
        assert!(!Options().check(&req, req.state()));

        let r = TestRequest::default().method(Method::CONNECT).finish();
        assert!(Connect().check(&r, r.state()));
        assert!(!Connect().check(&req, req.state()));

        let r = TestRequest::default().method(Method::PATCH).finish();
        assert!(Patch().check(&r, r.state()));
        assert!(!Patch().check(&req, req.state()));

        let r = TestRequest::default().method(Method::TRACE).finish();
        assert!(Trace().check(&r, r.state()));
        assert!(!Trace().check(&req, req.state()));
    }

    #[test]
    fn test_preds() {
        let r = TestRequest::default().method(Method::TRACE).finish();

        assert!(Not(Get()).check(&r, r.state()));
        assert!(!Not(Trace()).check(&r, r.state()));

        assert!(All(Trace()).and(Trace()).check(&r, r.state()));
        assert!(!All(Get()).and(Trace()).check(&r, r.state()));

        assert!(Any(Get()).or(Trace()).check(&r, r.state()));
        assert!(!Any(Get()).or(Get()).check(&r, r.state()));
    }
}