From 3a4c2f2cf9af2d8726c1209ff8f22c61933f2a7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20Gali=C4=87?= Date: Sun, 26 May 2019 11:59:53 +0200 Subject: [PATCH] create & attach an AdHoc Fairing for dealing with Custom Domains MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this rewrites the URL to /custom_domain/ (we have no route handlers for this path yet) Lots of help from @fdb-hiroshima & @BaptisteGelez in dealing with the borrow checker — thank you 💜️ --- plume-models/src/blogs.rs | 7 +++++++ src/main.rs | 14 +++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/plume-models/src/blogs.rs b/plume-models/src/blogs.rs index 2a64d886..69d3e129 100644 --- a/plume-models/src/blogs.rs +++ b/plume-models/src/blogs.rs @@ -25,6 +25,7 @@ use posts::Post; use safe_string::SafeString; use schema::blogs; use search::Searcher; +use std::fmt::{self, Display}; use users::User; use {Connection, Error, PlumeRocket, Result}; @@ -39,6 +40,12 @@ impl Host { } } +impl Display for Host { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} + impl AsRef for Host { fn as_ref(&self) -> &str { &self.0 diff --git a/src/main.rs b/src/main.rs index 6c466777..86d0dfc6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -42,12 +42,14 @@ extern crate webfinger; use clap::App; use diesel::r2d2::ConnectionManager; use plume_models::{ + blogs::Host, db_conn::{DbPool, PragmaForeignKey}, instance::Instance, migrations::IMPORTED_MIGRATIONS, search::{Searcher as UnmanagedSearcher, SearcherError}, Connection, Error, CONFIG, }; +use rocket::{fairing::AdHoc, http::uri::Origin}; use rocket_csrf::CsrfFairingBuilder; use scheduled_thread_pool::ScheduledThreadPool; use std::process::exit; @@ -175,8 +177,13 @@ Then try to restart Plume println!("Please refer to the documentation to see how to configure it."); } - let custom_domains = plume_models::blogs::Blog::list_custom_domains(&dbpool.get().unwrap()).unwrap(); - dbg!(custom_domains); + let custom_domain_fairing = AdHoc::on_request("Custom Blog Domains", |req, _data| { + let host = req.guard::(); + if host.is_success() { + let rewrite_uri = format!("/custom_domains/{}/{}", host.unwrap(), req.uri()); + req.set_uri(Origin::parse_owned(rewrite_uri).unwrap()) + } + }); let rocket = rocket::custom(CONFIG.rocket.clone().unwrap()) .mount( @@ -317,7 +324,8 @@ Then try to restart Plume ]) .finalize() .expect("main: csrf fairing creation error"), - ); + ) + .attach(custom_domain_fairing); #[cfg(feature = "test")] let rocket = rocket.mount("/test", routes![test_routes::health,]);