actix_web_middleware_redirect_scheme/
scheme.rs

1use crate::service::RedirectSchemeService;
2use actix_service::{Service, Transform};
3use actix_web::dev::{ServiceRequest, ServiceResponse};
4use actix_web::Error;
5use futures::future::{ok, Ready};
6
7/// Middleware for `actix-web` which redirects between `http` and `https` requests with optional url
8/// string replacements.
9///
10/// ## Usage
11/// ```
12/// extern crate actix_web_middleware_redirect_scheme;
13///
14/// use actix_web::{App, web, HttpResponse};
15/// use actix_web_middleware_redirect_scheme::RedirectSchemeBuilder;
16///
17/// App::new()
18///     .wrap(RedirectSchemeBuilder::new().temporary().build())
19///     .route("/", web::get().to(|| HttpResponse::Ok()
20///                                     .content_type("text/plain")
21///                                     .body("Always HTTPS!")));
22/// ```
23#[derive(Default, Clone)]
24pub struct RedirectScheme {
25    // Disabled redirections
26    pub disable: bool,
27    // Redirect to HTTP (true: HTTP -> HTTPS, false: HTTPS -> HTTP)
28    pub https_to_http: bool,
29    // Temporary redirect (true: 307 Temporary Redirect, false: 301 Moved Permanently)
30    pub temporary: bool,
31    // List of string replacements
32    pub replacements: Vec<(String, String)>,
33}
34
35impl RedirectScheme {
36    /// Creates a RedirectScheme middleware.
37    ///
38    /// ## Usage
39    /// ```
40    /// extern crate actix_web_middleware_redirect_scheme;
41    ///
42    /// use actix_web::{App, web, HttpResponse};
43    /// use actix_web_middleware_redirect_scheme::RedirectScheme;
44    ///
45    /// App::new()
46    ///     .wrap(RedirectScheme::simple(false))
47    ///     .route("/", web::get().to(|| HttpResponse::Ok()
48    ///                                     .content_type("text/plain")
49    ///                                     .body("Always HTTPS on non-default ports!")));
50    /// ```
51    pub fn simple(https_to_http: bool) -> Self {
52        RedirectScheme {
53            https_to_http,
54            ..Self::default()
55        }
56    }
57
58    /// Creates a RedirectScheme middleware which also performs string replacement on the final url.
59    /// This is useful when not running on the default web and ssl ports (80 and 443) since we will
60    /// need to change the development web port in the hostname to the development ssl port.
61    ///
62    /// ## Usage
63    /// ```
64    /// extern crate actix_web_middleware_redirect_scheme;
65    ///
66    /// use actix_web::{App, web, HttpResponse};
67    /// use actix_web_middleware_redirect_scheme::RedirectScheme;
68    ///
69    /// App::new()
70    ///     .wrap(RedirectScheme::with_replacements(false, &[(":8080", ":8443")]))
71    ///     .route("/", web::get().to(|| HttpResponse::Ok()
72    ///                                     .content_type("text/plain")
73    ///                                     .body("Always HTTPS on non-default ports!")));
74    /// ```
75    pub fn with_replacements<S: ToString>(https_to_http: bool, replacements: &[(S, S)]) -> Self {
76        let replacements = replacements
77            .iter()
78            .map(|(a, b)| ((*a).to_string(), (*b).to_string()))
79            .collect();
80        RedirectScheme {
81            https_to_http,
82            replacements,
83            ..Self::default()
84        }
85    }
86}
87
88impl<S, B> Transform<S> for RedirectScheme
89where
90    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
91    S::Future: 'static,
92{
93    type Request = ServiceRequest;
94    type Response = ServiceResponse<B>;
95    type Error = Error;
96    type InitError = ();
97    type Transform = RedirectSchemeService<S>;
98    type Future = Ready<Result<Self::Transform, Self::InitError>>;
99
100    fn new_transform(&self, service: S) -> Self::Future {
101        ok(RedirectSchemeService {
102            service,
103            disable: self.disable,
104            https_to_http: self.https_to_http,
105            temporary: self.temporary,
106            replacements: self.replacements.clone(),
107        })
108    }
109}