broken route prefix

This commit is contained in:
realaravinth
2021-04-12 19:03:55 +05:30
parent 420ff75817
commit de6ceb1b3f
9 changed files with 141 additions and 74 deletions

15
Cargo.lock generated
View File

@@ -641,8 +641,8 @@ dependencies = [
[[package]] [[package]]
name = "cache-buster" name = "cache-buster"
version = "0.1.0" version = "0.1.1"
source = "git+https://github.com/realaravinth/cache-buster#71d5ef67a2788789922eaa484e10269acbaeb8a7" source = "git+https://github.com/realaravinth/cache-buster#d5593b2db677406b2c086d7eb25c9efb33d3b168"
dependencies = [ dependencies = [
"data-encoding", "data-encoding",
"derive_builder 0.10.0", "derive_builder 0.10.0",
@@ -802,9 +802,9 @@ dependencies = [
[[package]] [[package]]
name = "crossbeam-channel" name = "crossbeam-channel"
version = "0.5.0" version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if 1.0.0",
"crossbeam-utils 0.8.3", "crossbeam-utils 0.8.3",
@@ -1297,6 +1297,7 @@ dependencies = [
"actix-http", "actix-http",
"actix-identity", "actix-identity",
"actix-rt", "actix-rt",
"actix-service",
"actix-web", "actix-web",
"argon2-creds", "argon2-creds",
"cache-buster", "cache-buster",
@@ -2385,9 +2386,9 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]] [[package]]
name = "sct" name = "sct"
version = "0.6.0" version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3042af939fca8c3453b7af0f1c66e533a15a86169e39de2657310ade8f98d3c" checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce"
dependencies = [ dependencies = [
"ring", "ring",
"untrusted", "untrusted",
@@ -2612,7 +2613,7 @@ dependencies = [
"byteorder", "byteorder",
"bytes 0.5.6", "bytes 0.5.6",
"crc", "crc",
"crossbeam-channel 0.5.0", "crossbeam-channel 0.5.1",
"crossbeam-queue", "crossbeam-queue",
"crossbeam-utils 0.8.3", "crossbeam-utils 0.8.3",
"either", "either",

View File

@@ -27,8 +27,8 @@ actix = "0.10"
actix-identity = "0.3" actix-identity = "0.3"
actix-http = "2.2" actix-http = "2.2"
actix-rt = "1" actix-rt = "1"
actix-cors= "0.5.4" actix-cors = "0.5.4"
actix-service = "1.0.6"
mime_guess = "2.0.3" mime_guess = "2.0.3"
rust-embed = "5.9.0" rust-embed = "5.9.0"
@@ -66,10 +66,14 @@ sailfish = "0.3.2"
[build-dependencies] [build-dependencies]
serde_yaml = "0.8.17" serde_yaml = "0.8.17"
serde = "1"
serde_json = "1" serde_json = "1"
yaml-rust = "0.4.5" yaml-rust = "0.4.5"
cache-buster = { version = "0.1", git = "https://github.com/realaravinth/cache-buster" } cache-buster = { version = "0.1", git = "https://github.com/realaravinth/cache-buster" }
mime = "0.3.16" mime = "0.3.16"
log = "0.4"
config = "0.11"
url = "2.2"
[dev-dependencies] [dev-dependencies]
pow_sha256 = { version = "0.2.1", git = "https://github.com/mcaptcha/pow_sha256" } pow_sha256 = { version = "0.2.1", git = "https://github.com/mcaptcha/pow_sha256" }

View File

@@ -15,9 +15,13 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use cache_buster::BusterBuilder;
use std::process::Command; use std::process::Command;
use cache_buster::BusterBuilder;
#[path = "./src/settings.rs"]
mod settings;
fn main() { fn main() {
// note: add error checking yourself. // note: add error checking yourself.
let output = Command::new("git") let output = Command::new("git")
@@ -37,6 +41,7 @@ fn main() {
} }
fn cache_bust() { fn cache_bust() {
let settings = settings::Settings::new().unwrap();
let types = vec![ let types = vec![
mime::IMAGE_PNG, mime::IMAGE_PNG,
mime::IMAGE_SVG, mime::IMAGE_SVG,
@@ -49,11 +54,12 @@ fn cache_bust() {
let config = BusterBuilder::default() let config = BusterBuilder::default()
.source("./static") .source("./static")
.result("./prod") .result("./prod")
.prefix(settings.server.url_prefix)
.mime_types(types) .mime_types(types)
.copy(true) .copy(true)
.follow_links(true) .follow_links(true)
.build() .build()
.unwrap(); .unwrap();
config.process().unwrap().to_env(); config.process().unwrap();
} }

View File

@@ -28,7 +28,7 @@ ip= "0.0.0.0"
# enter your hostname, eg: example.com # enter your hostname, eg: example.com
domain = "localhost" domain = "localhost"
allow_registration = true allow_registration = true
#url_prefix = "" url_prefix = "/test"
[pow] [pow]
# Please set a unique value, your mCaptcha instance's security depends on this being # Please set a unique value, your mCaptcha instance's security depends on this being

View File

@@ -39,7 +39,7 @@
window.onload = function() { window.onload = function() {
// Begin Swagger UI call region // Begin Swagger UI call region
const ui = SwaggerUIBundle({ const ui = SwaggerUIBundle({
url: "/docs/openapi.json", url: "./openapi.json",
dom_id: '#swagger-ui', dom_id: '#swagger-ui',
deepLinking: true, deepLinking: true,
presets: [ presets: [

View File

@@ -15,19 +15,22 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use std::borrow::Cow;
use actix_web::body::Body; use actix_web::body::Body;
use actix_web::{get, web, HttpResponse, Responder}; use actix_web::{get, web, HttpResponse, Responder};
use mime_guess::from_path; use mime_guess::from_path;
use rust_embed::RustEmbed; use rust_embed::RustEmbed;
use std::borrow::Cow; use crate::SETTINGS;
#[derive(RustEmbed)] #[derive(RustEmbed)]
#[folder = "docs/"] #[folder = "docs/"]
struct Asset; struct Asset;
pub fn handle_embedded_file(path: &str) -> HttpResponse { pub fn handle_embedded_file(path: &str) -> HttpResponse {
match Asset::get(path) { println!("{}", &path);
match Asset::get(&path) {
Some(content) => { Some(content) => {
let body: Body = match content { let body: Body = match content {
Cow::Borrowed(bytes) => bytes.into(), Cow::Borrowed(bytes) => bytes.into(),
@@ -55,6 +58,7 @@ async fn spec() -> HttpResponse {
#[get("/docs")] #[get("/docs")]
async fn index() -> HttpResponse { async fn index() -> HttpResponse {
println!("checking index");
handle_embedded_file("index.html") handle_embedded_file("index.html")
} }

View File

@@ -16,11 +16,10 @@
*/ */
use std::env; use std::env;
use actix_cors::Cors;
use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{ use actix_web::{
client::Client, error::InternalError, http::StatusCode, middleware, web::scope, error::InternalError, http::StatusCode, middleware, web::scope, web::JsonConfig, App,
web::JsonConfig, App, HttpServer, HttpServer,
}; };
//use awc::Client; //use awc::Client;
use cache_buster::Files as FileMap; use cache_buster::Files as FileMap;
@@ -49,8 +48,8 @@ lazy_static! {
// pub static ref OPEN_API_DOC: String = env::var("OPEN_API_DOCS").unwrap(); // pub static ref OPEN_API_DOC: String = env::var("OPEN_API_DOCS").unwrap();
pub static ref S: String = env::var("S").unwrap(); pub static ref S: String = env::var("S").unwrap();
pub static ref FILES: FileMap = FileMap::load(); pub static ref FILES: FileMap = FileMap::new();
pub static ref JS: &'static str = FILES.get("./static/bundle/main.js").unwrap(); pub static ref JS: &'static str = FILES.get_full_path("./static/bundle/main.js").unwrap();
pub static ref CSS: &'static str = FILES.get("./static/bundle/main.css").unwrap(); pub static ref CSS: &'static str = FILES.get("./static/bundle/main.css").unwrap();
} }
@@ -67,8 +66,6 @@ pub static VERIFICATION_PATH: &str = "mcaptchaVerificationChallenge.json";
#[cfg(not(tarpaulin_include))] #[cfg(not(tarpaulin_include))]
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
use api::v1;
use docs;
pretty_env_logger::init(); pretty_env_logger::init();
info!( info!(
"{}: {}.\nFor more information, see: {}\nBuild info:\nVersion: {} commit: {}", "{}: {}.\nFor more information, see: {}\nBuild info:\nVersion: {} commit: {}",
@@ -79,36 +76,36 @@ async fn main() -> std::io::Result<()> {
sqlx::migrate!("./migrations/").run(&data.db).await.unwrap(); sqlx::migrate!("./migrations/").run(&data.db).await.unwrap();
HttpServer::new(move || { HttpServer::new(move || {
let client = Client::default(); // let mut app = App::new()
// .wrap(middleware::Logger::default())
// let captcha_api_cors = Cors::default() // .wrap(get_identity_service())
// .allow_any_origin() // .wrap(middleware::Compress::default())
// .allowed_methods(vec!["POST"]) // .data(data.clone())
// .allow_any_header() // .data(client.clone())
// .max_age(0) // .wrap(middleware::NormalizePath::new(
// .send_wildcard(); // middleware::normalize::TrailingSlash::Trim,
// ))
App::new() // .app_data(get_json_err());
.wrap(middleware::Logger::default()) //
.wrap(get_identity_service()) // if let Some(prefix) = &SETTINGS.server.url_prefix {
.wrap(middleware::Compress::default()) // app = app.service(
.data(data.clone()) // scope(prefix)
.data(client.clone()) // .configure(v1::pow::services)
.wrap(middleware::NormalizePath::new( // .configure(v1::services)
middleware::normalize::TrailingSlash::Trim, // .configure(docs::services)
)) // .configure(templates::services)
.configure(v1::pow::services) // .configure(static_assets::services),
.configure(v1::services) // );
//.service( // } else {
// scope("/") // app = app
// .wrap(captcha_api_cors) // .configure(v1::pow::services)
// .configure(v1::pow::services), // .configure(v1::services)
//) // .configure(docs::services)
.configure(docs::services) // .configure(templates::services)
.configure(templates::services) // .configure(static_assets::services);
.configure(static_assets::services) // }
.app_data(get_json_err()) let app = get_scoped_app!(data);
// .service(Files::new("/", "./prod")) app
}) })
.bind(SETTINGS.server.get_ip()) .bind(SETTINGS.server.get_ip())
.unwrap() .unwrap()
@@ -136,3 +133,45 @@ pub fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {
.secure(false), .secure(false),
) )
} }
#[macro_export]
macro_rules! get_scoped_app {
($data:expr) => {
App::new()
.wrap(middleware::Logger::default())
.wrap(get_identity_service())
.wrap(middleware::Compress::default())
.data($data.clone())
.wrap(middleware::NormalizePath::new(
middleware::normalize::TrailingSlash::Trim,
))
.app_data(get_json_err())
.service(
scope(&crate::SETTINGS.server.url_prefix)
.configure(crate::api::v1::pow::services)
.configure(crate::api::v1::services)
.configure(crate::docs::services)
.configure(crate::templates::services)
.configure(crate::static_assets::services),
)
// if let Some(prefix) = &SETTINGS.server.url_prefix {
// app = app.service(
// scope(prefix)
// .configure(crate::api::v1::pow::services)
// .configure(crate::api::v1::services)
// .configure(crate::docs::services)
// .configure(crate::templates::services)
// .configure(crate::static_assets::services),
// );
// } else {
// app = app
//.configure(crate::api::v1::pow::services)
// .configure(crate::api::v1::services)
// .configure(crate::docs::services)
// .configure(crate::templates::services)
// .configure(crate::static_assets::services),
// }
// app
};
}

View File

@@ -17,7 +17,7 @@
use std::env; use std::env;
use config::{Config, ConfigError, Environment, File}; use config::{Config, ConfigError, Environment, File};
use log::debug; use log::{debug, info};
use serde::Deserialize; use serde::Deserialize;
use url::Url; use url::Url;
@@ -29,7 +29,7 @@ pub struct Server {
pub domain: String, pub domain: String,
pub cookie_secret: String, pub cookie_secret: String,
pub ip: String, pub ip: String,
pub url_prefix: Option<String>, pub url_prefix: String,
} }
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
@@ -44,13 +44,18 @@ impl Server {
format!("{}:{}", self.ip, self.port) format!("{}:{}", self.ip, self.port)
} }
fn check_url_prefix(&mut self) { fn check_url_prefix(prefix: Option<String>) -> String {
if let Some(prefix) = self.url_prefix.clone() { let mut url_prefix;
self.url_prefix = Some(prefix.trim().into()); if let Some(prefix) = prefix.clone() {
url_prefix = prefix.trim().into();
if prefix.trim().is_empty() { if prefix.trim().is_empty() {
self.url_prefix = None; url_prefix = "".into();
} }
} else {
url_prefix = "".into();
} }
url_prefix
} }
} }
@@ -133,11 +138,34 @@ impl Settings {
} }
set_database_url(&mut s); set_database_url(&mut s);
set_url_prefix(&mut s);
s.try_into() s.try_into()
} }
} }
#[cfg(not(tarpaulin_include))]
fn set_url_prefix(s: &mut Config) {
let prefix = s
.get::<Option<String>>("server.url_prefix")
.expect("Couldn't access server url prefix");
let mut url_prefix: String;
if let Some(prefix) = prefix.clone() {
url_prefix = prefix.trim().into();
if prefix.trim().is_empty() {
url_prefix = "".into();
}
} else {
url_prefix = "".into();
}
info!("Setting URL prefix to: {}", &url_prefix);
s.set("server.url_prefix", url_prefix)
.expect("Couldn't set url prefix");
}
#[cfg(not(tarpaulin_include))] #[cfg(not(tarpaulin_include))]
fn set_from_database_url(s: &mut Config, database_conf: &DatabaseBuilder) { fn set_from_database_url(s: &mut Config, database_conf: &DatabaseBuilder) {
s.set("database.username", database_conf.username.clone()) s.set("database.username", database_conf.username.clone())
@@ -172,19 +200,3 @@ fn set_database_url(s: &mut Config) {
) )
.expect("Couldn't set databse url"); .expect("Couldn't set databse url");
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_prefix_test() {
let mut settings = Settings::new().unwrap();
assert!(settings.server.url_prefix.is_none());
settings.server.url_prefix = Some("test".into());
settings.server.check_url_prefix();
settings.server.url_prefix = Some(" ".into());
settings.server.check_url_prefix();
assert!(settings.server.url_prefix.is_none());
}
}

View File

@@ -1,4 +1,5 @@
</body> </body>
<link rel="stylesheet" href="<.= &*crate::CSS .>" type="text/css" media="all"> <link rel="stylesheet" href="<.= &*crate::CSS .>" type="text/css" media="all">
<. println!("{}", &*crate::JS); .>
<script src="<.= &*crate::JS .>"></script> <script src="<.= &*crate::JS .>"></script>
</html> </html>